Skip to content

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

fix model hub recent sorting for on-device models (#9642)

Lee Jacksonebac1d4ff123
diff --git a/studio/backend/hub/schemas/datasets.py b/studio/backend/hub/schemas/datasets.py
index c72623d97e2..6f17cc7a590 100644
--- a/studio/backend/hub/schemas/datasets.py
+++ b/studio/backend/hub/schemas/datasets.py
@@ -94,6 +94,8 @@ class LocalDatasetsResponse(BaseModel):
class CachedDatasetItem(BaseModel):
repo_id: str
size_bytes: int = 0
+ # epoch seconds; unset when no cache path had a readable mtime
+ last_modified: Optional[float] = None
cache_path: Optional[str] = None
load_cache_path: Optional[str] = None
processed_cache: bool = False
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.py
index db8f95ad7f7..60ebf862ebb 100644
--- a/studio/backend/hub/schemas/inventory.py
+++ b/studio/backend/hub/schemas/inventory.py
@@ -260,6 +260,7 @@ class CachedGgufRepo(CachedRepoBase):
class CachedGgufResponse(BaseModel):
cached: List[CachedGgufRepo] = Field(default_factory = list)
+ scan_confirmed: bool = True
class CachedModelRepo(CachedRepoBase):
@@ -283,6 +284,7 @@ class CachedModelRepo(CachedRepoBase):
class CachedModelsResponse(BaseModel):
cached: List[CachedModelRepo] = Field(default_factory = list)
+ scan_confirmed: bool = True
class HiddenModelsResponse(BaseModel):
diff --git a/studio/backend/hub/services/datasets/cache_inventory.py b/studio/backend/hub/services/datasets/cache_inventory.py
index a4a8fb3b74c..b70bad1c04b 100644
--- a/studio/backend/hub/services/datasets/cache_inventory.py
+++ b/studio/backend/hub/services/datasets/cache_inventory.py
@@ -6,6 +6,7 @@
from __future__ import annotations
import asyncio
+import math
import os
from pathlib import Path
from typing import Optional
@@ -67,18 +68,87 @@ def _repo_id_from_hub_dataset_dir(name: str) -> str | None:
return repo_id if _is_valid_repo_id(repo_id) else None
-def _directory_size(path: Path) -> int:
+def _directory_stats(path: Path) -> tuple[int, float]:
total = 0
+ last_modified = 0.0
try:
for entry in path.rglob("*"):
try:
if entry.is_file() and not entry.is_symlink():
- total += entry.stat().st_size
+ stat = entry.stat()
+ total += stat.st_size
+ last_modified = max(last_modified, _usable_mtime(stat.st_mtime))
except OSError:
continue
except OSError:
- return 0
- return total
+ return 0, 0.0
+ return total, last_modified
+
+
+def _usable_mtime(value) -> float:
+ """a timestamp we are willing to publish, else 0.0 meaning "unknown".
+
+ Finiteness is not paranoia about stat(): ``candidate`` is whatever
+ huggingface_hub put on the object, and Starlette encodes with
+ ``allow_nan = False``, so one inf 500s the whole response.
+ """
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ return 0.0
+ value = float(value)
+ return value if math.isfinite(value) and value > 0 else 0.0
+
+
+def _safe_mtime(path: Path) -> float:
+ """directory mtime as POSIX seconds, or 0.0 when unreadable.
+
+ mtime only, so it is portable across Windows, macOS and Linux. A broken
+ symlink or a share with no clock lands on 0.0, which callers drop.
+ """
+ try:
+ return _usable_mtime(path.stat().st_mtime)
+ except OSError:
+ return 0.0
+
+
+def _dataset_last_modified(candidate, *paths: Optional[Path]) -> float:
+ """newest change time for a cached dataset row, as POSIX seconds.
+
+ Prefers huggingface_hub's own value, else stat()s the cache dirs. Same unit
+ as the cached-model scan.
+ """
+ newest = _usable_mtime(candidate)
+ for path in paths:
+ if path is None:
+ continue
+ newest = max(newest, _safe_mtime(path))
+ return newest
+
+
+def _merge_last_modified(existing: dict, row: dict) -> None:
+ """keep the newer timestamp when two scans describe one dataset."""
+ newest = max(
+ _usable_mtime(existing.get("last_modified")),
+ _usable_mtime(row.get("last_modified")),
+ )
+ if newest > 0:
+ existing["last_modified"] = newest
+
+
+def _adopt_newer_last_modified(winner: dict, loser: Optional[dict]) -> None:
+ """carry a discarded row's timestamp onto the row that replaces it.
+
+ Winning is decided on completeness then size, neither of which is recency,
+ so a bigger-but-older copy would otherwise bury the newer date and sink the
+ dataset in Recent. The cached-model scan keeps the max the same way.
+ """
+ if loser is None:
+ return
+ newest = max(
+ _usable_mtime(winner.get("last_modified")),
+ _usable_mtime(loser.get("last_modified")),
+ )
+ if newest > 0:
+ winner["last_modified"] = newest
def _prefer_dataset_cache_row(candidate: dict, existing: Optional[dict]) -> bool:
@@ -282,9 +352,9 @@ def _scan_hub_dataset_cache_dirs() -> list[dict]:
repo_id = _repo_id_from_hub_dataset_dir(entry.name)
if repo_id is None:
continue
- size_bytes = _directory_size(entry / "blobs")
+ size_bytes, payload_mtime = _directory_stats(entry / "blobs")
if size_bytes <= 0:
- size_bytes = _directory_size(entry)
+ size_bytes, payload_mtime = _directory_stats(entry)
if size_bytes <= 0:
continue
key = repo_id.lower()
@@ -294,6 +364,7 @@ def _scan_hub_dataset_cache_dirs() -> list[dict]:
or hf_cache_scan.is_snapshot_partial("dataset", repo_id, entry)
or not _raw_dataset_cache_has_data(repo_id, entry)
)
+ last_modified = _dataset_last_modified(payload_mtime, entry / "snapshots", entry)
row = {
"repo_id": repo_id,
"size_bytes": size_bytes,
@@ -319,8 +390,13 @@ def _scan_hub_dataset_cache_dirs() -> list[dict]:
else False
),
}
+ if last_modified > 0:
+ row["last_modified"] = last_modified
if _prefer_dataset_cache_row(row, existing):
+ _adopt_newer_last_modified(row, existing)
seen_lower[key] = row
+ elif existing is not None:
+ _merge_last_modified(existing, row)
return sorted(seen_lower.values(), key = lambda c: c["repo_id"])
@@ -351,8 +427,9 @@ def _is_processed_dataset_cache_path(repo_id: str, cache_path: str) -> bool:
return resolved.parent.resolve(strict = False) in roots
-def _processed_dataset_cache_size(path: Path) -> int:
+def _processed_dataset_cache_stats(path: Path) -> tuple[int, float]:
total = 0
+ last_modified = 0.0
try:
for directory, dirnames, filenames in os.walk(path, followlinks = False):
base = Path(directory)
@@ -361,12 +438,17 @@ def _processed_dataset_cache_size(path: Path) -> int:
entry = base / filename
try:
if entry.is_file() and not entry.is_symlink():
- total += entry.stat().st_size
+ stat = entry.stat()
+ total += stat.st_size
+ last_modified = max(
+ last_modified,
+ _usable_mtime(stat.st_mtime),
+ )
except OSError:
continue
except OSError:
- return 0
- return total
+ return 0, 0.0
+ return total, last_modified
def _scan_processed_dataset_caches() -> list[dict]:
@@ -383,33 +465,41 @@ def _scan_processed_dataset_caches() -> list[dict]:
continue
if not processed_dataset_cache_has_artifacts(entry):
continue
- size_bytes = _processed_dataset_cache_size(entry)
+ size_bytes, payload_mtime = _processed_dataset_cache_stats(entry)
if size_bytes <= 0:
continue
key = repo_id.lower()
existing = seen_lower.get(key)
+ processed_mtime = _dataset_last_modified(payload_mtime, entry)
if existing is None or size_bytes > existing["size_bytes"]:
- seen_lower[key] = {
+ processed_row = {
"repo_id": repo_id,
"size_bytes": size_bytes,
"cache_path": str(entry.resolve()),
"processed_cache": True,
"partial": False,
}
+ if processed_mtime > 0:
+ processed_row["last_modified"] = processed_mtime
+ _adopt_newer_last_modified(processed_row, existing)
+ seen_lower[key] = processed_row
+ elif processed_mtime > 0:
+ _merge_last_modified(existing, {"last_modified": processed_mtime})
return sorted(seen_lower.values(), key = lambda c: c["repo_id"])
def _scan_app_processed_dataset_caches() -> list[dict]:
grouped: dict[tuple[str, str], dict] = {}
for entry in iter_app_processed_dataset_caches():
- size_bytes = _processed_dataset_cache_size(entry.path)
+ size_bytes, payload_mtime = _processed_dataset_cache_stats(entry.path)
+ app_mtime = _dataset_last_modified(payload_mtime, entry.path)
key = (
entry.repo_id.casefold(),
os.path.normcase(str(entry.hub_cache)),
)
existing = grouped.get(key)
if existing is None:
- grouped[key] = {
+ app_row = {
"repo_id": entry.repo_id,
"size_bytes": size_bytes,
"cache_path": str(entry.path),
@@ -418,8 +508,12 @@ def _scan_app_processed_dataset_caches() -> list[dict]:
"app_processed_hub_cache": str(entry.hub_cache),
"partial": True,
}
+ if app_mtime > 0:
+ app_row["last_modified"] = app_mtime
+ grouped[key] = app_row
else:
existing["size_bytes"] += size_bytes
+ _merge_last_modified(existing, {"last_modified": app_mtime})
return sorted(
grouped.values(),
key = lambda row: (row["repo_id"].casefold(), row["app_processed_hub_cache"]),
@@ -456,6 +550,11 @@ def _scan_hf_dataset_caches() -> list[dict]:
repo_info.repo_id,
cache_dir,
) or not _raw_dataset_cache_has_data(repo_info.repo_id, cache_dir)
+ repo_last_modified = _dataset_last_modified(
+ getattr(repo_info, "last_modified", None),
+ cache_dir / "snapshots",
+ cache_dir,
+ )
row = {
"repo_id": repo_info.repo_id,
"size_bytes": total_size,
@@ -480,8 +579,13 @@ def _scan_hf_dataset_caches() -> list[dict]:
else False
),
}
+ if repo_last_modified > 0:
+ row["last_modified"] = repo_last_modified
if _prefer_dataset_cache_row(row, existing):
+ _adopt_newer_last_modified(row, existing)
seen_lower[key] = row
+ elif existing is not None:
+ _merge_last_modified(existing, row)
except Exception as exc:
label = getattr(repo_info, "repo_id", "<unknown>")
logger.warning("Skipping cached dataset repo %s: %s", label, exc)
@@ -489,9 +593,11 @@ def _scan_hf_dataset_caches() -> list[dict]:
key = row["repo_id"].lower()
existing = seen_lower.get(key)
if _prefer_dataset_cache_row(row, existing):
+ _adopt_newer_last_modified(row, existing)
seen_lower[key] = row
elif existing is not None and bool(existing.get("partial")) == bool(row.get("partial")):
existing["size_bytes"] = max(existing["size_bytes"], row["size_bytes"])
+ _merge_last_modified(existing, row)
existing["cache_path"] = existing.get("cache_path") or row.get("cache_path")
if (
existing.get("partial")
@@ -508,6 +614,7 @@ def _scan_hf_dataset_caches() -> list[dict]:
seen_lower[key] = row
continue
existing["size_bytes"] = max(existing["size_bytes"], row["size_bytes"])
+ _merge_last_modified(existing, row)
# Preserve the raw path for scoped deletion and expose the processed Arrow path separately.
if row.get("processed_cache"):
existing["processed_cache"] = True
@@ -532,6 +639,7 @@ def _scan_hf_dataset_caches() -> list[dict]:
existing["size_bytes"] = int(existing.get("size_bytes") or 0) + int(
row.get("size_bytes") or 0
)
+ _merge_last_modified(existing, row)
existing["processed_cache"] = True
existing["app_processed_cache"] = True
logger.info(
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.py
index b63acc15007..787916ffec3 100644
--- a/studio/backend/hub/services/download_lifecycle.py
+++ b/studio/backend/hub/services/download_lifecycle.py
@@ -373,6 +373,7 @@ def finalize_worker_exit(
metadata = registry.get_job_metadata(key)
state = classify_exit(rc, cancel_requested = cancel_requested)
if state == "complete":
+ hf_cache_scan.invalidate_hf_cache_scans()
registry.set_job(key, "complete")
# Where /v1 learns a new model exists: its resolver answers from a cached scan
# with no watcher, so it would report the model absent and serve whatever is
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index 512345a2274..3533ea41323 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -34,6 +34,7 @@ from hub.services.models.common import (
_is_gguf_filename,
_is_main_gguf_filename,
_is_mmproj_filename,
+ _is_mtp_drafter_path,
_is_transformers_safetensors_weight_name,
_local_inventory_id,
_local_path_can_chat,
@@ -66,6 +67,11 @@ _MODEL_METADATA_TIMEOUT_SECONDS = 5.0
_repo_size_cache_lock = threading.Lock()
+class _CachedInventoryScan(NamedTuple):
+ rows: list[dict]
+ confirmed: bool
+
+
_cached_inventory_flights: dict[
tuple[asyncio.AbstractEventLoop, tuple[str, int]], asyncio.Task[list[dict]]
] = {}
@@ -171,7 +177,11 @@ def _repo_gguf_last_modified(repo_info) -> float:
latest = 0.0
for revision in repo_info.revisions:
for f in cached_repo_files(revision):
- if _is_main_gguf_filename(_cached_repo_file_name(f)):
+ name = _cached_repo_file_name(f)
+ if _is_main_gguf_filename(name) or (
+ _is_gguf_filename(name)
+ and (_is_mmproj_filename(name) or _is_mtp_drafter_path(name))
+ ):
latest = max(latest, _blob_mtime(f))
return latest
@@ -694,7 +704,7 @@ def _scan_cached_inventory_snapshot(scanner, expected_epoch: int) -> list[dict]:
return rows
-async def _shared_cached_inventory_scan(name: str, scanner) -> list[dict]:
+async def _shared_cached_inventory_scan(name: str, scanner) -> _CachedInventoryScan:
for _attempt in range(_INVENTORY_SCAN_MAX_ATTEMPTS):
epoch = hf_cache_scan.hf_cache_scans_epoch()
try:
@@ -708,7 +718,7 @@ async def _shared_cached_inventory_scan(name: str, scanner) -> list[dict]:
except _CacheSourceChanged:
continue
_last_confirmed_inventory[name] = rows
- return rows
+ return _CachedInventoryScan(rows, True)
# Invalidations are arriving faster than the walk completes, so no scan will
# confirm as current. Answer with the last one that did rather than spin a
# full cache walk per epoch forever.
@@ -716,14 +726,14 @@ async def _shared_cached_inventory_scan(name: str, scanner) -> list[dict]:
"Cached %s inventory kept racing cache invalidations; serving the last confirmed scan",
name,
)
- return _last_confirmed_inventory.get(name, [])
+ return _CachedInventoryScan(_last_confirmed_inventory.get(name, []), False)
async def list_cached_gguf_response(hf_token: Optional[str] = None):
"""List GGUF repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""
try:
- cached = await _shared_cached_inventory_scan("gguf", _scan_cached_gguf)
- return {"cached": cached}
+ scan = await _shared_cached_inventory_scan("gguf", _scan_cached_gguf)
+ return {"cached": scan.rows, "scan_confirmed": scan.confirmed}
except Exception as e:
from fastapi import HTTPException
logger.error(
@@ -1216,8 +1226,8 @@ def _scan_cached_models(
async def list_cached_models_response(hf_token: Optional[str] = None):
"""List non-GGUF model repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""
try:
- cached = await _shared_cached_inventory_scan("models", _scan_cached_models)
- return {"cached": cached}
+ scan = await _shared_cached_inventory_scan("models", _scan_cached_models)
+ return {"cached": scan.rows, "scan_confirmed": scan.confirmed}
except Exception as e:
from fastapi import HTTPException
logger.error(
diff --git a/studio/backend/hub/tests/test_download_lifecycle.py b/studio/backend/hub/tests/test_download_lifecycle.py
index 159e299c42e..241b47354fd 100644
--- a/studio/backend/hub/tests/test_download_lifecycle.py
+++ b/studio/backend/hub/tests/test_download_lifecycle.py
@@ -55,6 +55,45 @@ def test_resolve_effective_use_xet(monkeypatch):
assert download_lifecycle.resolve_effective_use_xet(requested) is expected
+def test_completion_invalidates_inventory_before_publishing_state(monkeypatch):
+ events = []
+
+ class _Registry:
+ def cancel_requested(self, _key):
+ return False
+
+ def drop_process(self, _key, _proc):
+ return True
+
+ def get_job_metadata(self, _key):
+ return None
+
+ def set_job(self, _key, state):
+ events.append(state)
+
+ monkeypatch.setattr(
+ download_lifecycle.hf_cache_scan,
+ "invalidate_hf_cache_scans",
+ lambda: events.append("invalidate"),
+ )
+
+ assert (
+ download_lifecycle.finalize_worker_exit(
+ _Registry(),
+ "org/data",
+ _Proc(0),
+ hf_token = None,
+ label = "org/data",
+ log_prefix = "Download",
+ logger = logging.getLogger("test"),
+ repo_type = "dataset",
+ repo_id = "org/data",
+ )
+ == "complete"
+ )
+ assert events == ["invalidate", "complete"]
+
+
def test_xet_failure_retries_over_http_for_model_and_dataset(monkeypatch, tmp_path):
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index f4ffdcec854..e347509aeb7 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -82,6 +82,29 @@ def _sibling(name: str, size: int, sha: str):
return SimpleNamespace(rfilename = name, size = size, lfs = {"sha256": sha})
+def test_gguf_inventory_dates_rows_from_managed_companions(tmp_path):
+ repo = _repo(
+ "Org/Vision-GGUF",
+ [
+ SimpleNamespace(
+ file_name = "model-Q4_K_M.gguf",
+ size_on_disk = 100,
+ blob_path = None,
+ blob_last_modified = 10.0,
+ ),
+ SimpleNamespace(
+ file_name = "mmproj-F16.gguf",
+ size_on_disk = 20,
+ blob_path = None,
+ blob_last_modified = 30.0,
+ ),
+ ],
+ tmp_path,
+ )
+
+ assert cache_inventory._repo_gguf_last_modified(repo) == 30.0
+
+
class TestExtractQuantToken:
def test_trailing_precision_is_kept(self):
assert gguf.extract_quant_token("model-it-F16.gguf") == "F16"
@@ -775,7 +798,7 @@ def test_cached_inventory_requests_share_scan(monkeypatch, inventory_request, sc
releases[1].set()
return await asyncio.gather(second, changed)
- assert asyncio.run(run_requests()) == [{"cached": cached}] * 2
+ assert asyncio.run(run_requests()) == [{"cached": cached, "scan_confirmed": True}] * 2
assert scans == 1 and cache_inventory._cached_inventory_flights == {}
@@ -812,8 +835,9 @@ def test_cached_inventory_discards_a_scan_that_raced_an_invalidation(
monkeypatch.setattr(cache_inventory.hf_cache_scan, "hf_cache_scans_epoch", lambda: epoch[0])
monkeypatch.setattr(cache_inventory, "_last_confirmed_inventory", {})
- rows = asyncio.run(cache_inventory._shared_cached_inventory_scan(inventory_call, scan))
- assert rows == [{"repo_id": "Org/Kept"}], "rows from the superseded walk were served"
+ result = asyncio.run(cache_inventory._shared_cached_inventory_scan(inventory_call, scan))
+ assert result.rows == [{"repo_id": "Org/Kept"}], "rows from the superseded walk were served"
+ assert result.confirmed is True
assert len(scans) == 2, "the superseded walk was not retried"
assert cache_inventory._cached_inventory_flights == {}
@@ -840,7 +864,9 @@ def test_cached_inventory_scan_stops_retrying_under_constant_invalidation(monkey
cache_inventory._shared_cached_inventory_scan("gguf", scan), timeout = 5
)
- assert asyncio.run(run()) == []
+ result = asyncio.run(run())
+ assert result.rows == []
+ assert result.confirmed is False
assert len(scans) == cache_inventory._INVENTORY_SCAN_MAX_ATTEMPTS
assert cache_inventory._cached_inventory_flights == {}
diff --git a/studio/backend/tests/test_dataset_cache_timestamps.py b/studio/backend/tests/test_dataset_cache_timestamps.py
new file mode 100644
index 00000000000..b880e5cb348
--- /dev/null
+++ b/studio/backend/tests/test_dataset_cache_timestamps.py
@@ -0,0 +1,387 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""S9 for PR #9642: cached datasets need a timestamp for Recent to mean anything.
+
+/api/hub/datasets/cached carried no time field, while local recipe and upload
+datasets carried updated_at, so every cached Hub dataset sorted below every
+local one whatever the date.
+
+Deliberately not beside its subject in hub/tests/: studio-backend-ci runs
+`pytest tests/` from studio/backend, and hub/tests is a sibling of that path, so
+nothing there is collected. A guard that never runs is not a guard.
+"""
+
+import os
+from types import SimpleNamespace
+
+import pytest
+
+from hub.schemas.datasets import CachedDatasetItem
+from hub.services.datasets import cache_inventory
+
+
+def _stub_hf_scan(monkeypatch, repos):
+ monkeypatch.setattr(
+ cache_inventory,
+ "_collect_hf_cache_scans",
+ lambda: ([SimpleNamespace(repos = repos)], {"/cache"}),
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_raw_dataset_cache_has_data",
+ lambda *_args: True,
+ )
+ monkeypatch.setattr(cache_inventory, "_scan_hub_dataset_cache_dirs", lambda: [])
+ monkeypatch.setattr(cache_inventory, "_scan_processed_dataset_caches", lambda: [])
+ monkeypatch.setattr(cache_inventory, "_scan_app_processed_dataset_caches", lambda: [])
+
+
+def test_schema_carries_the_timestamp():
+ assert "last_modified" in CachedDatasetItem.__annotations__
+ # Unset rather than 0, or an unreadable cache sorts as 1970.
+ assert CachedDatasetItem(repo_id = "Org/Data").last_modified is None
+
+
+def test_hf_scan_reports_the_repo_timestamp_in_seconds(monkeypatch):
+ _stub_hf_scan(
+ monkeypatch,
+ [
+ SimpleNamespace(
+ repo_id = "Org/Data",
+ repo_type = "dataset",
+ repo_path = "/cache/datasets--Org--Data",
+ size_on_disk = 100,
+ last_modified = 1_700_000_000.5,
+ revisions = [SimpleNamespace(files = [], commit_hash = "abc")],
+ )
+ ],
+ )
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+
+ assert len(rows) == 1
+ # POSIX seconds, as the cached-model scan emits, so one normalizer covers both.
+ assert rows[0]["last_modified"] == pytest.approx(1_700_000_000.5)
+
+
+def test_the_key_is_omitted_when_no_mtime_is_readable(monkeypatch):
+ # Broken symlink, clockless share, or a cache deleted mid-scan. Still listed,
+ # just undated.
+ _stub_hf_scan(
+ monkeypatch,
+ [
+ SimpleNamespace(
+ repo_id = "Org/Data",
+ repo_type = "dataset",
+ repo_path = "/definitely/not/on/disk/datasets--Org--Data",
+ size_on_disk = 100,
+ revisions = [SimpleNamespace(files = [], commit_hash = "abc")],
+ )
+ ],
+ )
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+
+ assert len(rows) == 1
+ assert "last_modified" not in rows[0]
+
+
+def test_a_non_positive_mtime_is_dropped_rather_than_reported_as_1970(monkeypatch):
+ _stub_hf_scan(
+ monkeypatch,
+ [
+ SimpleNamespace(
+ repo_id = "Org/Data",
+ repo_type = "dataset",
+ repo_path = "/definitely/not/on/disk/datasets--Org--Data",
+ size_on_disk = 100,
+ last_modified = 0.0,
+ revisions = [SimpleNamespace(files = [], commit_hash = "abc")],
+ )
+ ],
+ )
+
+ assert "last_modified" not in cache_inventory._scan_hf_dataset_caches()[0]
+
+
+def test_falls_back_to_stat_when_the_library_reports_nothing(monkeypatch, tmp_path):
+ cache_dir = tmp_path / "datasets--Org--Data"
+ (cache_dir / "snapshots").mkdir(parents = True)
+ # Both candidates: the fallback takes the newest, or a freshly created parent
+ # directory would dominate.
+ os.utime(cache_dir / "snapshots", (1_700_000_000, 1_700_000_000))
+ os.utime(cache_dir, (1_690_000_000, 1_690_000_000))
+
+ _stub_hf_scan(
+ monkeypatch,
+ [
+ SimpleNamespace(
+ repo_id = "Org/Data",
+ repo_type = "dataset",
+ repo_path = str(cache_dir),
+ size_on_disk = 100,
+ revisions = [SimpleNamespace(files = [], commit_hash = "abc")],
+ )
+ ],
+ )
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+
+ assert rows[0]["last_modified"] == pytest.approx(1_700_000_000, abs = 2)
+
+
+def test_a_merge_keeps_the_newer_of_the_two_timestamps(monkeypatch):
+ _stub_hf_scan(
+ monkeypatch,
+ [
+ SimpleNamespace(
+ repo_id = "Org/Data",
+ repo_type = "dataset",
+ repo_path = "/cache/datasets--Org--Data",
+ size_on_disk = 100,
+ last_modified = 1_700_000_000.0,
+ revisions = [SimpleNamespace(files = [], commit_hash = "abc")],
+ )
+ ],
+ )
+ # The processed-cache scan describes the same dataset, more recently touched.
+ monkeypatch.setattr(
+ cache_inventory,
+ "_scan_processed_dataset_caches",
+ lambda: [
+ {
+ "repo_id": "org/data",
+ "size_bytes": 250,
+ "cache_path": "/processed/org___data",
+ "processed_cache": True,
+ "partial": False,
+ "last_modified": 1_800_000_000.0,
+ }
+ ],
+ )
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+
+ assert rows[0]["last_modified"] == pytest.approx(1_800_000_000.0)
+
+
+def test_a_merge_does_not_lose_a_timestamp_the_other_row_lacks(monkeypatch):
+ _stub_hf_scan(
+ monkeypatch,
+ [
+ SimpleNamespace(
+ repo_id = "Org/Data",
+ repo_type = "dataset",
+ repo_path = "/cache/datasets--Org--Data",
+ size_on_disk = 100,
+ last_modified = 1_700_000_000.0,
+ revisions = [SimpleNamespace(files = [], commit_hash = "abc")],
+ )
+ ],
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_scan_processed_dataset_caches",
+ lambda: [
+ {
+ "repo_id": "org/data",
+ "size_bytes": 250,
+ "cache_path": "/processed/org___data",
+ "processed_cache": True,
+ "partial": False,
+ }
+ ],
+ )
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+
+ assert rows[0]["last_modified"] == pytest.approx(1_700_000_000.0)
+
+
+def test_hf_scan_keeps_a_newer_timestamp_from_a_smaller_duplicate(monkeypatch):
+ def repo(size, last_modified):
+ return SimpleNamespace(
+ repo_id = "Org/Data",
+ repo_type = "dataset",
+ repo_path = f"/cache-{size}/datasets--Org--Data",
+ size_on_disk = size,
+ last_modified = last_modified,
+ revisions = [SimpleNamespace(files = [], commit_hash = str(size))],
+ )
+
+ _stub_hf_scan(
+ monkeypatch,
+ [repo(200, 1_700_000_000.0), repo(100, 1_900_000_000.0)],
+ )
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+
+ assert rows[0]["size_bytes"] == 200
+ assert rows[0]["last_modified"] == pytest.approx(1_900_000_000.0)
+
+
+def test_fallback_scan_keeps_a_newer_timestamp_from_a_smaller_duplicate(monkeypatch, tmp_path):
+ larger_root = tmp_path / "larger"
+ newer_root = tmp_path / "newer"
+ for root, modified in (
+ (larger_root, 1_700_000_000),
+ (newer_root, 1_900_000_000),
+ ):
+ cache_dir = root / "datasets--Org--Data"
+ snapshots = cache_dir / "snapshots"
+ snapshots.mkdir(parents = True)
+ os.utime(cache_dir, (modified, modified))
+ os.utime(snapshots, (modified, modified))
+
+ monkeypatch.setattr(
+ cache_inventory,
+ "_hf_hub_cache_roots",
+ lambda: [larger_root, newer_root],
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_directory_stats",
+ lambda path: (200 if "larger" in path.parts else 100, 0.0),
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_hub_dataset_snapshot_count",
+ lambda _path: 1,
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args: False,
+ )
+ monkeypatch.setattr(cache_inventory, "_raw_dataset_cache_has_data", lambda *_args: True)
+
+ rows = cache_inventory._scan_hub_dataset_cache_dirs()
+
+ assert rows[0]["size_bytes"] == 200
+ assert rows[0]["last_modified"] == pytest.approx(1_900_000_000.0)
+
+
+def test_fallback_scan_uses_the_newest_payload_mtime(monkeypatch, tmp_path):
+ root = tmp_path / "hub"
+ cache_dir = root / "datasets--Org--Data"
+ snapshots = cache_dir / "snapshots"
+ blobs = cache_dir / "blobs"
+ snapshots.mkdir(parents = True)
+ blobs.mkdir()
+ payload = blobs / "sha256"
+ payload.write_bytes(b"payload")
+ os.utime(payload, (1_900_000_000, 1_900_000_000))
+ os.utime(snapshots, (1_700_000_000, 1_700_000_000))
+ os.utime(cache_dir, (1_700_000_000, 1_700_000_000))
+
+ monkeypatch.setattr(cache_inventory, "_hf_hub_cache_roots", lambda: [root])
+ monkeypatch.setattr(
+ cache_inventory,
+ "_hub_dataset_snapshot_count",
+ lambda _path: 1,
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args: False,
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_raw_dataset_cache_has_data",
+ lambda *_args: True,
+ )
+
+ rows = cache_inventory._scan_hub_dataset_cache_dirs()
+
+ assert rows[0]["last_modified"] == pytest.approx(1_900_000_000.0)
+
+
+def test_processed_scan_keeps_a_newer_timestamp_from_a_smaller_duplicate(monkeypatch, tmp_path):
+ larger_root = tmp_path / "larger-processed"
+ newer_root = tmp_path / "newer-processed"
+ for root, size, modified in (
+ (larger_root, 200, 1_700_000_000),
+ (newer_root, 100, 1_900_000_000),
+ ):
+ cache_dir = root / "Org___Data"
+ cache_dir.mkdir(parents = True)
+ (cache_dir / "data.arrow").write_bytes(b"x" * size)
+ os.utime(cache_dir, (modified, modified))
+
+ monkeypatch.setattr(
+ cache_inventory,
+ "_hf_datasets_cache_roots",
+ lambda: [larger_root, newer_root],
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "processed_dataset_cache_has_artifacts",
+ lambda _path: True,
+ )
+
+ rows = cache_inventory._scan_processed_dataset_caches()
+
+ assert rows[0]["size_bytes"] == 200
+ assert rows[0]["last_modified"] == pytest.approx(1_900_000_000.0)
+
+
+def test_processed_scan_uses_the_newest_nested_artifact_mtime(monkeypatch, tmp_path):
+ root = tmp_path / "processed"
+ cache_dir = root / "Org___Data"
+ build_dir = cache_dir / "default" / "1.0.0" / "build"
+ build_dir.mkdir(parents = True)
+ artifact = build_dir / "data.arrow"
+ artifact.write_bytes(b"payload")
+ os.utime(artifact, (1_900_000_000, 1_900_000_000))
+ os.utime(cache_dir, (1_700_000_000, 1_700_000_000))
+
+ monkeypatch.setattr(
+ cache_inventory,
+ "_hf_datasets_cache_roots",
+ lambda: [root],
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "processed_dataset_cache_has_artifacts",
+ lambda _path: True,
+ )
+
+ rows = cache_inventory._scan_processed_dataset_caches()
+
+ assert rows[0]["last_modified"] == pytest.approx(1_900_000_000.0)
+
+
+def test_recent_order_is_now_derivable_from_the_payload(monkeypatch):
+ # The whole point: two cached datasets, and the newer one sorts first.
+ _stub_hf_scan(
+ monkeypatch,
+ [
+ SimpleNamespace(
+ repo_id = "Org/Older",
+ repo_type = "dataset",
+ repo_path = "/cache/datasets--Org--Older",
+ size_on_disk = 100,
+ last_modified = 1_700_000_000.0,
+ revisions = [SimpleNamespace(files = [], commit_hash = "a")],
+ ),
+ SimpleNamespace(
+ repo_id = "Org/Newer",
+ repo_type = "dataset",
+ repo_path = "/cache/datasets--Org--Newer",
+ size_on_disk = 100,
+ last_modified = 1_900_000_000.0,
+ revisions = [SimpleNamespace(files = [], commit_hash = "b")],
+ ),
+ ],
+ )
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+ by_recent = sorted(rows, key = lambda row: -(row.get("last_modified") or 0.0))
+
+ assert [row["repo_id"] for row in by_recent] == ["Org/Newer", "Org/Older"]
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 2cf06463607..6ea3f8064b9 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -492,8 +492,7 @@ export interface CachedGgufRepo {
load_id?: string | null;
size_bytes: number;
cache_path: string;
- /** Epoch seconds of the newest downloaded quant; sorts Downloaded
- * newest-first. Optional for older-backend compatibility. */
+ /** epoch seconds of the newest downloaded quant; optional for older backends. */
last_modified?: number;
/** True when the repo ships an mmproj adapter (image inputs). Optional for
* older-backend compatibility. */
@@ -635,8 +634,7 @@ export interface CachedModelRepo {
/** Weights format; "adapter" is a LoRA with no base weights of its own.
* Optional for older-backend compatibility. */
model_format?: string | null;
- /** Epoch seconds of the newest downloaded weight file; sorts Downloaded
- * newest-first. Optional for older-backend compatibility. */
+ /** epoch seconds of the newest downloaded weight; optional for older backends. */
last_modified?: number;
/** HF pipeline task: "text-to-image" for a cached diffusers pipeline repo (model_index.json present), so the chat picker can hide it. Absent = chat. */
task?: string | null;
diff --git a/studio/frontend/src/features/hub/catalog/inventory-sort.ts b/studio/frontend/src/features/hub/catalog/inventory-sort.ts
new file mode 100644
index 00000000000..dd5932b07af
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/inventory-sort.ts
@@ -0,0 +1,42 @@
+// 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 type { CachedInventoryRow, LocalInventoryRow } from "../types";
+
+export type InventoryItem =
+ | { variant: "cached"; row: CachedInventoryRow }
+ | { variant: "local"; row: LocalInventoryRow };
+
+export function inventoryItemTitle(item: InventoryItem): string {
+ return item.variant === "cached" ? item.row.repo : item.row.title;
+}
+
+export function inventoryItemSize(item: InventoryItem): number {
+ return item.variant === "cached" ? item.row.bytes : 0;
+}
+
+/** row timestamp in epoch milliseconds, or null when unknown. */
+export function inventoryItemUpdatedAt(item: InventoryItem): number | null {
+ return item.variant === "cached"
+ ? (item.row.lastModified ?? null)
+ : item.row.updatedAt;
+}
+
+/** newest known timestamp first; preserve source order for ties and unknowns. */
+export function compareInventoryItemsByRecent(
+ a: InventoryItem,
+ b: InventoryItem,
+): number {
+ const aUpdatedAt = inventoryItemUpdatedAt(a);
+ const bUpdatedAt = inventoryItemUpdatedAt(b);
+ if (aUpdatedAt === bUpdatedAt) {
+ return 0;
+ }
+ if (aUpdatedAt == null) {
+ return 1;
+ }
+ if (bUpdatedAt == null) {
+ return -1;
+ }
+ return bUpdatedAt - aUpdatedAt;
+}
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
index 73d8eb6ad7c..9c2d2978617 100644
--- a/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
@@ -26,6 +26,12 @@ import type {
DiscoverRow,
LocalInventoryRow,
} from "../types";
+import {
+ compareInventoryItemsByRecent,
+ type InventoryItem,
+ inventoryItemSize,
+ inventoryItemTitle,
+} from "./inventory-sort";
import {
DiscoverFetchMoreFooter,
DiscoverFetchMoreState,
@@ -49,18 +55,6 @@ import {
ResultSplitRow,
} from "./models-table";
-type InventoryItem =
- | { variant: "cached"; row: CachedInventoryRow }
- | { variant: "local"; row: LocalInventoryRow };
-
-function inventoryItemTitle(item: InventoryItem): string {
- return item.variant === "cached" ? item.row.repo : item.row.title;
-}
-
-function inventoryItemSize(item: InventoryItem): number {
- return item.variant === "cached" ? item.row.bytes : 0;
-}
-
export function InventoryWarningRow({
isDataset,
onRetry,
@@ -344,7 +338,12 @@ export function DownloadedList({
if (sort === "recent") {
return merged
.map((item, index) => ({ item, index }))
- .sort((a, b) => pinRank(a.item) - pinRank(b.item) || a.index - b.index)
+ .sort(
+ (a, b) =>
+ pinRank(a.item) - pinRank(b.item) ||
+ compareInventoryItemsByRecent(a.item, b.item) ||
+ a.index - b.index,
+ )
.map((entry) => entry.item);
}
return merged
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
index f1f4d0fde24..5b91a71e126 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
@@ -5,6 +5,11 @@ import { isTauri } from "@/lib/api-base";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { INVENTORY_HINT_KIND } from "../inventory/constants";
+import {
+ discardPendingInventoryHint,
+ forgetObservedInventoryHint,
+ rememberCompletedInventoryHints,
+} from "../inventory/inventory-hint-store";
import { inventoryHintKey } from "../inventory/inventory-hints";
import type { InventoryHint } from "../inventory/types";
import { createThrottledStorage, noopStorage } from "../stores/persist-storage";
@@ -233,6 +238,8 @@ function collectCompletedInventoryHints(
kind,
repoId: job.repoId,
...(bytes > 0 ? { bytes } : {}),
+ startedAt: job.startedAt,
+ ...(job.completedAt ? { createdAt: job.completedAt } : {}),
},
];
});
@@ -240,7 +247,10 @@ function collectCompletedInventoryHints(
function buildCompletedHintSignature(hints: readonly InventoryHint[]): string {
return hints
- .map((hint) => `${hint.kind}:${hint.repoId}:${hint.bytes ?? ""}`)
+ .map(
+ (hint) =>
+ `${hint.kind}:${hint.repoId}:${hint.bytes ?? ""}:${hint.startedAt ?? ""}:${hint.createdAt ?? ""}`,
+ )
.sort()
.join("|");
}
@@ -418,10 +428,29 @@ function refreshCompletedHintSignature(): void {
}
export function patchJob(key: string, patch: Partial<ManagedDownload>): void {
+ const previousJob = getState().jobs[key];
+ if (
+ previousJob &&
+ previousJob.state !== "complete" &&
+ patch.state === "complete"
+ ) {
+ runtimeRegistry.suppressedCompletedInventoryHints.delete(
+ inventoryHintKey(
+ completedInventoryHintKind(previousJob.kind, previousJob.variant),
+ previousJob.repoId,
+ ),
+ );
+ }
setState((state) => {
const job = state.jobs[key];
if (!job) return state;
- const nextJob = { ...job, ...patch };
+ const nextJob = {
+ ...job,
+ ...patch,
+ ...(job.state !== "complete" && patch.state === "complete"
+ ? { completedAt: patch.completedAt ?? Date.now() }
+ : {}),
+ };
const nextState = {
...state,
jobs: { ...state.jobs, [key]: nextJob },
@@ -431,10 +460,26 @@ export function patchJob(key: string, patch: Partial<ManagedDownload>): void {
}
return withCompletedHintSignature(nextState);
});
+ const completedJob = getState().jobs[key];
+ if (
+ previousJob &&
+ previousJob.state !== "complete" &&
+ completedJob?.state === "complete"
+ ) {
+ rememberCompletedInventoryHints(
+ collectCompletedInventoryHints({ [key]: completedJob }),
+ );
+ }
}
export function putJob(job: ManagedDownload): void {
runtimeRegistry.clearRemovalTimer(job.key);
+ if (!job.external) {
+ forgetObservedInventoryHint(
+ completedInventoryHintKind(job.kind, job.variant),
+ job.repoId,
+ );
+ }
const suppressionChanged =
runtimeRegistry.suppressedCompletedInventoryHints.delete(
inventoryHintKey(
@@ -462,23 +507,13 @@ export function putJob(job: ManagedDownload): void {
export function removeJob(key: string): void {
const job = getState().jobs[key];
teardownRuntime(key);
- let suppressionChanged = false;
- if (job) {
- suppressionChanged =
- runtimeRegistry.suppressedCompletedInventoryHints.delete(
- inventoryHintKey(
- completedInventoryHintKind(job.kind, job.variant),
- job.repoId,
- ),
- );
- }
runtimeRegistry.clearRemovalTimer(key);
setState((state) => {
if (!(key in state.jobs)) return state;
const next = { ...state.jobs };
delete next[key];
const nextState = { ...state, jobs: next };
- if (!suppressionChanged && job?.state !== "complete") return nextState;
+ if (job?.state !== "complete") return nextState;
return withCompletedHintSignature(nextState);
});
}
@@ -532,6 +567,42 @@ export function clearCompletedInventoryHint(hint: InventoryHint): void {
refreshCompletedHintSignature();
}
+export function discardDeletedInventoryHints(
+ repoId: string,
+ kinds: readonly InventoryHint["kind"][],
+): void {
+ for (const kind of kinds) {
+ discardPendingInventoryHint(kind, repoId);
+ clearCompletedInventoryHint({ kind, repoId });
+ }
+ const repoIdentity = normalizeRepoIdentity(repoId);
+ for (const job of Object.values(getState().jobs)) {
+ if (
+ job.state === "complete" &&
+ normalizeRepoIdentity(job.repoId) === repoIdentity &&
+ kinds.includes(completedInventoryHintKind(job.kind, job.variant))
+ ) {
+ removeJob(job.key);
+ }
+ }
+}
+
+export function discardDeletedModelInventoryHints(
+ repoId: string,
+ variant?: string,
+): void {
+ if (!variant) {
+ discardDeletedInventoryHints(repoId, ["model", "gguf"]);
+ return;
+ }
+ discardPendingInventoryHint("gguf", repoId);
+ clearCompletedInventoryHint({ kind: "gguf", repoId });
+ const job = getState().jobs[jobKeyOf(DOWNLOAD_KIND.MODEL, repoId, variant)];
+ if (job?.state === "complete") {
+ removeJob(job.key);
+ }
+}
+
export function subscribeJobListeners(
kind: DownloadKind,
repoId: string,
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
index a8f161cd133..1190a442b25 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
@@ -33,7 +33,10 @@ export interface ManagedDownload {
/** Seconds remaining, from the same estimator as {@link bytesPerSec}; 0 hides it. */
etaSeconds: number;
error: string | null;
+ /** epoch milliseconds from Date.now(). */
startedAt: number;
+ /** epoch milliseconds captured once when the job completes. */
+ completedAt?: number;
serverGeneration?: number;
/** Files a scoped job is fetching, when known. Every file set of one repo rides the same scope slot (see `scopedVariant`), so this separates "my transfer is already running" from "a different quant of this repo is running": adopting the latter would report ready for files nobody fetched. Unknown stays adoptable only for an UNSCOPED job. */
scopedFiles?: string[];
diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.ts
index 3b137ec4190..807b4138995 100644
--- a/studio/frontend/src/features/hub/index.ts
+++ b/studio/frontend/src/features/hub/index.ts
@@ -63,6 +63,7 @@ export {
defaultCapabilities,
deleteCachedDataset,
deleteCachedModel,
+ epochMillisecondsToSeconds,
fetchInventorySource,
findCompleteHfCacheLocalRow,
formatLocalUpdated,
diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.ts
index 4cab0e03f9f..b6cd241bae9 100644
--- a/studio/frontend/src/features/hub/inventory/api.ts
+++ b/studio/frontend/src/features/hub/inventory/api.ts
@@ -12,6 +12,10 @@ import { localPathCacheKey } from "@/features/hub/lib/local-path";
import { isHuggingFaceOffline } from "@/features/hub/lib/network";
import { fingerprintToken } from "@/features/hub/lib/token-fingerprint";
import { bumpInventoryVersion } from "@/features/hub/stores/inventory-events";
+import {
+ discardDeletedInventoryHints,
+ discardDeletedModelInventoryHints,
+} from "../download-manager/download-manager-state";
import type { ScanFolderStatus } from "../lib/scan-folder-status";
import type { LocalSource } from "./constants";
import { bumpGgufVariantsCacheVersion } from "./gguf-variants-cache-events";
@@ -49,6 +53,7 @@ export interface CachedGgufRepo {
capabilities?: BackendModelCapabilities | null;
size_bytes: number;
cache_path?: string;
+ /** epoch seconds; inventory view models normalize this to milliseconds. */
last_modified?: number | null;
partial?: boolean;
partial_transport?: string | null;
@@ -71,6 +76,7 @@ export interface CachedModelRepo {
capabilities?: BackendModelCapabilities | null;
size_bytes: number;
cache_path?: string;
+ /** epoch seconds; inventory view models normalize this to milliseconds. */
last_modified?: number | null;
partial?: boolean;
partial_transport?: string | null;
@@ -84,6 +90,11 @@ export interface CachedModelRepo {
quant_method?: string | null;
}
+export interface CachedInventoryResponse<Repo> {
+ cached: Repo[];
+ scan_confirmed?: boolean;
+}
+
export interface LocalModelInfo {
id: string;
inventory_id?: string | null;
@@ -126,6 +137,8 @@ export interface LocalModelListResponse {
export interface CachedDatasetRepo {
repo_id: string;
size_bytes: number;
+ /** epoch seconds; absent when no cache path has a readable mtime. */
+ last_modified?: number | null;
cache_path?: string;
load_cache_path?: string;
partial?: boolean;
@@ -228,30 +241,44 @@ export async function listLocalModels(): Promise<LocalModelListResponse> {
return parseJsonOrThrow<LocalModelListResponse>(response);
}
-export async function listCachedGguf(
+export async function fetchCachedGgufInventory(
hfToken?: string | null,
-): Promise<CachedGgufRepo[]> {
+): Promise<CachedInventoryResponse<CachedGgufRepo>> {
const response = await withHubTimeout(INVENTORY_TIMEOUT_MS, (signal) =>
authFetch("/api/hub/cached-gguf", {
headers: hubTokenHeader(hfToken),
signal,
}),
);
- const data = await parseJsonOrThrow<{ cached: CachedGgufRepo[] }>(response);
- return data.cached;
+ return await parseJsonOrThrow<CachedInventoryResponse<CachedGgufRepo>>(
+ response,
+ );
}
-export async function listCachedModels(
+export async function listCachedGguf(
hfToken?: string | null,
-): Promise<CachedModelRepo[]> {
+): Promise<CachedGgufRepo[]> {
+ return (await fetchCachedGgufInventory(hfToken)).cached;
+}
+
+export async function fetchCachedModelsInventory(
+ hfToken?: string | null,
+): Promise<CachedInventoryResponse<CachedModelRepo>> {
const response = await withHubTimeout(INVENTORY_TIMEOUT_MS, (signal) =>
authFetch("/api/hub/cached-models", {
headers: hubTokenHeader(hfToken),
signal,
}),
);
- const data = await parseJsonOrThrow<{ cached: CachedModelRepo[] }>(response);
- return data.cached;
+ return await parseJsonOrThrow<CachedInventoryResponse<CachedModelRepo>>(
+ response,
+ );
+}
+
+export async function listCachedModels(
+ hfToken?: string | null,
+): Promise<CachedModelRepo[]> {
+ return (await fetchCachedModelsInventory(hfToken)).cached;
}
export async function listLocalDatasets(): Promise<LocalDatasetsResponse> {
@@ -283,6 +310,7 @@ export async function deleteCachedDataset(
body: JSON.stringify(payload),
});
await throwIfNotOk(response, `Failed to delete dataset (${response.status})`);
+ discardDeletedInventoryHints(repoId, ["dataset"]);
bumpInventoryVersion();
}
@@ -366,6 +394,7 @@ export async function deleteCachedModel(
});
try {
await throwIfNotOk(response);
+ discardDeletedModelInventoryHints(repoId, variant);
bumpInventoryVersion();
} finally {
invalidateGgufVariantsCache(repoId);
diff --git a/studio/frontend/src/features/hub/inventory/index.ts b/studio/frontend/src/features/hub/inventory/index.ts
index bd2fe09a643..1001cbf8eda 100644
--- a/studio/frontend/src/features/hub/inventory/index.ts
+++ b/studio/frontend/src/features/hub/inventory/index.ts
@@ -49,8 +49,11 @@ export {
normalizeCapabilities,
normalizeModelFormat,
normalizeRuntime,
- normalizeTimestamp,
} from "./view-models";
+export {
+ epochMillisecondsToSeconds,
+ normalizeTimestamp,
+} from "./inventory-timestamps";
export {
resolveInventoryResource,
type InventoryResourceFormatHint,
diff --git a/studio/frontend/src/features/hub/inventory/inventory-hint-store.ts b/studio/frontend/src/features/hub/inventory/inventory-hint-store.ts
index b56e488519a..e493d89fbd4 100644
--- a/studio/frontend/src/features/hub/inventory/inventory-hint-store.ts
+++ b/studio/frontend/src/features/hub/inventory/inventory-hint-store.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { create } from "zustand";
+import { evictOldestUnprotected } from "../lib/lru-map.ts";
import { INVENTORY_HINT_KINDS } from "./constants.ts";
import {
type InventoryHintReconciliation,
@@ -15,7 +16,6 @@ import {
repoKey,
} from "./inventory-hints.ts";
import type { InventoryHint } from "./types.ts";
-import { evictOldestUnprotected } from "../lib/lru-map.ts";
export const MAX_OBSERVED_INVENTORY_KEYS_PER_KIND = 1024;
@@ -23,6 +23,7 @@ type ObservedInventoryKeys = Record<InventoryHint["kind"], Set<string>>;
export type PendingHintReconciliationCommit = {
kind: InventoryHint["kind"];
+ protectedObservedKeys?: ReadonlySet<string>;
reconciliation: Pick<
InventoryHintReconciliation,
"pending" | "staleCompletedHints" | "observedKeys"
@@ -44,6 +45,7 @@ const INVENTORY_HINT_EQUALITY_FIELDS = {
kind: true,
repoId: true,
bytes: true,
+ startedAt: true,
createdAt: true,
} satisfies Record<keyof InventoryHint, true>;
@@ -80,9 +82,13 @@ function inventoryHintEqual(
}
return INVENTORY_HINT_EQUALITY_KEYS.every((key) => {
const left =
- key === "bytes" || key === "createdAt" ? (a[key] ?? 0) : a[key];
+ key === "bytes" || key === "startedAt" || key === "createdAt"
+ ? (a[key] ?? 0)
+ : a[key];
const right =
- key === "bytes" || key === "createdAt" ? (b[key] ?? 0) : b[key];
+ key === "bytes" || key === "startedAt" || key === "createdAt"
+ ? (b[key] ?? 0)
+ : b[key];
return left === right;
});
}
@@ -136,7 +142,10 @@ function pendingHasHint(
if (!existing) {
return false;
}
- return (existing.bytes ?? 0) >= (hint.bytes ?? 0);
+ return (
+ (existing.bytes ?? 0) >= (hint.bytes ?? 0) &&
+ (existing.createdAt ?? 0) >= (hint.createdAt ?? 0)
+ );
}
export function pendingWithInventoryHints(
@@ -152,14 +161,47 @@ export function pendingWithInventoryHints(
return next;
}
+export function rememberCompletedInventoryHints(
+ hints: readonly InventoryHint[],
+): void {
+ if (hints.length === 0) {
+ return;
+ }
+ const state = useInventoryHintStore.getState();
+ const next = pendingWithInventoryHints(state.pending, hints);
+ if (!pendingInventoryHintsEqual(state.pending, next)) {
+ useInventoryHintStore.setState({
+ pending: clonePendingInventoryHints(next),
+ });
+ }
+}
+
+export function discardPendingInventoryHint(
+ kind: InventoryHint["kind"],
+ repoId: string,
+): void {
+ const state = useInventoryHintStore.getState();
+ const key = repoKey(repoId);
+ if (!state.pending[kind].has(key)) {
+ return;
+ }
+ const pending = clonePendingInventoryHints(state.pending);
+ pending[kind].delete(key);
+ useInventoryHintStore.setState({ pending });
+}
+
function rememberObservedInventoryKeys(
current: ObservedInventoryKeys,
kind: InventoryHint["kind"],
keys: ReadonlySet<string>,
pending: PendingInventoryHints,
+ protectedKeys: ReadonlySet<string>,
): ObservedInventoryKeys {
const observed = new Set(current[kind]);
for (const key of keys) {
+ if (pending[kind].has(key) || protectedKeys.has(key)) {
+ continue;
+ }
observed.delete(key);
observed.add(key);
}
@@ -174,6 +216,22 @@ function rememberObservedInventoryKeys(
return { ...current, [kind]: observed };
}
+export function forgetObservedInventoryHint(
+ kind: InventoryHint["kind"],
+ repoId: string,
+): void {
+ const state = useInventoryHintStore.getState();
+ const key = repoKey(repoId);
+ if (!state.observedKeys[kind].has(key)) {
+ return;
+ }
+ const observed = new Set(state.observedKeys[kind]);
+ observed.delete(key);
+ useInventoryHintStore.setState({
+ observedKeys: { ...state.observedKeys, [kind]: observed },
+ });
+}
+
export const useInventoryHintStore = create<InventoryHintState>()(
(set, get) => ({
pending: createPendingInventoryHints(),
@@ -190,7 +248,11 @@ export const useInventoryHintStore = create<InventoryHintState>()(
let next = pendingWithInventoryHints(state.pending, completedHints);
let observedKeys = state.observedKeys;
const completedHintsToSuppress: InventoryHint[] = [];
- for (const { kind, reconciliation } of reconciliations) {
+ for (const {
+ kind,
+ protectedObservedKeys = new Set<string>(),
+ reconciliation,
+ } of reconciliations) {
const committed = commitInventoryHintReconciliation({
current: next,
kind,
@@ -204,6 +266,7 @@ export const useInventoryHintStore = create<InventoryHintState>()(
kind,
reconciliation.observedKeys,
next,
+ protectedObservedKeys,
);
completedHintsToSuppress.push(...committed.completedHintsToSuppress);
}
diff --git a/studio/frontend/src/features/hub/inventory/inventory-hints.ts b/studio/frontend/src/features/hub/inventory/inventory-hints.ts
index 5e202e31504..dca0716efbd 100644
--- a/studio/frontend/src/features/hub/inventory/inventory-hints.ts
+++ b/studio/frontend/src/features/hub/inventory/inventory-hints.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import type { InventoryHint } from "./types";
+import { normalizeTimestamp } from "./inventory-timestamps";
export type PendingInventoryHints = Record<
InventoryHint["kind"],
@@ -13,6 +14,8 @@ export type InventoryHintRow = {
size_bytes: number;
partial?: boolean;
optimistic?: boolean;
+ /** epoch seconds from the server or milliseconds from an optimistic row. */
+ last_modified?: number | null;
};
export type InventoryHintReconciliation = {
@@ -43,6 +46,10 @@ function optimisticRow(hint: InventoryHint): InventoryHintRow {
size_bytes: hint.bytes ?? 0,
partial: false,
optimistic: true,
+ // keep a finished download first until the cache scan catches up
+ ...(hint.createdAt && hint.createdAt > 0
+ ? { last_modified: hint.createdAt }
+ : {}),
};
}
@@ -104,6 +111,10 @@ function mergeInventoryHint(
return [...rows, seed];
}
const serverRow = rows[idx];
+ const lastModified = Math.max(
+ normalizeTimestamp(serverRow.last_modified) ?? 0,
+ normalizeTimestamp(seed.last_modified) ?? 0,
+ );
const merged = {
...serverRow,
// A completed hint may arrive before a partial server scan catches up. In
@@ -112,6 +123,7 @@ function mergeInventoryHint(
// the hint's full-snapshot byte count, so do not mark that merge optimistic.
...(serverRow.partial ? seed : { optimistic: false }),
size_bytes: Math.max(rowSizeBytes(rows[idx]), rowSizeBytes(seed)),
+ ...(lastModified > 0 ? { last_modified: lastModified } : {}),
};
return [...rows.slice(0, idx), merged, ...rows.slice(idx + 1)];
}
@@ -124,11 +136,20 @@ export function rememberInventoryHint(
const key = repoKey(hint.repoId);
const existing = next[hint.kind].get(key);
const bytes = Math.max(existing?.bytes ?? 0, hint.bytes ?? 0);
- const createdAt = existing?.createdAt ?? hint.createdAt ?? Date.now();
+ const existingCreatedAt = existing?.createdAt ?? 0;
+ const hintCreatedAt = hint.createdAt ?? (existing ? 0 : Date.now());
+ const createdAt = Math.max(existingCreatedAt, hintCreatedAt);
+ const startedAt =
+ hintCreatedAt > existingCreatedAt
+ ? hint.startedAt
+ : hintCreatedAt < existingCreatedAt
+ ? existing?.startedAt
+ : (hint.startedAt ?? existing?.startedAt);
next[hint.kind].set(key, {
kind: hint.kind,
repoId: hint.repoId,
...(bytes > 0 ? { bytes } : {}),
+ ...(startedAt && startedAt > 0 ? { startedAt } : {}),
createdAt,
});
return next;
@@ -176,10 +197,21 @@ export function pruneExpiredInventoryHints(
function serverRowSatisfiesHint(
row: InventoryHintRow,
hint: InventoryHint,
+ refreshStartedAt?: number | null,
): boolean {
if (row.partial) {
return false;
}
+ const hintTimestamp = normalizeTimestamp(hint.startedAt ?? hint.createdAt);
+ if (hintTimestamp != null) {
+ const rowTimestamp = normalizeTimestamp(row.last_modified);
+ if (rowTimestamp != null && rowTimestamp >= hintTimestamp) {
+ return true;
+ }
+ return Boolean(
+ hint.createdAt && refreshStartedAt && refreshStartedAt >= hint.createdAt,
+ );
+ }
return !hint.bytes || rowSizeBytes(row) >= hint.bytes;
}
@@ -188,11 +220,13 @@ export function reconcileInventoryHints<T extends InventoryHintRow>({
kind,
rows,
previouslyObserved,
+ refreshStartedAt,
}: {
pending: PendingInventoryHints;
kind: InventoryHint["kind"];
rows: T[];
previouslyObserved: ReadonlySet<string>;
+ refreshStartedAt?: number | null;
}): InventoryHintReconciliation {
const pruned = pruneExpiredInventoryHints(pending);
const serverRows = new Map(rows.map((row) => [repoKey(rowRepoId(row)), row]));
@@ -212,7 +246,10 @@ export function reconcileInventoryHints<T extends InventoryHintRow>({
for (const [key, hint] of hints) {
const serverRow = serverRows.get(key);
- if (serverRow && serverRowSatisfiesHint(serverRow, hint)) {
+ if (
+ serverRow &&
+ serverRowSatisfiesHint(serverRow, hint, refreshStartedAt)
+ ) {
hints.delete(key);
} else if (!serverRow && previouslyObserved.has(key)) {
hints.delete(key);
@@ -259,7 +296,10 @@ export function commitInventoryHintReconciliation({
const nextHint = next[kind].get(key);
const currentHint = sharedHints.get(key);
const currentIsNewer =
- currentHint && (currentHint.bytes ?? 0) > (baselineHint.bytes ?? 0);
+ currentHint &&
+ ((currentHint.createdAt ?? 0) > (baselineHint.createdAt ?? 0) ||
+ ((currentHint.createdAt ?? 0) === (baselineHint.createdAt ?? 0) &&
+ (currentHint.bytes ?? 0) > (baselineHint.bytes ?? 0)));
if (nextHint) {
if (!currentIsNewer) {
diff --git a/studio/frontend/src/features/hub/inventory/inventory-timestamps.ts b/studio/frontend/src/features/hub/inventory/inventory-timestamps.ts
new file mode 100644
index 00000000000..b3b60eaa82b
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/inventory-timestamps.ts
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** normalize inventory timestamps to epoch milliseconds. */
+export function normalizeTimestamp(value?: number | null): number | null {
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
+ return null;
+ }
+ return value < 10_000_000_000 ? value * 1000 : value;
+}
+
+/** convert a normalized inventory timestamp back to the backend dto unit. */
+export function epochMillisecondsToSeconds(
+ value?: number | null,
+): number | undefined {
+ return value == null ? undefined : value / 1000;
+}
diff --git a/studio/frontend/src/features/hub/inventory/types.ts b/studio/frontend/src/features/hub/inventory/types.ts
index 9cf0ca5cf7a..b634bc88c49 100644
--- a/studio/frontend/src/features/hub/inventory/types.ts
+++ b/studio/frontend/src/features/hub/inventory/types.ts
@@ -30,6 +30,7 @@ export interface InventoryHint {
kind: InventoryHintKind;
repoId: string;
bytes?: number;
+ startedAt?: number;
createdAt?: number;
}
@@ -48,6 +49,7 @@ export interface CachedInventoryRow {
bytes: number;
cachePath?: string | null;
loadCachePath?: string | null;
+ /** last changed time as epoch milliseconds. */
lastModified?: number | null;
partial?: boolean;
partialTransport?: string | null;
@@ -96,6 +98,7 @@ export interface LocalInventoryRow {
trainingMethod?: string | null;
task?: string | null;
audioType?: string | null;
+ /** last changed time as epoch milliseconds. */
updatedAt: number | null;
partial?: boolean;
partialTransport?: string | null;
diff --git a/studio/frontend/src/features/hub/inventory/use-device-inventory.ts b/studio/frontend/src/features/hub/inventory/use-device-inventory.ts
index 3866248e949..7fc937612e2 100644
--- a/studio/frontend/src/features/hub/inventory/use-device-inventory.ts
+++ b/studio/frontend/src/features/hub/inventory/use-device-inventory.ts
@@ -7,9 +7,9 @@ import {
type CachedModelRepo,
type LocalDatasetInfo,
type LocalModelInfo,
+ fetchCachedGgufInventory,
+ fetchCachedModelsInventory,
listCachedDatasets,
- listCachedGguf,
- listCachedModels,
listLocalDatasets,
listLocalModels,
} from "./api";
@@ -47,6 +47,7 @@ export type DeviceInventorySourceState<Rows extends readonly unknown[]> = {
error: string | null;
key: string | null;
refreshedAt: number | null;
+ refreshStartedAt: number | null;
revalidatedAt: number | null;
};
@@ -75,6 +76,11 @@ type UseDeviceInventoryResult<
refreshIfOlderThan: (maxAgeMs: number) => Promise<void>;
};
+type InventorySourceFetchResult<K extends DeviceInventorySource> = {
+ rows: DeviceInventoryRows[K];
+ scanConfirmed: boolean;
+};
+
const TOKEN_SCOPED_SOURCES = new Set<DeviceInventorySource>([
"cachedGguf",
"cachedModels",
@@ -94,6 +100,7 @@ function emptySource<
error: null,
key: null,
refreshedAt: null,
+ refreshStartedAt: null,
revalidatedAt: null,
};
}
@@ -153,21 +160,41 @@ function logInventorySourceFailure(
async function runSourceFetch<K extends DeviceInventorySource>(
source: K,
hfToken?: string | null,
-): Promise<DeviceInventoryRows[K]> {
+): Promise<InventorySourceFetchResult<K>> {
switch (source) {
- case "cachedGguf":
+ case "cachedGguf": {
await ensureHiddenModelMatchers();
- return (await listCachedGguf(hfToken)) as DeviceInventoryRows[K];
- case "cachedModels":
+ const result = await fetchCachedGgufInventory(hfToken);
+ return {
+ rows: result.cached as DeviceInventoryRows[K],
+ scanConfirmed: result.scan_confirmed !== false,
+ };
+ }
+ case "cachedModels": {
await ensureHiddenModelMatchers();
- return (await listCachedModels(hfToken)) as DeviceInventoryRows[K];
+ const result = await fetchCachedModelsInventory(hfToken);
+ return {
+ rows: result.cached as DeviceInventoryRows[K],
+ scanConfirmed: result.scan_confirmed !== false,
+ };
+ }
case "cachedDatasets":
- return (await listCachedDatasets()) as DeviceInventoryRows[K];
- case "localModels":
+ return {
+ rows: (await listCachedDatasets()) as DeviceInventoryRows[K],
+ scanConfirmed: true,
+ };
+ case "localModels": {
await ensureHiddenModelMatchers();
- return (await listLocalModels()).models as DeviceInventoryRows[K];
+ return {
+ rows: (await listLocalModels()).models as DeviceInventoryRows[K],
+ scanConfirmed: true,
+ };
+ }
case "localDatasets":
- return (await listLocalDatasets()).datasets as DeviceInventoryRows[K];
+ return {
+ rows: (await listLocalDatasets()).datasets as DeviceInventoryRows[K],
+ scanConfirmed: true,
+ };
default:
throw new Error("Unsupported inventory source");
}
@@ -240,11 +267,13 @@ export function fetchInventorySource<K extends DeviceInventorySource>(
error: null,
key,
refreshedAt: current.key === key ? current.refreshedAt : null,
+ refreshStartedAt: current.key === key ? current.refreshStartedAt : null,
revalidatedAt: current.key === key ? current.revalidatedAt : null,
});
+ const refreshStartedAt = Date.now();
const request = runSourceFetch(source, options.hfToken)
- .then((rows) => {
+ .then(({ rows, scanConfirmed }) => {
if (useDeviceInventoryStore.getState()[source].key === key) {
const refreshedAt = Date.now();
updateSourceState(source, {
@@ -254,6 +283,7 @@ export function fetchInventorySource<K extends DeviceInventorySource>(
error: null,
key,
refreshedAt,
+ refreshStartedAt: scanConfirmed ? refreshStartedAt : null,
revalidatedAt: nextRevalidationStamp({
force: Boolean(options.force),
requestKey: key,
diff --git a/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts b/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
index ca09b0f34cb..71208ea3b67 100644
--- a/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
+++ b/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
@@ -24,9 +24,14 @@ import {
import {
type PendingInventoryHints,
nextInventoryHintExpiryDelay,
+ repoKey,
} from "./inventory-hints";
import { resolveInventorySettlement } from "./inventory-settlement";
-import type { CachedInventoryRow, LocalInventoryRow } from "./types";
+import type {
+ CachedInventoryRow,
+ InventoryHint,
+ LocalInventoryRow,
+} from "./types";
import {
type DeviceInventorySource,
useDeviceInventorySources,
@@ -35,8 +40,8 @@ import {
buildCachedInventoryRow,
buildLocalInventoryRows,
defaultCapabilities,
- normalizeTimestamp,
} from "./view-models";
+import { normalizeTimestamp } from "./inventory-timestamps";
import {
INVENTORY_FRESHNESS_WINDOW_MS,
isInventoryStampFresh,
@@ -130,6 +135,32 @@ function liveInventoryRank(job: ManagedDownload): number {
return 0;
}
+function inventoryHintKindForJob(job: ManagedDownload): InventoryHint["kind"] {
+ return job.kind === "dataset" ? "dataset" : job.variant ? "gguf" : "model";
+}
+
+function observedKeyProtections(
+ jobs: Record<string, ManagedDownload>,
+): Record<InventoryHint["kind"], Set<string>> {
+ const keys: Record<InventoryHint["kind"], Set<string>> = {
+ model: new Set(),
+ gguf: new Set(),
+ dataset: new Set(),
+ };
+ for (const job of Object.values(jobs)) {
+ if (
+ job.external ||
+ (job.state !== "running" &&
+ job.state !== "cancelling" &&
+ job.state !== "complete")
+ ) {
+ continue;
+ }
+ keys[inventoryHintKindForJob(job)].add(repoKey(job.repoId));
+ }
+ return keys;
+}
+
function shouldSurfaceLiveJob(
job: ManagedDownload,
isDatasetMode: boolean,
@@ -215,6 +246,8 @@ function liveDownloadInventoryRows(
? "transformers"
: "unknown",
size_bytes: job.displayBytes,
+ // live jobs already use epoch milliseconds
+ last_modified: job.startedAt,
partial: true,
partial_transport: null,
optimistic: true,
@@ -333,8 +366,14 @@ export function useHubInventory(
kind: "gguf",
rows: cachedGgufSource.rows,
previouslyObserved: observedInventoryKeys.gguf,
+ refreshStartedAt: cachedGgufSource.refreshStartedAt,
}),
- [cachedGgufSource.rows, observedInventoryKeys.gguf, pendingForRender],
+ [
+ cachedGgufSource.rows,
+ cachedGgufSource.refreshStartedAt,
+ observedInventoryKeys.gguf,
+ pendingForRender,
+ ],
);
const cachedModelsReconciliation = useMemo(
() =>
@@ -343,8 +382,14 @@ export function useHubInventory(
kind: "model",
rows: cachedModelsSource.rows,
previouslyObserved: observedInventoryKeys.model,
+ refreshStartedAt: cachedModelsSource.refreshStartedAt,
}),
- [cachedModelsSource.rows, observedInventoryKeys.model, pendingForRender],
+ [
+ cachedModelsSource.rows,
+ cachedModelsSource.refreshStartedAt,
+ observedInventoryKeys.model,
+ pendingForRender,
+ ],
);
const cachedDatasetsReconciliation = useMemo(
() =>
@@ -353,24 +398,31 @@ export function useHubInventory(
kind: "dataset",
rows: cachedDatasetsSource.rows,
previouslyObserved: observedInventoryKeys.dataset,
+ refreshStartedAt: cachedDatasetsSource.refreshStartedAt,
}),
[
cachedDatasetsSource.rows,
+ cachedDatasetsSource.refreshStartedAt,
observedInventoryKeys.dataset,
pendingForRender,
],
);
useEffect(() => {
+ const protectedObservedKeys = observedKeyProtections(
+ useDownloadManagerStore.getState().jobs,
+ );
const reconciliations: PendingHintReconciliationCommit[] = [];
if (!isDatasetMode) {
reconciliations.push(
{
kind: "gguf",
+ protectedObservedKeys: protectedObservedKeys.gguf,
reconciliation: cachedGgufReconciliation,
},
{
kind: "model",
+ protectedObservedKeys: protectedObservedKeys.model,
reconciliation: cachedModelsReconciliation,
},
);
@@ -378,6 +430,7 @@ export function useHubInventory(
if (isDatasetMode) {
reconciliations.push({
kind: "dataset",
+ protectedObservedKeys: protectedObservedKeys.dataset,
reconciliation: cachedDatasetsReconciliation,
});
}
@@ -637,11 +690,7 @@ export function useHubInventory(
void refreshDeviceInventory();
}, 500);
return () => window.clearTimeout(timer);
- }, [
- emptyRevalidationRequired,
- enabled,
- refreshDeviceInventory,
- ]);
+ }, [emptyRevalidationRequired, enabled, refreshDeviceInventory]);
return {
cachedRows,
diff --git a/studio/frontend/src/features/hub/inventory/view-models.ts b/studio/frontend/src/features/hub/inventory/view-models.ts
index f6feec8717f..15545cb1c5d 100644
--- a/studio/frontend/src/features/hub/inventory/view-models.ts
+++ b/studio/frontend/src/features/hub/inventory/view-models.ts
@@ -4,6 +4,7 @@
import { ownerOf, repoOf } from "../lib/format";
import { looksLikeLocalPath } from "../lib/local-path";
import { isGgufLike } from "../lib/model-identifiers";
+import { normalizeTimestamp } from "./inventory-timestamps";
import type {
BackendModelCapabilities,
LocalModelInfo,
@@ -33,13 +34,6 @@ export function localSourceLabel(source: LocalModelInfo["source"]): string {
}
}
-export function normalizeTimestamp(value?: number | null): number | null {
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
- return null;
- }
- return value < 10_000_000_000 ? value * 1000 : value;
-}
-
export function formatLocalUpdated(value?: number | null): string {
const normalized = normalizeTimestamp(value);
if (!normalized) return "Unknown update";
@@ -224,12 +218,7 @@ export function buildCachedInventoryRow(
bytes: row.size_bytes,
cachePath: row.cache_path ?? null,
loadCachePath: row.load_cache_path ?? null,
- lastModified:
- typeof row.last_modified === "number" &&
- Number.isFinite(row.last_modified) &&
- row.last_modified > 0
- ? row.last_modified
- : null,
+ lastModified: normalizeTimestamp(row.last_modified),
partial: row.partial ?? false,
partialTransport: row.partial_transport ?? null,
partialResumable: row.partial_resumable === true,
diff --git a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
index 9f5b57a733d..a6947d393f5 100644
--- a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
+++ b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
@@ -10,6 +10,7 @@ import {
type CachedInventoryRow,
type LocalInventoryRow,
type LocalSource,
+ epochMillisecondsToSeconds,
isHiddenModelId,
studioPageForTask,
useHubInventory,
@@ -35,7 +36,7 @@ function toCachedGgufRepo(row: CachedInventoryRow): CachedGgufRepo {
load_id: row.loadId,
size_bytes: row.bytes,
cache_path: row.cachePath ?? "",
- last_modified: row.lastModified ?? undefined,
+ last_modified: epochMillisecondsToSeconds(row.lastModified),
has_vision: row.capabilities.supportsVision,
task: row.task ?? null,
audio_type: row.audioType ?? null,
@@ -50,7 +51,7 @@ function toCachedModelRepo(row: CachedInventoryRow): CachedModelRepo {
// Delete targets the copy the row describes; without it the request hits the active cache.
cache_path: row.cachePath,
size_bytes: row.bytes,
- last_modified: row.lastModified ?? undefined,
+ last_modified: epochMillisecondsToSeconds(row.lastModified),
task: row.task ?? null,
audio_type: row.audioType ?? null,
tags: row.tags,
@@ -68,7 +69,7 @@ function toLocalModelInfo(row: LocalInventoryRow): LocalModelInfo {
source: row.source as LocalModelInfo["source"],
model_id: row.modelId ?? row.repoId,
model_format: row.modelFormat,
- updated_at: row.updatedAt,
+ updated_at: epochMillisecondsToSeconds(row.updatedAt),
task: row.task ?? null,
audio_type: row.audioType ?? null,
};
diff --git a/studio/frontend/tests/hub-inventory-recent-sort.test.ts b/studio/frontend/tests/hub-inventory-recent-sort.test.ts
new file mode 100644
index 00000000000..53402a8c85b
--- /dev/null
+++ b/studio/frontend/tests/hub-inventory-recent-sort.test.ts
@@ -0,0 +1,433 @@
+// 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 { registerStoreStubResolver } from "./helpers/kit.ts";
+
+registerStoreStubResolver();
+
+const { setAuthFetchHandler } = await import("./helpers/store-stubs/auth.ts");
+
+const { compareInventoryItemsByRecent } = await import(
+ "../src/features/hub/catalog/inventory-sort.ts"
+);
+const { buildCachedInventoryRow, buildLocalInventoryRows } = await import(
+ "../src/features/hub/inventory/view-models.ts"
+);
+const { epochMillisecondsToSeconds } = await import(
+ "../src/features/hub/inventory/inventory-timestamps.ts"
+);
+const {
+ createPendingInventoryHints,
+ INVENTORY_HINT_TTL_MS,
+ pruneExpiredInventoryHints,
+ reconcileInventoryHints,
+ rememberInventoryHint,
+} = await import("../src/features/hub/inventory/inventory-hints.ts");
+const { pendingWithInventoryHints, useInventoryHintStore } = await import(
+ "../src/features/hub/inventory/inventory-hint-store.ts"
+);
+const { deleteCachedModel } = await import(
+ "../src/features/hub/inventory/api.ts"
+);
+const {
+ discardDeletedInventoryHints,
+ getState,
+ jobKeyOf,
+ patchJob,
+ putJob,
+ removeJob,
+} = await import(
+ "../src/features/hub/download-manager/download-manager-state.ts"
+);
+
+function cached(repoId: string, lastModified?: number) {
+ return {
+ variant: "cached" as const,
+ row: buildCachedInventoryRow(
+ {
+ repo_id: repoId,
+ size_bytes: 1,
+ last_modified: lastModified,
+ },
+ "gguf",
+ ),
+ };
+}
+
+function local(displayName: string, updatedAt?: number) {
+ const [row] = buildLocalInventoryRows([
+ {
+ id: `local:${displayName}`,
+ display_name: displayName,
+ path: `C:\\models\\${displayName}.gguf`,
+ source: "lmstudio",
+ updated_at: updatedAt,
+ },
+ ]);
+ return { variant: "local" as const, row };
+}
+
+test("Recent sorts cached and local rows together by normalized timestamp", () => {
+ const oldCached = cached("Org/Alpha-Old", 1_700_000_000);
+ const middleLocal = local("LM Studio Middle", 1_800_000_000_000);
+ const newCached = cached("Org/Zulu-New", 1_900_000_000);
+
+ assert.equal(oldCached.row.lastModified, 1_700_000_000_000);
+ assert.equal(newCached.row.lastModified, 1_900_000_000_000);
+
+ const sorted = [oldCached, middleLocal, newCached].sort(
+ compareInventoryItemsByRecent,
+ );
+ assert.deepEqual(
+ sorted.map((item) => item.row.id),
+ [newCached.row.id, middleLocal.row.id, oldCached.row.id],
+ );
+});
+
+test("Recent puts unknown timestamps last and leaves ties stable", () => {
+ const unknownCached = cached("Org/Unknown");
+ const firstTie = local("First tie", 1_800_000_000);
+ const secondTie = cached("Org/Second-Tie", 1_800_000_000);
+
+ const sorted = [unknownCached, firstTie, secondTie].sort(
+ compareInventoryItemsByRecent,
+ );
+ assert.deepEqual(
+ sorted.map((item) => item.row.id),
+ [firstTie.row.id, secondTie.row.id, unknownCached.row.id],
+ );
+});
+
+test("Recent keeps a completed download first until the cache rescan", () => {
+ const completedAt = Date.now();
+ const pending = rememberInventoryHint(createPendingInventoryHints(), {
+ kind: "gguf",
+ repoId: "Org/Just-Downloaded",
+ bytes: 10,
+ createdAt: completedAt,
+ });
+ const reconciled = reconcileInventoryHints({
+ pending,
+ kind: "gguf",
+ rows: [
+ {
+ repo_id: "Org/Older",
+ size_bytes: 10,
+ last_modified: 1_700_000_000,
+ },
+ ],
+ previouslyObserved: new Set<string>(),
+ });
+ const sorted = reconciled.rows
+ .map((row) => ({
+ variant: "cached" as const,
+ row: buildCachedInventoryRow(row, "gguf"),
+ }))
+ .sort(compareInventoryItemsByRecent);
+
+ assert.equal(sorted[0]?.row.repoId, "Org/Just-Downloaded");
+ assert.equal(sorted[0]?.row.lastModified, completedAt);
+});
+
+test("a newer completion refreshes the same repo timestamp and expiry", () => {
+ const firstStartedAt = 1_899_999_940_000;
+ const firstCompletedAt = 1_900_000_000_000;
+ const secondStartedAt = firstCompletedAt + 30_000;
+ const secondCompletedAt = firstCompletedAt + 60_000;
+ let pending = pendingWithInventoryHints(createPendingInventoryHints(), [
+ {
+ kind: "gguf",
+ repoId: "Org/Repeated",
+ bytes: 20,
+ startedAt: firstStartedAt,
+ createdAt: firstCompletedAt,
+ },
+ ]);
+ pending = pendingWithInventoryHints(pending, [
+ {
+ kind: "gguf",
+ repoId: "Org/Repeated",
+ bytes: 10,
+ startedAt: secondStartedAt,
+ createdAt: secondCompletedAt,
+ },
+ ]);
+
+ assert.deepEqual(pending.gguf.get("org/repeated"), {
+ kind: "gguf",
+ repoId: "Org/Repeated",
+ bytes: 20,
+ startedAt: secondStartedAt,
+ createdAt: secondCompletedAt,
+ });
+ assert.equal(
+ pruneExpiredInventoryHints(
+ pending,
+ firstCompletedAt + INVENTORY_HINT_TTL_MS + 1,
+ ).gguf.size,
+ 1,
+ );
+ assert.equal(
+ pruneExpiredInventoryHints(
+ pending,
+ secondCompletedAt + INVENTORY_HINT_TTL_MS,
+ ).gguf.size,
+ 0,
+ );
+});
+
+test("a stale aggregate row cannot consume a newer variant hint", () => {
+ const completedAt = 1_900_000_000_000;
+ const startedAt = completedAt - 60_000;
+ const pending = pendingWithInventoryHints(createPendingInventoryHints(), [
+ {
+ kind: "gguf",
+ repoId: "Org/Existing",
+ bytes: 200,
+ startedAt,
+ createdAt: completedAt,
+ },
+ ]);
+ const stale = reconcileInventoryHints({
+ pending,
+ kind: "gguf",
+ rows: [
+ {
+ repo_id: "Org/Existing",
+ size_bytes: 500,
+ last_modified: (startedAt - 1_000) / 1000,
+ },
+ ],
+ previouslyObserved: new Set<string>(),
+ refreshStartedAt: completedAt - 1,
+ });
+
+ assert.equal(stale.pending.gguf.size, 1);
+ assert.equal(stale.rows[0]?.last_modified, completedAt);
+
+ const rescanned = reconcileInventoryHints({
+ pending: stale.pending,
+ kind: "gguf",
+ rows: [
+ {
+ repo_id: "Org/Existing",
+ size_bytes: 100,
+ last_modified: (startedAt - 1_000) / 1000,
+ },
+ ],
+ previouslyObserved: new Set(["org/existing"]),
+ refreshStartedAt: completedAt + 1,
+ });
+ assert.equal(rescanned.pending.gguf.size, 0);
+
+ const unconfirmed = reconcileInventoryHints({
+ pending: stale.pending,
+ kind: "gguf",
+ rows: rescanned.rows,
+ previouslyObserved: new Set(["org/existing"]),
+ refreshStartedAt: null,
+ });
+ assert.equal(unconfirmed.pending.gguf.size, 1);
+});
+
+test("a new download clears historical observation and records completion time", () => {
+ const repoId = "Org/Redownload";
+ const key = jobKeyOf("model", repoId, "Q4_K_M");
+ const hintState = useInventoryHintStore.getState();
+ useInventoryHintStore.setState({
+ pending: createPendingInventoryHints(),
+ observedKeys: {
+ ...hintState.observedKeys,
+ gguf: new Set(["org/redownload"]),
+ },
+ });
+ putJob({
+ key,
+ kind: "model",
+ repoId,
+ variant: "Q4_K_M",
+ state: "running",
+ downloadedBytes: 0,
+ completedBytes: 0,
+ completeOnDisk: false,
+ expectedBytes: 10,
+ fraction: 0,
+ bytesPerSec: 0,
+ etaSeconds: 0,
+ error: null,
+ startedAt: 1_900_000_000_000,
+ });
+ const afterStart = useInventoryHintStore.getState();
+ const staleRowReconciliation = reconcileInventoryHints({
+ pending: afterStart.pending,
+ kind: "gguf",
+ rows: [
+ {
+ repo_id: repoId,
+ size_bytes: 100,
+ last_modified: 1_800_000_000,
+ },
+ ],
+ previouslyObserved: afterStart.observedKeys.gguf,
+ });
+ const beforeCompletion = Date.now();
+ patchJob(key, { state: "complete" });
+ const afterCompletion = Date.now();
+ afterStart.commitReconciliations([], afterStart.pending, [
+ {
+ kind: "gguf",
+ protectedObservedKeys: new Set(["org/redownload"]),
+ reconciliation: staleRowReconciliation,
+ },
+ ]);
+ assert.equal(
+ useInventoryHintStore.getState().observedKeys.gguf.has("org/redownload"),
+ false,
+ );
+ const [hint] = getState().completedInventoryHints;
+ const completedState = useInventoryHintStore.getState();
+ const completedPending = pendingWithInventoryHints(
+ completedState.pending,
+ hint ? [hint] : [],
+ );
+ const missingRowReconciliation = reconcileInventoryHints({
+ pending: completedPending,
+ kind: "gguf",
+ rows: [],
+ previouslyObserved: completedState.observedKeys.gguf,
+ });
+ const suppressed = completedState.commitReconciliations(
+ hint ? [hint] : [],
+ completedPending,
+ [{ kind: "gguf", reconciliation: missingRowReconciliation }],
+ );
+
+ assert.equal(
+ useInventoryHintStore.getState().observedKeys.gguf.has("org/redownload"),
+ false,
+ );
+ assert.equal(suppressed.length, 0);
+ assert.equal(
+ useInventoryHintStore.getState().pending.gguf.has("org/redownload"),
+ true,
+ );
+ assert.ok(hint?.createdAt && hint.createdAt >= beforeCompletion);
+ assert.ok(hint?.createdAt && hint.createdAt <= afterCompletion);
+ assert.equal(hint?.startedAt, 1_900_000_000_000);
+
+ removeJob(key);
+ assert.equal(
+ useInventoryHintStore.getState().pending.gguf.has("org/redownload"),
+ true,
+ );
+ discardDeletedInventoryHints(repoId, ["gguf"]);
+ assert.equal(
+ useInventoryHintStore.getState().pending.gguf.has("org/redownload"),
+ false,
+ );
+ useInventoryHintStore.setState({
+ pending: createPendingInventoryHints(),
+ observedKeys: hintState.observedKeys,
+ });
+});
+
+test("full deletion removes every completed variant contribution", () => {
+ const repoId = "Org/Deleted-Variants";
+ const keys = ["Q4_K_M", "Q8_0"].map((variant, index) => {
+ const key = jobKeyOf("model", repoId, variant);
+ putJob({
+ key,
+ kind: "model",
+ repoId,
+ variant,
+ state: "running",
+ downloadedBytes: 10,
+ completedBytes: 10,
+ completeOnDisk: true,
+ expectedBytes: 10,
+ fraction: 1,
+ bytesPerSec: 0,
+ etaSeconds: 0,
+ error: null,
+ startedAt: 1_900_000_000_000 + index,
+ });
+ patchJob(key, {
+ state: "complete",
+ completedAt: 1_900_000_060_000 + index,
+ });
+ return key;
+ });
+
+ assert.equal(getState().completedInventoryHints.length, 2);
+ discardDeletedInventoryHints(repoId, ["gguf"]);
+ assert.equal(getState().completedInventoryHints.length, 0);
+ assert.equal(keys.some((key) => key in getState().jobs), false);
+
+ removeJob(keys[0]);
+ assert.equal(getState().completedInventoryHints.length, 0);
+ removeJob(keys[1]);
+ assert.equal(getState().completedInventoryHints.length, 0);
+});
+
+test("variant deletion clears its hint and permits a peer completion", async () => {
+ const repoId = "Org/Deleted-Quant";
+ const deletedKey = jobKeyOf("model", repoId, "Q4_K_M");
+ const peerKey = jobKeyOf("model", repoId, "Q8_0");
+ for (const [key, variant] of [
+ [deletedKey, "Q4_K_M"],
+ [peerKey, "Q8_0"],
+ ] as const) {
+ putJob({
+ key,
+ kind: "model",
+ repoId,
+ variant,
+ state: "running",
+ downloadedBytes: 10,
+ completedBytes: 10,
+ completeOnDisk: true,
+ expectedBytes: 10,
+ fraction: 1,
+ bytesPerSec: 0,
+ etaSeconds: 0,
+ error: null,
+ startedAt: 1_900_000_000_000,
+ });
+ }
+ patchJob(deletedKey, {
+ state: "complete",
+ completedAt: 1_900_000_060_000,
+ });
+
+ setAuthFetchHandler(() => new Response(null, { status: 204 }));
+ try {
+ await deleteCachedModel(repoId, "Q4_K_M");
+ } finally {
+ setAuthFetchHandler(null);
+ }
+
+ assert.equal(
+ useInventoryHintStore.getState().pending.gguf.has("org/deleted-quant"),
+ false,
+ );
+ assert.equal(getState().completedInventoryHints.length, 0);
+ assert.equal(getState().jobs[deletedKey], undefined);
+
+ patchJob(peerKey, {
+ state: "complete",
+ completedAt: 1_900_000_120_000,
+ });
+ assert.equal(getState().completedInventoryHints.length, 1);
+
+ discardDeletedInventoryHints(repoId, ["gguf"]);
+ removeJob(deletedKey);
+ removeJob(peerKey);
+});
+
+test("picker dto timestamps stay in epoch seconds", () => {
+ assert.equal(epochMillisecondsToSeconds(1_900_000_000_500), 1_900_000_000.5);
+ assert.equal(epochMillisecondsToSeconds(null), undefined);
+});
diff --git a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
index 8a21c62fc1c..f74084be97a 100644
--- a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
+++ b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
@@ -87,7 +87,7 @@ test("list header actions end where a hovered row's action does", () => {
assert.match(
SIDEBAR,
- /const scrollRowPadding = usesDesktopTitlebar \? "px-\[5px\]" : "px-1\.5";/,
+ /const unrailedRowPadding = usesDesktopTitlebar \? "px-\[5px\]" : "px-1\.5";/,
);
assert.ok(
SIDEBAR.includes(