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.

feat(studio): Hub + Download Manager (#5916)

Eyeraaec41d17edf2
diff --git a/studio/backend/hub/__init__.py b/studio/backend/hub/__init__.py
new file mode 100644
index 00000000000..706dae9224b
--- /dev/null
+++ b/studio/backend/hub/__init__.py
@@ -0,0 +1,8 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hub + Download Manager feature module.
+
+Self-contained routes, schemas, utilities, workers, and storage for the model
+inventory layer and the HuggingFace download manager. Wired into the FastAPI
+app via two routers plus startup/shutdown hooks in main.py."""
diff --git a/studio/backend/hub/dependencies.py b/studio/backend/hub/dependencies.py
new file mode 100644
index 00000000000..ff78dce8f6b
--- /dev/null
+++ b/studio/backend/hub/dependencies.py
@@ -0,0 +1,24 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shared FastAPI dependencies for Hub routes."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from fastapi import Header
+
+HUB_HF_TOKEN_HEADER = "X-Unsloth-HF-Token"
+HUB_HF_TOKEN_MAX_LENGTH = 512
+
+
+def get_hf_token(
+ hf_token: Optional[str] = Header(
+ None,
+ alias = HUB_HF_TOKEN_HEADER,
+ max_length = HUB_HF_TOKEN_MAX_LENGTH,
+ ),
+) -> Optional[str]:
+ token = (hf_token or "").strip()
+ return token or None
diff --git a/studio/backend/hub/routes/__init__.py b/studio/backend/hub/routes/__init__.py
new file mode 100644
index 00000000000..e9579635b00
--- /dev/null
+++ b/studio/backend/hub/routes/__init__.py
@@ -0,0 +1,12 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hub routers exposed at /api/hub/* and /api/hub/datasets/*."""
+
+from hub.routes.inventory import router as inventory_router
+from hub.routes.datasets import router as datasets_router
+
+__all__ = [
+ "inventory_router",
+ "datasets_router",
+]
diff --git a/studio/backend/hub/routes/datasets.py b/studio/backend/hub/routes/datasets.py
new file mode 100644
index 00000000000..edf4f36ac04
--- /dev/null
+++ b/studio/backend/hub/routes/datasets.py
@@ -0,0 +1,138 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Endpoints mounted at /api/hub/datasets/*."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from fastapi import APIRouter, Body, Depends, Query, UploadFile
+
+from auth.authentication import get_current_subject
+from hub.dependencies import get_hf_token
+from hub.schemas.datasets import (
+ AiAssistMappingRequest,
+ AiAssistMappingResponse,
+ CachedDatasetsResponse,
+ CheckFormatRequest,
+ CheckFormatResponse,
+ DeleteCachedDatasetResponse,
+ LocalDatasetsResponse,
+ UploadDatasetResponse,
+)
+from hub.schemas.downloads import (
+ ActiveDownloadsResponse,
+ CancelDatasetDownloadRequest,
+ CancelDatasetDownloadResponse,
+ DatasetDownloadJobStatus,
+ DatasetDownloadStartResponse,
+ DownloadProgressResponse,
+ DownloadDatasetRequest,
+ TransportStatusResponse,
+)
+from hub.services.datasets import cache_inventory, downloads, formatting, local
+
+router = APIRouter()
+
+
[email protected]("/upload", response_model = UploadDatasetResponse)
+async def upload_dataset(
+ file: UploadFile, current_subject: str = Depends(get_current_subject)
+) -> UploadDatasetResponse:
+ return await local.upload_dataset_response(file)
+
+
[email protected]("/local", response_model = LocalDatasetsResponse)
+def list_local_datasets(
+ current_subject: str = Depends(get_current_subject),
+) -> LocalDatasetsResponse:
+ return local.list_local_datasets_response()
+
+
+ "/cached",
+ response_model = CachedDatasetsResponse,
+ response_model_exclude_unset = True,
+)
+async def list_cached_datasets(current_subject: str = Depends(get_current_subject)):
+ return await cache_inventory.list_cached_datasets_response()
+
+
[email protected]("/cached", response_model = DeleteCachedDatasetResponse)
+async def delete_cached_dataset(
+ repo_id: str = Body(..., embed = True), current_subject: str = Depends(get_current_subject)
+):
+ return await cache_inventory.delete_cached_dataset_response(repo_id)
+
+
[email protected]("/download-progress", response_model = DownloadProgressResponse)
+async def get_dataset_download_progress(
+ repo_id: str = Query(..., description = "HuggingFace dataset repo ID, e.g. 'unsloth/LaTeX_OCR'"),
+ expected_bytes: int = Query(0, description = "Expected total download size in bytes"),
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.get_dataset_download_progress_response(
+ repo_id,
+ expected_bytes = expected_bytes,
+ hf_token = hf_token,
+ )
+
+
[email protected]("/download", response_model = DatasetDownloadStartResponse, status_code = 202)
+async def download_dataset(
+ body: DownloadDatasetRequest,
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.download_dataset_response(body, hf_token)
+
+
[email protected]("/download/cancel", response_model = CancelDatasetDownloadResponse, status_code = 202)
+async def cancel_dataset_download(
+ body: CancelDatasetDownloadRequest, current_subject: str = Depends(get_current_subject)
+):
+ return await downloads.cancel_dataset_download_response(body)
+
+
[email protected]("/download-status", response_model = DatasetDownloadJobStatus)
+async def get_dataset_download_status(
+ repo_id: str = Query(..., description = "HuggingFace dataset repo ID"),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.get_dataset_download_status_response(repo_id)
+
+
[email protected]("/active-downloads", response_model = ActiveDownloadsResponse)
+async def get_active_dataset_downloads(
+ repo_id: str = Query("", description = "HuggingFace dataset repo ID"),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.get_active_dataset_downloads_response(repo_id)
+
+
[email protected]("/transport-status", response_model = TransportStatusResponse)
+async def get_dataset_transport_status(
+ repo_id: str = Query(..., description = "HuggingFace dataset repo ID"),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.get_dataset_transport_status_response(repo_id)
+
+
[email protected]("/check-format", response_model = CheckFormatResponse)
+def check_format(
+ request: CheckFormatRequest,
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return formatting.check_format_response(request, hf_token)
+
+
[email protected]("/ai-assist-mapping", response_model = AiAssistMappingResponse)
+def ai_assist_mapping(
+ request: AiAssistMappingRequest,
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return formatting.ai_assist_mapping_response(request, hf_token)
diff --git a/studio/backend/hub/routes/inventory.py b/studio/backend/hub/routes/inventory.py
new file mode 100644
index 00000000000..fcfdd0ad14a
--- /dev/null
+++ b/studio/backend/hub/routes/inventory.py
@@ -0,0 +1,222 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Endpoints mounted at /api/hub/* for the model inventory."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from fastapi import APIRouter, Body, Depends, Query
+
+from auth.authentication import get_current_subject
+from hub.dependencies import get_hf_token
+from hub.schemas.downloads import (
+ ActiveDownloadsResponse,
+ CancelDownloadResponse,
+ CancelDownloadRequest,
+ DownloadProgressResponse,
+ DownloadJobStatus,
+ DownloadModelRequest,
+ DownloadStartResponse,
+ TransportStatusResponse,
+)
+from hub.schemas.inventory import (
+ AddScanFolderRequest,
+ BrowseFoldersResponse,
+ CachedGgufResponse,
+ CachedModelsResponse,
+ DeleteCachedModelResponse,
+ GgufVariantsResponse,
+ LocalModelListResponse,
+ RecommendedFoldersResponse,
+ RemoveScanFolderResponse,
+ ScanFolderInfo,
+ ScanFoldersResponse,
+)
+from hub.services.models import (
+ cache_inventory,
+ deletion,
+ downloads,
+ folder_browser,
+ gguf_variants,
+ local_inventory,
+)
+
+router = APIRouter()
+
+
[email protected]("/local", response_model = LocalModelListResponse)
+async def list_local_models(
+ models_dir: str = Query(
+ default = "./models", description = "Directory to scan for local model folders"
+ ),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await local_inventory.list_local_models_response(models_dir)
+
+
+# Plain `def` (not async): synchronous SQLite + filesystem work runs in
+# FastAPI's thread-pool instead of blocking the event loop.
[email protected]("/scan-folders", response_model = ScanFoldersResponse)
+def get_scan_folders(current_subject: str = Depends(get_current_subject)):
+ return local_inventory.get_scan_folders_response()
+
+
[email protected]("/scan-folders", response_model = ScanFolderInfo, status_code = 201)
+def add_scan_folder_endpoint(
+ body: AddScanFolderRequest, current_subject: str = Depends(get_current_subject)
+):
+ return local_inventory.add_scan_folder_response(body.path)
+
+
[email protected]("/scan-folders/{folder_id}", response_model = RemoveScanFolderResponse)
+def remove_scan_folder_endpoint(
+ folder_id: int, current_subject: str = Depends(get_current_subject)
+):
+ return local_inventory.remove_scan_folder_response(folder_id)
+
+
[email protected]("/recommended-folders", response_model = RecommendedFoldersResponse)
+def get_recommended_folders(current_subject: str = Depends(get_current_subject)):
+ return folder_browser.get_recommended_folders_response()
+
+
[email protected]("/browse-folders", response_model = BrowseFoldersResponse)
+def browse_folders(
+ path: Optional[str] = Query(None),
+ show_hidden: bool = Query(False),
+ current_subject: str = Depends(get_current_subject),
+):
+ return folder_browser.browse_folders_response(path, show_hidden)
+
+
[email protected]("/gguf-variants", response_model = GgufVariantsResponse)
+async def get_gguf_variants(
+ repo_id: str = Query(
+ ..., description = "HuggingFace repo ID (e.g. 'unsloth/gemma-3-4b-it-GGUF')"
+ ),
+ prefer_local_cache: bool = Query(False),
+ offline: bool = Query(False),
+ local_path: Optional[str] = Query(None),
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await gguf_variants.get_gguf_variants_response(
+ repo_id,
+ prefer_local_cache = prefer_local_cache,
+ offline = offline,
+ local_path = local_path,
+ hf_token = hf_token,
+ )
+
+
[email protected]("/download", response_model = DownloadStartResponse, status_code = 202)
+async def download_model(
+ body: DownloadModelRequest,
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.download_model_response(body, hf_token)
+
+
[email protected]("/download/cancel", response_model = CancelDownloadResponse, status_code = 202)
+async def cancel_download_model(
+ body: CancelDownloadRequest, current_subject: str = Depends(get_current_subject)
+):
+ return await downloads.cancel_download_model_response(body)
+
+
[email protected]("/download-status", response_model = DownloadJobStatus)
+async def get_download_status(
+ repo_id: str = Query(..., description = "HuggingFace repo ID"),
+ gguf_variant: str = Query("", description = "Quantization variant (empty for safetensors)"),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.get_download_status_response(repo_id, gguf_variant)
+
+
[email protected]("/active-downloads", response_model = ActiveDownloadsResponse)
+async def get_active_downloads(
+ repo_id: str = Query("", description = "HuggingFace repo ID"),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.get_active_downloads_response(repo_id)
+
+
[email protected]("/transport-status", response_model = TransportStatusResponse)
+async def get_model_transport_status(
+ repo_id: str = Query(..., description = "HuggingFace repo ID"),
+ gguf_variant: str = Query("", description = "Quantization variant (empty for safetensors)"),
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.get_model_transport_status_response(
+ repo_id,
+ gguf_variant,
+ hf_token,
+ )
+
+
+ "/gguf-download-progress",
+ response_model = DownloadProgressResponse,
+ response_model_exclude_none = True,
+)
+async def get_gguf_download_progress(
+ repo_id: str = Query(..., description = "HuggingFace repo ID"),
+ variant: str = Query("", description = "Quantization variant (e.g. UD-TQ1_0)"),
+ expected_bytes: int = Query(0, description = "Expected total download size in bytes"),
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.get_gguf_download_progress_response(
+ repo_id,
+ variant = variant,
+ expected_bytes = expected_bytes,
+ hf_token = hf_token,
+ )
+
+
[email protected]("/download-progress", response_model = DownloadProgressResponse)
+async def get_download_progress(
+ repo_id: str = Query(..., description = "HuggingFace repo ID"),
+ expected_bytes: int = Query(0, description = "Expected total download size in bytes"),
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await downloads.get_download_progress_response(
+ repo_id,
+ expected_bytes = expected_bytes,
+ hf_token = hf_token,
+ )
+
+
[email protected]("/cached-gguf", response_model = CachedGgufResponse)
+async def list_cached_gguf(
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await cache_inventory.list_cached_gguf_response(hf_token)
+
+
[email protected]("/cached-models", response_model = CachedModelsResponse)
+async def list_cached_models(
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await cache_inventory.list_cached_models_response(hf_token)
+
+
+ "/delete-cached",
+ response_model = DeleteCachedModelResponse,
+ response_model_exclude_none = True,
+)
+async def delete_cached_model(
+ repo_id: str = Body(...),
+ variant: Optional[str] = Body(None),
+ hf_token: Optional[str] = Depends(get_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ return await deletion.delete_cached_model_response(repo_id, variant, hf_token)
diff --git a/studio/backend/hub/schemas/__init__.py b/studio/backend/hub/schemas/__init__.py
new file mode 100644
index 00000000000..32014236c6a
--- /dev/null
+++ b/studio/backend/hub/schemas/__init__.py
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
diff --git a/studio/backend/hub/schemas/datasets.py b/studio/backend/hub/schemas/datasets.py
new file mode 100644
index 00000000000..02365b19925
--- /dev/null
+++ b/studio/backend/hub/schemas/datasets.py
@@ -0,0 +1,108 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Literal, Optional
+
+from pydantic import BaseModel, Field, model_validator
+
+
+class CheckFormatRequest(BaseModel):
+ dataset_name: str
+ is_vlm: bool = False
+ subset: Optional[str] = None
+ train_split: Optional[str] = "train"
+ prefer_local_cache: bool = False
+ local_path: Optional[str] = None
+
+ @model_validator(mode = "before")
+ @classmethod
+ def _compat_split(cls, values: Any) -> Any:
+ if isinstance(values, dict) and "split" in values:
+ merged = {**values}
+ merged.setdefault("train_split", merged.pop("split"))
+ return merged
+ return values
+
+
+class CheckFormatResponse(BaseModel):
+ requires_manual_mapping: bool
+ detected_format: str
+ columns: List[str]
+ is_image: bool = False
+ is_audio: bool = False
+ multimodal_columns: Optional[List[str]] = None
+ suggested_mapping: Optional[Dict[str, str]] = None
+ detected_image_column: Optional[str] = None
+ detected_audio_column: Optional[str] = None
+ detected_text_column: Optional[str] = None
+ detected_speaker_column: Optional[str] = None
+ preview_samples: Optional[List[Dict]] = None
+ total_rows: Optional[int] = None
+ warning: Optional[str] = None
+
+
+class AiAssistMappingRequest(BaseModel):
+ columns: List[str]
+ samples: List[Dict[str, Any]]
+ dataset_name: Optional[str] = None
+ model_name: Optional[str] = None
+ model_type: Optional[str] = None
+
+
+class AiAssistMappingResponse(BaseModel):
+ success: bool
+ suggested_mapping: Optional[Dict[str, str]] = None
+ warning: Optional[str] = None
+ system_prompt: Optional[str] = None
+ user_template: Optional[str] = None
+ assistant_template: Optional[str] = None
+ label_mapping: Optional[Dict[str, Dict[str, str]]] = None
+ dataset_type: Optional[str] = None
+ is_conversational: Optional[bool] = None
+ user_notification: Optional[str] = None
+
+
+class UploadDatasetResponse(BaseModel):
+ filename: str = Field(..., description = "Original filename")
+ stored_path: str = Field(..., description = "Absolute path stored on backend")
+
+
+class LocalDatasetItem(BaseModel):
+ class Metadata(BaseModel):
+ actual_num_records: Optional[int] = None
+ target_num_records: Optional[int] = None
+ total_num_batches: Optional[int] = None
+ num_completed_batches: Optional[int] = None
+ columns: Optional[List[str]] = None
+
+ id: str
+ label: str
+ path: str
+ source: Literal["recipe", "upload"]
+ rows: Optional[int] = None
+ updated_at: Optional[float] = None
+ metadata: Optional[Metadata] = None
+
+
+class LocalDatasetsResponse(BaseModel):
+ datasets: List[LocalDatasetItem] = Field(default_factory = list)
+
+
+class CachedDatasetItem(BaseModel):
+ repo_id: str
+ size_bytes: int = 0
+ cache_path: Optional[str] = None
+ processed_cache: bool = False
+ partial: bool = False
+ partial_transport: Optional[str] = None
+
+
+class CachedDatasetsResponse(BaseModel):
+ cached: List[CachedDatasetItem] = Field(default_factory = list)
+
+
+class DeleteCachedDatasetResponse(BaseModel):
+ status: str
+ repo_id: str
diff --git a/studio/backend/hub/schemas/downloads.py b/studio/backend/hub/schemas/downloads.py
new file mode 100644
index 00000000000..dccd0c67335
--- /dev/null
+++ b/studio/backend/hub/schemas/downloads.py
@@ -0,0 +1,161 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Pydantic schemas for the Hub download manager (/api/hub/downloads/*)."""
+
+from pydantic import BaseModel, Field
+from typing import List, Literal, Optional
+
+
+DownloadJobState = Literal["idle", "running", "cancelling", "cancelled", "complete", "error"]
+
+
+class DownloadModelRequest(BaseModel):
+ """Body for POST /api/hub/download.
+
+ The HuggingFace token travels in the internal Hub token header.
+ """
+
+ repo_id: str = Field(
+ ...,
+ description = "HuggingFace repo ID, e.g. 'unsloth/Qwen3-4B-GGUF'",
+ )
+ gguf_variant: Optional[str] = Field(
+ None,
+ description = "Quantization label (e.g. 'Q4_K_M'). Required for GGUF repos.",
+ )
+ use_xet: bool = Field(
+ False,
+ description = "Enable Xet parallel chunked transport. Default False uses HTTP Range-resume.",
+ )
+
+
+class CancelDownloadRequest(BaseModel):
+ repo_id: str = Field(..., description = "HuggingFace repo ID")
+ gguf_variant: Optional[str] = Field(
+ None,
+ description = "GGUF variant label; omit for safetensors snapshots",
+ )
+ generation: Optional[int] = Field(
+ None,
+ description = "Download generation tag from a prior start; passing it scopes the cancel to that exact run.",
+ )
+
+
+class DownloadJobStatus(BaseModel):
+ """Live state of a background download job."""
+
+ state: DownloadJobState = Field(
+ ...,
+ description = "Current download job state.",
+ )
+ error: Optional[str] = Field(None, description = "Error message if state == 'error'")
+ generation: int = Field(
+ 0,
+ description = "Current run generation; an adopting client stores it so a later cancel is scoped to this exact run.",
+ )
+
+
+class DownloadStartResponse(BaseModel):
+ job_key: str
+ state: str
+ accepted: bool
+ generation: int
+
+
+class CancelDownloadResponse(BaseModel):
+ job_key: str
+ state: str
+
+
+class ActiveDownload(BaseModel):
+ """One in-flight download for a repo. ``variant`` is null for safetensors."""
+
+ repo_id: Optional[str] = None
+ variant: Optional[str] = None
+ transport: Optional[str] = None
+ state: str
+ generation: int = Field(
+ 0,
+ description = "Current run generation; an adopting client stores it so a later cancel is scoped to this exact run.",
+ )
+
+
+class ActiveDownloadsResponse(BaseModel):
+ downloads: List[ActiveDownload]
+
+
+class TransportCapability(BaseModel):
+ available: bool
+ reason: Optional[str] = None
+
+
+class TransportCapabilities(BaseModel):
+ http: TransportCapability
+ xet: TransportCapability
+
+
+class TransportStatusResponse(BaseModel):
+ has_partial: bool
+ last_transport: Optional[str] = None
+ resumable: bool
+
+
+class DownloadProgressResponse(BaseModel):
+ downloaded_bytes: int
+ # Finalized-blob bytes only (no ``.incomplete``). Registry-loss completion
+ # fallbacks key off this so a partial isn't mistaken for a finished download.
+ completed_bytes: int = 0
+ complete_on_disk: bool = Field(
+ False,
+ description = (
+ "True only when the backend verified a usable completed snapshot/variant on disk."
+ ),
+ )
+ expected_bytes: int
+ progress: float
+ cache_path: Optional[str] = None
+
+
+class DownloadDatasetRequest(BaseModel):
+ """Body for POST /api/hub/datasets/download.
+
+ The HuggingFace token travels in the internal Hub token header.
+ """
+
+ repo_id: str = Field(..., description = "HuggingFace dataset repo ID")
+ use_xet: bool = Field(
+ False,
+ description = "Enable Xet parallel chunked transport. Default False uses HTTP Range-resume.",
+ )
+
+
+class CancelDatasetDownloadRequest(BaseModel):
+ repo_id: str = Field(..., description = "HuggingFace dataset repo ID")
+ generation: Optional[int] = Field(None, description = "Download generation")
+
+
+class DatasetDownloadJobStatus(BaseModel):
+ """Live state of a background dataset download job."""
+
+ state: DownloadJobState = Field(
+ ...,
+ description = "Current dataset download job state.",
+ )
+ error: Optional[str] = Field(None, description = "Error message if state == 'error'")
+ generation: int = Field(
+ 0,
+ description = "Current run generation; an adopting client stores it so a later cancel is scoped to this exact run.",
+ )
+
+
+class DatasetDownloadStartResponse(BaseModel):
+ repo_id: str
+ state: str
+ accepted: bool
+ generation: int
+
+
+class CancelDatasetDownloadResponse(BaseModel):
+ repo_id: str
+ state: str
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.py
new file mode 100644
index 00000000000..c333c7ca894
--- /dev/null
+++ b/studio/backend/hub/schemas/inventory.py
@@ -0,0 +1,286 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Pydantic schemas for the Hub inventory layer (/api/hub/*).
+
+Kept independent from upstream models/models.py so the Hub module can ship
+without modifying any upstream schema."""
+
+from pydantic import BaseModel, Field
+from typing import List, Literal, Optional
+
+
+ModelFormat = Literal["gguf", "safetensors", "adapter", "checkpoint", "unknown"]
+ModelRuntime = Literal["llama_cpp", "transformers", "adapter", "unknown"]
+
+
+class GgufVariantDetail(BaseModel):
+ """A single GGUF quantization variant in a HuggingFace repo."""
+
+ filename: str = Field(..., description = "GGUF filename (e.g., 'gemma-3-4b-it-Q4_K_M.gguf')")
+ quant: str = Field(..., description = "Quantization label or internal GGUF variant key")
+ display_label: Optional[str] = Field(
+ None, description = "Optional user-facing label when quant is an internal key"
+ )
+ size_bytes: int = Field(0, description = "File size in bytes")
+ download_size_bytes: int = Field(0, description = "Total bytes needed to download this variant")
+ downloaded: bool = Field(
+ False, description = "Whether this variant is already in the local HF cache"
+ )
+ partial: bool = Field(
+ False,
+ description = "Whether this variant has an in-progress (.incomplete) blob in cache",
+ )
+ partial_transport: Optional[str] = Field(
+ None,
+ description = (
+ 'Transport recorded for the partial state ("http" or '
+ '"xet"), or null if not partial / unknown. Frontend uses '
+ "this to pick Resume (http) vs Redownload (xet) labels."
+ ),
+ )
+
+
+class GgufVariantsResponse(BaseModel):
+ """Response for listing GGUF quantization variants in a HuggingFace repo."""
+
+ repo_id: str = Field(..., description = "HuggingFace repo ID")
+ variants: List[GgufVariantDetail] = Field(
+ default_factory = list, description = "Available GGUF variants"
+ )
+ has_vision: bool = Field(
+ False, description = "Whether the model has vision support (mmproj files)"
+ )
+ default_variant: Optional[str] = Field(
+ None, description = "Recommended default quantization variant"
+ )
+
+
+class LocalModelCapabilities(BaseModel):
+ can_train: bool = False
+ can_chat: bool = False
+ can_delete: bool = False
+ can_download: bool = False
+ requires_variant: bool = False
+ supports_lora: bool = False
+ supports_vision: bool = False
+
+
+class LocalModelInfo(BaseModel):
+ """Discovered local model candidate."""
+
+ id: str = Field(..., description = "Identifier to use for loading/training")
+ inventory_id: Optional[str] = Field(
+ None, description = "Stable semantic inventory row identifier"
+ )
+ load_id: Optional[str] = Field(
+ None, description = "Identifier/path to pass to load or train APIs"
+ )
+ display_name: str = Field(..., description = "Display label")
+ path: str = Field(..., description = "Local path where model data was discovered")
+ size_bytes: int = Field(0, description = "Observed model artifact size in bytes")
+ model_format: ModelFormat = Field("unknown", description = "Model file format")
+ runtime: ModelRuntime = Field("unknown", description = "Expected runtime backend")
+ format_variant: Optional[str] = Field(
+ None, description = "Format variant label, for example a GGUF quant"
+ )
+ capabilities: LocalModelCapabilities = Field(
+ default_factory = LocalModelCapabilities,
+ description = "Declared capabilities for this inventory row",
+ )
+ source: Literal["models_dir", "hf_cache", "lmstudio", "ollama", "custom"] = Field(
+ ...,
+ description = "Discovery source",
+ )
+ model_id: Optional[str] = Field(
+ None,
+ description = "HF repo id for cached models, e.g. org/model",
+ )
+ base_model: Optional[str] = Field(
+ None,
+ description = "Base model from adapter_config.json when this is an adapter",
+ )
+ base_model_source: Optional[Literal["huggingface", "local", "unknown"]] = Field(
+ None,
+ description = "Whether the adapter base model is a HF repo id or local path",
+ )
+ adapter_type: Optional[str] = Field(
+ None,
+ description = "Adapter type from adapter_config.json, e.g. LORA",
+ )
+ training_method: Optional[str] = Field(
+ None,
+ description = "Training method hint from adapter_config.json",
+ )
+ updated_at: Optional[float] = Field(
+ None,
+ description = "Unix timestamp of latest observed update",
+ )
+ partial: bool = Field(
+ False,
+ description = "True when this hf_cache entry has incomplete blobs",
+ )
+ partial_transport: Optional[str] = Field(
+ None,
+ description = (
+ 'Transport recorded for the partial state ("http" or '
+ '"xet"), or null if not partial / unknown.'
+ ),
+ )
+
+
+class LocalModelListResponse(BaseModel):
+ """Response schema for listing local/cached models."""
+
+ models_dir: str = Field(..., description = "Directory scanned for custom local models")
+ hf_cache_dir: Optional[str] = Field(
+ None,
+ description = "HF cache root that was scanned",
+ )
+ lmstudio_dirs: List[str] = Field(
+ default_factory = list,
+ description = "LM Studio model directories that were scanned",
+ )
+ ollama_dirs: List[str] = Field(
+ default_factory = list,
+ description = "Ollama model directories that were scanned",
+ )
+ models: List[LocalModelInfo] = Field(
+ default_factory = list,
+ description = "Discovered local/cached models",
+ )
+
+
+class CachedRepoBase(BaseModel):
+ """Shared shape for a cached HF repo row surfaced under On Device."""
+
+ repo_id: str
+ size_bytes: int = 0
+ cache_path: Optional[str] = None
+ partial: bool = False
+ partial_transport: Optional[str] = None
+ inventory_id: Optional[str] = None
+ load_id: Optional[str] = None
+ model_format: ModelFormat = "unknown"
+ runtime: ModelRuntime = "unknown"
+ format_variant: Optional[str] = None
+ capabilities: LocalModelCapabilities = Field(default_factory = LocalModelCapabilities)
+
+
+class CachedGgufRepo(CachedRepoBase):
+ model_format: ModelFormat = "gguf"
+
+
+class CachedGgufResponse(BaseModel):
+ cached: List[CachedGgufRepo] = Field(default_factory = list)
+
+
+class CachedModelRepo(CachedRepoBase):
+ quant_method: Optional[str] = None
+ pipeline_tag: Optional[str] = None
+ library_name: Optional[str] = None
+ tags: Optional[List[str]] = None
+
+
+class CachedModelsResponse(BaseModel):
+ cached: List[CachedModelRepo] = Field(default_factory = list)
+
+
+class AddScanFolderRequest(BaseModel):
+ """Request body for adding a custom scan folder."""
+
+ path: str = Field(
+ ...,
+ description = "Absolute or relative folder path, or a model weight file path",
+ )
+
+
+class ScanFolderInfo(BaseModel):
+ """A registered custom model scan folder."""
+
+ id: int = Field(..., description = "Database row ID")
+ path: str = Field(..., description = "Normalized absolute path")
+ created_at: str = Field(..., description = "ISO 8601 creation timestamp")
+
+
+class ScanFoldersResponse(BaseModel):
+ folders: List[ScanFolderInfo] = Field(default_factory = list)
+
+
+class RemoveScanFolderResponse(BaseModel):
+ ok: bool
+
+
+class RecommendedFoldersResponse(BaseModel):
+ folders: List[str] = Field(default_factory = list)
+
+
+class DeleteCachedModelResponse(BaseModel):
+ status: str
+ repo_id: str
+ variant: Optional[str] = None
+
+
+class BrowseEntry(BaseModel):
+ """A directory entry surfaced by the folder browser."""
+
+ name: str = Field(..., description = "Entry name (basename, not full path)")
+ has_models: bool = Field(
+ False,
+ description = (
+ "Hint that the directory likely contains models "
+ "(*.gguf, *.safetensors, config.json, or HF-style "
+ "`models--*` subfolders). Used by the UI to highlight "
+ "promising candidates; the scanner itself is authoritative."
+ ),
+ )
+ hidden: bool = Field(
+ False,
+ description = "Name starts with a dot (e.g. `.cache`)",
+ )
+
+
+class BrowseFoldersResponse(BaseModel):
+ """Response schema for the folder browser endpoint."""
+
+ current: str = Field(..., description = "Absolute path of the directory just listed")
+ parent: Optional[str] = Field(
+ None,
+ description = (
+ "Parent directory of `current`, or null if `current` is the "
+ "filesystem root. The frontend uses this to render an `Up` row."
+ ),
+ )
+ entries: List[BrowseEntry] = Field(
+ default_factory = list,
+ description = (
+ "Subdirectories of `current`. Sorted with model-bearing "
+ "directories first, then alphabetically case-insensitive; "
+ "hidden entries come last within each group."
+ ),
+ )
+ suggestions: List[str] = Field(
+ default_factory = list,
+ description = (
+ "Handy starting points (home, HF cache, already-registered "
+ "scan folders). Rendered as quick-pick chips above the list."
+ ),
+ )
+ truncated: bool = Field(
+ False,
+ description = (
+ "True when the listing was capped because the directory had "
+ "more subfolders than the server is willing to enumerate in "
+ "one request. The UI should show a hint telling the user to "
+ "narrow their path."
+ ),
+ )
+ model_files_here: int = Field(
+ 0,
+ description = (
+ "Count of GGUF/safetensors files immediately inside "
+ "``current``. Used by the UI to surface a hint on leaf "
+ "model directories (which otherwise look `empty` because "
+ "they contain only files, no subdirectories)."
+ ),
+ )
diff --git a/studio/backend/hub/services/__init__.py b/studio/backend/hub/services/__init__.py
new file mode 100644
index 00000000000..e86fcb6f462
--- /dev/null
+++ b/studio/backend/hub/services/__init__.py
@@ -0,0 +1,29 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shared helpers for the Hub service layer."""
+
+from __future__ import annotations
+
+from typing import Iterable
+
+from fastapi import HTTPException
+
+from hub.utils.hf_cache_state import resolve_destructive_case_matches
+
+
+def resolve_destructive_repo_ids(repo_id: str, candidates: Iterable[str], *, noun: str) -> set[str]:
+ """Cache-dir repo ids a destructive op on *repo_id* may target.
+
+ Refuses with 409 on ambiguous case-only matches so a delete never removes
+ the wrong casing. *noun* is the plural shown to the user."""
+ resolved = resolve_destructive_case_matches(repo_id, candidates)
+ if resolved is None:
+ raise HTTPException(
+ status_code = 409,
+ detail = (
+ f"Multiple cached {noun} differ only by case. "
+ "Delete the exact repo casing from On Device."
+ ),
+ )
+ return resolved
diff --git a/studio/backend/hub/services/datasets/__init__.py b/studio/backend/hub/services/datasets/__init__.py
new file mode 100644
index 00000000000..c917f7bc021
--- /dev/null
+++ b/studio/backend/hub/services/datasets/__init__.py
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Dataset services for Hub routes."""
diff --git a/studio/backend/hub/services/datasets/cache_inventory.py b/studio/backend/hub/services/datasets/cache_inventory.py
new file mode 100644
index 00000000000..a180c9df580
--- /dev/null
+++ b/studio/backend/hub/services/datasets/cache_inventory.py
@@ -0,0 +1,474 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Cached dataset inventory and deletion services."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+from pathlib import Path
+from typing import Optional
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.services import resolve_destructive_repo_ids
+from hub.services.datasets import downloads
+from hub.utils import download_manifest
+from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils.hf_cache_state import (
+ purge_partial_repo,
+ purge_repo_cache_dirs,
+ resolve_destructive_case_matches,
+)
+from hub.utils.paths import (
+ hf_default_cache_dir,
+ is_valid_repo_id as _is_valid_repo_id,
+ legacy_hf_cache_dir,
+ resolve_cached_repo_id_case,
+)
+
+logger = get_logger(__name__)
+
+
+def _collect_hf_cache_scans() -> tuple[list, set[str]]:
+ scans = hf_cache_scan.all_hf_cache_scans()
+ seen_roots = {
+ str(cache_dir)
+ for cache_dir in (getattr(scan, "cache_dir", None) for scan in scans)
+ if cache_dir is not None
+ }
+ return scans, seen_roots
+
+
+def _hf_hub_cache_roots() -> list[Path]:
+ roots: list[Path] = []
+ seen: set[str] = set()
+
+ def _add(path: Optional[Path]) -> None:
+ if path is None or not path.is_dir():
+ return
+ try:
+ resolved = str(path.resolve())
+ except OSError:
+ return
+ if resolved in seen:
+ return
+ seen.add(resolved)
+ roots.append(path)
+
+ try:
+ from huggingface_hub.constants import HF_HUB_CACHE
+ _add(Path(HF_HUB_CACHE))
+ except Exception:
+ pass
+
+ hf_hub_cache = os.environ.get("HF_HUB_CACHE")
+ if hf_hub_cache:
+ _add(Path(hf_hub_cache).expanduser())
+
+ hf_home = os.environ.get("HF_HOME")
+ if hf_home:
+ _add(Path(hf_home).expanduser() / "hub")
+
+ _add(legacy_hf_cache_dir())
+ _add(hf_default_cache_dir())
+ return roots
+
+
+def _repo_id_from_hub_dataset_dir(name: str) -> str | None:
+ if not name.startswith("datasets--"):
+ return None
+ encoded = name.removeprefix("datasets--")
+ owner, sep, repo = encoded.partition("--")
+ if not sep or not owner or not repo:
+ return None
+ repo_id = f"{owner}/{repo}"
+ return repo_id if _is_valid_repo_id(repo_id) else None
+
+
+def _directory_size(path: Path) -> int:
+ total = 0
+ try:
+ for entry in path.rglob("*"):
+ try:
+ if entry.is_file() and not entry.is_symlink():
+ total += entry.stat().st_size
+ except OSError:
+ continue
+ except OSError:
+ return 0
+ return total
+
+
+def _prefer_dataset_cache_row(candidate: dict, existing: Optional[dict]) -> bool:
+ if existing is None:
+ return True
+ candidate_partial = bool(candidate.get("partial"))
+ existing_partial = bool(existing.get("partial"))
+ if candidate_partial != existing_partial:
+ return not candidate_partial
+ return int(candidate.get("size_bytes") or 0) > int(existing.get("size_bytes") or 0)
+
+
+def _hub_dataset_snapshot_count(path: Path) -> int:
+ snapshots = path / "snapshots"
+ try:
+ return sum(1 for entry in snapshots.iterdir() if entry.is_dir())
+ except OSError:
+ return 0
+
+
+def _scan_hub_dataset_cache_dirs() -> list[dict]:
+ """Fallback scanner: ``scan_cache_dir()`` skips repos when one cache entry is partially corrupt, so this keeps On Device matching disk."""
+ seen_lower: dict[str, dict] = {}
+ for root in _hf_hub_cache_roots():
+ try:
+ entries = [entry for entry in root.iterdir() if entry.is_dir()]
+ except OSError:
+ continue
+ for entry in entries:
+ repo_id = _repo_id_from_hub_dataset_dir(entry.name)
+ if repo_id is None:
+ continue
+ size_bytes = _directory_size(entry / "blobs")
+ if size_bytes <= 0:
+ size_bytes = _directory_size(entry)
+ if size_bytes <= 0:
+ continue
+ key = repo_id.lower()
+ existing = seen_lower.get(key)
+ snapshot_partial = _hub_dataset_snapshot_count(
+ entry
+ ) == 0 or hf_cache_scan.is_snapshot_partial("dataset", repo_id, entry)
+ row = {
+ "repo_id": repo_id,
+ "size_bytes": size_bytes,
+ "cache_path": str(entry.resolve()),
+ # snapshot_count == 0 catches blobs-but-no-snapshot;
+ # is_snapshot_partial adds active-row state checks.
+ "partial": snapshot_partial,
+ "partial_transport": (
+ hf_cache_scan.partial_transport_for(
+ "dataset",
+ repo_id,
+ repo_cache_dir = entry,
+ )
+ if snapshot_partial
+ else None
+ ),
+ }
+ if _prefer_dataset_cache_row(row, existing):
+ seen_lower[key] = row
+ return sorted(seen_lower.values(), key = lambda c: c["repo_id"])
+
+
+def _hf_datasets_cache_roots() -> list[Path]:
+ roots: list[Path] = []
+ seen: set[str] = set()
+
+ def _add(path: Optional[Path]) -> None:
+ if path is None or not path.is_dir():
+ return
+ try:
+ resolved = str(path.resolve())
+ except OSError:
+ return
+ if resolved in seen:
+ return
+ seen.add(resolved)
+ roots.append(path)
+
+ env_cache = os.environ.get("HF_DATASETS_CACHE")
+ if env_cache:
+ _add(Path(env_cache).expanduser())
+
+ try:
+ from datasets import config as datasets_config
+ _add(Path(datasets_config.HF_DATASETS_CACHE))
+ except Exception:
+ pass
+
+ hf_home = os.environ.get("HF_HOME")
+ if hf_home:
+ _add(Path(hf_home).expanduser() / "datasets")
+
+ xdg_cache = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")).expanduser()
+ _add(xdg_cache / "huggingface" / "datasets")
+ return roots
+
+
+def _repo_id_from_datasets_cache_dir(name: str) -> str | None:
+ if "___" not in name:
+ return None
+ owner, repo = name.split("___", 1)
+ repo_id = f"{owner}/{repo}"
+ return repo_id if _is_valid_repo_id(repo_id) else None
+
+
+def _processed_dataset_cache_size(path: Path) -> int:
+ total = 0
+ try:
+ for entry in path.rglob("*"):
+ try:
+ if entry.is_file():
+ total += entry.stat().st_size
+ except OSError:
+ continue
+ except OSError:
+ return 0
+ return total
+
+
+def _looks_like_processed_dataset_cache(path: Path) -> bool:
+ try:
+ for entry in path.rglob("*"):
+ if not entry.is_file():
+ continue
+ if entry.name in {"dataset_info.json", "state.json"}:
+ return True
+ if entry.suffix == ".arrow":
+ return True
+ except OSError:
+ return False
+ return False
+
+
+def _scan_processed_dataset_caches() -> list[dict]:
+ """`load_dataset()` stores processed Arrow caches separately from the Hub snapshot cache, so they're usable on-device but invisible to `scan_cache_dir()`."""
+ seen_lower: dict[str, dict] = {}
+ for root in _hf_datasets_cache_roots():
+ try:
+ entries = [entry for entry in root.iterdir() if entry.is_dir()]
+ except OSError:
+ continue
+ for entry in entries:
+ repo_id = _repo_id_from_datasets_cache_dir(entry.name)
+ if repo_id is None:
+ continue
+ if not _looks_like_processed_dataset_cache(entry):
+ continue
+ size_bytes = _processed_dataset_cache_size(entry)
+ if size_bytes <= 0:
+ continue
+ key = repo_id.lower()
+ existing = seen_lower.get(key)
+ if existing is None or size_bytes > existing["size_bytes"]:
+ seen_lower[key] = {
+ "repo_id": repo_id,
+ "size_bytes": size_bytes,
+ "cache_path": str(entry.resolve()),
+ "processed_cache": True,
+ "partial": False,
+ }
+ return sorted(seen_lower.values(), key = lambda c: c["repo_id"])
+
+
+def _scan_hf_dataset_caches() -> list[dict]:
+ scans, seen_roots = _collect_hf_cache_scans()
+
+ seen_lower: dict[str, dict] = {}
+ inspected = 0
+ for hf_cache in scans:
+ for repo_info in hf_cache.repos:
+ inspected += 1
+ try:
+ # str(...) guards against the library switching repo_type to an Enum.
+ if str(repo_info.repo_type) != "dataset":
+ continue
+ total_size = int(getattr(repo_info, "size_on_disk", 0) or 0)
+ if total_size == 0:
+ unique_blobs: dict[str, int] = {}
+ for rev in repo_info.revisions:
+ rev_id = getattr(rev, "commit_hash", None) or str(id(rev))
+ for f in rev.files:
+ blob_path = getattr(f, "blob_path", None)
+ key = str(blob_path) if blob_path else f"{rev_id}:{f.file_name}"
+ unique_blobs[key] = int(f.size_on_disk or 0)
+ total_size = sum(unique_blobs.values())
+ key = repo_info.repo_id.lower()
+ existing = seen_lower.get(key)
+ cache_dir = Path(repo_info.repo_path)
+ snapshot_partial = hf_cache_scan.is_snapshot_partial(
+ "dataset",
+ repo_info.repo_id,
+ cache_dir,
+ )
+ row = {
+ "repo_id": repo_info.repo_id,
+ "size_bytes": total_size,
+ "cache_path": str(repo_info.repo_path),
+ "partial": snapshot_partial,
+ "partial_transport": (
+ hf_cache_scan.partial_transport_for(
+ "dataset",
+ repo_info.repo_id,
+ repo_cache_dir = cache_dir,
+ )
+ if snapshot_partial
+ else None
+ ),
+ }
+ if _prefer_dataset_cache_row(row, existing):
+ seen_lower[key] = row
+ except Exception as exc:
+ label = getattr(repo_info, "repo_id", "<unknown>")
+ logger.warning("Skipping cached dataset repo %s: %s", label, exc)
+ for row in _scan_hub_dataset_cache_dirs():
+ key = row["repo_id"].lower()
+ existing = seen_lower.get(key)
+ if _prefer_dataset_cache_row(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"])
+ existing["cache_path"] = existing.get("cache_path") or row.get("cache_path")
+ if (
+ existing.get("partial")
+ and not existing.get("partial_transport")
+ and row.get("partial_transport")
+ ):
+ existing["partial_transport"] = row["partial_transport"]
+ for row in _scan_processed_dataset_caches():
+ key = row["repo_id"].lower()
+ existing = seen_lower.get(key)
+ if existing is None or (bool(existing.get("partial")) and not bool(row.get("partial"))):
+ seen_lower[key] = row
+ else:
+ existing["size_bytes"] = max(existing["size_bytes"], row["size_bytes"])
+ # Keep the processed-cache marker when a repo is both snapshot and
+ # processed Arrow cache; merging by size alone dropped it.
+ if row.get("processed_cache"):
+ existing["processed_cache"] = True
+ logger.info(
+ "Cached dataset scan: roots=%d inspected=%d returned=%d",
+ len(seen_roots) or len(scans),
+ inspected,
+ len(seen_lower),
+ )
+ return sorted(seen_lower.values(), key = lambda c: c["repo_id"])
+
+
+async def list_cached_datasets_response() -> dict:
+ """List dataset repos already downloaded into the HF cache."""
+ try:
+ return {"cached": await asyncio.to_thread(_scan_hf_dataset_caches)}
+ except Exception as exc:
+ logger.error("Error listing cached datasets: %s", exc, exc_info = True)
+ raise HTTPException(
+ status_code = 500,
+ detail = "Failed to read the local dataset cache.",
+ ) from exc
+
+
+async def delete_cached_dataset_response(repo_id: str) -> dict:
+ """Remove a cached dataset repo from the HF cache."""
+ if not _is_valid_repo_id(repo_id):
+ raise HTTPException(status_code = 400, detail = "Invalid repo_id format")
+
+ repo_key = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "dataset")
+ if not downloads.registry.begin_delete(repo_key):
+ raise HTTPException(
+ status_code = 400,
+ detail = "Cancel the active download before deleting.",
+ )
+ try:
+ return await asyncio.to_thread(_delete_cached_dataset_blocking, repo_key)
+ finally:
+ downloads.registry.end_delete(repo_key)
+ hf_cache_scan.invalidate_hf_cache_scans()
+
+
+def _delete_cached_dataset_blocking(repo_id: str) -> dict:
+ scans, _seen_roots = _collect_hf_cache_scans()
+
+ candidate_entries = []
+ for hf_cache in scans:
+ for repo_info in hf_cache.repos:
+ if str(repo_info.repo_type) != "dataset":
+ continue
+ if repo_info.repo_id.lower() == repo_id.lower():
+ candidate_entries.append((hf_cache, repo_info))
+ matched_repo_ids = resolve_destructive_repo_ids(
+ repo_id,
+ [str(repo_info.repo_id) for _hf_cache, repo_info in candidate_entries],
+ noun = "datasets",
+ )
+
+ deleted = False
+ failures: list[str] = []
+ for hf_cache, repo_info in candidate_entries:
+ if str(repo_info.repo_id) not in matched_repo_ids:
+ continue
+ try:
+ strategy = hf_cache.delete_revisions(*(rev.commit_hash for rev in repo_info.revisions))
+ strategy.execute()
+ deleted = True
+ except Exception as exc:
+ failures.append(str(exc))
+ logger.error(
+ "Failed deleting cached dataset %s from %s: %s",
+ repo_id,
+ getattr(hf_cache, "cache_dir", "<unknown>"),
+ exc,
+ exc_info = True,
+ )
+
+ processed_deleted, processed_failures = _delete_processed_dataset_cache(repo_id)
+ failures.extend(processed_failures)
+ if failures:
+ raise HTTPException(
+ status_code = 500,
+ detail = (
+ f"Failed to delete dataset from {len(failures)} cache "
+ "location(s). Some files may remain."
+ ),
+ )
+
+ # ``scan_cache_dir()`` skips blob-only/corrupt repos the revision delete
+ # can't touch, yet the fallback scanner shows them; purge the whole dir.
+ cache_purged = purge_repo_cache_dirs("dataset", repo_id)
+ partial_purged = purge_partial_repo("dataset", repo_id)
+ state_purged = download_manifest.purge_all_state_for_repo("dataset", repo_id) > 0
+ if not (deleted or processed_deleted or cache_purged or partial_purged or state_purged):
+ raise HTTPException(status_code = 404, detail = "Dataset not found in cache")
+ return {"status": "deleted", "repo_id": repo_id}
+
+
+def _delete_processed_dataset_cache(repo_id: str) -> tuple[bool, list[str]]:
+ import shutil
+
+ target = repo_id.replace("/", "___")
+ folded_target = target.lower()
+ deleted = False
+ failures: list[str] = []
+ for root in _hf_datasets_cache_roots():
+ try:
+ entries = [
+ entry
+ for entry in root.iterdir()
+ if entry.is_dir() and entry.name.lower() == folded_target
+ ]
+ except OSError:
+ continue
+ matched_names = resolve_destructive_case_matches(
+ target,
+ (entry.name for entry in entries),
+ )
+ if not matched_names:
+ continue
+ for entry in entries:
+ if entry.name not in matched_names:
+ continue
+ try:
+ shutil.rmtree(entry)
+ deleted = True
+ except Exception as exc:
+ failures.append(str(exc))
+ logger.error(
+ "Failed deleting processed dataset cache %s: %s",
+ repo_id,
+ exc,
+ exc_info = True,
+ )
+ return deleted, failures
diff --git a/studio/backend/hub/services/datasets/downloads.py b/studio/backend/hub/services/datasets/downloads.py
new file mode 100644
index 00000000000..ac90be8c6f7
--- /dev/null
+++ b/studio/backend/hub/services/datasets/downloads.py
@@ -0,0 +1,268 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Start, cancel, and report progress for dataset downloads."""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+import time
+from collections import OrderedDict
+from typing import Optional
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.schemas.downloads import (
+ ActiveDownloadsResponse,
+ CancelDatasetDownloadRequest,
+ DatasetDownloadJobStatus,
+ DownloadDatasetRequest,
+)
+from hub.services import snapshot_progress
+from hub.services import download_lifecycle
+from hub.utils import download_manifest
+from hub.utils import download_registry
+from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils.hf_cache_state import has_active_incomplete_blobs
+from hub.utils.paths import (
+ is_valid_repo_id as _is_valid_repo_id,
+ resolve_cached_repo_id_case,
+)
+from hub.utils.snapshot_filters import (
+ blob_hashes_for_siblings,
+ total_size_for_siblings,
+)
+
+logger = get_logger(__name__)
+
+_dataset_size_cache: "OrderedDict[str, tuple[int, frozenset[str], bool, str, float]]" = (
+ OrderedDict()
+)
+_dataset_size_neg_cache: "OrderedDict[tuple[str, str], float]" = OrderedDict()
+_DATASET_SIZE_CACHE_MAX = 256
+_DATASET_SIZE_POS_TTL = 60.0
+_DATASET_SIZE_NEG_TTL = 60.0
+_DATASET_SIZE_TIMEOUT_SECONDS = 5.0
+_dataset_size_cache_lock = threading.Lock()
+
+_registry = download_registry.get_datasets_registry()
+
+
+def _download_job_key(repo_id: str) -> str:
+ return download_registry.normalize_repo_key(repo_id)
+
+
+def get_dataset_snapshot_metadata_cached(
+ repo_id: str, hf_token: Optional[str] = None
+) -> tuple[int, frozenset[str]]:
+ """Raw snapshot size + expected blob hashes for a dataset repo.
+
+ The dataset worker downloads every sibling, so the denominator is the full
+ sibling-size sum and the hashes cover every file. Consumed by the shared
+ ``snapshot_progress`` accounting."""
+ token_fp = hf_cache_scan.token_fingerprint(hf_token)
+ cache_key = (repo_id, token_fp)
+ with _dataset_size_cache_lock:
+ cached = _dataset_size_cache.get(repo_id)
+ if cached is not None:
+ size, hashes, restricted, cached_fp, ts = cached
+ if (time.monotonic() - ts) >= _DATASET_SIZE_POS_TTL:
+ del _dataset_size_cache[repo_id]
+ # A gated/private repo's metadata is only served back to the token
+ # that fetched it; another token may have no access at all.
+ elif not restricted or cached_fp == token_fp:
+ _dataset_size_cache.move_to_end(repo_id)
+ return size, hashes
+ neg_ts = _dataset_size_neg_cache.get(cache_key)
+ if neg_ts is not None and (time.monotonic() - neg_ts) < _DATASET_SIZE_NEG_TTL:
+ return 0, frozenset()
+ try:
+ from huggingface_hub import HfApi
+
+ info = HfApi(token = hf_token).dataset_info(
+ repo_id,
+ files_metadata = True,
+ timeout = _DATASET_SIZE_TIMEOUT_SECONDS,
+ )
+ total = total_size_for_siblings(info.siblings)
+ hashes = blob_hashes_for_siblings(info.siblings)
+ restricted = bool(getattr(info, "private", False) or getattr(info, "gated", False))
+ except Exception:
+ with _dataset_size_cache_lock:
+ _dataset_size_neg_cache[cache_key] = time.monotonic()
+ _dataset_size_neg_cache.move_to_end(cache_key)
+ while len(_dataset_size_neg_cache) > _DATASET_SIZE_CACHE_MAX:
+ _dataset_size_neg_cache.popitem(last = False)
+ return 0, frozenset()
+ with _dataset_size_cache_lock:
+ _dataset_size_cache[repo_id] = (
+ total,
+ hashes,
+ restricted,
+ token_fp,
+ time.monotonic(),
+ )
+ _dataset_size_cache.move_to_end(repo_id)
+ _dataset_size_neg_cache.pop(cache_key, None)
+ while len(_dataset_size_cache) > _DATASET_SIZE_CACHE_MAX:
+ _dataset_size_cache.popitem(last = False)
+ return total, hashes
+
+
+async def get_dataset_download_progress_response(
+ repo_id: str,
+ expected_bytes: int = 0,
+ hf_token: Optional[str] = None,
+) -> dict:
+ """Return download progress for a HuggingFace dataset repo.
+
+ Scans the ``datasets--owner--name`` cache dir and shares the blob accounting
+ with the model path via ``snapshot_progress``. Returns ``cache_path`` for the
+ UI."""
+ return await snapshot_progress.snapshot_progress_response(
+ repo_type = "dataset",
+ repo_id = repo_id,
+ job_key = _download_job_key(repo_id),
+ expected_bytes = expected_bytes,
+ hf_token = hf_token,
+ registry = _registry,
+ metadata_resolver = get_dataset_snapshot_metadata_cached,
+ )
+
+
+def _dataset_status(key: str, *, repo_id: Optional[str] = None) -> DatasetDownloadJobStatus:
+ state, error, generation = download_lifecycle.idle_status(
+ _registry,
+ key,
+ repo_type = "dataset",
+ repo_id = repo_id,
+ variant = None,
+ )
+ return DatasetDownloadJobStatus(state = state, error = error, generation = generation)
+
+
+async def download_dataset_response(
+ body: DownloadDatasetRequest, hf_token: Optional[str] = None
+) -> dict:
+ """Start a background download for a HuggingFace dataset."""
+ repo_id = body.repo_id.strip()
+ if not _is_valid_repo_id(repo_id):
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Invalid repo_id: {repo_id!r}",
+ )
+ # Canonicalize so two different-cased paste-ins share one job + cache dir.
+ repo_id = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "dataset")
+ key = _download_job_key(repo_id)
+
+ transport = download_lifecycle.resolve_transport(body.use_xet)
+
+ claimed, claim_state = _registry.claim(
+ key,
+ transport,
+ repo_type = "dataset",
+ repo_id = repo_id,
+ )
+ generation = _registry.current_generation(key)
+ if not claimed:
+ # Pollable when rejected by this repo's own in-flight job; an
+ # in-progress delete leaves no job, so flag it via ``adoptable``.
+ return {
+ "repo_id": repo_id,
+ "state": claim_state,
+ "accepted": _registry.adoptable(key),
+ "generation": generation,
+ }
+ download_manifest.clear_cancel_marker("dataset", repo_id, None)
+
+ state = download_lifecycle.launch_worker(
+ _registry,
+ key,
+ spawn = lambda: download_lifecycle.spawn_worker(
+ ["--repo-id", repo_id, "--dataset"],
+ hf_token,
+ use_xet = body.use_xet,
+ ),
+ hf_token = hf_token,
+ label = repo_id,
+ log_prefix = "Dataset download",
+ logger = logger,
+ repo_type = "dataset",
+ repo_id = repo_id,
+ transport = transport,
+ watch_name = f"hf-dataset-download-watch-{repo_id}",
+ )
+
+ return {
+ "repo_id": repo_id,
+ "state": state,
+ "accepted": True,
+ "generation": generation,
+ }
+
+
+async def cancel_dataset_download_response(body: CancelDatasetDownloadRequest) -> dict:
+ """Cancel an in-flight dataset download (SIGKILL; HF cache resumes on next download)."""
+ repo_id = body.repo_id.strip()
+ if not _is_valid_repo_id(repo_id):
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Invalid repo_id: {repo_id!r}",
+ )
+ repo_id = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "dataset")
+ key = _download_job_key(repo_id)
+
+ state = download_lifecycle.cancel_worker(
+ _registry,
+ key,
+ generation = body.generation,
+ label = f"dataset {repo_id}",
+ logger = logger,
+ )
+ return {"repo_id": repo_id, "state": state}
+
+
+async def get_dataset_download_status_response(repo_id: str) -> DatasetDownloadJobStatus:
+ """Return the latest state of a background dataset download job."""
+ repo_id = repo_id.strip()
+ if not _is_valid_repo_id(repo_id):
+ return DatasetDownloadJobStatus(state = "idle")
+ repo_id = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "dataset")
+ return _dataset_status(_download_job_key(repo_id), repo_id = repo_id)
+
+
+async def get_active_dataset_downloads_response(repo_id: str = "") -> ActiveDownloadsResponse:
+ repo_id = repo_id.strip()
+ if repo_id and not _is_valid_repo_id(repo_id):
+ return ActiveDownloadsResponse(downloads = [])
+ canonical_repo_id = (
+ await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "dataset")
+ if repo_id
+ else None
+ )
+ return ActiveDownloadsResponse(
+ downloads = download_lifecycle.active_download_refs(
+ _registry,
+ canonical_repo_id,
+ with_variant = False,
+ )
+ )
+
+
+async def get_dataset_transport_status_response(repo_id: str) -> dict:
+ """Last transport used, whether partial blobs exist, and whether they
+ support byte-level resume. XET partials show via ``has_partial`` but are not
+ byte-level resumable (see ``models.get_model_transport_status``)."""
+ repo_id = repo_id.strip()
+ if not _is_valid_repo_id(repo_id):
+ return {"has_partial": False, "last_transport": None, "resumable": False}
+ return {
+ "has_partial": has_active_incomplete_blobs("dataset", repo_id),
+ "last_transport": download_registry.read_active_transport_marker("dataset", repo_id),
+ "resumable": download_registry.is_resumable_partial("dataset", repo_id),
+ }
+
+
+registry = _registry
diff --git a/studio/backend/hub/services/datasets/formatting.py b/studio/backend/hub/services/datasets/formatting.py
new file mode 100644
index 00000000000..8b0ff39f632
--- /dev/null
+++ b/studio/backend/hub/services/datasets/formatting.py
@@ -0,0 +1,527 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Dataset preview, format-check, and mapping-assist services."""
+
+from __future__ import annotations
+
+import base64
+import errno
+import io
+import re
+from pathlib import Path
+from typing import Optional
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.schemas.datasets import (
+ AiAssistMappingRequest,
+ AiAssistMappingResponse,
+ CheckFormatRequest,
+ CheckFormatResponse,
+)
+from hub.services.datasets.local import (
+ DATA_EXTS,
+ _TABULAR_EXTS,
+ _load_local_preview_slice,
+ _stream_file_preview_slice,
+)
+from hub.utils.dataset_cache import (
+ cached_dataset_candidates as _shared_cached_dataset_candidates,
+ latest_cached_dataset_snapshot as _shared_latest_cached_dataset_snapshot,
+ split_label_matches as _split_label_matches,
+)
+from hub.utils import download_registry
+from hub.utils.dataset_format import check_dataset_format, format_dataset_preview
+from hub.utils.hf_errors import hf_error_status
+from hub.utils.paths import (
+ is_valid_repo_id as _is_valid_repo_id,
+ resolve_dataset_path,
+)
+
+logger = get_logger(__name__)
+
+_BINARY_IMAGE_PREVIEW_MAX_BYTES = 10 * 1024 * 1024
+_IMAGE_PREVIEW_MAX_PIXELS = 16_000_000
+_IMAGE_PREVIEW_THUMBNAIL_SIZE = (512, 512)
+
+
+def _image_pixel_count(image) -> int:
+ width = max(int(getattr(image, "width", 0) or 0), 0)
+ height = max(int(getattr(image, "height", 0) or 0), 0)
+ return width * height
+
+
+def _pil_image_has_transparency(image) -> bool:
+ if "A" in image.getbands():
+ extrema = image.getchannel("A").getextrema()
+ return bool(extrema and extrema[0] < 255)
+ if image.mode == "P":
+ transparency = image.info.get("transparency")
+ if transparency is None:
+ return False
+ if isinstance(transparency, bytes):
+ return any(alpha < 255 for alpha in transparency)
+ return True
+ return False
+
+
+def _serialize_pil_image(image):
+ pixel_count = _image_pixel_count(image)
+ if pixel_count > _IMAGE_PREVIEW_MAX_PIXELS:
+ return (
+ f"<image preview omitted, {image.width}x{image.height} pixels "
+ f"exceeds {_IMAGE_PREVIEW_MAX_PIXELS:,} pixel limit>"
+ )
+
+ preview = image.copy()
+ preview.thumbnail(_IMAGE_PREVIEW_THUMBNAIL_SIZE)
+ buffer = io.BytesIO()
+ if _pil_image_has_transparency(preview):
+ preview.save(buffer, format = "PNG")
+ mime = "image/png"
+ else:
+ preview.convert("RGB").save(buffer, format = "JPEG", quality = 85)
+ mime = "image/jpeg"
+ return {
+ "type": "image",
+ "mime": mime,
+ "width": preview.width,
+ "height": preview.height,
+ "data": base64.b64encode(buffer.getvalue()).decode("ascii"),
+ }
+
+
+def _serialize_binary_value(data):
+ if len(data) > _BINARY_IMAGE_PREVIEW_MAX_BYTES:
+ return (
+ f"<binary data omitted, {len(data)} bytes exceeds "
+ f"{_BINARY_IMAGE_PREVIEW_MAX_BYTES:,} byte preview limit>"
+ )
+
+ try:
+ from PIL import Image as PILImageModule
+ with PILImageModule.open(io.BytesIO(data)) as image:
+ return _serialize_pil_image(image)
+ except Exception:
+ return f"<binary data, {len(data)} bytes>"
+
+
+def _serialize_preview_value(value):
+ if value is None or isinstance(value, (str, int, float, bool)):
+ return value
+
+ if isinstance(value, (bytes, bytearray, memoryview)):
+ return _serialize_binary_value(value)
+
+ try:
+ from PIL.Image import Image as PILImage
+ if isinstance(value, PILImage):
+ return _serialize_pil_image(value)
+ except Exception:
+ pass
+
+ if isinstance(value, dict):
+ # Undecoded HF Image/Audio cells are {"bytes": b"...", "path": ...}.
+ raw = value.get("bytes")
+ if isinstance(raw, (bytes, bytearray, memoryview)) and not (
+ value.keys() - {"bytes", "path"}
+ ):
+ return _serialize_binary_value(raw)
+ return {str(key): _serialize_preview_value(item) for key, item in value.items()}
+
+ if isinstance(value, (list, tuple)):
+ return [_serialize_preview_value(item) for item in value]
+
+ return str(value)
+
+
+def _serialize_preview_rows(rows):
+ return [
+ {str(key): _serialize_preview_value(value) for key, value in dict(row).items()}
+ for row in rows
+ ]
+
+
+def _latest_cached_dataset_snapshot(
+ repo_id: str, local_path: Optional[str] = None
+) -> Optional[Path]:
+ return _shared_latest_cached_dataset_snapshot(repo_id, local_path)
+
+
+def _cached_dataset_candidates(
+ snapshot: Path, *, subset: Optional[str], train_split: str
+) -> list[Path]:
+ return _shared_cached_dataset_candidates(
+ snapshot,
+ subset = subset,
+ train_split = train_split,
+ extensions = DATA_EXTS,
+ preferred_extensions = _TABULAR_EXTS,
+ )
+
+
+def _repo_file_label_tokens(path: str) -> set[str]:
+ return {token for token in re.split(r"[^a-z0-9]+", path.lower()) if token}
+
+
+def _repo_file_matches_label(path: str, label: str) -> bool:
+ return label.strip().lower() in _repo_file_label_tokens(path)
+
+
+def _repo_file_matches_split(path: str, split: str) -> bool:
+ return _split_label_matches(path, split)
+
+
+def _select_tier1_repo_file(
+ files: list[str], *, subset: Optional[str], train_split: str
+) -> Optional[str]:
+ data_files = sorted(f for f in files if any(f.lower().endswith(ext) for ext in DATA_EXTS))
+ if not data_files:
+ return None
+ tabular_files = [f for f in data_files if any(f.lower().endswith(ext) for ext in _TABULAR_EXTS)]
+ candidates = tabular_files or data_files
+ if subset:
+ candidates = [f for f in candidates if _repo_file_matches_label(f, subset)]
+ if not candidates:
+ return None
+ candidates = [f for f in candidates if _repo_file_matches_split(f, train_split)]
+ return candidates[0] if candidates else None
+
+
+def _load_cached_hf_preview_slice(request: CheckFormatRequest, preview_size: int):
+ if not _is_valid_repo_id(request.dataset_name):
+ return None
+ snapshot = _latest_cached_dataset_snapshot(
+ request.dataset_name,
+ request.local_path,
+ )
+ if snapshot is None:
+ return None
+ train_split = request.train_split or "train"
+ for candidate in _cached_dataset_candidates(
+ snapshot,
+ subset = request.subset,
+ train_split = train_split,
+ ):
+ try:
+ preview = _stream_file_preview_slice(candidate, preview_size)
+ except Exception as exc:
+ logger.debug("Cached dataset preview failed for %s: %s", candidate, exc)
+ continue
+ if preview is not None:
+ return preview
+ return None
+
+
+def _load_processed_hf_preview_slice(
+ request: CheckFormatRequest,
+ preview_size: int,
+ hf_token: Optional[str] = None,
+):
+ if not _is_valid_repo_id(request.dataset_name):
+ return None
+ try:
+ from datasets import DownloadConfig, load_dataset
+ except Exception:
+ return None
+
+ load_kwargs = {
+ "path": request.dataset_name,
+ "split": request.train_split or "train",
+ "download_config": DownloadConfig(local_files_only = True),
+ }
+ if request.subset:
+ load_kwargs["name"] = request.subset
+ if hf_token:
+ load_kwargs["token"] = hf_token
+
+ dataset = load_dataset(**load_kwargs)
+ total_rows = len(dataset)
+ preview_slice = dataset.select(range(min(preview_size, total_rows)))
+ return preview_slice, total_rows
+
+
+def _load_any_cached_hf_preview_slice(
+ request: CheckFormatRequest,
+ preview_size: int,
+ hf_token: Optional[str] = None,
+):
+ cached_preview = _load_cached_hf_preview_slice(request, preview_size)
+ if cached_preview is not None:
+ return cached_preview
+ try:
+ return _load_processed_hf_preview_slice(request, preview_size, hf_token)
+ except Exception as exc:
+ logger.debug(
+ "Processed dataset cache preview failed for %s: %s",
+ request.dataset_name,
+ exc,
+ )
+ return None
+
+
+def check_format_response(
+ request: CheckFormatRequest, hf_token: Optional[str] = None
+) -> CheckFormatResponse:
+ """
+ Check if a dataset requires manual column mapping.
+
+ HF datasets: tier 1 loads a single requested split/subset file (avoids
+ resolving thousands of files); tier 2 falls back to full streaming. Local
+ files load directly. Plain `def` so FastAPI runs the blocking IO in a
+ thread-pool.
+ """
+ try:
+ from itertools import islice
+
+ PREVIEW_SIZE = 10
+
+ logger.info(f"Checking format for dataset: {request.dataset_name}")
+
+ try:
+ dataset_path = resolve_dataset_path(request.dataset_name)
+ except ValueError as e:
+ # Malformed path (null bytes, '..', outside roots) is a client error:
+ # surface 400 rather than the generic 500 below.
+ raise HTTPException(status_code = 400, detail = str(e)) from e
+ total_rows = None
+
+ if dataset_path.exists():
+ train_split = request.train_split or "train"
+ preview_slice, total_rows = _load_local_preview_slice(
+ dataset_path = dataset_path,
+ train_split = train_split,
+ preview_size = PREVIEW_SIZE,
+ )
+ else:
+ from datasets import Dataset, load_dataset
+
+ # Tier 1: list_repo_files → load only the first data file
+ cached_preview = (
+ _load_any_cached_hf_preview_slice(request, PREVIEW_SIZE, hf_token)
+ if request.prefer_local_cache
+ else None
+ )
+ if cached_preview is not None:
+ preview_slice, total_rows = cached_preview
+ elif request.prefer_local_cache:
+ raise HTTPException(
+ status_code = 404,
+ detail = "Dataset is not available in the local cache.",
+ )
+ else:
+ preview_slice = None
+
+ try:
+ from huggingface_hub import HfApi
+
+ api = HfApi()
+ repo_files = api.list_repo_files(
+ request.dataset_name,
+ repo_type = "dataset",
+ token = hf_token or None,
+ )
+ train_split = request.train_split or "train"
+ first_file = _select_tier1_repo_file(
+ repo_files,
+ subset = request.subset,
+ train_split = train_split,
+ )
+ if first_file:
+ logger.info(f"Tier 1: loading single file {first_file}")
+ load_kwargs = {
+ "path": request.dataset_name,
+ "data_files": {train_split: [first_file]},
+ "split": train_split,
+ "streaming": True,
+ }
+ if hf_token:
+ load_kwargs["token"] = hf_token
+
+ streamed_ds = load_dataset(**load_kwargs)
+ rows = list(islice(streamed_ds, PREVIEW_SIZE))
+ if rows:
+ preview_slice = Dataset.from_list(rows)
+ except Exception as e:
+ logger.warning(
+ "Tier 1 (single-file) failed: %s",
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+
+ if preview_slice is None:
+ # Tier 2: full streaming (resolves all files — slow for large repos)
+ logger.info("Tier 2: falling back to full streaming load_dataset")
+ try:
+ load_kwargs = {
+ "path": request.dataset_name,
+ "split": request.train_split or "train",
+ "streaming": True,
+ }
+ if request.subset:
+ load_kwargs["name"] = request.subset
+ if hf_token:
+ load_kwargs["token"] = hf_token
+
+ streamed_ds = load_dataset(**load_kwargs)
+
+ rows = list(islice(streamed_ds, PREVIEW_SIZE))
+ if not rows:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Dataset appears to be empty or could not be streamed",
+ )
+
+ preview_slice = Dataset.from_list(rows)
+ total_rows = None
+ except Exception:
+ cached_preview = _load_any_cached_hf_preview_slice(
+ request,
+ PREVIEW_SIZE,
+ hf_token,
+ )
+ if cached_preview is None:
+ raise
+ preview_slice, total_rows = cached_preview
+
+ result = check_dataset_format(preview_slice, is_vlm = request.is_vlm)
+
+ logger.info(
+ f"Format check result: requires_mapping={result['requires_manual_mapping']}, format={result['detected_format']}, is_image={result.get('is_image', False)}"
+ )
+
+ preview_samples = None
+ if not result["requires_manual_mapping"]:
+ if result.get("suggested_mapping"):
+ # Heuristic-detected: show raw data so columns match the response;
+ # column stripping happens at training time, not preview.
+ preview_samples = _serialize_preview_rows(preview_slice)
+ else:
+ try:
+ processed = format_dataset_preview(preview_slice)
+ preview_samples = _serialize_preview_rows(processed)
+ except Exception as e:
+ logger.warning(f"Processed preview generation failed (non-fatal): {e}")
+ preview_samples = _serialize_preview_rows(preview_slice)
+ else:
+ preview_samples = _serialize_preview_rows(preview_slice)
+
+ # Collect warnings: from check_dataset_format + URL-based image detection
+ warning = result.get("warning")
+ image_col = result.get("detected_image_column")
+ if image_col and image_col in (result.get("columns") or []):
+ try:
+ sample_val = preview_slice[0][image_col]
+ if isinstance(sample_val, str) and sample_val.startswith(("http://", "https://")):
+ url_warning = (
+ "This dataset contains image URLs instead of embedded images. "
+ "Images will be downloaded during training, which may be slow for large datasets."
+ )
+ logger.info(f"URL-based image column detected: {image_col}")
+ warning = f"{warning} {url_warning}" if warning else url_warning
+ except Exception:
+ pass
+
+ return CheckFormatResponse(
+ requires_manual_mapping = result["requires_manual_mapping"],
+ detected_format = result["detected_format"],
+ columns = result["columns"],
+ is_image = result.get("is_image", False),
+ is_audio = result.get("is_audio", False),
+ multimodal_columns = result.get("multimodal_columns"),
+ suggested_mapping = result.get("suggested_mapping"),
+ detected_image_column = result.get("detected_image_column"),
+ detected_audio_column = result.get("detected_audio_column"),
+ detected_text_column = result.get("detected_text_column"),
+ detected_speaker_column = result.get("detected_speaker_column"),
+ preview_samples = preview_samples,
+ total_rows = total_rows,
+ warning = warning,
+ )
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ scrubbed = download_registry.scrub_secrets(str(e), hf_token = hf_token)
+ # Missing/gated/bad-token and malformed names are client errors, not 500s.
+ status = hf_error_status(e)
+ if (
+ status is None
+ and isinstance(e, OSError)
+ and getattr(e, "errno", None) == errno.ENAMETOOLONG
+ ):
+ status, scrubbed = 400, "Invalid dataset name"
+ elif status is None and isinstance(e, FileNotFoundError):
+ # datasets raises DatasetNotFoundError (FileNotFoundError) for missing/gated.
+ status = 404
+ elif status is None and isinstance(e, ValueError):
+ status = 400
+ if status is not None:
+ raise HTTPException(status_code = status, detail = scrubbed)
+ logger.error("Error checking dataset format: %s", scrubbed)
+ raise HTTPException(
+ status_code = 500,
+ detail = "Failed to check dataset format: " + scrubbed,
+ )
+
+
+def ai_assist_mapping_response(
+ request: AiAssistMappingRequest, hf_token: Optional[str] = None
+) -> AiAssistMappingResponse:
+ """
+ Run the LLM-assisted dataset conversion advisor (user-triggered).
+
+ Multi-pass analysis with a 7B helper model: classify dataset type, generate
+ a conversion strategy, then validate it. Falls back to simple column
+ classification if the advisor fails.
+ """
+ try:
+ from hub.utils.llm_assist import llm_conversion_advisor
+
+ truncated = [
+ {col: str(s.get(col, ""))[:200] for col in request.columns} for s in request.samples[:5]
+ ]
+
+ result = llm_conversion_advisor(
+ column_names = request.columns,
+ samples = truncated,
+ dataset_name = request.dataset_name,
+ hf_token = hf_token,
+ model_name = request.model_name,
+ model_type = request.model_type,
+ )
+
+ if result and result.get("success"):
+ return AiAssistMappingResponse(
+ success = True,
+ suggested_mapping = result.get("suggested_mapping"),
+ system_prompt = result.get("system_prompt"),
+ user_template = result.get("user_template"),
+ assistant_template = result.get("assistant_template"),
+ label_mapping = result.get("label_mapping"),
+ dataset_type = result.get("dataset_type"),
+ is_conversational = result.get("is_conversational"),
+ user_notification = result.get("user_notification"),
+ warning = result.get("warning"),
+ )
+
+ return AiAssistMappingResponse(
+ success = False,
+ warning = "AI could not determine column roles. Please assign them manually.",
+ )
+
+ except Exception as e:
+ scrubbed = download_registry.scrub_secrets(str(e), hf_token = hf_token)
+ status = hf_error_status(e)
+ if status is None and isinstance(e, FileNotFoundError):
+ status = 404
+ elif status is None and isinstance(e, ValueError):
+ status = 400
+ if status is not None:
+ raise HTTPException(status_code = status, detail = scrubbed)
+ logger.error("AI assist mapping failed: %s", scrubbed)
+ raise HTTPException(
+ status_code = 500,
+ detail = "AI assist failed: " + scrubbed,
+ )
diff --git a/studio/backend/hub/services/datasets/local.py b/studio/backend/hub/services/datasets/local.py
new file mode 100644
index 00000000000..2d2c7c3a0d3
--- /dev/null
+++ b/studio/backend/hub/services/datasets/local.py
@@ -0,0 +1,330 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Local dataset upload and listing services."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import uuid
+from pathlib import Path
+
+from fastapi import HTTPException, UploadFile
+
+from hub.schemas.datasets import (
+ LocalDatasetItem,
+ LocalDatasetsResponse,
+ UploadDatasetResponse,
+)
+from hub.utils.paths import dataset_uploads_root, ensure_dir, recipe_datasets_root
+
+# Tabular formats are preferred over archives for Tier 1 preview: archives
+# (e.g. images.zip) load as ImageFolder with synthetic columns that don't
+# match the real schema.
+_TABULAR_EXTS = (".parquet", ".json", ".jsonl", ".csv", ".tsv", ".arrow")
+_ARCHIVE_EXTS = (".tar", ".tar.gz", ".tgz", ".gz", ".zst", ".zip", ".txt")
+DATA_EXTS = _TABULAR_EXTS + _ARCHIVE_EXTS
+LOCAL_FILE_EXTS = (".json", ".jsonl", ".csv", ".parquet")
+LOCAL_UPLOAD_EXTS = {".csv", ".json", ".jsonl", ".parquet"}
+LOCAL_UPLOAD_CHUNK_BYTES = 1024 * 1024
+LOCAL_UPLOAD_MAX_BYTES = 500 * 1024 * 1024
+LOCAL_DATASETS_ROOT = recipe_datasets_root()
+DATASET_UPLOAD_DIR = dataset_uploads_root()
+
+
+def _safe_read_metadata(path: Path) -> dict | None:
+ try:
+ payload = json.loads(path.read_text(encoding = "utf-8"))
+ except (OSError, ValueError, TypeError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ return payload
+
+
+def _safe_read_rows_from_metadata(payload: dict | None) -> int | None:
+ if not payload:
+ return None
+ for key in ("actual_num_records", "target_num_records"):
+ value = payload.get(key)
+ if isinstance(value, int):
+ return value
+ return None
+
+
+def _safe_read_metadata_summary(payload: dict | None) -> dict | None:
+ if not payload:
+ return None
+
+ actual_num_records = (
+ payload.get("actual_num_records")
+ if isinstance(payload.get("actual_num_records"), int)
+ else None
+ )
+ target_num_records = (
+ payload.get("target_num_records")
+ if isinstance(payload.get("target_num_records"), int)
+ else actual_num_records
+ )
+
+ columns: list[str] | None = None
+ schema = payload.get("schema")
+ if isinstance(schema, dict):
+ columns = [str(key) for key in schema.keys()]
+ if not columns:
+ stats = payload.get("column_statistics")
+ if isinstance(stats, list):
+ derived = [
+ str(item.get("column_name"))
+ for item in stats
+ if isinstance(item, dict) and item.get("column_name")
+ ]
+ columns = derived or None
+
+ parquet_files_count = None
+ file_paths = payload.get("file_paths")
+ if isinstance(file_paths, dict):
+ parquet_files = file_paths.get("parquet-files")
+ if isinstance(parquet_files, list):
+ parquet_files_count = len(parquet_files)
+
+ total_num_batches = (
+ payload.get("total_num_batches")
+ if isinstance(payload.get("total_num_batches"), int)
+ else parquet_files_count
+ )
+ num_completed_batches = (
+ payload.get("num_completed_batches")
+ if isinstance(payload.get("num_completed_batches"), int)
+ else total_num_batches
+ )
+
+ return {
+ "actual_num_records": actual_num_records,
+ "target_num_records": target_num_records,
+ "total_num_batches": total_num_batches,
+ "num_completed_batches": num_completed_batches,
+ "columns": columns,
+ }
+
+
+def _safe_mtime(path: Path) -> float | None:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return None
+
+
+def _display_uploaded_dataset_name(path: Path) -> str:
+ stem = path.stem
+ prefix, sep, rest = stem.partition("_")
+ if sep and len(prefix) == 32 and all(c in "0123456789abcdef" for c in prefix):
+ return f"{rest}{path.suffix}"
+ return path.name
+
+
+def _build_recipe_dataset_items() -> list[LocalDatasetItem]:
+ if not LOCAL_DATASETS_ROOT.exists():
+ return []
+
+ items: list[LocalDatasetItem] = []
+ for entry in LOCAL_DATASETS_ROOT.iterdir():
+ if not entry.is_dir() or not entry.name.startswith("recipe_"):
+ continue
+ parquet_dir = entry / "parquet-files"
+ if not parquet_dir.exists() or not any(parquet_dir.glob("*.parquet")):
+ continue
+
+ rows = None
+ metadata_summary = None
+ metadata_path = entry / "metadata.json"
+ if metadata_path.exists():
+ metadata_payload = _safe_read_metadata(metadata_path)
+ rows = _safe_read_rows_from_metadata(metadata_payload)
+ metadata_summary = _safe_read_metadata_summary(metadata_payload)
+
+ items.append(
+ LocalDatasetItem(
+ id = entry.name,
+ label = entry.name,
+ path = str(parquet_dir.resolve()),
+ source = "recipe",
+ rows = rows,
+ updated_at = _safe_mtime(entry),
+ metadata = metadata_summary,
+ )
+ )
+
+ return items
+
+
+def _build_uploaded_dataset_items() -> list[LocalDatasetItem]:
+ if not DATASET_UPLOAD_DIR.exists():
+ return []
+
+ items: list[LocalDatasetItem] = []
+ for path in DATASET_UPLOAD_DIR.iterdir():
+ if not path.is_file() or path.suffix.lower() not in LOCAL_UPLOAD_EXTS:
+ continue
+ try:
+ if path.stat().st_size == 0:
+ continue
+ except OSError:
+ continue
+ label = _display_uploaded_dataset_name(path)
+ items.append(
+ LocalDatasetItem(
+ id = path.name,
+ label = label,
+ path = str(path.resolve()),
+ source = "upload",
+ updated_at = _safe_mtime(path),
+ )
+ )
+ return items
+
+
+def _build_local_dataset_items() -> list[LocalDatasetItem]:
+ items = _build_recipe_dataset_items() + _build_uploaded_dataset_items()
+ items.sort(key = lambda item: item.updated_at or 0, reverse = True)
+ return items
+
+
+def _stream_file_preview_slice(path: Path, preview_size: int):
+ """Stream the first ``preview_size`` rows so a large file is never fully parsed into Arrow; returns ``(Dataset, None)`` or ``None`` if empty/unsupported."""
+ from itertools import islice
+
+ from datasets import Dataset, load_dataset
+
+ name = path.name.lower()
+ if name.endswith((".json", ".jsonl")):
+ loader = "json"
+ elif name.endswith((".csv", ".tsv")):
+ loader = "csv"
+ elif name.endswith(".parquet"):
+ loader = "parquet"
+ elif name.endswith(".arrow"):
+ loader = "arrow"
+ elif name.endswith(".txt"):
+ loader = "text"
+ else:
+ return None
+
+ streamed = load_dataset(
+ loader,
+ data_files = str(path),
+ split = "train",
+ streaming = True,
+ )
+ rows = list(islice(streamed, preview_size))
+ if not rows:
+ return None
+ return Dataset.from_list(rows), None
+
+
+def _load_local_preview_slice(*, dataset_path: Path, train_split: str, preview_size: int):
+ from datasets import load_dataset
+
+ if dataset_path.is_dir():
+ parquet_dir = (
+ dataset_path / "parquet-files"
+ if (dataset_path / "parquet-files").exists()
+ else dataset_path
+ )
+ parquet_files = sorted(parquet_dir.glob("*.parquet"))
+ if parquet_files:
+ dataset = load_dataset(
+ "parquet",
+ data_files = [str(path) for path in parquet_files],
+ split = train_split,
+ )
+ total_rows = len(dataset)
+ preview_slice = dataset.select(range(min(preview_size, total_rows)))
+ return preview_slice, total_rows
+
+ candidate_files: list[Path] = []
+ for ext in LOCAL_FILE_EXTS:
+ candidate_files.extend(sorted(dataset_path.glob(f"*{ext}")))
+ if not candidate_files:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Unsupported local dataset directory (expected parquet/json/jsonl/csv files)",
+ )
+ dataset_path = candidate_files[0]
+
+ suffix = dataset_path.suffix.lower()
+ # Parquet/Arrow give a cheap exact total_rows via len()+select; JSON/CSV
+ # carry no such metadata, so stream them and report total_rows=None.
+ if suffix == ".parquet":
+ dataset = load_dataset("parquet", data_files = str(dataset_path), split = train_split)
+ total_rows = len(dataset)
+ preview_slice = dataset.select(range(min(preview_size, total_rows)))
+ return preview_slice, total_rows
+
+ if suffix in (".json", ".jsonl", ".csv"):
+ preview = _stream_file_preview_slice(dataset_path, preview_size)
+ if preview is None:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Dataset appears to be empty or could not be read",
+ )
+ return preview
+
+ raise HTTPException(status_code = 400, detail = f"Unsupported file format: {dataset_path.suffix}")
+
+
+def _sanitize_filename(filename: str) -> str:
+ name = Path(filename).name.strip().replace("\x00", "")
+ if not name:
+ return "dataset_upload"
+ return name
+
+
+def _upload_too_large(size_bytes: int) -> HTTPException:
+ return HTTPException(
+ status_code = 413,
+ detail = (f"Upload is too large " f"({size_bytes:,} bytes; max {LOCAL_UPLOAD_MAX_BYTES:,})."),
+ )
+
+
+async def upload_dataset_response(file: UploadFile) -> UploadDatasetResponse:
+ filename = _sanitize_filename(file.filename or "dataset_upload")
+ ext = Path(filename).suffix.lower()
+ if ext not in LOCAL_UPLOAD_EXTS:
+ allowed = ", ".join(sorted(LOCAL_UPLOAD_EXTS))
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Unsupported file type: {ext}. Allowed: {allowed}",
+ )
+
+ declared_size = getattr(file, "size", None)
+ if isinstance(declared_size, int) and declared_size > LOCAL_UPLOAD_MAX_BYTES:
+ raise _upload_too_large(declared_size)
+
+ ensure_dir(DATASET_UPLOAD_DIR)
+ stem = Path(filename).stem
+ stored_name = f"{uuid.uuid4().hex}_{stem}{ext}"
+ stored_path = DATASET_UPLOAD_DIR / stored_name
+
+ written = 0
+ try:
+ with open(stored_path, "wb") as f:
+ while chunk := await file.read(LOCAL_UPLOAD_CHUNK_BYTES):
+ written += len(chunk)
+ if written > LOCAL_UPLOAD_MAX_BYTES:
+ raise _upload_too_large(written)
+ await asyncio.to_thread(f.write, chunk)
+ except Exception:
+ stored_path.unlink(missing_ok = True)
+ raise
+
+ if written == 0:
+ stored_path.unlink(missing_ok = True)
+ raise HTTPException(status_code = 400, detail = "Empty upload payload")
+
+ return UploadDatasetResponse(filename = filename, stored_path = str(stored_path))
+
+
+def list_local_datasets_response() -> LocalDatasetsResponse:
+ return LocalDatasetsResponse(datasets = _build_local_dataset_items())
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.py
new file mode 100644
index 00000000000..8256b002520
--- /dev/null
+++ b/studio/backend/hub/services/download_lifecycle.py
@@ -0,0 +1,449 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import os
+import signal
+import subprocess
+import sys
+import threading
+from pathlib import Path
+from typing import Callable, Optional
+
+from fastapi import HTTPException
+
+from hub.schemas.downloads import ActiveDownload, DownloadJobState
+from hub.utils import download_manifest
+from hub.utils import download_registry
+from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils.hf_cache_state import EXIT_CANCELLED
+from hub.utils.state_dir import RepoType
+
+
+def backend_dir() -> Path:
+ return Path(__file__).resolve().parent.parent.parent
+
+
+def resolve_transport(use_xet: bool) -> str:
+ transport = download_registry.TRANSPORT_XET if use_xet else download_registry.TRANSPORT_HTTP
+ unavailable_reason = download_registry.download_transport_unavailable_reason(transport)
+ if unavailable_reason is not None:
+ raise HTTPException(status_code = 400, detail = unavailable_reason)
+ return transport
+
+
+def spawn_worker(
+ args: list[str],
+ hf_token: Optional[str],
+ *,
+ use_xet: bool,
+ protected_blob_hashes: Optional[frozenset[str]] = None,
+) -> subprocess.Popen:
+ """Spawn the download worker.
+
+ XET and ``hf_transfer`` write chunks out of order, so their partials can't
+ resume under a sequential writer; the HTTP path stays sequential so
+ SIGKILL -> resume is byte-identical. ``protected_blob_hashes`` are blobs a
+ concurrent same-repo peer is writing, excluded from the cache-prep purge so a
+ shared ``.incomplete`` (e.g. bundled mmproj) is never deleted.
+ """
+ cwd = backend_dir()
+ mode = download_registry.TRANSPORT_XET if use_xet else download_registry.TRANSPORT_HTTP
+ env = os.environ.copy()
+ if protected_blob_hashes:
+ env["UNSLOTH_PROTECTED_BLOB_HASHES"] = ",".join(sorted(protected_blob_hashes))
+ else:
+ env.pop("UNSLOTH_PROTECTED_BLOB_HASHES", None)
+ env["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
+ env["HF_HUB_DISABLE_TELEMETRY"] = "1"
+ env["HF_HUB_DISABLE_XET"] = "0" if use_xet else "1"
+ env["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "0" if hf_token else "1"
+ # hf_transfer's parallel Range chunks can leave sparse partials even in
+ # "http" mode; disable so the worker's writer is always sequential.
+ env["HF_HUB_ENABLE_HF_TRANSFER"] = "0"
+ for token_key in (
+ "HF_TOKEN",
+ "HF_HUB_TOKEN",
+ "HUGGING_FACE_HUB_TOKEN",
+ "HUGGINGFACE_HUB_TOKEN",
+ "HUGGINGFACEHUB_API_TOKEN",
+ ):
+ env.pop(token_key, None)
+ if hf_token:
+ env["HF_TOKEN"] = hf_token
+ existing_path = env.get("PYTHONPATH", "")
+ env["PYTHONPATH"] = f"{cwd}{os.pathsep}{existing_path}" if existing_path else str(cwd)
+ return subprocess.Popen(
+ [
+ sys.executable,
+ "-m",
+ "hub.workers.hf_download",
+ *args,
+ "--parent-pid",
+ str(os.getpid()),
+ "--transport",
+ mode,
+ ],
+ env = env,
+ cwd = str(cwd),
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.PIPE,
+ start_new_session = sys.platform != "win32",
+ )
+
+
+def drain_stderr_excerpt(stream, edge_bytes: int = 500) -> bytes:
+ """Drain a worker's stderr to EOF, retaining the first and last bytes.
+
+ Incremental reads keep the pipe from filling while bounding memory; long
+ messages keep both ends since stderr prefixes often name the failing repo."""
+ if stream is None:
+ return b""
+ edge_bytes = max(1, edge_bytes)
+ max_bytes = edge_bytes * 2
+ full = bytearray()
+ head = bytearray()
+ tail = bytearray()
+ truncated = False
+ for chunk in iter(lambda: stream.read(4096), b""):
+ if not truncated:
+ full.extend(chunk)
+ if len(full) <= max_bytes:
+ continue
+ truncated = True
+ head.extend(full[:edge_bytes])
+ tail.extend(full[-edge_bytes:])
+ full.clear()
+ continue
+ tail.extend(chunk)
+ if len(tail) > edge_bytes:
+ del tail[:-edge_bytes]
+ if not truncated:
+ return bytes(full)
+ return bytes(head + b"\n...[stderr truncated]...\n" + tail)
+
+
+def _cancellation_return_codes() -> frozenset[int]:
+ """Returncodes for intentional cancellation only (SIGKILL/SIGTERM/SIGINT); crash signals stay errors, and ``getattr`` tolerates Windows where these signals are absent."""
+ codes: set[int] = set()
+ for name in ("SIGKILL", "SIGTERM", "SIGINT"):
+ sig = getattr(signal, name, None)
+ if sig is not None:
+ codes.add(-int(sig))
+ return frozenset(codes)
+
+
+_CANCELLATION_RETURN_CODES = _cancellation_return_codes()
+
+
+def _sigpipe_return_codes() -> frozenset[int]:
+ sig = getattr(signal, "SIGPIPE", None)
+ if sig is None:
+ return frozenset()
+ value = int(sig)
+ return frozenset({-value, 128 + value})
+
+
+_SIGPIPE_RETURN_CODES = _sigpipe_return_codes()
+
+
+def classify_exit(rc: int, *, cancel_requested: bool = False) -> str:
+ """Map a worker process exit code to a job state.
+
+ - rc == 0: clean completion.
+ - rc == EXIT_CANCELLED (130): the worker trapped a stop signal and exited
+ cleanly with a resumable partial. In-app cancel uses untrappable SIGKILL
+ and the OOM killer never produces 130, so 130 is always a resumable cancel.
+ - rc killed by SIGKILL/SIGTERM/SIGINT: a cancel only when *we* asked for it.
+ The OOM killer also sends SIGKILL, so an unrequested kill surfaces as error.
+ - rc killed by SIGPIPE (or 128+SIGPIPE): parent pipe is gone; treated as
+ cancelled.
+ - any other non-zero rc (incl. crash signals): worker errored out.
+
+ Windows has no POSIX signal exit encoding, so a user cancel can't be told from
+ an error by code alone; there ``cancel_requested`` decides.
+ """
+ if rc == 0:
+ return "complete"
+ if rc == EXIT_CANCELLED:
+ return "cancelled"
+ if rc in _SIGPIPE_RETURN_CODES:
+ return "cancelled"
+ if rc in _CANCELLATION_RETURN_CODES:
+ return "cancelled" if cancel_requested else "error"
+ if cancel_requested and sys.platform == "win32":
+ return "cancelled"
+ return "error"
+
+
+def finalize_worker_exit(
+ registry: download_registry.DownloadRegistry,
+ key: str,
+ proc: subprocess.Popen,
+ *,
+ hf_token: Optional[str],
+ label: str,
+ log_prefix: str,
+ logger,
+ repo_type: Optional[RepoType] = None,
+ repo_id: Optional[str] = None,
+ transport: Optional[str] = None,
+) -> None:
+ """Block until *proc* exits, then record the job's terminal state in
+ *registry*. Drains and scrubs stderr first, then classifies the exit code.
+ A no-op when the process was already dropped (e.g. superseded).
+
+ No stall watchdog: huggingface_hub already times out chunk reads and raises
+ a resumable error on a dead connection, so the worker's exit code is the
+ single source of truth."""
+ stderr_data = drain_stderr_excerpt(proc.stderr)
+ rc = proc.wait()
+ cancel_requested = registry.cancel_requested(key)
+ if not registry.drop_process(key, proc):
+ return
+ stderr_text = download_registry.scrub_secrets(
+ (stderr_data or b"").decode("utf-8", "replace").strip(),
+ hf_token = hf_token,
+ )
+ state = classify_exit(rc, cancel_requested = cancel_requested)
+ if state == "complete":
+ registry.set_job(key, "complete")
+ if stderr_text:
+ if download_manifest.MANIFEST_DEGRADED_MARKER in stderr_text:
+ logger.warning(
+ f"{log_prefix} complete with degraded diagnostics for "
+ f"{label}: {stderr_text}"
+ )
+ else:
+ logger.info(f"{log_prefix} worker diagnostics for {label}: {stderr_text}")
+ logger.info(f"{log_prefix} complete: {label}")
+ # Defensive cleanup: the canonical clear is at download-start; this
+ # catches the rare case where that failed but the download succeeded.
+ if repo_type and repo_id:
+ try:
+ download_manifest.clear_cancel_marker(
+ repo_type,
+ repo_id,
+ download_registry.variant_from_key(key),
+ )
+ except Exception as exc:
+ logger.debug(f"clear_cancel_marker failed for {repo_id} (rc=0): {exc}")
+ elif state == "cancelled":
+ # Read metadata before the terminal set_job so a concurrent eviction
+ # can't drop it; the job key is the fallback variant label.
+ metadata = registry.get_job_metadata(key)
+ registry.set_job(key, "cancelled")
+ logger.info(f"{log_prefix} cancelled: {label} (rc={rc})")
+ download_registry.persist_cancel_marker(
+ repo_type,
+ repo_id,
+ metadata.variant
+ if metadata is not None and metadata.variant
+ else download_registry.variant_from_key(key),
+ transport,
+ logger = logger,
+ )
+ else:
+ registry.set_job(
+ key,
+ "error",
+ stderr_text or f"worker exited with code {rc}",
+ )
+ logger.error(
+ f"{log_prefix} failed for {label} (rc={rc}): {stderr_text}",
+ )
+
+
+def kill_and_reap_process(
+ proc: subprocess.Popen,
+ *,
+ label: str,
+ logger,
+ timeout: float = 10.0,
+) -> None:
+ try:
+ proc.kill()
+ except ProcessLookupError:
+ pass
+ except Exception as exc:
+ logger.warning(f"Cancel SIGKILL for {label} failed: {exc}")
+ try:
+ proc.wait(timeout = timeout)
+ except subprocess.TimeoutExpired:
+ logger.warning(f"Cancelled worker for {label} did not exit after SIGKILL")
+ except Exception:
+ pass
+
+
+def register_worker(
+ registry: download_registry.DownloadRegistry,
+ key: str,
+ proc: subprocess.Popen,
+ *,
+ hf_token: Optional[str],
+ label: str,
+ log_prefix: str,
+ logger,
+ repo_type: RepoType,
+ repo_id: str,
+ transport: str,
+ watch_name: str,
+) -> bool:
+ if not registry.register_process(key, proc):
+ kill_and_reap_process(proc, label = label, logger = logger)
+ return False
+
+ worker_token = hf_token
+
+ def _watch() -> None:
+ finalize_worker_exit(
+ registry,
+ key,
+ proc,
+ hf_token = worker_token,
+ label = label,
+ log_prefix = log_prefix,
+ logger = logger,
+ repo_type = repo_type,
+ repo_id = repo_id,
+ transport = transport,
+ )
+ if registry.get_job(key).state in ("error", "cancelled"):
+ download_registry.purge_empty_marker_dir(
+ repo_type,
+ repo_id,
+ download_registry.variant_from_key(key),
+ )
+ hf_cache_scan.invalidate_hf_cache_scans()
+
+ threading.Thread(target = _watch, name = watch_name, daemon = True).start()
+ return True
+
+
+def launch_worker(
+ registry: download_registry.DownloadRegistry,
+ key: str,
+ *,
+ spawn: Callable[[], subprocess.Popen],
+ hf_token: Optional[str],
+ label: str,
+ log_prefix: str,
+ logger,
+ repo_type: RepoType,
+ repo_id: str,
+ transport: str,
+ watch_name: str,
+) -> str:
+ try:
+ proc = spawn()
+ except Exception as e:
+ scrubbed = download_registry.scrub_secrets(str(e), hf_token = hf_token)
+ logger.error(
+ f"Failed to spawn {log_prefix.lower()} worker for {label}: {scrubbed}",
+ exc_info = True,
+ )
+ registry.set_job(key, "error", scrubbed)
+ raise HTTPException(
+ status_code = 500,
+ detail = f"Failed to start {log_prefix.lower()}: {scrubbed}",
+ ) from e
+ register_worker(
+ registry,
+ key,
+ proc,
+ hf_token = hf_token,
+ label = label,
+ log_prefix = log_prefix,
+ logger = logger,
+ repo_type = repo_type,
+ repo_id = repo_id,
+ transport = transport,
+ watch_name = watch_name,
+ )
+ return registry.get_job(key).state
+
+
+def cancel_worker(
+ registry: download_registry.DownloadRegistry,
+ key: str,
+ *,
+ generation: Optional[int],
+ label: str,
+ logger,
+) -> str:
+ proc = registry.get_process(key)
+ # No worker process yet: arm a pending cancel so register_process kills it on
+ # arrival during the claim-to-register window.
+ if proc is None:
+ if registry.mark_pending_cancel(key, generation):
+ return "cancelling"
+ return registry.get_job(key).state
+ # Worker already exited; let its watcher classify the real return code.
+ # Arming a pending cancel here could mislabel a genuine failure as a cancel.
+ if proc.poll() is not None:
+ return registry.get_job(key).state
+
+ if not registry.request_cancel(key, proc, generation):
+ return registry.get_job(key).state
+ # No eager marker: finalize_worker_exit writes it on a "cancelled" exit.
+ # Persisting before the kill races a clean completion and strands a stale marker.
+ try:
+ proc.kill()
+ except ProcessLookupError:
+ pass
+ except Exception as e:
+ logger.warning(f"Cancel SIGKILL for {label} failed: {e}")
+
+ return "cancelling"
+
+
+def idle_status(
+ registry: download_registry.DownloadRegistry,
+ key: str,
+ *,
+ repo_type: RepoType,
+ repo_id: Optional[str],
+ variant: Optional[str],
+) -> tuple[DownloadJobState, Optional[str], int]:
+ state = registry.get_job(key)
+ generation = registry.current_generation(key)
+ if (
+ state.state == "idle"
+ and repo_id
+ and download_manifest.has_cancel_marker(
+ repo_type,
+ repo_id,
+ variant,
+ )
+ ):
+ return ("cancelled", None, generation)
+ return (state.state, state.error, generation)
+
+
+def active_download_refs(
+ registry: download_registry.DownloadRegistry, repo_id: Optional[str], *, with_variant: bool
+) -> list[ActiveDownload]:
+ downloads: list[ActiveDownload] = []
+ for ref in registry.active_job_refs(repo_id):
+ metadata = ref.metadata
+ if with_variant:
+ ref_repo_id = metadata.repo_id if metadata is not None else ref.key.split("::", 1)[0]
+ if metadata is not None:
+ variant = metadata.variant
+ else:
+ _repo, sep, raw_variant = ref.key.partition("::")
+ variant = raw_variant if sep and raw_variant else None
+ else:
+ ref_repo_id = metadata.repo_id if metadata is not None else ref.key
+ variant = None
+ downloads.append(
+ ActiveDownload(
+ repo_id = ref_repo_id,
+ variant = variant,
+ transport = metadata.transport if metadata is not None else None,
+ state = ref.state,
+ generation = ref.generation,
+ )
+ )
+ return downloads
diff --git a/studio/backend/hub/services/models/__init__.py b/studio/backend/hub/services/models/__init__.py
new file mode 100644
index 00000000000..707a7c633ab
--- /dev/null
+++ b/studio/backend/hub/services/models/__init__.py
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Model service layer."""
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
new file mode 100644
index 00000000000..a961a6ae9dd
--- /dev/null
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -0,0 +1,461 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Cached model inventory."""
+
+from __future__ import annotations
+
+import json
+import asyncio
+import threading
+import time
+from collections import OrderedDict
+from pathlib import Path
+from typing import NamedTuple, Optional
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.schemas.inventory import ModelFormat
+from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils import download_registry
+from hub.utils.snapshot_filters import (
+ snapshot_download_blob_hashes,
+ snapshot_download_size,
+)
+from hub.services.models.common import (
+ _capabilities_for_format,
+ _classify_non_gguf_model_format,
+ _gguf_variant_state_summary,
+ _is_adapter_weight_name,
+ _is_checkpoint_weight_name,
+ _is_gguf_filename,
+ _is_main_gguf_filename,
+ _is_transformers_safetensors_weight_name,
+ _local_inventory_id,
+ _prefer_complete_larger,
+ _runtime_for_format,
+)
+
+logger = get_logger(__name__)
+
+_repo_size_cache: "OrderedDict[tuple[str, str], tuple[int, frozenset[str], float]]" = OrderedDict()
+_repo_size_neg_cache: "OrderedDict[tuple[str, str], float]" = OrderedDict()
+_REPO_SIZE_CACHE_MAX = 256
+_REPO_SIZE_POS_TTL = 60.0
+_REPO_SIZE_NEG_TTL = 60.0
+_MODEL_METADATA_TIMEOUT_SECONDS = 5.0
+_repo_size_cache_lock = threading.Lock()
+
+
+def get_repo_snapshot_metadata_cached(
+ repo_id: str, hf_token: Optional[str] = None
+) -> tuple[int, frozenset[str]]:
+ token_fp = hf_cache_scan.token_fingerprint(hf_token)
+ cache_key = (repo_id, token_fp)
+ with _repo_size_cache_lock:
+ cached = _repo_size_cache.get(cache_key)
+ if cached is not None:
+ total, blob_hashes, ts = cached
+ if (time.monotonic() - ts) < _REPO_SIZE_POS_TTL:
+ _repo_size_cache.move_to_end(cache_key)
+ return total, blob_hashes
+ del _repo_size_cache[cache_key]
+ neg_ts = _repo_size_neg_cache.get(cache_key)
+ if neg_ts is not None and (time.monotonic() - neg_ts) < _REPO_SIZE_NEG_TTL:
+ return 0, frozenset()
+ try:
+ from huggingface_hub import HfApi
+
+ info = HfApi(token = hf_token).model_info(
+ repo_id,
+ files_metadata = True,
+ timeout = _MODEL_METADATA_TIMEOUT_SECONDS,
+ )
+ total = snapshot_download_size(info.siblings)
+ blob_hashes = snapshot_download_blob_hashes(info.siblings)
+ except Exception as e:
+ logger.warning(
+ "Failed to get repo size for %s: %s",
+ repo_id,
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+ with _repo_size_cache_lock:
+ _repo_size_neg_cache[cache_key] = time.monotonic()
+ _repo_size_neg_cache.move_to_end(cache_key)
+ while len(_repo_size_neg_cache) > _REPO_SIZE_CACHE_MAX:
+ _repo_size_neg_cache.popitem(last = False)
+ return 0, frozenset()
+ with _repo_size_cache_lock:
+ _repo_size_cache[cache_key] = (total, blob_hashes, time.monotonic())
+ _repo_size_cache.move_to_end(cache_key)
+ _repo_size_neg_cache.pop(cache_key, None)
+ while len(_repo_size_cache) > _REPO_SIZE_CACHE_MAX:
+ _repo_size_cache.popitem(last = False)
+ return total, blob_hashes
+
+
+def all_hf_cache_scans():
+ return hf_cache_scan.all_hf_cache_scans()
+
+
+def _repo_gguf_size_bytes(repo_info) -> int:
+ """Sum primary GGUF blob sizes across revisions, deduped by blob path (HF hardlinks shared blobs); mmproj is excluded so a vision-adapter-only repo isn't classed as GGUF."""
+ unique_blobs: dict[str, int] = {}
+ for revision in repo_info.revisions:
+ rev_id = getattr(revision, "commit_hash", None) or str(id(revision))
+ for f in revision.files:
+ if _is_main_gguf_filename(f.file_name):
+ blob_path = getattr(f, "blob_path", None)
+ size = f.size_on_disk or 0
+ if blob_path:
+ unique_blobs[str(blob_path)] = size
+ else:
+ unique_blobs[f"{rev_id}:{f.file_name}"] = size
+ return sum(unique_blobs.values())
+
+
+def _repo_has_gguf_files(repo_info) -> bool:
+ return _repo_gguf_size_bytes(repo_info) > 0
+
+
+def _prefer_cache_row(candidate: dict, existing: Optional[dict]) -> bool:
+ if existing is None:
+ return True
+ return _prefer_complete_larger(
+ bool(candidate.get("partial")),
+ int(candidate.get("size_bytes") or 0),
+ bool(existing.get("partial")),
+ int(existing.get("size_bytes") or 0),
+ )
+
+
+def _cache_inventory_fields(
+ repo_id: str,
+ model_format: ModelFormat,
+ *,
+ partial: bool = False,
+ requires_variant: bool = False,
+) -> dict:
+ return {
+ "inventory_id": _local_inventory_id("cache", model_format, repo_id),
+ "load_id": repo_id,
+ "model_format": model_format,
+ "runtime": _runtime_for_format(model_format),
+ "format_variant": None,
+ "capabilities": _capabilities_for_format(
+ model_format,
+ "hf_cache",
+ partial = partial,
+ requires_variant = requires_variant,
+ ).model_dump(),
+ }
+
+
+def invalidate_hf_cache_scans() -> None:
+ hf_cache_scan.invalidate_hf_cache_scans()
+
+
+def _scan_cached_gguf() -> list[dict]:
+ """Synchronous HF-cache disk walk for GGUF repos; runs in a worker thread."""
+ cache_scans = all_hf_cache_scans()
+
+ seen_lower: dict[str, dict] = {}
+ for hf_cache in cache_scans:
+ for repo_info in hf_cache.repos:
+ try:
+ if str(repo_info.repo_type) != "model":
+ continue
+ repo_id = repo_info.repo_id
+ total_size = _repo_gguf_size_bytes(repo_info)
+ has_variant_state, variant_state_size = _gguf_variant_state_summary(repo_id)
+ if total_size == 0 and not has_variant_state:
+ continue
+ partial = hf_cache_scan.is_gguf_repo_partial(
+ repo_id,
+ Path(repo_info.repo_path),
+ )
+ if total_size == 0 and not partial:
+ continue
+ key = repo_id.lower()
+ existing = seen_lower.get(key)
+ row = {
+ "repo_id": repo_id,
+ "size_bytes": max(total_size, variant_state_size),
+ "cache_path": str(repo_info.repo_path),
+ "partial": partial,
+ # GGUF row-level transport is ambiguous (variants may differ);
+ # per-variant detail lives on GgufVariantDetail.
+ "partial_transport": None,
+ }
+ row.update(
+ _cache_inventory_fields(
+ repo_id,
+ "gguf",
+ partial = bool(row["partial"]),
+ requires_variant = True,
+ )
+ )
+ if _prefer_cache_row(row, existing):
+ seen_lower[key] = row
+ except Exception as e:
+ repo_label = getattr(repo_info, "repo_id", "<unknown>")
+ logger.warning(f"Skipping cached GGUF repo {repo_label}: {e}")
+ continue
+ return sorted(seen_lower.values(), key = lambda c: c["repo_id"])
+
+
+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 asyncio.to_thread(_scan_cached_gguf)
+ return {"cached": cached}
+ except Exception as e:
+ logger.error(
+ "Error listing cached GGUF repos: %s",
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+ raise HTTPException(
+ status_code = 500,
+ detail = "Failed to read the local model cache.",
+ ) from e
+
+
+class _CachedNonGgufPayload(NamedTuple):
+ size_bytes: int
+ has_runnable_weights: bool
+ model_format: ModelFormat
+
+
+def _repo_non_gguf_model_payload(repo_info) -> _CachedNonGgufPayload:
+ all_weight_blobs: dict[str, int] = {}
+ adapter_blobs: dict[str, int] = {}
+ safetensors_blobs: dict[str, int] = {}
+ checkpoint_blobs: dict[str, int] = {}
+ has_config = False
+ has_adapter_config = False
+ has_adapter_weights = False
+ has_safetensors = False
+ has_transformers_safetensors = False
+ has_checkpoint = False
+
+ def _record_blob(target: dict[str, int], file_obj, rev_id: str, file_name: str) -> None:
+ blob_path = getattr(file_obj, "blob_path", None)
+ size = int(file_obj.size_on_disk or 0)
+ key = str(blob_path) if blob_path else f"{rev_id}:{file_name}"
+ target[key] = size
+ all_weight_blobs[key] = size
+
+ for revision in repo_info.revisions:
+ rev_id = getattr(revision, "commit_hash", None) or str(id(revision))
+ for f in revision.files:
+ file_name = str(f.file_name)
+ lower = file_name.lower()
+ name = lower.replace("\\", "/").rsplit("/", 1)[-1]
+ if _is_gguf_filename(lower):
+ continue
+ if name == "config.json":
+ has_config = True
+ continue
+ if name == "adapter_config.json":
+ has_adapter_config = True
+ continue
+ is_adapter = _is_adapter_weight_name(name)
+ is_safetensors = name.endswith(".safetensors") and not is_adapter
+ is_checkpoint = _is_checkpoint_weight_name(name)
+ if is_adapter:
+ has_adapter_weights = True
+ _record_blob(adapter_blobs, f, rev_id, file_name)
+ if is_safetensors:
+ has_safetensors = True
+ if _is_transformers_safetensors_weight_name(name):
+ has_transformers_safetensors = True
+ _record_blob(safetensors_blobs, f, rev_id, file_name)
+ if is_checkpoint:
+ has_checkpoint = True
+ _record_blob(checkpoint_blobs, f, rev_id, file_name)
+
+ model_format = (
+ _classify_non_gguf_model_format(
+ has_config = has_config,
+ has_adapter_config = has_adapter_config,
+ has_adapter_weights = has_adapter_weights,
+ has_safetensors = has_safetensors,
+ has_transformers_safetensors = has_transformers_safetensors,
+ has_checkpoint_weights = has_checkpoint,
+ trusted_hf_cache_repo = True,
+ )
+ or "unknown"
+ )
+ if model_format == "adapter":
+ size_bytes = sum(adapter_blobs.values())
+ elif model_format == "safetensors":
+ size_bytes = sum(safetensors_blobs.values())
+ elif model_format == "checkpoint":
+ size_bytes = sum(checkpoint_blobs.values())
+ else:
+ size_bytes = sum(all_weight_blobs.values())
+
+ return _CachedNonGgufPayload(
+ size_bytes = size_bytes,
+ has_runnable_weights = model_format != "unknown",
+ model_format = model_format,
+ )
+
+
+def _cached_model_snapshot_path(repo_path: Path) -> Optional[Path]:
+ resolved = hf_cache_scan.resolve_hf_cache_realpath(repo_path)
+ if not resolved:
+ return None
+ path = Path(resolved)
+ return path if path.is_dir() else None
+
+
+def _read_json_object(path: Path) -> dict:
+ try:
+ with open(path, "r", encoding = "utf-8") as f:
+ data = json.load(f)
+ return data if isinstance(data, dict) else {}
+ except Exception:
+ return {}
+
+
+def _read_model_card_frontmatter(path: Path) -> dict:
+ try:
+ text = path.read_text(encoding = "utf-8")
+ except Exception:
+ return {}
+ lines = text.splitlines()
+ if not lines or lines[0].strip() != "---":
+ return {}
+ body: list[str] = []
+ for line in lines[1:]:
+ if line.strip() == "---":
+ break
+ body.append(line)
+ if not body:
+ return {}
+ try:
+ import yaml
+ data = yaml.safe_load("\n".join(body)) or {}
+ return data if isinstance(data, dict) else {}
+ except Exception:
+ return {}
+
+
+def _cached_model_local_metadata(repo_path: Path) -> dict:
+ snapshot = _cached_model_snapshot_path(repo_path)
+ if snapshot is None:
+ return {}
+
+ result: dict = {}
+ config = _read_json_object(snapshot / "config.json")
+ quant_method = (
+ config.get("quantization_config", {}).get("quant_method")
+ if isinstance(config.get("quantization_config"), dict)
+ else None
+ )
+ if isinstance(quant_method, str) and quant_method.strip():
+ result["quant_method"] = quant_method.strip()
+
+ card = _read_model_card_frontmatter(snapshot / "README.md")
+ pipeline_tag = card.get("pipeline_tag")
+ if isinstance(pipeline_tag, str) and pipeline_tag.strip():
+ result["pipeline_tag"] = pipeline_tag.strip()
+ library_name = card.get("library_name")
+ if isinstance(library_name, str) and library_name.strip():
+ result["library_name"] = library_name.strip()
+ tags = card.get("tags")
+ if isinstance(tags, list):
+ clean_tags = [tag.strip() for tag in tags if isinstance(tag, str) and tag.strip()]
+ if clean_tags:
+ result["tags"] = clean_tags
+ return result
+
+
+def _scan_cached_models() -> list[dict]:
+ """Synchronous HF-cache disk walk for non-GGUF model repos; runs in a worker thread."""
+ cache_scans = all_hf_cache_scans()
+
+ seen_lower: dict[str, dict] = {}
+ inspected = 0
+ skipped_gguf = 0
+ skipped_no_weights = 0
+ for hf_cache in cache_scans:
+ for repo_info in hf_cache.repos:
+ inspected += 1
+ try:
+ if str(repo_info.repo_type) != "model":
+ continue
+ repo_id = repo_info.repo_id
+ has_main_gguf = _repo_has_gguf_files(repo_info)
+ payload = _repo_non_gguf_model_payload(repo_info)
+ if payload.size_bytes == 0:
+ if has_main_gguf:
+ skipped_gguf += 1
+ continue
+ if not payload.has_runnable_weights:
+ skipped_no_weights += 1
+ continue
+ key = repo_id.lower()
+ existing = seen_lower.get(key)
+ repo_path = Path(repo_info.repo_path)
+ snapshot_partial = hf_cache_scan.is_snapshot_partial(
+ "model",
+ repo_id,
+ repo_path,
+ )
+ row = {
+ "repo_id": repo_id,
+ "size_bytes": payload.size_bytes,
+ "cache_path": str(repo_info.repo_path),
+ "partial": snapshot_partial,
+ "partial_transport": (
+ hf_cache_scan.partial_transport_for(
+ "model",
+ repo_id,
+ repo_cache_dir = repo_path,
+ )
+ if snapshot_partial
+ else None
+ ),
+ **_cached_model_local_metadata(repo_path),
+ }
+ row.update(
+ _cache_inventory_fields(
+ repo_id,
+ payload.model_format,
+ partial = bool(row["partial"]),
+ )
+ )
+ if _prefer_cache_row(row, existing):
+ seen_lower[key] = row
+ except Exception as e:
+ repo_label = getattr(repo_info, "repo_id", "<unknown>")
+ logger.warning(f"Skipping cached model repo {repo_label}: {e}")
+ continue
+ cached = sorted(seen_lower.values(), key = lambda c: c["repo_id"])
+ logger.info(
+ "Cached model scan: inspected=%d skipped_gguf=%d skipped_no_weights=%d returned=%d",
+ inspected,
+ skipped_gguf,
+ skipped_no_weights,
+ len(cached),
+ )
+ return cached
+
+
+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 asyncio.to_thread(_scan_cached_models)
+ return {"cached": cached}
+ except Exception as e:
+ logger.error(
+ "Error listing cached models: %s",
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+ raise HTTPException(
+ status_code = 500,
+ detail = "Failed to read the local model cache.",
+ ) from e
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
new file mode 100644
index 00000000000..688d324a606
--- /dev/null
+++ b/studio/backend/hub/services/models/common.py
@@ -0,0 +1,610 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shared model inventory helpers for the Hub service layer."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+from typing import List, Literal, Optional
+from urllib.parse import quote
+
+from hub.schemas.inventory import (
+ LocalModelCapabilities,
+ LocalModelInfo,
+ ModelFormat,
+ ModelRuntime,
+)
+from hub.utils.gguf import (
+ extract_quant_label,
+ is_gguf_filename as _is_gguf_filename,
+ is_mmproj_filename as _is_mmproj_filename,
+)
+from hub.utils.paths import is_valid_repo_id as _is_valid_repo_id
+
+ModelType = Literal["text", "vision", "audio", "embeddings"]
+LocalModelSource = Literal["models_dir", "hf_cache", "lmstudio", "ollama", "custom"]
+
+
+def _safe_is_dir(path) -> bool:
+ # Py >= 3.12 propagates PermissionError (EACCES) from is_dir(); folder scans
+ # probe root-owned system dirs, so treat un-stat-able paths as not-a-dir.
+ try:
+ return Path(path).is_dir()
+ except OSError:
+ return False
+
+
+_LOCAL_CHECKPOINT_EXTENSIONS = (
+ ".bin",
+ ".pt",
+ ".pth",
+ ".ckpt",
+ ".h5",
+ ".msgpack",
+ ".npz",
+)
+
+_LOCAL_BASE_MODEL_PREFIXES = {
+ "checkpoint",
+ "checkpoints",
+ "export",
+ "exports",
+ "model",
+ "models",
+ "output",
+ "outputs",
+ "run",
+ "runs",
+ "train",
+}
+_HF_CACHE_MODEL_FILE_PROBE_LIMIT = 2000
+
+
+def _is_model_directory(d: Path) -> bool:
+ """True when *d* has a config plus real weights; excludes mmproj GGUFs and non-weight ``.bin`` files (``tokenizer.bin``) to avoid false positives."""
+
+ def _is_weight_file(f: Path) -> bool:
+ suffix = f.suffix.lower()
+ if suffix == ".safetensors":
+ return True
+ if suffix == ".gguf":
+ return "mmproj" not in f.name.lower()
+ if suffix == ".bin":
+ name = f.name.lower()
+ return (
+ name.startswith("pytorch_model")
+ or name.startswith("model")
+ or name.startswith("adapter_model")
+ or name.startswith("consolidated")
+ )
+ return False
+
+ try:
+ has_config = (d / "config.json").exists() or (d / "adapter_config.json").exists()
+ if not has_config:
+ return False
+ return any(_is_weight_file(f) for f in d.iterdir() if f.is_file())
+ except OSError:
+ return False
+
+
+def _local_inventory_id(
+ source: str,
+ model_format: ModelFormat,
+ semantic_id: str,
+ variant: Optional[str] = None,
+) -> str:
+ parts = [
+ source,
+ model_format,
+ quote(semantic_id, safe = ""),
+ ]
+ if variant:
+ parts.append(quote(variant, safe = ""))
+ return ":".join(parts)
+
+
+def _runtime_for_format(model_format: ModelFormat) -> ModelRuntime:
+ if model_format == "gguf":
+ return "llama_cpp"
+ if model_format == "adapter":
+ return "adapter"
+ if model_format in {"safetensors", "checkpoint"}:
+ return "transformers"
+ return "unknown"
+
+
+def _capabilities_for_format(
+ model_format: ModelFormat,
+ source: str,
+ *,
+ partial: bool = False,
+ requires_variant: bool = False,
+) -> LocalModelCapabilities:
+ is_complete = not partial
+ can_chat = model_format in {"gguf", "safetensors", "adapter", "checkpoint"}
+ can_train = model_format in {"safetensors", "checkpoint"} and is_complete
+ return LocalModelCapabilities(
+ can_train = can_train,
+ can_chat = can_chat and is_complete,
+ can_delete = source == "hf_cache",
+ can_download = False,
+ requires_variant = requires_variant,
+ supports_lora = model_format in {"safetensors", "checkpoint"} and is_complete,
+ supports_vision = False,
+ )
+
+
+def _prefer_complete_larger(
+ candidate_partial: bool,
+ candidate_size_bytes: int,
+ existing_partial: bool,
+ existing_size_bytes: int,
+) -> bool:
+ if candidate_partial != existing_partial:
+ return not candidate_partial
+ return candidate_size_bytes > existing_size_bytes
+
+
+def _gguf_variant_state_summary(repo_id: str) -> tuple[bool, int]:
+ """Whether GGUF variant-scoped state exists and its expected size; a cancelled/in-progress variant may have only manifests/markers/`.incomplete` blobs, which inventory needs to avoid a generic fallback row."""
+ from hub.utils import download_manifest
+
+ variant_keys: set[str] = set()
+ size_by_variant: dict[str, int] = {}
+ for variant, _path in download_manifest.iter_variant_manifests(
+ "model",
+ repo_id,
+ ):
+ key = variant.lower()
+ variant_keys.add(key)
+ manifest = download_manifest.read_manifest("model", repo_id, variant)
+ if manifest is None:
+ continue
+ size_by_variant[key] = max(
+ size_by_variant.get(key, 0),
+ sum(max(0, int(file.size or 0)) for file in manifest.expected_files),
+ )
+ for variant, _path in download_manifest.iter_variant_markers(
+ "model",
+ repo_id,
+ ):
+ variant_keys.add(variant.lower())
+ return bool(variant_keys), sum(size_by_variant.values())
+
+
+def _apply_format_aware_partial(
+ rows: List[LocalModelInfo],
+ *,
+ snapshot_partial: bool,
+ gguf_partial: bool,
+ snapshot_partial_transport: Optional[str] = None,
+) -> List[LocalModelInfo]:
+ """Rewrite each row's partial flag with format-aware predicates so a hybrid (gguf + safetensors) repo's broken format doesn't taint the clean one; capabilities are recomputed from the new flag."""
+ rewritten: List[LocalModelInfo] = []
+ for row in rows:
+ target = gguf_partial if row.model_format == "gguf" else snapshot_partial
+ if not target:
+ rewritten.append(row)
+ continue
+ # GGUF row-level transport is ambiguous (variants may differ); per-variant
+ # detail lives on GgufVariantDetail.partial_transport via the variants endpoint.
+ partial_transport = None if row.model_format == "gguf" else snapshot_partial_transport
+ rewritten.append(
+ row.model_copy(
+ update = {
+ "partial": True,
+ "partial_transport": partial_transport,
+ "capabilities": _capabilities_for_format(
+ row.model_format,
+ row.source,
+ partial = True,
+ requires_variant = row.capabilities.requires_variant,
+ ),
+ }
+ )
+ )
+ return rewritten
+
+
+def _weight_basename(name: str) -> str:
+ return name.replace("\\", "/").rsplit("/", 1)[-1].lower()
+
+
+def _is_adapter_weight_name(name: str) -> bool:
+ lower = _weight_basename(name)
+ return lower.startswith("adapter_model") and lower.endswith((".safetensors", ".bin"))
+
+
+def _is_transformers_safetensors_weight_name(name: str) -> bool:
+ lower = _weight_basename(name)
+ return lower.endswith(".safetensors") and lower.startswith(
+ ("model", "pytorch_model", "consolidated")
+ )
+
+
+def _is_transformers_bin_weight_name(name: str) -> bool:
+ lower = _weight_basename(name)
+ if not lower.endswith(".bin"):
+ return False
+ return lower.startswith(("pytorch_model", "model", "consolidated", "adapter_model"))
+
+
+def _is_checkpoint_weight_name(name: str) -> bool:
+ lower = _weight_basename(name)
+ if lower.endswith(".bin"):
+ return _is_transformers_bin_weight_name(lower)
+ return lower.endswith(_LOCAL_CHECKPOINT_EXTENSIONS)
+
+
+def _is_adapter_weight_file(path: Path) -> bool:
+ return _is_adapter_weight_name(path.name)
+
+
+def _is_transformers_safetensors_weight_file(path: Path) -> bool:
+ return _is_transformers_safetensors_weight_name(path.name)
+
+
+def _is_transformers_bin_weight_file(path: Path) -> bool:
+ return _is_transformers_bin_weight_name(path.name)
+
+
+def _is_checkpoint_weight_file(path: Path) -> bool:
+ return _is_checkpoint_weight_name(path.name)
+
+
+def _classify_non_gguf_model_format(
+ *,
+ has_config: bool,
+ has_adapter_config: bool,
+ has_adapter_weights: bool,
+ has_safetensors: bool,
+ has_transformers_safetensors: bool,
+ has_checkpoint_weights: bool,
+ trusted_hf_cache_repo: bool = False,
+) -> Optional[ModelFormat]:
+ if has_safetensors and (has_config or (trusted_hf_cache_repo and has_transformers_safetensors)):
+ return "safetensors"
+ if has_adapter_config and has_adapter_weights:
+ return "adapter"
+ if has_config and has_checkpoint_weights:
+ return "checkpoint"
+ return None
+
+
+def _is_main_gguf_filename(name: str) -> bool:
+ return _is_gguf_filename(name) and not _is_mmproj_filename(name)
+
+
+def _iter_gguf_paths(root: Path):
+ stack = [root]
+ while stack:
+ current = stack.pop()
+ try:
+ entries = list(current.iterdir())
+ except OSError:
+ continue
+ for path in entries:
+ try:
+ if path.is_dir() and not path.is_symlink():
+ stack.append(path)
+ elif path.is_file() and _is_gguf_filename(path.name):
+ yield path
+ except OSError:
+ continue
+
+
+def _iter_immediate_files(path: Path, *, include_symlinks: bool = False) -> list[Path]:
+ if path.is_file():
+ return [path]
+ if not path.is_dir():
+ return []
+ try:
+ return [
+ entry
+ for entry in path.iterdir()
+ if entry.is_file() or (include_symlinks and entry.is_symlink())
+ ]
+ except OSError:
+ return []
+
+
+def _iter_hf_cache_model_files(path: Path) -> list[Path]:
+ files = _iter_immediate_files(path, include_symlinks = True)
+ if not path.is_dir():
+ return files
+ if any(
+ _is_main_gguf_filename(entry.name)
+ or _is_transformers_safetensors_weight_file(entry)
+ or _is_checkpoint_weight_file(entry)
+ for entry in files
+ ):
+ return files
+ try:
+ bounded: list[Path] = []
+ for index, entry in enumerate(path.rglob("*"), start = 1):
+ if index > _HF_CACHE_MODEL_FILE_PROBE_LIMIT:
+ break
+ if entry.is_file() or entry.is_symlink():
+ bounded.append(entry)
+ return bounded
+ except OSError:
+ return []
+
+
+def _file_size_bytes(path: Path) -> int:
+ try:
+ if path.is_file() or path.is_symlink():
+ return path.stat().st_size
+ except OSError:
+ return 0
+ return 0
+
+
+def _sum_file_sizes(paths) -> int:
+ return sum(_file_size_bytes(path) for path in paths)
+
+
+def _main_gguf_files(path: Path, *, include_symlinks: bool = False) -> list[Path]:
+ return [
+ entry
+ for entry in _iter_immediate_files(path, include_symlinks = include_symlinks)
+ if _is_main_gguf_filename(entry.name)
+ ]
+
+
+def _format_label(model_format: ModelFormat) -> str:
+ if model_format == "gguf":
+ return "GGUF"
+ if model_format == "safetensors":
+ return "Safetensors"
+ if model_format == "adapter":
+ return "Adapter"
+ if model_format == "checkpoint":
+ return "Checkpoint"
+ return "Unknown"
+
+
+def _read_adapter_config(path: Path) -> dict:
+ if not path.is_dir():
+ return {}
+ try:
+ with (path / "adapter_config.json").open("r", encoding = "utf-8") as f:
+ data = json.load(f)
+ except Exception:
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _clean_optional_string(value: object) -> Optional[str]:
+ return value.strip() if isinstance(value, str) and value.strip() else None
+
+
+def _base_model_looks_local(value: str) -> bool:
+ raw = value.strip()
+ normalized = raw.replace("\\", "/")
+ if raw.startswith(("/", "./", "../", "~", "\\\\")) or (
+ len(raw) >= 3 and raw[1] == ":" and raw[0].isalpha()
+ ):
+ return True
+ first = normalized.split("/", 1)[0].lower()
+ return "/" in normalized and first in _LOCAL_BASE_MODEL_PREFIXES
+
+
+def _base_model_source(value: Optional[str], adapter_dir: Path) -> Optional[str]:
+ if not value:
+ return None
+ candidates = [value, value.replace("\\", "/")]
+ for candidate in candidates:
+ try:
+ expanded = Path(os.path.expanduser(candidate))
+ if expanded.exists() or (adapter_dir / candidate).exists():
+ return "local"
+ except (OSError, ValueError):
+ return "unknown"
+ if _base_model_looks_local(value):
+ return "local"
+ if _is_valid_repo_id(value):
+ return "huggingface"
+ return "unknown"
+
+
+def _local_model_info(
+ *,
+ scan_path: Path,
+ load_path: Path,
+ source: LocalModelSource,
+ model_format: ModelFormat,
+ display_name: Optional[str] = None,
+ model_id: Optional[str] = None,
+ updated_at: Optional[float] = None,
+ partial: bool = False,
+ requires_variant: bool = False,
+ format_variant: Optional[str] = None,
+ size_bytes: int = 0,
+ base_model: Optional[str] = None,
+ base_model_source: Optional[str] = None,
+ adapter_type: Optional[str] = None,
+ training_method: Optional[str] = None,
+) -> LocalModelInfo:
+ load_id = model_id if source == "hf_cache" and model_id else str(load_path)
+ semantic_id = model_id or str(load_path)
+ return LocalModelInfo(
+ id = load_id,
+ inventory_id = _local_inventory_id(
+ source,
+ model_format,
+ semantic_id,
+ format_variant,
+ ),
+ load_id = load_id,
+ model_id = model_id,
+ display_name = display_name or (scan_path.stem if scan_path.is_file() else scan_path.name),
+ path = str(load_path),
+ size_bytes = max(0, int(size_bytes or 0)),
+ source = source,
+ base_model = base_model,
+ base_model_source = base_model_source,
+ adapter_type = adapter_type,
+ training_method = training_method,
+ updated_at = updated_at,
+ partial = partial,
+ model_format = model_format,
+ runtime = _runtime_for_format(model_format),
+ format_variant = format_variant,
+ capabilities = _capabilities_for_format(
+ model_format,
+ source,
+ partial = partial,
+ requires_variant = requires_variant,
+ ),
+ )
+
+
+def _classify_local_path(
+ scan_path: Path,
+ source: LocalModelSource,
+ *,
+ load_path: Optional[Path] = None,
+ display_name: Optional[str] = None,
+ model_id: Optional[str] = None,
+ updated_at: Optional[float] = None,
+ partial: bool = False,
+) -> list[LocalModelInfo]:
+ load_path = load_path or scan_path
+ files = (
+ _iter_hf_cache_model_files(scan_path)
+ if source == "hf_cache"
+ else _iter_immediate_files(scan_path)
+ )
+ if not files:
+ return []
+
+ rows: list[LocalModelInfo] = []
+ include_broken_snapshot_symlinks = source == "hf_cache"
+ gguf_files = _main_gguf_files(
+ scan_path,
+ include_symlinks = include_broken_snapshot_symlinks,
+ )
+ if gguf_files:
+ gguf_size_bytes = _sum_file_sizes(gguf_files)
+ variant = (
+ extract_quant_label(gguf_files[0].name)
+ if scan_path.is_file() and len(gguf_files) == 1
+ else None
+ )
+ rows.append(
+ _local_model_info(
+ scan_path = scan_path,
+ load_path = load_path,
+ source = source,
+ model_format = "gguf",
+ display_name = display_name,
+ model_id = model_id,
+ updated_at = updated_at,
+ partial = partial,
+ requires_variant = scan_path.is_dir(),
+ format_variant = variant,
+ size_bytes = gguf_size_bytes,
+ )
+ )
+
+ has_config = (scan_path / "config.json").is_file() if scan_path.is_dir() else False
+ has_adapter_config = (
+ (scan_path / "adapter_config.json").is_file() if scan_path.is_dir() else False
+ )
+ adapter_config = _read_adapter_config(scan_path) if has_adapter_config else {}
+ adapter_base_model = _clean_optional_string(adapter_config.get("base_model_name_or_path"))
+ adapter_type = _clean_optional_string(adapter_config.get("peft_type"))
+ training_method = _clean_optional_string(adapter_config.get("unsloth_training_method"))
+ has_adapter_weights = any(_is_adapter_weight_file(f) for f in files)
+ has_safetensors = any(
+ f.suffix.lower() == ".safetensors" and not _is_adapter_weight_file(f) for f in files
+ )
+ has_transformers_safetensors = any(
+ _is_transformers_safetensors_weight_file(f) and not _is_adapter_weight_file(f)
+ for f in files
+ )
+ has_checkpoint_weights = any(_is_checkpoint_weight_file(f) for f in files)
+ trusted_hf_cache_repo = source == "hf_cache" and bool(model_id)
+
+ model_format = _classify_non_gguf_model_format(
+ has_config = has_config,
+ has_adapter_config = has_adapter_config,
+ has_adapter_weights = has_adapter_weights,
+ has_safetensors = has_safetensors,
+ has_transformers_safetensors = has_transformers_safetensors,
+ has_checkpoint_weights = has_checkpoint_weights,
+ trusted_hf_cache_repo = trusted_hf_cache_repo,
+ )
+
+ if model_format is not None:
+ if model_format == "adapter":
+ size_bytes = _sum_file_sizes(f for f in files if _is_adapter_weight_file(f))
+ elif model_format == "safetensors":
+ size_bytes = _sum_file_sizes(
+ f
+ for f in files
+ if f.suffix.lower() == ".safetensors" and not _is_adapter_weight_file(f)
+ )
+ else:
+ size_bytes = _sum_file_sizes(f for f in files if _is_checkpoint_weight_file(f))
+ rows.append(
+ _local_model_info(
+ scan_path = scan_path,
+ load_path = load_path,
+ source = source,
+ model_format = model_format,
+ display_name = display_name,
+ model_id = model_id,
+ updated_at = updated_at,
+ partial = partial,
+ size_bytes = size_bytes,
+ base_model = adapter_base_model if model_format == "adapter" else None,
+ base_model_source = (
+ _base_model_source(adapter_base_model, scan_path)
+ if model_format == "adapter"
+ else None
+ ),
+ adapter_type = adapter_type if model_format == "adapter" else None,
+ training_method = training_method if model_format == "adapter" else None,
+ )
+ )
+ elif not rows:
+ fallback_format: ModelFormat = (
+ "safetensors" if trusted_hf_cache_repo and has_config else "unknown"
+ )
+ size_bytes = _sum_file_sizes(files)
+ rows.append(
+ _local_model_info(
+ scan_path = scan_path,
+ load_path = load_path,
+ source = source,
+ model_format = fallback_format,
+ display_name = display_name,
+ model_id = model_id,
+ updated_at = updated_at,
+ partial = partial or trusted_hf_cache_repo,
+ size_bytes = size_bytes,
+ )
+ )
+
+ if len(rows) > 1:
+ rows = [
+ row.model_copy(
+ update = {
+ "display_name": f"{row.display_name} ({_format_label(row.model_format)})",
+ "inventory_id": _local_inventory_id(
+ row.source,
+ row.model_format,
+ row.model_id or row.path,
+ row.format_variant,
+ ),
+ }
+ )
+ for row in rows
+ ]
+ return rows
diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.py
new file mode 100644
index 00000000000..d4aed0d59f3
--- /dev/null
+++ b/studio/backend/hub/services/models/deletion.py
@@ -0,0 +1,455 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Cached model deletion."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import Optional
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.utils import download_manifest
+from hub.utils import download_registry
+from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils.gguf import extract_quant_label
+from hub.utils.hf_cache_state import (
+ INCOMPLETE_SUFFIX,
+ purge_partial_repo,
+ purge_repo_cache_dirs,
+)
+from hub.utils.paths import (
+ is_valid_gguf_variant as _is_valid_gguf_variant,
+ is_valid_repo_id as _is_valid_repo_id,
+ resolve_cached_repo_id_case,
+)
+from hub.services import resolve_destructive_repo_ids
+from hub.services.models import cache_inventory, downloads, gguf_variants
+from hub.services.models.common import (
+ _is_gguf_filename,
+ _is_main_gguf_filename,
+ _is_mmproj_filename,
+)
+
+logger = get_logger(__name__)
+
+
+def _snapshot_blob_reference_counts(repo_dir: Optional[Path]) -> dict[Path, int]:
+ """Map each blob's realpath to its live snapshot symlink count, so per-variant deletion never unlinks a blob another revision still references (call after the target variant's own symlinks are removed)."""
+ counts: dict[Path, int] = {}
+ if repo_dir is None:
+ return counts
+ snapshots = repo_dir / "snapshots"
+ if not snapshots.is_dir():
+ return counts
+ try:
+ entries = list(snapshots.rglob("*"))
+ except OSError:
+ return counts
+ for link in entries:
+ try:
+ if not link.is_symlink():
+ continue
+ target = link.resolve()
+ except OSError:
+ continue
+ counts[target] = counts.get(target, 0) + 1
+ return counts
+
+
+def _blob_hash_from_path(blob: Path) -> Optional[str]:
+ name = blob.name
+ if not name or name.endswith(INCOMPLETE_SUFFIX):
+ return None
+ return name
+
+
+def _path_exists_or_symlink(path: Path) -> bool:
+ try:
+ return path.is_symlink() or path.exists()
+ except OSError:
+ return False
+
+
+def _repo_file_matches(target_repo, predicate) -> list[tuple[Path, Optional[Path], str]]:
+ matches: list[tuple[Path, Optional[Path], str]] = []
+ for rev in getattr(target_repo, "revisions", ()):
+ for f in getattr(rev, "files", ()):
+ name = str(getattr(f, "file_name", ""))
+ if not predicate(name):
+ continue
+ file_path = getattr(f, "file_path", None)
+ if not file_path:
+ continue
+ blob_path = getattr(f, "blob_path", None)
+ matches.append(
+ (
+ Path(file_path),
+ Path(blob_path) if blob_path else None,
+ name,
+ )
+ )
+ return matches
+
+
+def _has_remaining_main_gguf(target_repo) -> bool:
+ return any(
+ _path_exists_or_symlink(snap)
+ for snap, _blob, _name in _repo_file_matches(
+ target_repo,
+ _is_main_gguf_filename,
+ )
+ )
+
+
+def _delete_gguf_variant_from_repos(
+ repo_id: str,
+ variant: str,
+ target_repos: list,
+ hf_token: Optional[str],
+ *,
+ sibling_active: bool = False,
+) -> dict:
+ failures: list[str] = []
+ removed_snapshots = 0
+ deleted_bytes = 0
+ deleted_blobs = 0
+ completed_hashes: set[str] = set()
+
+ for target_repo in target_repos:
+ repo_dir = Path(target_repo.repo_path) if getattr(target_repo, "repo_path", None) else None
+ matched = _repo_file_matches(
+ target_repo,
+ lambda name: _is_main_gguf_filename(name)
+ and extract_quant_label(name).lower() == variant.lower(),
+ )
+
+ for snap, _blob, name in matched:
+ try:
+ if _path_exists_or_symlink(snap):
+ snap.unlink()
+ removed_snapshots += 1
+ except OSError as e:
+ failures.append(f"{name}: {e}")
+
+ companion_matches: list[tuple[Path, Optional[Path], str]] = []
+ if matched and not sibling_active and not _has_remaining_main_gguf(target_repo):
+ companion_matches = _repo_file_matches(
+ target_repo,
+ lambda name: _is_gguf_filename(name) and _is_mmproj_filename(name),
+ )
+ for snap, _blob, name in companion_matches:
+ try:
+ if _path_exists_or_symlink(snap):
+ snap.unlink()
+ removed_snapshots += 1
+ except OSError as e:
+ failures.append(f"{name}: {e}")
+
+ ref_counts = _snapshot_blob_reference_counts(repo_dir)
+ seen_blobs: set[Path] = set()
+ for _snap, blob, name in [*matched, *companion_matches]:
+ if blob is None:
+ continue
+ blob_hash = _blob_hash_from_path(blob)
+ if blob_hash:
+ completed_hashes.add(blob_hash)
+ try:
+ blob_key = blob.resolve()
+ except OSError:
+ blob_key = blob
+ if blob_key in seen_blobs:
+ continue
+ seen_blobs.add(blob_key)
+ if ref_counts.get(blob_key, 0) > 0:
+ continue
+ try:
+ if blob.exists():
+ deleted_bytes += blob.stat().st_size
+ blob.unlink()
+ deleted_blobs += 1
+ except OSError as e:
+ failures.append(f"{name}: {e}")
+
+ if failures:
+ raise HTTPException(
+ status_code = 409,
+ detail = (
+ f"Couldn't fully delete {variant} for {repo_id}: "
+ f"{len(failures)} file(s) are in use. "
+ "Unload the model and try again."
+ ),
+ )
+
+ incomplete_result = gguf_variants.delete_variant_incomplete_blobs_result(
+ repo_id,
+ variant,
+ hf_token,
+ extra_hashes = frozenset(completed_hashes),
+ companions = not sibling_active,
+ )
+ if incomplete_result.unresolved:
+ raise HTTPException(
+ status_code = 409,
+ detail = (
+ f"Couldn't fully delete {variant} for {repo_id}: partial "
+ "download bytes exist but this variant's blob hashes are unavailable. "
+ "Reconnect or provide access to the repo, then try again."
+ ),
+ )
+
+ state_purged = download_manifest.purge_state("model", repo_id, variant)
+ if (
+ removed_snapshots == 0
+ and deleted_blobs == 0
+ and incomplete_result.deleted == 0
+ and not state_purged
+ ):
+ raise HTTPException(
+ status_code = 404,
+ detail = f"Variant {variant} not found in cache for {repo_id}",
+ )
+
+ freed_mb = deleted_bytes / (1024 * 1024)
+ logger.info(
+ f"Deleted {removed_snapshots} file(s) for {repo_id} variant {variant}: "
+ f"{freed_mb:.1f} MB freed"
+ )
+ return {"status": "deleted", "repo_id": repo_id, "variant": variant}
+
+
+def _loaded_id_matches_repo(loaded_id: str, repo_id: str) -> bool:
+ """True when *loaded_id* is *repo_id* or a file within it; ``/``-boundary aware so ``org/model`` doesn't match sibling ``org/model-v2``."""
+ rid = repo_id.lower()
+ lid = loaded_id.lower()
+ return lid == rid or lid.startswith(f"{rid}/")
+
+
+def _loaded_repo_variant_blocks_delete(
+ loaded_id: str, repo_id: str, delete_variant: Optional[str], loaded_variant: Optional[str]
+) -> bool:
+ if not _loaded_id_matches_repo(loaded_id, repo_id):
+ return False
+ if not delete_variant:
+ return True
+ if not loaded_variant:
+ return True
+ return loaded_variant.lower() == delete_variant.lower()
+
+
+_LOAD_STATE_UNVERIFIABLE_DETAIL = (
+ "Couldn't verify whether this model is still loaded for inference. "
+ "Unload it if it is active, then try deleting again."
+)
+
+
+def _llama_cpp_blocks_delete(repo_id: str, variant: Optional[str]) -> bool:
+ """Whether the llama.cpp backend holds *repo_id* (/variant). Acquiring fails open (import error means nothing loaded); reading load state is unguarded so a raise propagates and the caller fails closed rather than delete a live model."""
+ try:
+ from routes.inference import get_llama_cpp_backend
+ backend = get_llama_cpp_backend()
+ except Exception as e:
+ logger.debug(f"llama.cpp backend unavailable during delete guard for {repo_id}: {e}")
+ return False
+ loaded_id = backend.model_identifier
+ loaded_variant = getattr(backend, "hf_variant", None)
+ if backend.is_active and not backend.is_loaded and loaded_id:
+ return _loaded_repo_variant_blocks_delete(
+ loaded_id,
+ repo_id,
+ variant,
+ loaded_variant,
+ )
+ if backend.is_loaded and loaded_id:
+ return _loaded_repo_variant_blocks_delete(
+ loaded_id,
+ repo_id,
+ variant,
+ loaded_variant,
+ )
+ return False
+
+
+def _inference_backend_blocks_delete(repo_id: str) -> bool:
+ """Whether the subprocess inference backend holds *repo_id*; same fail-open-on-acquire / surface-on-query contract as :func:`_llama_cpp_blocks_delete`."""
+ try:
+ from core.inference import get_inference_backend
+ backend = get_inference_backend()
+ except Exception as e:
+ logger.debug(f"Inference backend unavailable during delete guard for {repo_id}: {e}")
+ return False
+ active_name = backend.active_model_name
+ return bool(active_name) and _loaded_id_matches_repo(active_name, repo_id)
+
+
+async def delete_cached_model_response(
+ repo_id: str,
+ variant: Optional[str] = None,
+ hf_token: Optional[str] = None,
+):
+ """Delete a cached model repo (or a specific GGUF variant) from the HF cache.
+
+ When *variant* is provided, only the GGUF files matching that quant label
+ are removed (e.g. ``UD-Q4_K_XL``). Otherwise the entire repo is deleted.
+ Refuses if the model is currently loaded for inference.
+ """
+ if not _is_valid_repo_id(repo_id):
+ raise HTTPException(status_code = 400, detail = "Invalid repo_id format")
+ variant = (variant or "").strip() or None
+ if variant is not None and not _is_valid_gguf_variant(variant):
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Invalid gguf_variant: {variant!r}",
+ )
+
+ # Guard fails closed: if a live backend's load state can't be read, abort
+ # with 503 rather than risk unlinking weights under a running process.
+ try:
+ blocks_delete = _llama_cpp_blocks_delete(repo_id, variant) or (
+ _inference_backend_blocks_delete(repo_id)
+ )
+ except Exception as e:
+ logger.warning(f"Load-state verification failed for {repo_id}; refusing delete: {e}")
+ raise HTTPException(
+ status_code = 503,
+ detail = _LOAD_STATE_UNVERIFIABLE_DETAIL,
+ )
+ if blocks_delete:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Unload the model before deleting",
+ )
+
+ repo_key = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "model")
+ if not downloads.registry.begin_delete(repo_key, variant):
+ detail = (
+ f"Cancel the {variant} download before deleting it."
+ if variant is not None
+ else "Cancel the active downloads before deleting."
+ )
+ raise HTTPException(status_code = 400, detail = detail)
+ try:
+ return await asyncio.to_thread(_delete_cached_model_blocking, repo_id, variant, hf_token)
+ finally:
+ downloads.registry.end_delete(repo_key, variant)
+ cache_inventory.invalidate_hf_cache_scans()
+
+
+def _delete_cached_model_blocking(
+ repo_id: str, variant: Optional[str], hf_token: Optional[str]
+) -> dict:
+ try:
+ # If a sibling quant is downloading concurrently, restrict this delete to
+ # the variant's own files and leave the shared mmproj companion for it.
+ sibling_active = bool(
+ variant and downloads.registry.has_active_peer_variant(repo_id, variant)
+ )
+
+ cache_scans = cache_inventory.all_hf_cache_scans()
+
+ candidate_entries = []
+ for hf_cache in cache_scans:
+ for repo_info in hf_cache.repos:
+ if str(repo_info.repo_type) != "model":
+ continue
+ if repo_info.repo_id.lower() == repo_id.lower():
+ candidate_entries.append((hf_cache, repo_info))
+
+ matched_repo_ids = resolve_destructive_repo_ids(
+ repo_id,
+ [str(repo_info.repo_id) for _hf_cache, repo_info in candidate_entries],
+ noun = "models",
+ )
+ target_entries = [
+ (hf_cache, repo_info)
+ for hf_cache, repo_info in candidate_entries
+ if str(repo_info.repo_id) in matched_repo_ids
+ ]
+
+ if not target_entries:
+ if variant is None:
+ cache_purged = purge_repo_cache_dirs("model", repo_id) or purge_partial_repo(
+ "model", repo_id
+ )
+ state_purged = download_manifest.purge_all_state_for_repo("model", repo_id) > 0
+ if cache_purged or state_purged:
+ return {"status": "deleted", "repo_id": repo_id}
+ if variant:
+ incomplete_result = gguf_variants.delete_variant_incomplete_blobs_result(
+ repo_id,
+ variant,
+ hf_token,
+ companions = not sibling_active,
+ )
+ if incomplete_result.unresolved:
+ raise HTTPException(
+ status_code = 409,
+ detail = (
+ f"Couldn't fully delete {variant} for {repo_id}: partial "
+ "download bytes exist but this variant's blob hashes are unavailable. "
+ "Reconnect or provide access to the repo, then try again."
+ ),
+ )
+ state_purged = download_manifest.purge_state(
+ "model",
+ repo_id,
+ variant,
+ )
+ if incomplete_result.deleted > 0 or state_purged:
+ return {
+ "status": "deleted",
+ "repo_id": repo_id,
+ "variant": variant,
+ }
+ raise HTTPException(status_code = 404, detail = "Model not found in cache")
+
+ if variant:
+ return _delete_gguf_variant_from_repos(
+ repo_id,
+ variant,
+ [repo for _cache, repo in target_entries],
+ hf_token,
+ sibling_active = sibling_active,
+ )
+
+ deleted_revisions = False
+ for hf_cache, repo_info in target_entries:
+ revision_hashes = [
+ rev.commit_hash for rev in repo_info.revisions if getattr(rev, "commit_hash", None)
+ ]
+ if not revision_hashes:
+ continue
+ delete_strategy = hf_cache.delete_revisions(*revision_hashes)
+ logger.info(
+ f"Deleting cached model {repo_id} from "
+ f"{getattr(hf_cache, 'cache_dir', '<unknown>')}: "
+ f"{delete_strategy.expected_freed_size_str} will be freed"
+ )
+ delete_strategy.execute()
+ deleted_revisions = True
+
+ cache_purged = purge_repo_cache_dirs("model", repo_id)
+ partial_purged = purge_partial_repo("model", repo_id)
+ state_purged = download_manifest.purge_all_state_for_repo("model", repo_id) > 0
+
+ if not (deleted_revisions or cache_purged or partial_purged or state_purged):
+ raise HTTPException(status_code = 404, detail = "No revisions found for model")
+
+ return {"status": "deleted", "repo_id": repo_id}
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(
+ "Error deleting cached model %s: %s",
+ repo_id,
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+ raise HTTPException(
+ status_code = 500,
+ detail = "Failed to delete cached model: "
+ + download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
diff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.py
new file mode 100644
index 00000000000..db95b82c950
--- /dev/null
+++ b/studio/backend/hub/services/models/downloads.py
@@ -0,0 +1,411 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Download orchestration."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Optional, TYPE_CHECKING
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.schemas.downloads import (
+ ActiveDownloadsResponse,
+ CancelDownloadRequest,
+ DownloadJobStatus,
+ DownloadModelRequest,
+)
+from hub.utils import download_registry
+from hub.utils import download_manifest
+from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils.hf_cache_state import has_active_incomplete_blobs
+from hub.utils.paths import (
+ is_valid_gguf_variant as _is_valid_gguf_variant,
+ is_valid_repo_id as _is_valid_repo_id,
+ resolve_cached_repo_id_case,
+)
+from hub.services import snapshot_progress
+from hub.services import download_lifecycle
+from hub.services.models import cache_inventory, gguf_variants
+
+logger = get_logger(__name__)
+
+if TYPE_CHECKING:
+ import subprocess
+
+_registry = download_registry.get_models_registry()
+
+
+def _download_job_key(repo_id: str, variant: Optional[str]) -> str:
+ return download_registry.normalize_job_key(
+ f"{download_registry.normalize_repo_key(repo_id)}::{variant or ''}"
+ )
+
+
+def _job_status(
+ key: str,
+ *,
+ repo_id: Optional[str] = None,
+ variant: Optional[str] = None,
+) -> DownloadJobStatus:
+ state, error, generation = download_lifecycle.idle_status(
+ _registry,
+ key,
+ repo_type = "model",
+ repo_id = repo_id,
+ variant = variant,
+ )
+ return DownloadJobStatus(state = state, error = error, generation = generation)
+
+
+def _spawn_download_worker(
+ repo_id: str,
+ variant: Optional[str],
+ hf_token: Optional[str],
+ use_xet: bool = False,
+ protected_blob_hashes: Optional[frozenset[str]] = None,
+) -> subprocess.Popen:
+ args = ["--repo-id", repo_id]
+ if variant:
+ args.extend(["--variant", variant])
+ return download_lifecycle.spawn_worker(
+ args,
+ hf_token,
+ use_xet = use_xet,
+ protected_blob_hashes = protected_blob_hashes,
+ )
+
+
+async def download_model_response(body: DownloadModelRequest, hf_token: Optional[str] = None):
+ """Start a background download for a HuggingFace model."""
+ repo_id = body.repo_id.strip()
+ if not _is_valid_repo_id(repo_id):
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Invalid repo_id: {repo_id!r}",
+ )
+ # Canonicalize so two different-cased paste-ins share one job + cache dir.
+ repo_id = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "model")
+
+ variant = (body.gguf_variant or "").strip() or None
+ if variant is not None and not _is_valid_gguf_variant(variant):
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Invalid gguf_variant: {variant!r}",
+ )
+ key = _download_job_key(repo_id, variant)
+ transport = download_lifecycle.resolve_transport(body.use_xet)
+ variant_blob_hashes = frozenset()
+ variant_progress_blob_hashes = frozenset()
+ completed_baseline_bytes = 0
+ if variant is not None:
+ try:
+ variant_blob_hashes = await asyncio.to_thread(
+ gguf_variants.gguf_variant_blob_hashes,
+ repo_id,
+ variant,
+ hf_token,
+ include_companions = False,
+ )
+ variant_progress_blob_hashes = await asyncio.to_thread(
+ gguf_variants.gguf_variant_blob_hashes,
+ repo_id,
+ variant,
+ hf_token,
+ include_companions = True,
+ )
+ except Exception as e:
+ logger.warning(
+ "GGUF hash pre-resolution failed for %s [%s]; continuing without "
+ "a completed-bytes baseline or peer-protection hashes (the worker "
+ "re-resolves its own blobs before purging): %s",
+ repo_id,
+ variant,
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+ has_variant_resume_state = (
+ download_manifest.has_cancel_marker("model", repo_id, variant)
+ or download_manifest.read_manifest("model", repo_id, variant) is not None
+ )
+ if variant_progress_blob_hashes and not has_variant_resume_state:
+ completed_baseline_bytes = await asyncio.to_thread(
+ download_registry.completed_blob_bytes,
+ "model",
+ repo_id,
+ variant_progress_blob_hashes,
+ )
+
+ claimed, claim_state = _registry.claim(
+ key,
+ transport,
+ repo_type = "model",
+ repo_id = repo_id,
+ variant = variant,
+ blob_hashes = variant_blob_hashes,
+ progress_blob_hashes = variant_progress_blob_hashes,
+ completed_baseline_bytes = completed_baseline_bytes,
+ )
+ generation = _registry.current_generation(key)
+ if not claimed:
+ # claim_state is the blocking job's state. The client can attach only
+ # when the blocker is this key's own in-flight job (adoptable); a
+ # cross-variant conflict or in-progress delete is not accepted.
+ return {
+ "job_key": key,
+ "state": claim_state,
+ "accepted": _registry.adoptable(key),
+ "generation": generation,
+ }
+ download_manifest.clear_cancel_marker("model", repo_id, variant)
+ # Blobs a concurrent same-repo variant is already writing (e.g. a shared
+ # mmproj). The worker must not purge these during cache preparation.
+ protected_blob_hashes = _registry.peer_blob_hashes(key) if variant else frozenset()
+
+ label = f"{repo_id}{f' [{variant}]' if variant else ''}"
+ state = download_lifecycle.launch_worker(
+ _registry,
+ key,
+ spawn = lambda: _spawn_download_worker(
+ repo_id,
+ variant,
+ hf_token,
+ use_xet = body.use_xet,
+ protected_blob_hashes = protected_blob_hashes,
+ ),
+ hf_token = hf_token,
+ label = label,
+ log_prefix = "Download",
+ logger = logger,
+ repo_type = "model",
+ repo_id = repo_id,
+ transport = transport,
+ watch_name = f"hf-download-watch-{repo_id}",
+ )
+
+ return {
+ "job_key": key,
+ "state": state,
+ "accepted": True,
+ "generation": generation,
+ }
+
+
+async def cancel_download_model_response(body: CancelDownloadRequest):
+ """Cancel an in-flight model download (SIGKILL; HF cache resumes on next download)."""
+ repo_id = body.repo_id.strip()
+ if not _is_valid_repo_id(repo_id):
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Invalid repo_id: {repo_id!r}",
+ )
+ repo_id = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "model")
+ variant = (body.gguf_variant or "").strip() or None
+ if variant is not None and not _is_valid_gguf_variant(variant):
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Invalid gguf_variant: {variant!r}",
+ )
+ key = _download_job_key(repo_id, variant)
+
+ state = download_lifecycle.cancel_worker(
+ _registry,
+ key,
+ generation = body.generation,
+ label = repo_id,
+ logger = logger,
+ )
+ return {"job_key": key, "state": state}
+
+
+async def get_download_status_response(repo_id: str, gguf_variant: str = "") -> DownloadJobStatus:
+ """Return the latest state of a background download job."""
+ repo_id = repo_id.strip()
+ if not _is_valid_repo_id(repo_id):
+ return DownloadJobStatus(state = "idle")
+ repo_id = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "model")
+ variant = (gguf_variant or "").strip() or None
+ key = _download_job_key(repo_id, variant)
+ return _job_status(key, repo_id = repo_id, variant = variant)
+
+
+async def get_active_downloads_response(repo_id: str = "") -> ActiveDownloadsResponse:
+ """Return every in-flight download for a repo in a single call."""
+ repo_id = repo_id.strip()
+ if repo_id and not _is_valid_repo_id(repo_id):
+ return ActiveDownloadsResponse(downloads = [])
+ canonical_repo_id = (
+ await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "model")
+ if repo_id
+ else None
+ )
+ return ActiveDownloadsResponse(
+ downloads = download_lifecycle.active_download_refs(
+ _registry,
+ canonical_repo_id,
+ with_variant = True,
+ )
+ )
+
+
+def _variant_transport_status(repo_id: str, variant: str, hf_token: Optional[str]) -> dict:
+ incomplete_hashes = download_registry.incomplete_blob_hashes(
+ "model",
+ repo_id,
+ active_only = True,
+ )
+ variant_hashes = gguf_variants.gguf_variant_blob_hashes(
+ repo_id,
+ variant,
+ hf_token,
+ allow_remote = False,
+ )
+ has_partial = hf_cache_scan.is_variant_partial(
+ repo_id,
+ variant,
+ incomplete_blob_hashes = incomplete_hashes,
+ variant_blob_hashes = variant_hashes,
+ )
+ last_transport = hf_cache_scan.partial_transport_for("model", repo_id, variant)
+ if (
+ last_transport is None
+ and has_partial
+ and incomplete_hashes
+ and variant_hashes
+ and incomplete_hashes.intersection(variant_hashes)
+ ):
+ last_transport = download_registry.read_active_transport_marker(
+ "model",
+ repo_id,
+ variant,
+ )
+ has_matching_incomplete = bool(
+ incomplete_hashes and variant_hashes and incomplete_hashes.intersection(variant_hashes)
+ )
+ return {
+ "has_partial": has_partial,
+ "last_transport": last_transport,
+ "resumable": (
+ has_matching_incomplete and last_transport == download_registry.TRANSPORT_HTTP
+ ),
+ }
+
+
+async def get_model_transport_status_response(
+ repo_id: str,
+ gguf_variant: str = "",
+ hf_token: Optional[str] = None,
+) -> dict:
+ """Return last transport used for this repo + whether any partial blobs
+ exist + whether that partial supports byte-level resume.
+
+ ``resumable`` is True only when an HTTP partial exists. XET partials
+ are reported via ``has_partial`` but always have ``resumable=False``
+ because ``hf_xet`` rewrites the destination from scratch on every
+ call (network resume happens transparently via its chunk cache).
+ """
+ repo_id = repo_id.strip()
+ if not _is_valid_repo_id(repo_id):
+ return {"has_partial": False, "last_transport": None, "resumable": False}
+ variant = (gguf_variant or "").strip()
+ if variant:
+ if not _is_valid_gguf_variant(variant):
+ return {"has_partial": False, "last_transport": None, "resumable": False}
+ return _variant_transport_status(repo_id, variant, hf_token)
+ return {
+ "has_partial": has_active_incomplete_blobs("model", repo_id),
+ "last_transport": download_registry.read_active_transport_marker("model", repo_id),
+ "resumable": download_registry.is_resumable_partial("model", repo_id),
+ }
+
+
+async def get_gguf_download_progress_response(
+ repo_id: str,
+ variant: str = "",
+ expected_bytes: int = 0,
+ hf_token: Optional[str] = None,
+) -> dict:
+ """Return download progress for a specific GGUF variant."""
+ expected_total = max(expected_bytes, 0)
+ progress_variant = variant.strip() or None
+ if progress_variant is not None and not _is_valid_gguf_variant(progress_variant):
+ return {
+ "downloaded_bytes": 0,
+ "completed_bytes": 0,
+ "complete_on_disk": False,
+ "expected_bytes": expected_total,
+ "progress": 0,
+ "cache_path": None,
+ }
+
+ def _metadata_resolver(
+ resolved_repo_id: str, token: Optional[str]
+ ) -> tuple[int, frozenset[str]]:
+ if progress_variant is None:
+ return expected_total, frozenset()
+ requirement = gguf_variants.gguf_variant_requirements(
+ resolved_repo_id,
+ progress_variant,
+ token,
+ )
+ if requirement is not None:
+ return requirement.download_size_bytes, requirement.required_hashes
+ manifest = download_manifest.read_manifest(
+ "model",
+ resolved_repo_id,
+ progress_variant,
+ )
+ if manifest is not None:
+ return (
+ sum(max(0, int(file.size or 0)) for file in manifest.expected_files),
+ frozenset(file.sha256 for file in manifest.expected_files if file.sha256),
+ )
+ return (
+ expected_total,
+ gguf_variants.gguf_variant_blob_hashes(
+ resolved_repo_id,
+ progress_variant,
+ token,
+ allow_remote = False,
+ ),
+ )
+
+ return await snapshot_progress.snapshot_progress_response(
+ repo_type = "model",
+ repo_id = repo_id,
+ job_key = _download_job_key(repo_id, progress_variant),
+ expected_bytes = expected_total,
+ hf_token = hf_token,
+ registry = _registry,
+ metadata_resolver = _metadata_resolver,
+ variant = progress_variant,
+ )
+
+
+async def get_download_progress_response(
+ repo_id: str,
+ expected_bytes: int = 0,
+ hf_token: Optional[str] = None,
+) -> dict:
+ """Return download progress for any HuggingFace model repo.
+
+ Checks the local HF cache for completed blobs and in-progress
+ (.incomplete) downloads. Uses the caller-supplied expected total
+ when available; otherwise queries HF metadata and caches it.
+ Also returns ``cache_path``: the realpath of the snapshot directory
+ (or the cache repo root if no snapshot exists yet) so the UI can
+ show users where the weights actually live on disk.
+ """
+ return await snapshot_progress.snapshot_progress_response(
+ repo_type = "model",
+ repo_id = repo_id,
+ job_key = _download_job_key(repo_id, None),
+ expected_bytes = expected_bytes,
+ hf_token = hf_token,
+ registry = _registry,
+ metadata_resolver = cache_inventory.get_repo_snapshot_metadata_cached,
+ )
+
+
+registry = _registry
diff --git a/studio/backend/hub/services/models/folder_browser.py b/studio/backend/hub/services/models/folder_browser.py
new file mode 100644
index 00000000000..9b0b46509bb
--- /dev/null
+++ b/studio/backend/hub/services/models/folder_browser.py
@@ -0,0 +1,518 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Model folder recommendation and browsing services."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Optional
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.schemas.inventory import BrowseEntry, BrowseFoldersResponse
+from hub.storage.scan_folders import (
+ contains_sensitive_path_component,
+ list_scan_folders,
+)
+from hub.utils.paths import (
+ exports_root,
+ hf_default_cache_dir,
+ legacy_hf_cache_dir,
+ lmstudio_model_dirs,
+ normalize_path,
+ outputs_root,
+ studio_root,
+ well_known_model_dirs,
+)
+from hub.services.models.common import _safe_is_dir
+from hub.services.models.local_inventory import _resolve_hf_cache_dir
+
+logger = get_logger(__name__)
+
+
+def get_recommended_folders_response() -> dict:
+ """Return well-known model directories that exist on this machine."""
+ folders: list[str] = []
+ seen: set[str] = set()
+
+ def _add(p: Optional[Path]) -> None:
+ if p is None:
+ return
+ try:
+ resolved = str(p.resolve())
+ except OSError:
+ return
+ if resolved in seen:
+ return
+ if _safe_is_dir(resolved) and os.access(resolved, os.R_OK | os.X_OK):
+ seen.add(resolved)
+ folders.append(resolved)
+
+ try:
+ for p in lmstudio_model_dirs():
+ _add(p)
+ except Exception as e:
+ logger.warning("Failed to scan for LM Studio model directories: %s", e)
+
+ ollama_env = os.environ.get("OLLAMA_MODELS")
+ if ollama_env:
+ _add(Path(normalize_path(ollama_env)).expanduser())
+ for candidate in (
+ Path.home() / ".ollama" / "models",
+ Path("/usr/share/ollama/.ollama/models"),
+ Path("/var/lib/ollama/.ollama/models"),
+ ):
+ _add(candidate)
+
+ return {"folders": folders}
+
+
+# Ceiling on children to stat when guessing if a directory holds models.
+_BROWSE_MODEL_HINT_PROBE = 64
+# Hard cap on returned subdirectory entries so pointing at ``/usr/lib`` or
+# ``/proc`` can't stat-storm the process or flood the client.
+_BROWSE_ENTRY_CAP = 2000
+
+
+def _count_model_files(directory: Path, cap: int = 200) -> int:
+ """Count GGUF/safetensors files immediately inside *directory*, bounded by visited entries (not matches) so the hint never costs more than ``cap`` stats."""
+ n = 0
+ visited = 0
+ try:
+ for f in directory.iterdir():
+ visited += 1
+ if visited > cap:
+ break
+ try:
+ if f.is_file():
+ low = f.name.lower()
+ if low.endswith((".gguf", ".safetensors")):
+ n += 1
+ except OSError:
+ continue
+ except PermissionError as e:
+ logger.debug("browse-folders: permission denied counting %s: %s", directory, e)
+ return 0
+ except OSError as e:
+ logger.debug("browse-folders: OS error counting %s: %s", directory, e)
+ return 0
+ return n
+
+
+def _has_direct_model_signal(directory: Path) -> bool:
+ """True if an immediate child signals a model (GGUF/safetensors/config file or ``models--*`` HF-cache subdir); bounded by the hint probe."""
+ try:
+ it = directory.iterdir()
+ except OSError:
+ return False
+ try:
+ for i, child in enumerate(it):
+ if i >= _BROWSE_MODEL_HINT_PROBE:
+ break
+ try:
+ name = child.name
+ if child.is_file():
+ low = name.lower()
+ if low.endswith((".gguf", ".safetensors")):
+ return True
+ if low in ("config.json", "adapter_config.json"):
+ return True
+ elif child.is_dir() and name.startswith("models--"):
+ return True
+ except OSError:
+ continue
+ except OSError:
+ return False
+ return False
+
+
+def _looks_like_model_dir(directory: Path) -> bool:
+ """Bounded heuristic flagging dirs worth exploring (false negatives are fine; the scanner is authoritative). Three signals, cheapest first: a ``models--*`` name, a direct child signal, or a grandchild signal (LM Studio / Ollama ``publisher/model/weights.gguf`` layout)."""
+ if directory.name.startswith("models--"):
+ return True
+ if _has_direct_model_signal(directory):
+ return True
+ try:
+ it = directory.iterdir()
+ except OSError:
+ return False
+ try:
+ for i, child in enumerate(it):
+ if i >= _BROWSE_MODEL_HINT_PROBE:
+ break
+ try:
+ if not child.is_dir():
+ continue
+ except OSError:
+ continue
+ if child.name.startswith("models--"):
+ return True
+ if _has_direct_model_signal(child):
+ return True
+ except OSError:
+ return False
+ return False
+
+
+def _build_browse_allowlist() -> list[Path]:
+ """Root directories the browser may walk (also seeds the suggestion chips): HOME, resolved HF cache dirs, Studio outputs/exports/root, registered scan folders, and well-known local-LLM dirs. Each is added only if it resolves to a real directory so the sandbox has no dead boundary."""
+ from hub.storage.scan_folders import list_scan_folders
+
+ candidates: list[Path] = []
+
+ def _add(p: Optional[Path | str]) -> None:
+ if p is None:
+ return
+ try:
+ p = Path(normalize_path(str(p))).expanduser()
+ resolved = p.resolve()
+ except (OSError, RuntimeError, ValueError):
+ return
+ if _safe_is_dir(resolved):
+ candidates.append(resolved)
+
+ _add(Path.home())
+ _add(_resolve_hf_cache_dir())
+ try:
+ _add(hf_default_cache_dir())
+ except Exception: # noqa: BLE001 -- best-effort
+ pass
+ try:
+ _add(legacy_hf_cache_dir())
+ except Exception: # noqa: BLE001 -- best-effort
+ pass
+ try:
+ _add(studio_root())
+ _add(outputs_root())
+ _add(exports_root())
+ except Exception as exc: # noqa: BLE001 -- best-effort
+ logger.debug("browse-folders: studio roots unavailable: %s", exc)
+ try:
+ for folder in list_scan_folders():
+ p = folder.get("path")
+ if p:
+ _add(p)
+ except Exception as exc: # noqa: BLE001 -- best-effort
+ logger.debug("browse-folders: could not load scan folders: %s", exc)
+ try:
+ for p in well_known_model_dirs():
+ _add(p)
+ except Exception as exc: # noqa: BLE001 -- best-effort
+ logger.debug("browse-folders: well-known dirs unavailable: %s", exc)
+
+ seen: set[str] = set()
+ deduped: list[Path] = []
+ for p in candidates:
+ key = os.path.normcase(os.path.realpath(str(p)))
+ if key in seen:
+ continue
+ seen.add(key)
+ deduped.append(p)
+ return deduped
+
+
+def _is_path_inside_allowlist(target: Path, allowed_roots: list[Path]) -> bool:
+ """True if *target* equals or descends from any allowed root; uses ``os.path.realpath`` so symlinks cannot escape the sandbox."""
+ try:
+ target_real = os.path.normcase(os.path.realpath(str(target)))
+ except OSError:
+ return False
+ for root in allowed_roots:
+ try:
+ root_real = os.path.normcase(os.path.realpath(str(root)))
+ except OSError:
+ continue
+ try:
+ if os.path.commonpath([target_real, root_real]) == root_real:
+ return True
+ except ValueError:
+ continue
+ if target_real == root_real:
+ return True
+ return False
+
+
+def _normalize_browse_request_path(path: Optional[str], *, relative_root: Path) -> str:
+ """Normalize the browse request path lexically, without touching the FS."""
+ if path is None or not path.strip():
+ return os.path.normpath(str(Path.home()))
+
+ expanded = os.path.expanduser(normalize_path(path.strip()))
+ if not os.path.isabs(expanded):
+ expanded = os.path.join(str(relative_root), expanded)
+ return os.path.normpath(expanded)
+
+
+def _browse_relative_parts(requested_path: str, root: Path) -> Optional[list[str]]:
+ if "\x00" in requested_path:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Path cannot contain null bytes",
+ )
+ root_text = os.path.normcase(os.path.normpath(str(root)))
+ requested_text = os.path.normcase(os.path.normpath(requested_path))
+ try:
+ rel_text = os.path.relpath(requested_text, root_text)
+ except ValueError:
+ return None
+
+ if rel_text == ".":
+ return []
+ if rel_text == ".." or rel_text.startswith(f"..{os.sep}"):
+ return None
+
+ parts = [part for part in rel_text.split(os.sep) if part not in ("", ".")]
+ altsep = os.altsep
+ for part in parts:
+ if part == ".." or "\x00" in part or os.sep in part or (altsep and altsep in part):
+ return None
+ return parts
+
+
+def _match_browse_child(current: Path, name: str) -> Optional[Path]:
+ """Immediate child named ``name`` under ``current``, or None. ``name`` is pre-validated as a safe single component, so the join is O(1); case resolution follows OS filesystem semantics."""
+ child = current / name
+ try:
+ child.stat()
+ except (FileNotFoundError, NotADirectoryError):
+ return None
+ except PermissionError:
+ raise HTTPException(
+ status_code = 403,
+ detail = f"Permission denied reading {current}",
+ ) from None
+ except OSError as exc:
+ raise HTTPException(
+ status_code = 500,
+ detail = f"Could not read {current}: {exc}",
+ ) from exc
+ return child
+
+
+def _resolve_browse_target(path: Optional[str], allowed_roots: list[Path]) -> Path:
+ """Resolve a requested browse path by walking from trusted allowlist roots."""
+ requested_path = _normalize_browse_request_path(path, relative_root = Path.home())
+ resolved_roots: list[Path] = []
+ seen_roots: set[str] = set()
+ for root in sorted(allowed_roots, key = lambda p: len(str(p)), reverse = True):
+ try:
+ resolved = root.resolve()
+ except OSError:
+ continue
+ key = os.path.normcase(os.path.realpath(str(resolved)))
+ if key in seen_roots:
+ continue
+ seen_roots.add(key)
+ resolved_roots.append(resolved)
+
+ for root in resolved_roots:
+ parts = _browse_relative_parts(requested_path, root)
+ if parts is None:
+ continue
+
+ current = root
+ for part in parts:
+ child = _match_browse_child(current, part)
+ if child is None:
+ raise HTTPException(
+ status_code = 404,
+ detail = f"Path does not exist: {requested_path}",
+ )
+ try:
+ resolved_child = child.resolve()
+ except OSError as exc:
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Invalid path: {exc}",
+ ) from exc
+ if not _is_path_inside_allowlist(resolved_child, resolved_roots):
+ raise HTTPException(
+ status_code = 403,
+ detail = (
+ "Path is not in the browseable allowlist. Register it via "
+ "POST /api/hub/scan-folders first, or pick a directory "
+ "under your home folder."
+ ),
+ )
+ # HOME is in the allowlist, so without this denylist (same one
+ # registration enforces) a user could browse into ~/.ssh, ~/.aws, etc.
+ if contains_sensitive_path_component(str(resolved_child)):
+ raise HTTPException(
+ status_code = 403,
+ detail = "Credential or configuration directories are not browseable.",
+ )
+ current = resolved_child
+
+ if not current.is_dir():
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Not a directory: {current}",
+ )
+ return current
+
+ raise HTTPException(
+ status_code = 403,
+ detail = (
+ "Path is not in the browseable allowlist. Register it via "
+ "POST /api/hub/scan-folders first, or pick a directory "
+ "under your home folder."
+ ),
+ )
+
+
+def browse_folders_response(
+ path: Optional[str] = None, show_hidden: bool = False
+) -> BrowseFoldersResponse:
+ """List immediate subdirectories of *path* for the Custom Folders picker.
+
+ Requests are bounded to the :func:`_build_browse_allowlist` roots; paths
+ outside it return 403 (symlinks resolved via realpath first, so traversal
+ can't escape). Sorting: model-bearing dirs first, then plain, then hidden.
+ """
+ from hub.storage.scan_folders import list_scan_folders
+
+ # Build the allowlist once -- the sandbox check and suggestion chips share
+ # it so chips are always navigable.
+ allowed_roots = _build_browse_allowlist()
+
+ try:
+ target = _resolve_browse_target(path, allowed_roots)
+ except HTTPException:
+ requested_path = _normalize_browse_request_path(
+ path,
+ relative_root = Path.home(),
+ )
+ if path is not None and path.strip():
+ logger.warning(
+ "browse-folders: rejected path %r (normalized=%s)",
+ path,
+ requested_path,
+ )
+ raise
+
+ # Enumerate immediate subdirectories with a bounded cap so a stray
+ # query against ``/usr/lib`` or ``/proc`` can't stat-storm the process.
+ entries: list[BrowseEntry] = []
+ truncated = False
+ visited = 0
+ try:
+ it = target.iterdir()
+ except PermissionError:
+ raise HTTPException(
+ status_code = 403,
+ detail = f"Permission denied reading {target}",
+ )
+ except OSError as exc:
+ raise HTTPException(
+ status_code = 500,
+ detail = f"Could not read {target}: {exc}",
+ )
+
+ try:
+ for child in it:
+ # Bound by visited entries, not appended ones, so a directory full
+ # of files still caps work at ``_BROWSE_ENTRY_CAP`` stats.
+ visited += 1
+ if visited > _BROWSE_ENTRY_CAP:
+ truncated = True
+ break
+ try:
+ if not child.is_dir():
+ continue
+ except OSError:
+ continue
+ name = child.name
+ is_hidden = name.startswith(".")
+ if is_hidden and not show_hidden:
+ continue
+ # Don't surface credential/config dirs even with show_hidden:
+ # descending into them is refused and registration rejects them.
+ if contains_sensitive_path_component(name):
+ continue
+ entries.append(
+ BrowseEntry(
+ name = name,
+ has_models = _looks_like_model_dir(child),
+ hidden = is_hidden,
+ )
+ )
+ except PermissionError as exc:
+ logger.debug(
+ "browse-folders: permission denied during enumeration of %s: %s",
+ target,
+ exc,
+ )
+ except OSError as exc:
+ # Rare: iterdir succeeded but reading a specific entry failed.
+ logger.warning("browse-folders: partial enumeration of %s: %s", target, exc)
+
+ # Model-bearing dirs first, then plain, then hidden; case-insensitive
+ # alphabetical within each bucket.
+ def _sort_key(e: BrowseEntry) -> tuple[int, str]:
+ bucket = 0 if e.has_models else (2 if e.hidden else 1)
+ return (bucket, e.name.lower())
+
+ entries.sort(key = _sort_key)
+
+ # Parent is None at the FS root and when it would step outside the sandbox,
+ # so the up-row never 403s on click.
+ parent: Optional[str]
+ if target.parent == target or not _is_path_inside_allowlist(target.parent, allowed_roots):
+ parent = None
+ else:
+ parent = str(target.parent)
+
+ # Handy starting points for the quick-pick chips.
+ suggestions: list[str] = []
+ seen_sug: set[str] = set()
+
+ def _add_sug(p: Optional[Path | str]) -> None:
+ if p is None:
+ return
+ try:
+ p = Path(normalize_path(str(p))).expanduser()
+ resolved = str(p.resolve())
+ except (OSError, RuntimeError, ValueError):
+ return
+ if resolved in seen_sug:
+ return
+ if _safe_is_dir(resolved):
+ seen_sug.add(resolved)
+ suggestions.append(resolved)
+
+ # Home first as the safe fallback.
+ _add_sug(Path.home())
+ # The HF cache root in use (honors HF_HOME / HF_HUB_CACHE), then the default.
+ try:
+ _add_sug(_resolve_hf_cache_dir())
+ except Exception:
+ pass
+ try:
+ _add_sug(hf_default_cache_dir())
+ except Exception:
+ pass
+ # Already-registered scan folders (what the user has curated).
+ try:
+ for folder in list_scan_folders():
+ _add_sug(folder.get("path", ""))
+ except Exception as exc:
+ logger.debug("browse-folders: could not load scan folders: %s", exc)
+ # Well-known third-party dirs (LM Studio, Ollama, ~/models). Each helper
+ # only returns existing paths so we never show dead chips.
+ try:
+ for p in well_known_model_dirs():
+ _add_sug(p)
+ except Exception as exc:
+ logger.debug("browse-folders: could not load well-known dirs: %s", exc)
+
+ return BrowseFoldersResponse(
+ current = str(target),
+ parent = parent,
+ entries = entries,
+ suggestions = suggestions,
+ truncated = truncated,
+ model_files_here = _count_model_files(target),
+ )
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.py
new file mode 100644
index 00000000000..efe6bdf6c4a
--- /dev/null
+++ b/studio/backend/hub/services/models/gguf_variants.py
@@ -0,0 +1,643 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""GGUF variant resolution."""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+import time
+from collections import OrderedDict
+from typing import NamedTuple, Optional
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.schemas.inventory import GgufVariantDetail, GgufVariantsResponse
+from hub.utils import download_manifest
+from hub.utils import download_registry
+from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils.hf_errors import hf_error_status
+from hub.utils.hf_cache_state import (
+ INCOMPLETE_SUFFIX,
+ iter_destructive_repo_cache_dirs,
+)
+from hub.utils.gguf import (
+ extract_quant_label,
+ iter_hf_cache_snapshots,
+ list_gguf_variants,
+ list_gguf_variants_from_hf_cache,
+ list_local_gguf_variants,
+ list_partial_gguf_variants_from_state,
+ pick_best_gguf,
+)
+from hub.utils.paths import (
+ is_local_path,
+ is_valid_repo_id as _is_valid_repo_id,
+)
+from hub.services.models.common import (
+ _is_mmproj_filename,
+ _iter_gguf_paths,
+)
+from hub.utils.gguf_plan import (
+ GgufVariantPlan as _GgufVariantRequirement,
+ build_gguf_variant_plans,
+ is_main_gguf_variant_path,
+)
+
+logger = get_logger(__name__)
+
+_VARIANT_HASH_CACHE: "OrderedDict[tuple[str, str, str, bool], tuple[frozenset[str], float]]" = (
+ OrderedDict()
+)
+_VARIANT_REQUIREMENT_CACHE: "OrderedDict[tuple[str, str, str], tuple[_GgufVariantRequirement, float]]" = OrderedDict()
+_VARIANT_REQUIREMENT_NEG_CACHE: "OrderedDict[tuple[str, str], float]" = OrderedDict()
+_VARIANT_HASH_MAX = 512
+# Blob hashes are derived from the same mutable remote revision metadata as
+# variant requirements, so they must not outlive that freshness window.
+_VARIANT_HASH_POS_TTL = 60.0
+# Refresh resolved variant requirements so a moved repo revision is picked up
+# within the session instead of being pinned for the backend's lifetime.
+_VARIANT_REQUIREMENT_POS_TTL = 60.0
+# Suppress retries on a metadata-fetch failure so a slow/flaky link doesn't
+# re-hammer the API on every page refresh.
+_VARIANT_REQUIREMENT_NEG_TTL = 60.0
+# Fail fast on a slow link so the variant render isn't blocked for seconds.
+_GGUF_METADATA_TIMEOUT_SECONDS = 5.0
+_VARIANT_HASH_LOCK = threading.Lock()
+
+
+class VariantIncompleteDeleteResult(NamedTuple):
+ deleted: int
+ unresolved: bool
+
+
+def _variant_hash_cache_key(
+ repo_id: str, variant: str, hf_token: Optional[str]
+) -> tuple[str, str, str]:
+ return (
+ repo_id.lower(),
+ variant.lower(),
+ hf_cache_scan.token_fingerprint(hf_token),
+ )
+
+
+def _variant_blob_hash_cache_key(
+ repo_id: str, variant: str, hf_token: Optional[str], include_companions: bool
+) -> tuple[str, str, str, bool]:
+ base = _variant_hash_cache_key(repo_id, variant, hf_token)
+ return (*base, include_companions)
+
+
+def _variant_repo_cache_key(repo_id: str, hf_token: Optional[str]) -> tuple[str, str]:
+ return (repo_id.lower(), hf_cache_scan.token_fingerprint(hf_token))
+
+
+def _variant_requirement_neg_cache_active(key: tuple[str, str]) -> bool:
+ with _VARIANT_HASH_LOCK:
+ cached_at = _VARIANT_REQUIREMENT_NEG_CACHE.get(key)
+ if cached_at is None:
+ return False
+ if (time.monotonic() - cached_at) < _VARIANT_REQUIREMENT_NEG_TTL:
+ _VARIANT_REQUIREMENT_NEG_CACHE.move_to_end(key)
+ return True
+ _VARIANT_REQUIREMENT_NEG_CACHE.pop(key, None)
+ return False
+
+
+def _variant_requirement_neg_cache_set(key: tuple[str, str]) -> None:
+ with _VARIANT_HASH_LOCK:
+ _VARIANT_REQUIREMENT_NEG_CACHE[key] = time.monotonic()
+ _VARIANT_REQUIREMENT_NEG_CACHE.move_to_end(key)
+ while len(_VARIANT_REQUIREMENT_NEG_CACHE) > _VARIANT_HASH_MAX:
+ _VARIANT_REQUIREMENT_NEG_CACHE.popitem(last = False)
+
+
+def _variant_requirement_neg_cache_clear(key: tuple[str, str]) -> None:
+ with _VARIANT_HASH_LOCK:
+ _VARIANT_REQUIREMENT_NEG_CACHE.pop(key, None)
+
+
+def _variant_hash_cache_get(key: tuple[str, str, str, bool]) -> Optional[frozenset[str]]:
+ with _VARIANT_HASH_LOCK:
+ cached = _VARIANT_HASH_CACHE.get(key)
+ if cached is None:
+ return None
+ hashes, ts = cached
+ if (time.monotonic() - ts) >= _VARIANT_HASH_POS_TTL:
+ _VARIANT_HASH_CACHE.pop(key, None)
+ return None
+ _VARIANT_HASH_CACHE.move_to_end(key)
+ return hashes
+
+
+def _variant_hash_cache_set(key: tuple[str, str, str, bool], hashes: frozenset[str]) -> None:
+ with _VARIANT_HASH_LOCK:
+ _VARIANT_HASH_CACHE[key] = (hashes, time.monotonic())
+ _VARIANT_HASH_CACHE.move_to_end(key)
+ while len(_VARIANT_HASH_CACHE) > _VARIANT_HASH_MAX:
+ _VARIANT_HASH_CACHE.popitem(last = False)
+
+
+def _variant_requirement_cache_get(key: tuple[str, str, str]) -> Optional[_GgufVariantRequirement]:
+ with _VARIANT_HASH_LOCK:
+ cached = _VARIANT_REQUIREMENT_CACHE.get(key)
+ if cached is None:
+ return None
+ requirement, ts = cached
+ if (time.monotonic() - ts) >= _VARIANT_REQUIREMENT_POS_TTL:
+ _VARIANT_REQUIREMENT_CACHE.pop(key, None)
+ return None
+ _VARIANT_REQUIREMENT_CACHE.move_to_end(key)
+ return requirement
+
+
+def _variant_requirement_cache_set_many(
+ repo_id: str, hf_token: Optional[str], requirements: dict[str, _GgufVariantRequirement]
+) -> None:
+ with _VARIANT_HASH_LOCK:
+ now = time.monotonic()
+ for quant, requirement in requirements.items():
+ key = _variant_hash_cache_key(repo_id, quant, hf_token)
+ _VARIANT_REQUIREMENT_CACHE[key] = (requirement, now)
+ _VARIANT_REQUIREMENT_CACHE.move_to_end(key)
+ while len(_VARIANT_REQUIREMENT_CACHE) > _VARIANT_HASH_MAX:
+ _VARIANT_REQUIREMENT_CACHE.popitem(last = False)
+
+
+def _build_gguf_variant_requirements(siblings: list) -> dict[str, _GgufVariantRequirement]:
+ return build_gguf_variant_plans(siblings)
+
+
+def gguf_variant_requirements(
+ repo_id: str,
+ variant: str,
+ hf_token: Optional[str] = None,
+) -> Optional[_GgufVariantRequirement]:
+ key = _variant_hash_cache_key(repo_id, variant, hf_token)
+ cached = _variant_requirement_cache_get(key)
+ if cached is not None:
+ return cached
+ requirements = _fetch_gguf_variant_requirements(repo_id, hf_token)
+ return requirements.get(variant.lower())
+
+
+def _fetch_gguf_variant_requirements(
+ repo_id: str,
+ hf_token: Optional[str] = None,
+ *,
+ siblings: Optional[list] = None,
+) -> dict[str, _GgufVariantRequirement]:
+ repo_key = _variant_repo_cache_key(repo_id, hf_token)
+ if siblings is None:
+ if _variant_requirement_neg_cache_active(repo_key):
+ return {}
+ try:
+ from huggingface_hub import HfApi
+ info = HfApi(token = hf_token).model_info(
+ repo_id,
+ files_metadata = True,
+ timeout = _GGUF_METADATA_TIMEOUT_SECONDS,
+ )
+ except Exception as e:
+ logger.warning(
+ "model_info failed resolving GGUF files for %s: %s",
+ repo_id,
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+ _variant_requirement_neg_cache_set(repo_key)
+ return {}
+ siblings = list(info.siblings)
+ requirements = _build_gguf_variant_requirements(siblings)
+ if requirements:
+ _variant_requirement_cache_set_many(repo_id, hf_token, requirements)
+ _variant_requirement_neg_cache_clear(repo_key)
+ return requirements
+
+
+def _gguf_all_variant_requirements(
+ repo_id: str,
+ hf_token: Optional[str] = None,
+ *,
+ siblings: Optional[list] = None,
+) -> dict[str, _GgufVariantRequirement]:
+ return _fetch_gguf_variant_requirements(repo_id, hf_token, siblings = siblings)
+
+
+def _manifest_variant_blob_hashes(
+ repo_id: str,
+ variant: str,
+ *,
+ include_companions: bool = True,
+) -> frozenset[str]:
+ manifest = download_manifest.read_manifest("model", repo_id, variant)
+ if manifest is None:
+ return frozenset()
+ variant_key = variant.lower()
+ hashes: set[str] = set()
+ for expected in manifest.expected_files:
+ if not expected.sha256:
+ continue
+ if include_companions:
+ hashes.add(expected.sha256)
+ continue
+ if is_main_gguf_variant_path(expected.path, variant_key):
+ hashes.add(expected.sha256)
+ return frozenset(hashes)
+
+
+def gguf_variant_blob_hashes(
+ repo_id: str,
+ variant: str,
+ hf_token: Optional[str] = None,
+ *,
+ include_companions: bool = True,
+ allow_remote: bool = True,
+) -> frozenset[str]:
+ key = _variant_blob_hash_cache_key(
+ repo_id,
+ variant,
+ hf_token,
+ include_companions,
+ )
+ cached = _variant_hash_cache_get(key)
+ if cached is not None:
+ return cached
+ hashes = _manifest_variant_blob_hashes(
+ repo_id,
+ variant,
+ include_companions = include_companions,
+ )
+ if hashes:
+ _variant_hash_cache_set(key, hashes)
+ return hashes
+ requirement_key = _variant_hash_cache_key(repo_id, variant, hf_token)
+ requirement = _variant_requirement_cache_get(requirement_key)
+ if requirement is None and allow_remote:
+ requirement = gguf_variant_requirements(repo_id, variant, hf_token)
+ if requirement is not None:
+ hashes = requirement.required_hashes if include_companions else requirement.main_hashes
+ if hashes:
+ _variant_hash_cache_set(key, hashes)
+ return hashes
+ return frozenset()
+
+
+def _partial_transport_for_variant(repo_id: str, variant: str) -> Optional[str]:
+ return hf_cache_scan.partial_transport_for("model", repo_id, variant)
+
+
+def delete_variant_incomplete_blobs_result(
+ repo_id: str,
+ variant: str,
+ hf_token: Optional[str],
+ *,
+ extra_hashes: frozenset[str] = frozenset(),
+ companions: bool = True,
+) -> VariantIncompleteDeleteResult:
+ # With a sibling still downloading, ``companions=False`` keeps a shared mmproj
+ # from being unlinked out from under it; the repo's last delete reclaims it.
+ target_hashes = (
+ gguf_variant_blob_hashes(repo_id, variant, hf_token, include_companions = companions)
+ | extra_hashes
+ )
+ if not target_hashes:
+ has_variant_partial_state = hf_cache_scan.is_variant_partial(
+ repo_id,
+ variant,
+ incomplete_blob_hashes = set(),
+ variant_blob_hashes = frozenset(),
+ )
+ has_repo_partials = bool(download_registry.incomplete_blob_hashes("model", repo_id))
+ return VariantIncompleteDeleteResult(
+ deleted = 0,
+ unresolved = has_variant_partial_state and has_repo_partials,
+ )
+ deleted = 0
+ # Destructive iterator: only the exact-case match (or abort if ambiguous),
+ # so a case-variant sibling repo's partials are never unlinked.
+ for entry in iter_destructive_repo_cache_dirs("model", repo_id):
+ blobs_dir = entry / "blobs"
+ if not blobs_dir.is_dir():
+ continue
+ for h in target_hashes:
+ incomplete = blobs_dir / f"{h}{INCOMPLETE_SUFFIX}"
+ if incomplete.exists():
+ try:
+ incomplete.unlink()
+ deleted += 1
+ except OSError as e:
+ logger.warning(f"Failed to unlink {incomplete}: {e}")
+ return VariantIncompleteDeleteResult(deleted = deleted, unresolved = False)
+
+
+async def get_gguf_variants_response(
+ repo_id: str,
+ prefer_local_cache: bool = False,
+ offline: bool = False,
+ local_path: Optional[str] = None,
+ hf_token: Optional[str] = None,
+):
+ """
+ List available GGUF quantization variants for a HuggingFace repo
+ or a local directory (e.g. LM Studio model folder).
+
+ Returns all available quantization variants (Q4_K_M, Q8_0, BF16, etc.)
+ with file sizes, whether the model supports vision, and the recommended
+ default variant.
+ """
+
+ def _compute() -> GgufVariantsResponse:
+ def _local_response(
+ response_repo_id: str, variants, has_vision: bool
+ ) -> GgufVariantsResponse:
+ filenames = [v.filename for v in variants]
+ best = pick_best_gguf(filenames)
+ default_variant = extract_quant_label(best) if best else None
+ return GgufVariantsResponse(
+ repo_id = response_repo_id,
+ variants = [
+ GgufVariantDetail(
+ filename = v.filename,
+ quant = v.quant,
+ display_label = v.display_label,
+ size_bytes = v.size_bytes,
+ download_size_bytes = v.size_bytes,
+ downloaded = True,
+ )
+ for v in variants
+ ],
+ has_vision = has_vision,
+ default_variant = default_variant,
+ )
+
+ def _partial_local_response(
+ response_repo_id: str, variants, has_vision: bool
+ ) -> GgufVariantsResponse:
+ filenames = [v.filename for v in variants]
+ best = pick_best_gguf(filenames)
+ default_variant = extract_quant_label(best) if best else None
+ return GgufVariantsResponse(
+ repo_id = response_repo_id,
+ variants = [
+ GgufVariantDetail(
+ filename = v.filename,
+ quant = v.quant,
+ display_label = v.display_label,
+ size_bytes = v.size_bytes,
+ download_size_bytes = v.download_size_bytes or v.size_bytes,
+ downloaded = False,
+ partial = True,
+ partial_transport = _partial_transport_for_variant(
+ response_repo_id,
+ v.quant,
+ ),
+ )
+ for v in variants
+ ],
+ has_vision = has_vision,
+ default_variant = default_variant,
+ )
+
+ # Local directory path (e.g. LM Studio models) — scan filesystem
+ if is_local_path(repo_id):
+ variants, has_vision = list_local_gguf_variants(repo_id)
+
+ return _local_response(repo_id, variants, has_vision)
+
+ # Reject invalid remote repo_ids up front (like download/delete) so a
+ # malformed id returns 400 instead of a 500 from the HF client.
+ if not _is_valid_repo_id(repo_id):
+ raise HTTPException(status_code = 400, detail = f"Invalid repo_id: {repo_id!r}")
+
+ local_only = prefer_local_cache or offline
+ if local_only:
+ cached = list_gguf_variants_from_hf_cache(repo_id)
+ if cached is not None:
+ variants, has_vision = cached
+ return _local_response(repo_id, variants, has_vision)
+ if local_path and is_local_path(local_path):
+ variants, has_vision = list_local_gguf_variants(local_path)
+ if variants or has_vision:
+ return _local_response(repo_id, variants, has_vision)
+ partial = list_partial_gguf_variants_from_state(repo_id)
+ if partial is not None:
+ variants, has_vision = partial
+ return _partial_local_response(repo_id, variants, has_vision)
+ if local_path and offline:
+ return GgufVariantsResponse(
+ repo_id = repo_id,
+ variants = [],
+ has_vision = False,
+ default_variant = None,
+ )
+ if offline:
+ raise HTTPException(
+ status_code = 404,
+ detail = "No cached GGUF variants available while offline.",
+ )
+
+ try:
+ variants, has_vision, siblings = list_gguf_variants(repo_id, hf_token = hf_token)
+ except Exception:
+ cached = list_gguf_variants_from_hf_cache(repo_id)
+ if cached is not None:
+ variants, has_vision = cached
+ return _local_response(repo_id, variants, has_vision)
+ partial = list_partial_gguf_variants_from_state(repo_id)
+ if partial is not None:
+ variants, has_vision = partial
+ return _partial_local_response(repo_id, variants, has_vision)
+ raise
+
+ filenames = [v.filename for v in variants]
+ best = pick_best_gguf(filenames)
+ default_variant = extract_quant_label(best) if best else None
+
+ # Per-snapshot accounting: a variant counts as present only when one
+ # snapshot holds all its files (split GGUFs need every shard together),
+ # sizes are max across snapshots so shared blobs aren't double-counted,
+ # and keys are lowercased since cache dir casing can differ from repo_id.
+ cached_filenames_by_snapshot: list[dict[str, int]] = []
+ cached_quant_bytes_by_snapshot: list[dict[str, int]] = []
+ if _is_valid_repo_id(repo_id):
+ for snap in iter_hf_cache_snapshots(repo_id):
+ try:
+ gguf_paths = list(_iter_gguf_paths(snap))
+ except (OSError, RuntimeError, ValueError) as e:
+ logger.debug("Skipping GGUF cache snapshot %s: %s", snap, e)
+ continue
+ by_filename: dict[str, int] = {}
+ by_quant: dict[str, int] = {}
+ for f in gguf_paths:
+ try:
+ rel = f.relative_to(snap).as_posix()
+ size = f.stat().st_size
+ except (OSError, RuntimeError, ValueError) as e:
+ logger.debug("Skipping GGUF cache file %s: %s", f, e)
+ continue
+ key = rel.lower()
+ by_filename[key] = max(by_filename.get(key, 0), size)
+ if _is_mmproj_filename(f.name):
+ continue
+ q = extract_quant_label(rel).lower()
+ by_quant[q] = by_quant.get(q, 0) + size
+ if by_filename:
+ cached_filenames_by_snapshot.append(by_filename)
+ if by_quant:
+ cached_quant_bytes_by_snapshot.append(by_quant)
+
+ requirements_by_quant = {
+ v.quant.lower(): _variant_requirement_cache_get(
+ _variant_hash_cache_key(repo_id, v.quant, hf_token)
+ )
+ for v in variants
+ }
+ if any(req is None for req in requirements_by_quant.values()):
+ fetched_requirements = _gguf_all_variant_requirements(
+ repo_id, hf_token, siblings = siblings
+ )
+ for v in variants:
+ key = v.quant.lower()
+ if requirements_by_quant.get(key) is None:
+ requirements_by_quant[key] = fetched_requirements.get(key)
+
+ def _filenames_cached(filenames: frozenset[str], expected_size: int) -> bool:
+ if not filenames:
+ return False
+ wanted = [name.lower() for name in filenames]
+ # All files must live in a single snapshot, not spread across several.
+ for by_filename in cached_filenames_by_snapshot:
+ cached = 0
+ for name in wanted:
+ size = by_filename.get(name)
+ if size is None:
+ break
+ cached += size
+ else:
+ return expected_size <= 0 or cached >= expected_size * 0.99
+ return False
+
+ def _any_mmproj_cached(filenames: frozenset[str]) -> bool:
+ return any(
+ by_filename.get(name.lower()) is not None
+ for by_filename in cached_filenames_by_snapshot
+ for name in filenames
+ )
+
+ def _is_fully_downloaded(variant) -> bool:
+ requirement = requirements_by_quant.get(variant.quant.lower())
+ if requirement is None:
+ if variant.size_bytes == 0:
+ return False
+ quant = variant.quant.lower()
+ # Allow small rounding tolerance (symlinks vs real sizes).
+ return any(
+ by_quant.get(quant, 0) >= variant.size_bytes * 0.99
+ for by_quant in cached_quant_bytes_by_snapshot
+ )
+ if not _filenames_cached(
+ requirement.main_filenames,
+ requirement.main_size_bytes,
+ ):
+ return False
+ # Vision repos ship an mmproj adapter per variant. Any mmproj
+ # precision on disk suffices (the loader picks whichever is present);
+ # requiring the API-preferred one would falsely demote variants.
+ if requirement.mmproj_filenames and not _any_mmproj_cached(
+ requirement.mmproj_filenames,
+ ):
+ return False
+ return True
+
+ partial_quants: set[str] = set()
+ partial_quant_transports: dict[str, Optional[str]] = {}
+ try:
+ incomplete_hashes = download_registry.incomplete_blob_hashes("model", repo_id)
+ except Exception as e:
+ logger.warning(f"Failed to compute partial GGUF variants for {repo_id}: {e}")
+ incomplete_hashes = set()
+ scan_snapshot_dir = hf_cache_scan.resolve_snapshot_dir_for_scan("model", repo_id)
+ # Manifest + marker + main incomplete-blob check: catches variants whose
+ # download was cancelled or whose expected shards are missing/undersized.
+ for variant in variants:
+ try:
+ requirement = requirements_by_quant.get(variant.quant.lower())
+ variant_hashes = requirement.main_hashes if requirement is not None else None
+ if variant_hashes is None and incomplete_hashes:
+ variant_hashes = gguf_variant_blob_hashes(
+ repo_id,
+ variant.quant,
+ hf_token,
+ include_companions = False,
+ )
+ if hf_cache_scan.is_variant_partial(
+ repo_id,
+ variant.quant,
+ scan_snapshot_dir,
+ incomplete_blob_hashes = incomplete_hashes,
+ variant_blob_hashes = variant_hashes,
+ ):
+ partial_quants.add(variant.quant)
+ partial_quant_transports[variant.quant] = _partial_transport_for_variant(
+ repo_id,
+ variant.quant,
+ )
+ except Exception as e:
+ logger.warning(
+ f"Manifest-based partial check failed for " f"{repo_id}/{variant.quant}: {e}"
+ )
+ if incomplete_hashes:
+ for variant in variants:
+ requirement = requirements_by_quant.get(variant.quant.lower())
+ if requirement is None:
+ continue
+ if requirement.mmproj_hashes & incomplete_hashes and _filenames_cached(
+ requirement.main_filenames,
+ requirement.main_size_bytes,
+ ):
+ partial_quants.add(variant.quant)
+ partial_quant_transports.setdefault(
+ variant.quant,
+ _partial_transport_for_variant(repo_id, variant.quant),
+ )
+
+ def _variant_detail(v) -> GgufVariantDetail:
+ is_partial = v.quant in partial_quants
+ requirement = requirements_by_quant.get(v.quant.lower())
+ return GgufVariantDetail(
+ filename = v.filename,
+ quant = v.quant,
+ display_label = v.display_label,
+ size_bytes = v.size_bytes,
+ download_size_bytes = (
+ requirement.download_size_bytes if requirement is not None else v.size_bytes
+ ),
+ downloaded = _is_fully_downloaded(v) and not is_partial,
+ partial = is_partial,
+ partial_transport = (partial_quant_transports.get(v.quant) if is_partial else None),
+ )
+
+ return GgufVariantsResponse(
+ repo_id = repo_id,
+ variants = [_variant_detail(v) for v in variants],
+ has_vision = has_vision,
+ default_variant = default_variant,
+ )
+
+ try:
+ return await asyncio.to_thread(_compute)
+ except HTTPException:
+ raise
+ except Exception as e:
+ scrubbed = download_registry.scrub_secrets(str(e), hf_token = hf_token)
+ # Client-side HF error (missing repo, gated, bad token): pass the status through.
+ status = hf_error_status(e)
+ if status is not None:
+ raise HTTPException(status_code = status, detail = scrubbed)
+ logger.error("Error listing GGUF variants for %s: %s", repo_id, scrubbed)
+ raise HTTPException(
+ status_code = 500,
+ detail = "Failed to list GGUF variants: " + scrubbed,
+ )
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
new file mode 100644
index 00000000000..6e6a28b9198
--- /dev/null
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -0,0 +1,679 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Local model, HF cache, LM Studio, and Ollama inventory services.
+
+Ollama logic lives in :mod:`hub.services.models.ollama`; this module
+orchestrates all on-device sources and exposes the route handlers.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+from pathlib import Path
+from typing import List, Optional
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.schemas.inventory import LocalModelInfo, LocalModelListResponse, ModelFormat
+from hub.storage.scan_folders import (
+ add_scan_folder,
+ list_scan_folders,
+ remove_scan_folder,
+)
+from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils.paths import (
+ hf_default_cache_dir,
+ legacy_hf_cache_dir,
+ lmstudio_model_dirs,
+ normalize_path,
+ ollama_model_dirs,
+ outputs_root,
+ path_is_same_or_child,
+ studio_root,
+)
+from hub.services.models import common as model_common
+from hub.services.models.ollama import scan_ollama_dir
+
+logger = get_logger(__name__)
+_MAX_MODELS_PER_CUSTOM_FOLDER = 200
+_MAX_CUSTOM_FOLDER_ENTRIES = 2000
+_MODEL_SIGNAL_PROBE_LIMIT = 200
+
+# Local aliases keep the extracted code close to the original implementation.
+_is_model_directory = model_common._is_model_directory
+_local_inventory_id = model_common._local_inventory_id
+_local_model_info = model_common._local_model_info
+_capabilities_for_format = model_common._capabilities_for_format
+_apply_format_aware_partial = model_common._apply_format_aware_partial
+_classify_local_path = model_common._classify_local_path
+_is_main_gguf_filename = model_common._is_main_gguf_filename
+_is_transformers_bin_weight_file = model_common._is_transformers_bin_weight_file
+_prefer_complete_larger = model_common._prefer_complete_larger
+_gguf_variant_state_summary = model_common._gguf_variant_state_summary
+
+
+def _is_immediate_model_weight_file(path: Path) -> bool:
+ suffix = path.suffix.lower()
+ if suffix == ".safetensors":
+ return True
+ if suffix == ".gguf":
+ return _is_main_gguf_filename(path.name)
+ if suffix == ".bin":
+ return _is_transformers_bin_weight_file(path)
+ return False
+
+
+def _has_immediate_model_weight(
+ path: Path, *, probe_limit: int = _MODEL_SIGNAL_PROBE_LIMIT
+) -> bool:
+ try:
+ for index, entry in enumerate(path.iterdir(), start = 1):
+ if index > probe_limit:
+ break
+ try:
+ if entry.is_file() and _is_immediate_model_weight_file(entry):
+ return True
+ except OSError:
+ continue
+ except OSError:
+ return False
+ return False
+
+
+def _has_immediate_model_signal(
+ path: Path, *, probe_limit: int = _MODEL_SIGNAL_PROBE_LIMIT
+) -> bool:
+ try:
+ if (path / "config.json").exists() or (path / "adapter_config.json").exists():
+ return True
+ except OSError:
+ return False
+ return _has_immediate_model_weight(path, probe_limit = probe_limit)
+
+
+def _is_model_directory_for_scan(path: Path, *, entry_limit: int | None) -> bool:
+ if entry_limit is None:
+ return _is_model_directory(path)
+ try:
+ has_config = (path / "config.json").exists() or (path / "adapter_config.json").exists()
+ except OSError:
+ return False
+ return has_config and _has_immediate_model_weight(path)
+
+
+def _resolve_hf_cache_dir() -> Path:
+ try:
+ from huggingface_hub.constants import HF_HUB_CACHE
+ return Path(HF_HUB_CACHE)
+ except Exception:
+ return Path.home() / ".cache" / "huggingface" / "hub"
+
+
+def _scan_models_dir(
+ models_dir: Path,
+ *,
+ limit: int | None = None,
+ entry_limit: int | None = None,
+) -> List[LocalModelInfo]:
+ if not models_dir.exists() or not models_dir.is_dir():
+ return []
+
+ _is_self_model = _is_model_directory_for_scan(
+ models_dir,
+ entry_limit = entry_limit,
+ )
+
+ if _is_self_model:
+ try:
+ updated_at = models_dir.stat().st_mtime
+ except OSError:
+ updated_at = None
+ return _classify_local_path(
+ models_dir,
+ "models_dir",
+ updated_at = updated_at,
+ )
+
+ found: List[LocalModelInfo] = []
+ visited = 0
+ try:
+ children = models_dir.iterdir()
+ except OSError:
+ return found
+ for child in children:
+ if limit is not None and len(found) >= limit:
+ break
+ visited += 1
+ if entry_limit is not None and visited > entry_limit:
+ break
+ try:
+ is_dir = child.is_dir()
+ is_gguf_file = not is_dir and child.suffix.lower() == ".gguf" and child.is_file()
+ if not is_dir and not is_gguf_file:
+ continue
+ has_model_files = is_gguf_file or _has_immediate_model_signal(child)
+ except OSError:
+ # Skip individual children that are unreadable (permissions, broken
+ # symlinks, etc.) rather than failing the entire scan.
+ continue
+ if not has_model_files:
+ continue
+ try:
+ updated_at = child.stat().st_mtime
+ except OSError:
+ updated_at = None
+ rows = _classify_local_path(
+ child,
+ "models_dir",
+ updated_at = updated_at,
+ )
+ if limit is not None:
+ rows = rows[: max(0, limit - len(found))]
+ found.extend(rows)
+
+ return found
+
+
+def _hf_repo_dir_has_content(repo_dir: Path) -> bool:
+ blobs_dir = repo_dir / "blobs"
+ if not blobs_dir.is_dir():
+ return False
+ try:
+ for entry in blobs_dir.iterdir():
+ if entry.is_file() or entry.is_symlink():
+ return True
+ except OSError:
+ return False
+ return False
+
+
+def _scan_hf_cache(cache_dir: Path, *, entry_limit: int | None = None) -> List[LocalModelInfo]:
+ if not cache_dir.exists() or not cache_dir.is_dir():
+ return []
+
+ discovered: List[tuple[Path, str, Optional[float]]] = []
+ visited = 0
+ try:
+ entries = cache_dir.iterdir()
+ except OSError:
+ return []
+ for repo_dir in entries:
+ visited += 1
+ if entry_limit is not None and visited > entry_limit:
+ break
+ if not repo_dir.name.startswith("models--"):
+ continue
+ if not repo_dir.is_dir():
+ continue
+ if not _hf_repo_dir_has_content(repo_dir):
+ continue
+ repo_name = repo_dir.name[len("models--") :]
+ if not repo_name:
+ continue
+ model_id = repo_name.replace("--", "/")
+ try:
+ updated_at = repo_dir.stat().st_mtime
+ except OSError:
+ updated_at = None
+ discovered.append((repo_dir, model_id, updated_at))
+
+ found: list[LocalModelInfo] = []
+ for repo_dir, model_id, updated_at in discovered:
+ snapshot_partial = hf_cache_scan.is_snapshot_partial(
+ "model",
+ model_id,
+ repo_dir,
+ )
+ gguf_partial = hf_cache_scan.is_gguf_repo_partial(model_id, repo_dir)
+ has_gguf_variant_state, gguf_variant_state_size = _gguf_variant_state_summary(model_id)
+ snapshot_partial_transport = (
+ hf_cache_scan.partial_transport_for(
+ "model",
+ model_id,
+ repo_cache_dir = repo_dir,
+ )
+ if snapshot_partial
+ else None
+ )
+ resolved = hf_cache_scan.resolve_hf_cache_realpath(repo_dir)
+ scan_path = Path(resolved) if resolved else repo_dir
+ # partial=False here; _apply_format_aware_partial below rewrites per-row
+ # so a hybrid repo's gguf row doesn't taint its safetensors row.
+ rows = _classify_local_path(
+ scan_path,
+ "hf_cache",
+ load_path = repo_dir,
+ display_name = model_id.split("/")[-1],
+ model_id = model_id,
+ updated_at = updated_at,
+ partial = False,
+ )
+ if not rows:
+ if has_gguf_variant_state and gguf_partial:
+ rows = [
+ _local_model_info(
+ scan_path = repo_dir,
+ load_path = repo_dir,
+ source = "hf_cache",
+ model_format = "gguf",
+ display_name = model_id.split("/")[-1],
+ model_id = model_id,
+ updated_at = updated_at,
+ partial = True,
+ requires_variant = True,
+ size_bytes = gguf_variant_state_size,
+ )
+ ]
+ else:
+ # Fallback row's model_format is "unknown"; either signal
+ # applies because we can't dispatch to a specific predicate.
+ rows = [
+ _local_model_info(
+ scan_path = repo_dir,
+ load_path = repo_dir,
+ source = "hf_cache",
+ model_format = "unknown",
+ display_name = model_id.split("/")[-1],
+ model_id = model_id,
+ updated_at = updated_at,
+ partial = snapshot_partial or gguf_partial,
+ )
+ ]
+ elif (
+ has_gguf_variant_state
+ and gguf_partial
+ and not any(row.model_format == "gguf" for row in rows)
+ ):
+ rows.append(
+ _local_model_info(
+ scan_path = repo_dir,
+ load_path = repo_dir,
+ source = "hf_cache",
+ model_format = "gguf",
+ display_name = model_id.split("/")[-1],
+ model_id = model_id,
+ updated_at = updated_at,
+ partial = True,
+ requires_variant = True,
+ size_bytes = gguf_variant_state_size,
+ )
+ )
+ rows = _apply_format_aware_partial(
+ rows,
+ snapshot_partial = snapshot_partial,
+ gguf_partial = gguf_partial,
+ snapshot_partial_transport = snapshot_partial_transport,
+ )
+ found.extend(rows)
+ return found
+
+
+def _scan_lmstudio_dir(lm_dir: Path, *, entry_limit: int | None = None) -> List[LocalModelInfo]:
+ """Scan an LM Studio models dir (``publisher/model-name`` folders of GGUFs, or top-level standalone GGUFs)."""
+ if not lm_dir.exists() or not lm_dir.is_dir():
+ return []
+
+ # If the dir is itself a model dir (config + weights), it's not an LM Studio
+ # publisher structure -- return it as a single entry rather than descend.
+ if _is_model_directory(lm_dir):
+ try:
+ updated_at = lm_dir.stat().st_mtime
+ except OSError:
+ updated_at = None
+ return _classify_local_path(
+ lm_dir,
+ "lmstudio",
+ updated_at = updated_at,
+ )
+
+ found: List[LocalModelInfo] = []
+ visited = 0
+ exhausted = False
+
+ def _consume_visit() -> bool:
+ nonlocal visited
+ visited += 1
+ return entry_limit is not None and visited > entry_limit
+
+ try:
+ children = lm_dir.iterdir()
+ except OSError:
+ return found
+ for child in children:
+ if _consume_visit():
+ break
+ try:
+ if not child.is_dir():
+ if child.suffix == ".gguf" and child.is_file():
+ try:
+ updated_at = child.stat().st_mtime
+ except OSError:
+ updated_at = None
+ found.extend(
+ _classify_local_path(
+ child,
+ "lmstudio",
+ updated_at = updated_at,
+ )
+ )
+ continue
+
+ # Child is itself a model dir: surface it directly, not as a publisher.
+ if _is_model_directory(child):
+ try:
+ updated_at = child.stat().st_mtime
+ except OSError:
+ updated_at = None
+ found.extend(
+ _classify_local_path(
+ child,
+ "lmstudio",
+ updated_at = updated_at,
+ )
+ )
+ continue
+
+ # child is a publisher directory -- scan its sub-directories
+ for model_dir in child.iterdir():
+ if _consume_visit():
+ exhausted = True
+ break
+ try:
+ if model_dir.is_dir():
+ has_model = _has_immediate_model_signal(model_dir)
+ if not has_model:
+ continue
+ model_id = f"{child.name}/{model_dir.name}"
+ try:
+ updated_at = model_dir.stat().st_mtime
+ except OSError:
+ updated_at = None
+ found.extend(
+ _classify_local_path(
+ model_dir,
+ "lmstudio",
+ display_name = model_dir.name,
+ model_id = model_id,
+ updated_at = updated_at,
+ )
+ )
+ elif model_dir.suffix == ".gguf" and model_dir.is_file():
+ try:
+ updated_at = model_dir.stat().st_mtime
+ except OSError:
+ updated_at = None
+ found.extend(
+ _classify_local_path(
+ model_dir,
+ "lmstudio",
+ model_id = f"{child.name}/{model_dir.stem}",
+ updated_at = updated_at,
+ )
+ )
+ except OSError:
+ continue
+ if exhausted:
+ break
+ except OSError:
+ continue
+ return found
+
+
+def _resolve_allowed_models_dir(models_dir: str, allowed_roots: list[Path]) -> Path:
+ """Resolve a requested model scan directory without widening subpaths."""
+ if not models_dir or not models_dir.strip():
+ raise ValueError("Directory not allowed")
+
+ requested = Path(os.path.realpath(os.path.expanduser(normalize_path(models_dir.strip()))))
+ if any(path_is_same_or_child(requested, root) for root in allowed_roots):
+ return requested
+
+ raise ValueError("Directory not allowed")
+
+
+def _coerce_scan_folder_path(raw_path: str) -> str:
+ """Normalize a scan registration target; the registry stores directories, so a pasted weight-file path is reduced to its parent folder."""
+ if not raw_path or not raw_path.strip():
+ raise ValueError("Path cannot be empty")
+ raw = raw_path.strip()
+ if "\x00" in raw:
+ raise ValueError("Path cannot contain null bytes")
+
+ def normalize(value: str) -> Path:
+ return Path(os.path.realpath(os.path.expanduser(normalize_path(value))))
+
+ try:
+ normalized = normalize(raw)
+ except (OSError, ValueError) as e:
+ raise ValueError(f"Path is not readable: {e}") from e
+ try:
+ exists = normalized.exists()
+ is_dir = normalized.is_dir()
+ is_file = normalized.is_file()
+ except (OSError, ValueError) as e:
+ raise ValueError(f"Path is not readable: {e}") from e
+
+ if not exists and "\\" in raw:
+ try:
+ slash_normalized = normalize(raw.replace("\\", "/"))
+ slash_exists = slash_normalized.exists()
+ except (OSError, ValueError) as e:
+ raise ValueError(f"Path is not readable: {e}") from e
+ if slash_exists:
+ normalized = slash_normalized
+ try:
+ is_dir = normalized.is_dir()
+ is_file = normalized.is_file()
+ except (OSError, ValueError) as e:
+ raise ValueError(f"Path is not readable: {e}") from e
+ exists = True
+
+ if not exists:
+ return str(normalized)
+ if is_dir:
+ return str(normalized)
+ if is_file:
+ suffix = normalized.suffix.lower()
+ if suffix not in {".gguf", ".safetensors", ".bin"}:
+ raise ValueError("Path must be a folder or model weight file")
+ return str(normalized.parent)
+ return str(normalized)
+
+
+async def _scan_source(label: str, scanner, path: Path) -> List[LocalModelInfo]:
+ try:
+ return await asyncio.to_thread(scanner, path)
+ except Exception as e:
+ logger.warning("Skipping %s scan for %s: %s", label, path, e)
+ return []
+
+
+async def _collect_models_from_default_sources(
+ models_root: Path,
+ hf_cache_dir: Path,
+ legacy_hf: Path,
+ hf_default: Path,
+ lm_dirs: list[Path],
+ ollama_dirs: list[Path],
+) -> List[LocalModelInfo]:
+ local_models = await _scan_source("models directory", _scan_models_dir, models_root)
+ local_models += await _scan_source("HF cache", _scan_hf_cache, hf_cache_dir)
+
+ if legacy_hf.is_dir() and legacy_hf.resolve() != hf_cache_dir.resolve():
+ local_models += await _scan_source("legacy HF cache", _scan_hf_cache, legacy_hf)
+
+ if (
+ hf_default.is_dir()
+ and hf_default.resolve() != hf_cache_dir.resolve()
+ and hf_default.resolve() != legacy_hf.resolve()
+ ):
+ local_models += await _scan_source("default HF cache", _scan_hf_cache, hf_default)
+
+ for lm_dir in lm_dirs:
+ local_models += await _scan_source("LM Studio", _scan_lmstudio_dir, lm_dir)
+
+ for ollama_dir in ollama_dirs:
+ local_models += await _scan_source("Ollama", scan_ollama_dir, ollama_dir)
+
+ return local_models
+
+
+def _scan_custom_folder(folder_path: Path) -> List[LocalModelInfo]:
+ supported_formats: set[ModelFormat] = {"gguf", "safetensors", "adapter"}
+ generic = [
+ m
+ for m in (
+ _scan_models_dir(
+ folder_path,
+ limit = _MAX_MODELS_PER_CUSTOM_FOLDER,
+ entry_limit = _MAX_CUSTOM_FOLDER_ENTRIES,
+ )
+ + _scan_hf_cache(folder_path, entry_limit = _MAX_CUSTOM_FOLDER_ENTRIES)
+ + _scan_lmstudio_dir(folder_path, entry_limit = _MAX_CUSTOM_FOLDER_ENTRIES)
+ )
+ if m.model_format in supported_formats
+ if not any(p in (".studio_links", "ollama_links") for p in Path(m.path).parts)
+ ]
+ return generic[:_MAX_MODELS_PER_CUSTOM_FOLDER]
+
+
+def _promote_to_custom_source(model: LocalModelInfo) -> LocalModelInfo:
+ if model.source == "hf_cache":
+ return model
+ return model.model_copy(
+ update = {
+ "source": "custom",
+ "model_id": None,
+ "inventory_id": _local_inventory_id(
+ "custom",
+ model.model_format,
+ model.path,
+ model.format_variant,
+ ),
+ "capabilities": _capabilities_for_format(
+ model.model_format,
+ "custom",
+ partial = model.partial,
+ requires_variant = model.capabilities.requires_variant,
+ ),
+ }
+ )
+
+
+async def _collect_models_from_custom_folders() -> List[LocalModelInfo]:
+ try:
+ custom_folders = await asyncio.to_thread(list_scan_folders)
+ except Exception as e:
+ logger.warning("Could not load custom scan folders: %s", e)
+ return []
+
+ local_models: List[LocalModelInfo] = []
+ for folder in custom_folders:
+ folder_path = Path(normalize_path(folder["path"])).expanduser()
+ try:
+ custom_models = await asyncio.to_thread(_scan_custom_folder, folder_path)
+ except Exception as e:
+ logger.warning("Skipping unreadable scan folder %s: %s", folder_path, e)
+ continue
+ local_models.extend(_promote_to_custom_source(m) for m in custom_models)
+ return local_models
+
+
+def _dedupe_local_models(local_models: List[LocalModelInfo]) -> list[LocalModelInfo]:
+ deduped: dict[str, LocalModelInfo] = {}
+ for model in local_models:
+ if model.source == "hf_cache" and model.model_id:
+ key = "\x00".join(
+ (
+ "hf_cache",
+ model.model_id.strip().lower(),
+ model.model_format,
+ model.format_variant or "",
+ )
+ )
+ else:
+ row_key = model.inventory_id or model.id
+ key = f"{row_key}\x00custom" if model.source == "custom" else row_key
+ existing = deduped.get(key)
+ if existing is None or _prefer_complete_larger(
+ model.partial,
+ model.size_bytes,
+ existing.partial,
+ existing.size_bytes,
+ ):
+ deduped[key] = model
+ return sorted(
+ deduped.values(),
+ key = lambda item: (item.updated_at or 0),
+ reverse = True,
+ )
+
+
+async def list_local_models_response(models_dir: str = "./models") -> LocalModelListResponse:
+ """List local model candidates from every supported on-device source."""
+ hf_cache_dir = _resolve_hf_cache_dir()
+ legacy_hf = legacy_hf_cache_dir()
+ hf_default = hf_default_cache_dir()
+ lm_dirs = lmstudio_model_dirs()
+ ollama_dirs = ollama_model_dirs()
+
+ allowed_roots: list[Path] = [Path("./models").resolve(), hf_cache_dir]
+ if legacy_hf.is_dir():
+ allowed_roots.append(legacy_hf)
+ if hf_default.is_dir():
+ allowed_roots.append(hf_default)
+ allowed_roots.extend([studio_root(), outputs_root()])
+
+ try:
+ models_root = _resolve_allowed_models_dir(models_dir, allowed_roots)
+ except ValueError:
+ raise HTTPException(status_code = 403, detail = "Directory not allowed")
+
+ try:
+ local_models = await _collect_models_from_default_sources(
+ models_root,
+ hf_cache_dir,
+ legacy_hf,
+ hf_default,
+ lm_dirs,
+ ollama_dirs,
+ )
+ local_models += await _collect_models_from_custom_folders()
+ models = _dedupe_local_models(local_models)
+
+ return LocalModelListResponse(
+ models_dir = str(models_root),
+ hf_cache_dir = str(hf_cache_dir),
+ lmstudio_dirs = [str(d) for d in lm_dirs],
+ ollama_dirs = [str(d) for d in ollama_dirs],
+ models = models,
+ )
+ except Exception as e:
+ logger.error(f"Error listing local models: {e}", exc_info = True)
+ raise HTTPException(
+ status_code = 500,
+ detail = f"Failed to list local models: {str(e)}",
+ )
+
+
+def get_scan_folders_response() -> dict:
+ return {"folders": list_scan_folders()}
+
+
+def add_scan_folder_response(path: str) -> dict:
+ try:
+ folder = add_scan_folder(_coerce_scan_folder_path(path))
+ except ValueError as e:
+ logger.warning("Scan folder rejected: %s (path=%s)", e, path)
+ raise HTTPException(status_code = 400, detail = str(e))
+ logger.info("Scan folder added: %s", folder.get("path"))
+ return folder
+
+
+def remove_scan_folder_response(folder_id: int) -> dict:
+ remove_scan_folder(folder_id)
+ logger.info("Scan folder removed: id=%s", folder_id)
+ return {"ok": True}
diff --git a/studio/backend/hub/services/models/ollama.py b/studio/backend/hub/services/models/ollama.py
new file mode 100644
index 00000000000..96a4114620c
--- /dev/null
+++ b/studio/backend/hub/services/models/ollama.py
@@ -0,0 +1,394 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Ollama model inventory: manifest parsing and writable-symlink materialization.
+
+Ollama stores models content-addressed under ``<root>/manifests/`` and
+``<root>/blobs/``. Inventory scans read the manifests directly (no writes),
+returning rows whose ``id`` is an opaque ``ollama-manifest:`` reference. The
+load path then calls :func:`materialize_ollama_model_ref`, which creates a
+``.gguf``-named symlink (or hardlink) so that downstream loaders see a path
+with the GGUF suffix without copying multi-GB blobs inside an API request.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import uuid
+from pathlib import Path
+from typing import List, Optional
+from urllib.parse import quote, unquote
+
+from loggers import get_logger
+
+from hub.schemas.inventory import LocalModelInfo
+from hub.services.models.common import (
+ _capabilities_for_format,
+ _local_inventory_id,
+)
+from hub.utils.paths import (
+ cache_root,
+ ollama_model_dirs,
+ path_is_same_or_child,
+ tmp_root,
+)
+
+logger = get_logger(__name__)
+
+_OLLAMA_MANIFEST_REF_PREFIX = "ollama-manifest:"
+_OLLAMA_BLOB_NAME_CHARS = frozenset(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._+-"
+)
+
+
+def _ollama_manifest_ref(tag_file: Path) -> str:
+ return f"{_OLLAMA_MANIFEST_REF_PREFIX}{quote(str(tag_file), safe = '')}"
+
+
+def _safe_is_file(path: Path) -> bool:
+ try:
+ return path.is_file()
+ except OSError:
+ return False
+
+
+def _ollama_blob_path(blobs_dir: Path, digest: object) -> Optional[Path]:
+ if not isinstance(digest, str):
+ return None
+ algorithm, separator, value = digest.partition(":")
+ if separator != ":" or not algorithm or not value:
+ return None
+ name = f"{algorithm}-{value}"
+ if (
+ not name
+ or name in (".", "..")
+ or any(char not in _OLLAMA_BLOB_NAME_CHARS for char in name)
+ or not name.isprintable()
+ ):
+ return None
+ return blobs_dir / name
+
+
+def _contained_link_path(link_dir: Path, link_name: str) -> Optional[Path]:
+ """Resolve *link_name* to a direct child of *link_dir*, or ``None``. ``link_name`` derives from manifest fields, so requiring a direct child keeps a crafted value with separators, ``..``, or a drive prefix from escaping the links dir."""
+ if not link_name or link_name in (".", ".."):
+ return None
+ link_path = link_dir / link_name
+ try:
+ if link_path.parent.resolve() != link_dir.resolve():
+ return None
+ except OSError:
+ return None
+ return link_path
+
+
+def _ollama_links_dir(ollama_dir: Path) -> Optional[Path]:
+ """Writable directory for Ollama ``.gguf`` symlinks. Prefers ``<ollama_dir>/.studio_links/`` next to the blobs; falls back to Studio's cache (read-only system installs), then the temp dir (sandboxed installs)."""
+
+ def _ensure_writable_dir(path: Path) -> Optional[Path]:
+ try:
+ path.mkdir(parents = True, exist_ok = True)
+ probe = path / f".write-test-{uuid.uuid4().hex[:8]}"
+ probe.mkdir()
+ probe.rmdir()
+ return path
+ except OSError as e:
+ logger.debug("Ollama link dir %s is not writable: %s", path, e)
+ return None
+
+ primary = ollama_dir / ".studio_links"
+ if _ensure_writable_dir(primary) is not None:
+ return primary
+
+ # Namespace by a hash of the ollama_dir so two different Ollama roots
+ # don't collide. This is a cache path, not a security boundary.
+ try:
+ digest = hashlib.sha256(str(ollama_dir.resolve()).encode()).hexdigest()[:12]
+ except (OSError, RuntimeError):
+ digest = "default"
+
+ fallback = cache_root() / "ollama_links" / digest
+ if _ensure_writable_dir(fallback) is not None:
+ return fallback
+
+ tmp_fallback = tmp_root() / "ollama_links" / digest
+ if _ensure_writable_dir(tmp_fallback) is not None:
+ return tmp_fallback
+
+ logger.warning(
+ "Could not create a writable Ollama link directory for %s",
+ ollama_dir,
+ )
+ return None
+
+
+def _make_ollama_blob_link(link_dir: Path, link_name: str, target: Path) -> Optional[str]:
+ """Create a .gguf-named link to an Ollama blob: tries symlink then hardlink, skips the model if neither works (a full multi-GB copy would block the API). Idempotent."""
+ try:
+ link_dir.mkdir(parents = True, exist_ok = True)
+ except OSError as e:
+ logger.warning(
+ "Could not create Ollama link directory %s: %s",
+ link_dir,
+ e,
+ )
+ return None
+ link_path = _contained_link_path(link_dir, link_name)
+ if link_path is None:
+ logger.warning("Refusing unsafe Ollama link name %r under %s", link_name, link_dir)
+ return None
+ try:
+ resolved = target.resolve()
+ except OSError as e:
+ logger.debug("Could not resolve Ollama blob %s: %s", target, e)
+ return None
+
+ # Skip if the link already points at the same blob. Use samefile, not size:
+ # `ollama pull` can swap a tag to a same-sized blob, leaving a stale link.
+ try:
+ if link_path.exists() and os.path.samefile(str(link_path), str(resolved)):
+ return str(link_path)
+ except OSError as e:
+ logger.debug("Error checking existing link %s: %s", link_path, e)
+
+ tmp_path = link_dir / f".{link_name}.tmp-{uuid.uuid4().hex[:8]}"
+ try:
+ if tmp_path.is_symlink() or tmp_path.exists():
+ tmp_path.unlink()
+ try:
+ tmp_path.symlink_to(resolved)
+ except OSError:
+ try:
+ os.link(str(resolved), str(tmp_path))
+ except OSError:
+ logger.warning(
+ "Could not create link for Ollama blob %s "
+ "(symlinks and hardlinks both failed). "
+ "Skipping model to avoid blocking the API.",
+ target,
+ )
+ return None
+ os.replace(str(tmp_path), str(link_path))
+ return str(link_path)
+ except OSError as e:
+ logger.debug("Could not create Ollama link %s: %s", link_path, e)
+ try:
+ if tmp_path.is_symlink() or tmp_path.exists():
+ tmp_path.unlink()
+ except OSError as cleanup_err:
+ logger.debug("Could not clean up tmp path %s: %s", tmp_path, cleanup_err)
+ return None
+
+
+def _ollama_model_info_from_manifest(
+ ollama_dir: Path,
+ tag_file: Path,
+ *,
+ materialize_links: bool = False,
+ links_root: Optional[Path] = None,
+) -> Optional[LocalModelInfo]:
+ manifests_root = ollama_dir / "manifests"
+ blobs_dir = ollama_dir / "blobs"
+
+ try:
+ rel = tag_file.relative_to(manifests_root)
+ except ValueError:
+ return None
+ parts = rel.parts
+ if len(parts) < 3:
+ return None
+
+ host = parts[0]
+ repo_parts = list(parts[1:-1])
+ tag = parts[-1]
+
+ if host == "registry.ollama.ai" and repo_parts and repo_parts[0] == "library":
+ repo_name = "/".join(repo_parts[1:])
+ elif host == "registry.ollama.ai":
+ repo_name = "/".join(repo_parts)
+ else:
+ repo_name = "/".join([host] + repo_parts)
+
+ if not repo_name:
+ return None
+
+ try:
+ manifest = json.loads(tag_file.read_text())
+ except (json.JSONDecodeError, OSError) as e:
+ logger.debug("Skipping unreadable/invalid Ollama manifest %s: %s", tag_file, e)
+ return None
+
+ config = manifest.get("config", {})
+ config_digest = config.get("digest", "") if isinstance(config, dict) else ""
+ model_type = ""
+ file_type = ""
+ if config_digest and blobs_dir.is_dir():
+ config_blob = _ollama_blob_path(blobs_dir, config_digest)
+ if config_blob is not None and _safe_is_file(config_blob):
+ try:
+ cfg = json.loads(config_blob.read_text())
+ model_type = cfg.get("model_type", "")
+ file_type = cfg.get("file_type", "")
+ except (json.JSONDecodeError, OSError) as e:
+ logger.debug("Could not parse Ollama config blob %s: %s", config_blob, e)
+
+ layers = manifest.get("layers") or []
+ if not isinstance(layers, list):
+ return None
+
+ model_blob: Optional[Path] = None
+ gguf_link_path: Optional[str] = None
+ stem_hash = hashlib.sha256(rel.as_posix().encode()).hexdigest()[:10]
+ model_link_dir = links_root / stem_hash if links_root is not None else None
+ safe_name = repo_name.replace("/", "-")
+ quant = f"-{file_type}" if file_type else ""
+
+ for layer in layers:
+ if not isinstance(layer, dict):
+ continue
+ media = layer.get("mediaType", "")
+ digest = layer.get("digest", "")
+ if not digest:
+ continue
+
+ if media == "application/vnd.ollama.image.model":
+ candidate = _ollama_blob_path(blobs_dir, digest)
+ if candidate is None or not _safe_is_file(candidate):
+ continue
+ model_blob = candidate
+ if materialize_links and model_link_dir is not None:
+ link_name = f"{safe_name}-{tag}{quant}.gguf"
+ gguf_link_path = _make_ollama_blob_link(model_link_dir, link_name, candidate)
+
+ elif materialize_links and media == "application/vnd.ollama.image.projector":
+ candidate = _ollama_blob_path(blobs_dir, digest)
+ if candidate is not None and _safe_is_file(candidate) and model_link_dir is not None:
+ mmproj_name = f"{safe_name}-{tag}-mmproj.gguf"
+ _make_ollama_blob_link(model_link_dir, mmproj_name, candidate)
+
+ if model_blob is None:
+ return None
+ if materialize_links and not gguf_link_path:
+ return None
+
+ suffix = ""
+ if model_type:
+ suffix += f" ({model_type}"
+ if file_type:
+ suffix += f" {file_type}"
+ suffix += ")"
+
+ try:
+ updated_at = tag_file.stat().st_mtime
+ except OSError:
+ updated_at = None
+
+ display = f"{repo_name}:{tag}"
+ model_id = f"ollama/{repo_name}:{tag}"
+ path = gguf_link_path if materialize_links and gguf_link_path else str(model_blob)
+ load_id = path if materialize_links else _ollama_manifest_ref(tag_file)
+ return LocalModelInfo(
+ id = load_id,
+ inventory_id = _local_inventory_id("ollama", "gguf", model_id),
+ load_id = load_id,
+ model_id = model_id,
+ display_name = display + suffix,
+ path = path,
+ source = "ollama",
+ updated_at = updated_at,
+ model_format = "gguf",
+ runtime = "llama_cpp",
+ capabilities = _capabilities_for_format("gguf", "ollama"),
+ )
+
+
+def scan_ollama_dir(
+ ollama_dir: Path,
+ *,
+ limit: Optional[int] = None,
+ materialize_links: bool = False,
+) -> List[LocalModelInfo]:
+ """Scan an Ollama models directory for downloaded models.
+
+ Ollama uses a content-addressable layout
+ (``manifests/<host>/<namespace>/<model>/<tag>`` + ``blobs/sha256-...``),
+ iterated via ``rglob`` to find every depth. Each manifest's ``model`` layer
+ holds the GGUF weights (vision models add a projector layer).
+
+ Scans are read-only by default and return an opaque manifest reference;
+ the load route later calls :func:`materialize_ollama_model_ref` to create a
+ ``.gguf`` symlink/hardlink, keeping GET /local free of filesystem writes.
+ """
+ manifests_root = ollama_dir / "manifests"
+ if not manifests_root.is_dir():
+ return []
+
+ found: List[LocalModelInfo] = []
+ links_root = _ollama_links_dir(ollama_dir) if materialize_links else None
+ if materialize_links and links_root is None:
+ logger.warning(
+ "Skipping Ollama scan for %s: no writable location for .gguf links",
+ ollama_dir,
+ )
+ return []
+
+ try:
+ for tag_file in manifests_root.rglob("*"):
+ if not _safe_is_file(tag_file):
+ continue
+
+ info = _ollama_model_info_from_manifest(
+ ollama_dir,
+ tag_file,
+ materialize_links = materialize_links,
+ links_root = links_root,
+ )
+ if info is None:
+ continue
+ found.append(info)
+ if limit is not None and len(found) >= limit:
+ return found
+ except OSError as e:
+ logger.warning("Error scanning Ollama directory %s: %s", ollama_dir, e)
+ return found
+
+
+def _ollama_dir_for_manifest(tag_file: Path) -> Optional[Path]:
+ """Discovered Ollama root whose ``manifests/`` contains *tag_file*, or ``None``. Validating against known roots keeps a crafted reference from driving materialization to an arbitrary path."""
+ for ollama_dir in ollama_model_dirs():
+ if path_is_same_or_child(tag_file, ollama_dir / "manifests"):
+ return ollama_dir
+ return None
+
+
+def materialize_ollama_model_ref(ref: str) -> str:
+ """Resolve an ``ollama-manifest:`` reference to a loadable ``.gguf`` path,
+ creating the writable symlink/hardlink on demand.
+
+ Raises ``ValueError`` if the reference is malformed, points outside a
+ discovered Ollama models directory, or cannot be materialized.
+ """
+ if not ref.startswith(_OLLAMA_MANIFEST_REF_PREFIX):
+ raise ValueError("Not an Ollama manifest reference")
+
+ tag_file = Path(unquote(ref[len(_OLLAMA_MANIFEST_REF_PREFIX) :]))
+
+ ollama_dir = _ollama_dir_for_manifest(tag_file)
+ if ollama_dir is None:
+ raise ValueError("Reference is outside any known Ollama models directory")
+
+ links_root = _ollama_links_dir(ollama_dir)
+ if links_root is None:
+ raise ValueError("No writable location for Ollama .gguf links")
+
+ info = _ollama_model_info_from_manifest(
+ ollama_dir,
+ tag_file,
+ materialize_links = True,
+ links_root = links_root,
+ )
+ if info is None or not info.path:
+ raise ValueError("Could not materialize Ollama model from manifest")
+ return info.path
diff --git a/studio/backend/hub/services/snapshot_progress.py b/studio/backend/hub/services/snapshot_progress.py
new file mode 100644
index 00000000000..9c8bc9a8919
--- /dev/null
+++ b/studio/backend/hub/services/snapshot_progress.py
@@ -0,0 +1,260 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shared snapshot download-progress computation for models and datasets.
+
+Both scan the cache's ``blobs/`` dir, split finalized vs ``.incomplete`` bytes,
+filter to the target revision's expected hashes, and divide by its total size;
+only the ``metadata_resolver`` differs. One copy keeps the two from drifting (a
+prior hash-filter fix once landed only on the model copy, leaving datasets
+summing stale blobs against the wrong total)."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import Callable, Optional
+
+from loggers import get_logger
+
+from hub.utils import download_manifest
+from hub.utils import download_registry
+from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils.state_dir import RepoType
+from hub.utils.hf_cache_state import (
+ INCOMPLETE_SUFFIX,
+ blob_bytes_present,
+ latest_snapshot_dir,
+ preferred_repo_cache_dirs,
+)
+from hub.utils.paths import is_valid_repo_id as _is_valid_repo_id
+
+logger = get_logger(__name__)
+
+# (repo_id, hf_token) -> (expected_total_bytes, expected_blob_hashes)
+SnapshotMetadataResolver = Callable[[str, Optional[str]], "tuple[int, frozenset[str]]"]
+
+
+def _empty_progress(expected_bytes: int) -> dict:
+ return {
+ "downloaded_bytes": 0,
+ "completed_bytes": 0,
+ "complete_on_disk": False,
+ "expected_bytes": max(expected_bytes, 0),
+ "progress": 0,
+ "cache_path": None,
+ }
+
+
+def _snapshot_complete_on_disk(
+ *,
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str],
+ entry: Path,
+ expected_total: int,
+ completed_bytes: int,
+ in_progress_bytes: int,
+) -> bool:
+ if expected_total <= 0 or completed_bytes < expected_total or in_progress_bytes > 0:
+ return False
+ snapshot_dir = latest_snapshot_dir(entry)
+ if snapshot_dir is None:
+ return False
+ if variant is None and hf_cache_scan.repo_cache_dir_has_incomplete_blobs(entry):
+ return False
+ if download_manifest.has_cancel_marker(repo_type, repo_id, variant):
+ return False
+ manifest = download_manifest.read_manifest(repo_type, repo_id, variant)
+ if manifest is None:
+ return False
+ return download_manifest.verify_against_disk(manifest, snapshot_dir).ok
+
+
+def compute_snapshot_progress(
+ *,
+ repo_type: RepoType,
+ repo_id: str,
+ job_key: str,
+ expected_bytes: int,
+ hf_token: Optional[str],
+ registry,
+ metadata_resolver: SnapshotMetadataResolver,
+ variant: Optional[str] = None,
+) -> dict:
+ """Synchronous progress reading. Safe to run under ``asyncio.to_thread``."""
+ empty = _empty_progress(expected_bytes)
+ if not _is_valid_repo_id(repo_id):
+ return empty
+
+ job_state = registry.get_job(job_key).state
+ force_active = job_state in {"running", "cancelling"}
+ get_job_metadata = getattr(registry, "get_job_metadata", None)
+ metadata = get_job_metadata(job_key) if callable(get_job_metadata) else None
+ completed_baseline_bytes = max(
+ 0,
+ int(getattr(metadata, "completed_baseline_bytes", 0) or 0),
+ )
+
+ expected_total = max(expected_bytes, 0)
+ # Always resolve the revision's blob hashes so stale blobs from a superseded
+ # revision can't inflate the count; hashes degrade to empty (count-all) only
+ # when metadata is unavailable (e.g. offline). Take the larger total so a low
+ # caller hint can't cap the bar below the revision's real size.
+ meta_total, expected_hashes = metadata_resolver(repo_id, hf_token)
+ expected_total = max(expected_total, meta_total)
+
+ # Without resolved hashes, a variant must not count unscoped blobs: sibling
+ # quants share one blobs/ dir, so a sibling's bytes (or .incomplete) would be
+ # misattributed and make the bar jump backward. A no-variant snapshot owns
+ # the whole dir, so it counts unscoped.
+ count_finalized_unscoped = variant is None
+
+ readings: list[tuple[int, int, Optional[str], bool]] = []
+ for entry in preferred_repo_cache_dirs(
+ repo_type,
+ repo_id,
+ force_active = force_active,
+ ):
+ completed_bytes = 0
+ in_progress_bytes = 0
+ cache_path = hf_cache_scan.resolve_hf_cache_realpath(entry)
+ blobs_dir = entry / "blobs"
+ if blobs_dir.is_dir():
+ try:
+ blob_entries = list(blobs_dir.iterdir())
+ except OSError:
+ blob_entries = []
+ for f in blob_entries:
+ # Skip a blob that vanished mid-poll rather than zeroing the reading.
+ try:
+ if not f.is_file():
+ continue
+ if f.name.endswith(INCOMPLETE_SUFFIX):
+ blob_hash = f.name[: -len(INCOMPLETE_SUFFIX)]
+ if expected_hashes:
+ if blob_hash not in expected_hashes:
+ continue
+ elif not count_finalized_unscoped:
+ continue
+ in_progress_bytes += blob_bytes_present(f)
+ else:
+ if expected_hashes:
+ if f.name not in expected_hashes:
+ continue
+ elif not count_finalized_unscoped:
+ continue
+ completed_bytes += f.stat().st_size
+ except OSError:
+ continue
+ readings.append(
+ (
+ completed_bytes,
+ in_progress_bytes,
+ cache_path,
+ _snapshot_complete_on_disk(
+ repo_type = repo_type,
+ repo_id = repo_id,
+ variant = variant,
+ entry = entry,
+ expected_total = expected_total,
+ completed_bytes = completed_bytes,
+ in_progress_bytes = in_progress_bytes,
+ ),
+ )
+ )
+
+ selected = max(
+ readings,
+ key = lambda item: (item[0] + item[1], item[0]),
+ default = None,
+ )
+ if selected is None:
+ return empty
+
+ completed_bytes, in_progress_bytes, cache_path, complete_on_disk = selected
+ downloaded_bytes = completed_bytes + in_progress_bytes
+ # Subtract the companion baseline only while still counted in completed_bytes
+ # and the variant is not yet verified complete, else genuine progress reads as
+ # 0-byte.
+ effective_baseline_bytes = (
+ completed_baseline_bytes
+ if not complete_on_disk and completed_baseline_bytes <= completed_bytes
+ else 0
+ )
+ display_completed_bytes = max(0, completed_bytes - effective_baseline_bytes)
+ display_downloaded_bytes = max(0, downloaded_bytes - effective_baseline_bytes)
+
+ if expected_total <= 0:
+ # Cannot determine total; report bytes only, no percentage.
+ return {
+ "downloaded_bytes": display_downloaded_bytes,
+ "completed_bytes": display_completed_bytes,
+ "complete_on_disk": False,
+ "expected_bytes": 0,
+ "progress": 0,
+ "cache_path": cache_path,
+ }
+
+ display_expected_total = max(0, expected_total - effective_baseline_bytes)
+ if downloaded_bytes == 0:
+ return {
+ **empty,
+ "expected_bytes": display_expected_total,
+ "cache_path": cache_path,
+ }
+
+ # Cap at 0.99 until the manifest-backed disk check verifies completion: on
+ # resume, completed bytes can sit above the threshold while files still download.
+ progress = (
+ 1.0
+ if complete_on_disk
+ else (
+ min(display_downloaded_bytes / display_expected_total, 0.99)
+ if display_expected_total > 0
+ else 0
+ )
+ )
+ return {
+ "downloaded_bytes": display_downloaded_bytes,
+ "completed_bytes": display_completed_bytes,
+ "complete_on_disk": complete_on_disk,
+ "expected_bytes": display_expected_total,
+ "progress": round(progress, 3),
+ "cache_path": cache_path,
+ }
+
+
+async def snapshot_progress_response(
+ *,
+ repo_type: RepoType,
+ repo_id: str,
+ job_key: str,
+ expected_bytes: int,
+ hf_token: Optional[str],
+ registry,
+ metadata_resolver: SnapshotMetadataResolver,
+ variant: Optional[str] = None,
+) -> dict:
+ """Async wrapper: offloads the blocking cache walk and never raises."""
+ try:
+ return await asyncio.to_thread(
+ compute_snapshot_progress,
+ repo_type = repo_type,
+ repo_id = repo_id,
+ job_key = job_key,
+ expected_bytes = expected_bytes,
+ hf_token = hf_token,
+ registry = registry,
+ metadata_resolver = metadata_resolver,
+ variant = variant,
+ )
+ except Exception as e:
+ logger.warning(
+ "Error checking %s download progress for %s: %s: %s",
+ repo_type,
+ repo_id,
+ type(e).__name__,
+ download_registry.scrub_secrets(str(e), hf_token = hf_token),
+ )
+ return _empty_progress(expected_bytes)
diff --git a/studio/backend/hub/storage/__init__.py b/studio/backend/hub/storage/__init__.py
new file mode 100644
index 00000000000..32014236c6a
--- /dev/null
+++ b/studio/backend/hub/storage/__init__.py
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
diff --git a/studio/backend/hub/storage/scan_folders.py b/studio/backend/hub/storage/scan_folders.py
new file mode 100644
index 00000000000..85f515da006
--- /dev/null
+++ b/studio/backend/hub/storage/scan_folders.py
@@ -0,0 +1,194 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Persistence for user-registered custom model scan folders.
+
+Self-bootstrapping table inside the existing studio SQLite so the Hub module
+doesn't have to modify upstream studio_db.py's schema init."""
+
+from __future__ import annotations
+
+import os
+import platform
+import sqlite3
+import threading
+from datetime import datetime, timezone
+
+from storage.studio_db import get_connection
+from hub.utils.paths import normalize_path
+
+
+_schema_lock = threading.Lock()
+_schema_ready = False
+_SENSITIVE_PATH_COMPONENTS = {
+ ".aws",
+ ".azure",
+ ".config",
+ ".docker",
+ ".gcloud",
+ ".gnupg",
+ ".huggingface",
+ ".kaggle",
+ ".kube",
+ ".modelscope",
+ ".ngc",
+ ".local",
+ ".mozilla",
+ ".pki",
+ ".thunderbird",
+ ".ssh",
+ ".1password",
+ ".bitwarden",
+ ".password-store",
+ "1password",
+ "bitwarden",
+ "keychains",
+ "keyrings",
+ "mozilla",
+ "thunderbird",
+}
+
+
+def _denied_path_prefixes() -> list[str]:
+ system = platform.system()
+ if system == "Linux":
+ return ["/proc", "/sys", "/dev", "/etc", "/boot", "/run"]
+ if system == "Darwin":
+ # realpath() resolves /etc -> /private/etc, /tmp -> /private/tmp on macOS,
+ # so include the /private variants to avoid bypasses.
+ return [
+ "/System",
+ "/Library",
+ "/dev",
+ "/etc",
+ "/private/etc",
+ "/tmp",
+ "/private/tmp",
+ "/var",
+ "/private/var",
+ ]
+ if system == "Windows":
+ win = os.environ.get("SystemRoot", r"C:\Windows")
+ pf = os.environ.get("ProgramFiles", r"C:\Program Files")
+ pf86 = os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")
+ return [os.path.normcase(p) for p in [win, pf, pf86]]
+ return []
+
+
+def _contains_sensitive_path_component(path: str) -> bool:
+ parts = os.path.normpath(path).split(os.sep)
+ return any(part.lower() in _SENSITIVE_PATH_COMPONENTS for part in parts)
+
+
+def contains_sensitive_path_component(path: str) -> bool:
+ """Public predicate for the credential/config denylist (.ssh, .aws, ...).
+
+ Shared with the folder browser so browse and register enforce one policy."""
+ return _contains_sensitive_path_component(path)
+
+
+def _ensure_schema(conn: sqlite3.Connection) -> None:
+ global _schema_ready
+ if _schema_ready:
+ return
+ with _schema_lock:
+ if _schema_ready:
+ return
+ collation = "COLLATE NOCASE" if platform.system() == "Windows" else ""
+ conn.execute(
+ f"""
+ CREATE TABLE IF NOT EXISTS scan_folders (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ path TEXT NOT NULL UNIQUE {collation},
+ created_at TEXT NOT NULL
+ )
+ """
+ )
+ conn.commit()
+ _schema_ready = True
+
+
+def list_scan_folders() -> list[dict]:
+ conn = get_connection()
+ try:
+ _ensure_schema(conn)
+ rows = conn.execute(
+ "SELECT id, path, created_at FROM scan_folders ORDER BY created_at"
+ ).fetchall()
+ return [dict(row) for row in rows]
+ finally:
+ conn.close()
+
+
+def add_scan_folder(path: str) -> dict:
+ """Add a readable directory for the local OS user; not a multi-user sandbox."""
+ if not path or not path.strip():
+ raise ValueError("Path cannot be empty")
+ normalized = os.path.realpath(os.path.expanduser(normalize_path(path.strip())))
+
+ if not os.path.exists(normalized):
+ raise ValueError("Path does not exist")
+ if not os.path.isdir(normalized):
+ raise ValueError("Path must be a directory, not a file")
+ if not os.access(normalized, os.R_OK | os.X_OK):
+ raise ValueError("Path is not readable")
+ if os.path.dirname(normalized) == normalized:
+ # Registering a filesystem root would expose denied system dirs via browse.
+ raise ValueError("The filesystem root cannot be registered")
+ if _contains_sensitive_path_component(normalized):
+ raise ValueError("Credential or configuration directories are not allowed")
+
+ is_win = platform.system() == "Windows"
+ check = os.path.normcase(normalized) if is_win else normalized
+ for prefix in _denied_path_prefixes():
+ if check == prefix or check.startswith(prefix + os.sep):
+ raise ValueError(f"Path under {prefix} is not allowed")
+
+ conn = get_connection()
+ try:
+ _ensure_schema(conn)
+ now = datetime.now(timezone.utc).isoformat()
+ if is_win:
+ existing = conn.execute(
+ "SELECT id, path, created_at FROM scan_folders WHERE path = ? COLLATE NOCASE",
+ (normalized,),
+ ).fetchone()
+ else:
+ existing = conn.execute(
+ "SELECT id, path, created_at FROM scan_folders WHERE path = ?",
+ (normalized,),
+ ).fetchone()
+ if existing is not None:
+ return dict(existing)
+ try:
+ conn.execute(
+ "INSERT INTO scan_folders (path, created_at) VALUES (?, ?)",
+ (normalized, now),
+ )
+ conn.commit()
+ except sqlite3.IntegrityError:
+ pass
+ fallback_sql = (
+ "SELECT id, path, created_at FROM scan_folders WHERE path = ? COLLATE NOCASE"
+ if is_win
+ else "SELECT id, path, created_at FROM scan_folders WHERE path = ?"
+ )
+ row = conn.execute(fallback_sql, (normalized,)).fetchone()
+ if row is None:
+ raise ValueError("Folder was concurrently removed")
+ return dict(row)
+ finally:
+ conn.close()
+
+
+def remove_scan_folder(id: int) -> None:
+ # sqlite INTEGER is signed 64-bit; ids outside that range cannot exist.
+ if not -(2**63) <= id < 2**63:
+ return
+ conn = get_connection()
+ try:
+ _ensure_schema(conn)
+ conn.execute("DELETE FROM scan_folders WHERE id = ?", (id,))
+ conn.commit()
+ finally:
+ conn.close()
diff --git a/studio/backend/hub/tests/conftest.py b/studio/backend/hub/tests/conftest.py
new file mode 100644
index 00000000000..38b6bed9384
--- /dev/null
+++ b/studio/backend/hub/tests/conftest.py
@@ -0,0 +1,106 @@
+# 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 sys
+import types
+
+
+class _BaseModel:
+ def __init__(self, **kwargs):
+ for name, value in self.__class__.__dict__.items():
+ if name.startswith("_") or callable(value):
+ continue
+ if name not in kwargs:
+ setattr(self, name, value)
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+ def model_dump(self):
+ return dict(self.__dict__)
+
+ def model_copy(self, update = None):
+ data = self.model_dump()
+ if update:
+ data.update(update)
+ return self.__class__(**data)
+
+
+def _field(default = ..., **kwargs):
+ if "default_factory" in kwargs:
+ return kwargs["default_factory"]()
+ return None if default is ... else default
+
+
+def _model_validator(*args, **kwargs):
+ def decorator(fn):
+ return fn
+
+ return decorator
+
+
+class _HTTPException(Exception):
+ def __init__(
+ self,
+ status_code: int,
+ detail = None,
+ ):
+ super().__init__(detail)
+ self.status_code = status_code
+ self.detail = detail
+
+
+class _APIRouter:
+ def get(self, *args, **kwargs):
+ return lambda fn: fn
+
+ def post(self, *args, **kwargs):
+ return lambda fn: fn
+
+ def delete(self, *args, **kwargs):
+ return lambda fn: fn
+
+
+def _fastapi_marker(
+ default = None,
+ *args,
+ **kwargs,
+):
+ return default
+
+
+class _DummyLogger:
+ def __getattr__(self, _name):
+ return lambda *args, **kwargs: None
+
+
+sys.modules.setdefault(
+ "pydantic",
+ types.SimpleNamespace(
+ BaseModel = _BaseModel,
+ Field = _field,
+ model_validator = _model_validator,
+ ),
+)
+sys.modules.setdefault(
+ "fastapi",
+ types.SimpleNamespace(
+ APIRouter = _APIRouter,
+ Body = _fastapi_marker,
+ Depends = _fastapi_marker,
+ Header = _fastapi_marker,
+ HTTPException = _HTTPException,
+ Query = _fastapi_marker,
+ UploadFile = object,
+ ),
+)
+sys.modules.setdefault(
+ "loggers",
+ types.SimpleNamespace(get_logger = lambda *args, **kwargs: _DummyLogger()),
+)
+sys.modules.setdefault(
+ "structlog",
+ types.SimpleNamespace(
+ BoundLogger = _DummyLogger,
+ get_logger = lambda *args, **kwargs: _DummyLogger(),
+ ),
+)
diff --git a/studio/backend/hub/tests/test_dataset_services.py b/studio/backend/hub/tests/test_dataset_services.py
new file mode 100644
index 00000000000..4890714cd07
--- /dev/null
+++ b/studio/backend/hub/tests/test_dataset_services.py
@@ -0,0 +1,356 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+from hub.schemas.datasets import CheckFormatRequest, LocalDatasetItem
+from hub.services.datasets import cache_inventory, downloads, formatting, local
+from hub.utils import download_manifest, download_registry, state_dir
+
+
+class _Upload:
+ def __init__(self, filename: str, payload: bytes):
+ self.filename = filename
+ self._payload = payload
+ self._offset = 0
+
+ async def read(self, size: int) -> bytes:
+ if self._offset >= len(self._payload):
+ return b""
+ chunk = self._payload[self._offset : self._offset + size]
+ self._offset += len(chunk)
+ return chunk
+
+
+def test_dataset_cache_scan_merges_raw_and_processed_rows(monkeypatch):
+ raw_repo = SimpleNamespace(
+ repo_id = "Org/Data",
+ repo_type = "dataset",
+ repo_path = "/cache/datasets--Org--Data",
+ size_on_disk = 100,
+ revisions = [SimpleNamespace(files = [], commit_hash = "abc")],
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_collect_hf_cache_scans",
+ lambda: ([SimpleNamespace(repos = [raw_repo])], {"/cache"}),
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda _repo_type, _repo_id, _cache_dir: False,
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_scan_hub_dataset_cache_dirs",
+ lambda: [],
+ )
+ 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 len(rows) == 1
+ assert rows[0]["repo_id"] == "Org/Data"
+ assert rows[0]["size_bytes"] == 250
+ assert rows[0]["partial"] is False
+
+
+def test_delete_cached_dataset_attempts_all_roots_before_raising(monkeypatch):
+ calls = []
+ purged_state = []
+
+ class _DeleteStrategy:
+ def __init__(self, label: str, fail: bool):
+ self.label = label
+ self.fail = fail
+
+ def execute(self):
+ calls.append(self.label)
+ if self.fail:
+ raise RuntimeError(f"{self.label} failed")
+
+ class _Cache:
+ def __init__(self, label: str, fail: bool):
+ self.cache_dir = label
+ self.repos = [
+ SimpleNamespace(
+ repo_type = "dataset",
+ repo_id = "Org/Data",
+ revisions = [SimpleNamespace(commit_hash = f"{label}-rev")],
+ )
+ ]
+ self.fail = fail
+
+ def delete_revisions(self, *_revisions):
+ return _DeleteStrategy(self.cache_dir, self.fail)
+
+ monkeypatch.setattr(
+ cache_inventory,
+ "_collect_hf_cache_scans",
+ lambda: ([_Cache("first", True), _Cache("second", False)], set()),
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_delete_processed_dataset_cache",
+ lambda _repo_id: (True, []),
+ )
+ monkeypatch.setattr(
+ cache_inventory.download_manifest,
+ "purge_all_state_for_repo",
+ lambda *_args: purged_state.append(True) or 1,
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ cache_inventory._delete_cached_dataset_blocking("Org/Data")
+
+ assert exc_info.value.status_code == 500
+ assert calls == ["first", "second"]
+ assert purged_state == []
+
+
+def test_delete_cached_dataset_purges_blob_only_repo_dir(monkeypatch):
+ """A blob-only ``datasets--owner--repo`` dir (no usable snapshot/refs) is
+ fully removable: purge_partial_repo alone clears only ``.incomplete`` files
+ and would leave the complete blobs and the row."""
+ purged_dirs: list[str] = []
+
+ monkeypatch.setattr(
+ cache_inventory,
+ "_collect_hf_cache_scans",
+ lambda: ([], set()),
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_delete_processed_dataset_cache",
+ lambda _repo_id: (False, []),
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "purge_repo_cache_dirs",
+ lambda _repo_type, repo_id: purged_dirs.append(repo_id) or True,
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "purge_partial_repo",
+ lambda *_args: False,
+ )
+ monkeypatch.setattr(
+ cache_inventory.download_manifest,
+ "purge_all_state_for_repo",
+ lambda *_args: 0,
+ )
+
+ result = cache_inventory._delete_cached_dataset_blocking("Org/Data")
+
+ assert result == {"status": "deleted", "repo_id": "Org/Data"}
+ assert purged_dirs == ["Org/Data"]
+
+
+def test_delete_cached_dataset_absent_everywhere_raises_404(monkeypatch):
+ monkeypatch.setattr(
+ cache_inventory,
+ "_collect_hf_cache_scans",
+ lambda: ([], set()),
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "_delete_processed_dataset_cache",
+ lambda _repo_id: (False, []),
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "purge_repo_cache_dirs",
+ lambda *_args: False,
+ )
+ monkeypatch.setattr(
+ cache_inventory,
+ "purge_partial_repo",
+ lambda *_args: False,
+ )
+ monkeypatch.setattr(
+ cache_inventory.download_manifest,
+ "purge_all_state_for_repo",
+ lambda *_args: 0,
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ cache_inventory._delete_cached_dataset_blocking("Org/Missing")
+
+ assert exc_info.value.status_code == 404
+
+
+def test_check_format_rejects_invalid_path_as_400():
+ with pytest.raises(HTTPException) as exc_info:
+ formatting.check_format_response(CheckFormatRequest(dataset_name = "../../etc/passwd"))
+
+ assert exc_info.value.status_code == 400
+
+
+def test_dataset_download_status_preserves_idle_shape():
+ status = downloads._dataset_status("Org/Data")
+
+ assert status.state == "idle"
+ assert status.error is None
+
+
+def test_dataset_download_registry_key_is_case_insensitive():
+ registry = download_registry.DownloadRegistry()
+
+ claimed, state = registry.claim(
+ "Org/Data",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "dataset",
+ repo_id = "Org/Data",
+ )
+ duplicate_claimed, duplicate_state = registry.claim(
+ "org/data",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "dataset",
+ repo_id = "org/data",
+ )
+
+ assert claimed is True
+ assert state == "running"
+ assert duplicate_claimed is False
+ assert duplicate_state == "running"
+ assert registry.active_jobs("ORG/DATA") == {"org/data": "running"}
+
+
+def test_dataset_idle_status_uses_cancel_marker_after_restart(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
+ monkeypatch.setattr(downloads, "_registry", download_registry.DownloadRegistry())
+ assert download_manifest.write_cancel_marker("dataset", "Owner/Data", None, "http")
+
+ status = asyncio.run(downloads.get_dataset_download_status_response("owner/data"))
+
+ assert status.state == "cancelled"
+ assert status.error is None
+
+
+def test_dataset_claim_register_cancel_uses_registry_marker_owner(monkeypatch):
+ killed = []
+
+ class _Registry:
+ def claim(self, *_args, **_kwargs):
+ return True, "running"
+
+ def current_generation(self, _key):
+ return 1
+
+ def register_process(self, _key, _proc):
+ return False
+
+ def persist_cancel_for_key(self, *_args, **_kwargs):
+ raise AssertionError("register_process owns pending-cancel markers")
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "cancelled", error = None)
+
+ monkeypatch.setattr(downloads, "_registry", _Registry())
+ monkeypatch.setattr(
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
+ )
+ monkeypatch.setattr(
+ downloads.download_registry,
+ "download_transport_unavailable_reason",
+ lambda _transport: None,
+ )
+ monkeypatch.setattr(
+ downloads.download_lifecycle,
+ "spawn_worker",
+ lambda *_args, **_kwargs: object(),
+ )
+ monkeypatch.setattr(
+ downloads.download_lifecycle,
+ "kill_and_reap_process",
+ lambda proc, **_kwargs: killed.append(proc),
+ )
+
+ result = asyncio.run(
+ downloads.download_dataset_response(SimpleNamespace(repo_id = "Org/Data", use_xet = False))
+ )
+
+ assert result["state"] == "cancelled"
+ assert killed
+
+
+def test_dataset_cancel_pending_spawn_arms_pending_cancel(monkeypatch):
+ events = []
+
+ class _Registry:
+ def get_process(self, _key):
+ return None
+
+ def mark_pending_cancel(self, key, generation):
+ events.append(("pending", key, generation))
+ return True
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running")
+
+ monkeypatch.setattr(downloads, "_registry", _Registry())
+ monkeypatch.setattr(
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
+ )
+
+ result = asyncio.run(
+ downloads.cancel_dataset_download_response(
+ SimpleNamespace(repo_id = "Org/Data", generation = 5)
+ )
+ )
+
+ assert result == {"repo_id": "Org/Data", "state": "cancelling"}
+ assert events == [("pending", "org/data", 5)]
+
+
+def test_upload_dataset_response_writes_non_empty_file(monkeypatch, tmp_path):
+ payload = b'{"text":"hello"}\n'
+ monkeypatch.setattr(local, "DATASET_UPLOAD_DIR", tmp_path)
+
+ response = asyncio.run(local.upload_dataset_response(_Upload("../train.jsonl", payload)))
+
+ stored_path = Path(response.stored_path)
+ assert response.filename == "train.jsonl"
+ assert stored_path.parent == tmp_path
+ assert stored_path.name.endswith("_train.jsonl")
+ assert stored_path.read_bytes() == payload
+
+
+def test_local_dataset_items_expose_recipe_and_upload_source(monkeypatch, tmp_path):
+ recipe_root = tmp_path / "recipes"
+ upload_root = tmp_path / "uploads"
+ parquet_dir = recipe_root / "recipe_alpha" / "parquet-files"
+ parquet_dir.mkdir(parents = True)
+ (parquet_dir / "part.parquet").write_bytes(b"parquet")
+ upload_root.mkdir()
+ (upload_root / "manual.jsonl").write_text('{"text":"hello"}\n', encoding = "utf-8")
+ monkeypatch.setattr(local, "LOCAL_DATASETS_ROOT", recipe_root)
+ monkeypatch.setattr(local, "DATASET_UPLOAD_DIR", upload_root)
+
+ response = local.list_local_datasets_response()
+
+ assert "source" in LocalDatasetItem.__annotations__
+ by_id = {item.id: item for item in response.datasets}
+ assert by_id["recipe_alpha"].source == "recipe"
+ assert by_id["manual.jsonl"].source == "upload"
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
new file mode 100644
index 00000000000..44ab4b80d0b
--- /dev/null
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -0,0 +1,2962 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import asyncio
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+from hub.dependencies import get_hf_token
+from hub.storage import scan_folders
+from hub.services import download_lifecycle
+from hub.services import snapshot_progress
+from hub.services.datasets import downloads as dataset_downloads
+from hub.services.models import (
+ cache_inventory,
+ common as model_common,
+ deletion,
+ downloads,
+ folder_browser,
+ gguf_variants,
+ local_inventory,
+ ollama,
+)
+from hub.utils import (
+ download_manifest,
+ download_registry,
+ gguf,
+ hf_cache_state,
+ inventory_scan,
+ paths,
+ state_dir,
+)
+from hub.workers import hf_download
+
+
+def _repo(repo_id: str, files: list[SimpleNamespace], repo_path: Path):
+ return SimpleNamespace(
+ repo_id = repo_id,
+ repo_type = "model",
+ repo_path = repo_path,
+ revisions = [SimpleNamespace(files = files)],
+ )
+
+
+def _file(
+ name: str,
+ size: int,
+ blob_path: str | None = None,
+):
+ return SimpleNamespace(file_name = name, size_on_disk = size, blob_path = blob_path)
+
+
+def _sibling(name: str, size: int, sha: str):
+ return SimpleNamespace(rfilename = name, size = size, lfs = {"sha256": sha})
+
+
+class TestExtractQuantToken:
+ def test_trailing_precision_is_kept(self):
+ assert gguf.extract_quant_token("model-it-F16.gguf") == "F16"
+ assert gguf.extract_quant_token("model-BF16.gguf") == "BF16"
+
+ def test_real_quant_wins_over_infix_precision(self):
+ assert gguf.extract_quant_token("Foo-BF16-Q4_K_M.gguf") == "Q4_K_M"
+ assert gguf.extract_quant_token("Foo-F16-Q8_0.gguf") == "Q8_0"
+ assert gguf.extract_quant_token("Foo-F32-IQ4_XS.gguf") == "IQ4_XS"
+
+ def test_ud_prefix_preserved(self):
+ assert gguf.extract_quant_token("Foo-BF16-UD-Q4_K_XL.gguf") == "UD-Q4_K_XL"
+
+ def test_precision_infix_variants_do_not_collapse(self):
+ labels = {
+ gguf.extract_quant_label("Foo-BF16-Q4_K_M.gguf"),
+ gguf.extract_quant_label("Foo-BF16-Q8_0.gguf"),
+ }
+ assert labels == {"Q4_K_M", "Q8_0"}
+
+
[email protected]("repo_id", ["bert-base-uncased", "owner/repo"])
+def test_repo_id_validation_accepts_hf_repo_id_contract(repo_id):
+ assert paths.is_valid_repo_id(repo_id)
+
+
+ "repo_id",
+ [
+ "datasets/foo/bar",
+ ".repo",
+ "repo.git",
+ "foo..bar",
+ "foo--bar",
+ "../repo",
+ "owner/../repo",
+ ],
+)
+def test_repo_id_validation_rejects_unsafe_or_invalid_ids(repo_id):
+ assert not paths.is_valid_repo_id(repo_id)
+
+
+class _RecordingLogger:
+ def __init__(self):
+ self.warnings = []
+
+ def warning(self, *args, **kwargs):
+ self.warnings.append((args, kwargs))
+
+
+def test_resolve_browse_target_preserves_allowlist_and_symlink_safety(tmp_path):
+ home = tmp_path / "home"
+ scan = tmp_path / "scan"
+ target = scan / "nested"
+ home.mkdir()
+ target.mkdir(parents = True)
+ (home / "scan-link").symlink_to(scan, target_is_directory = True)
+
+ resolved = folder_browser._resolve_browse_target(
+ str(home / "scan-link" / "nested"),
+ [home, scan],
+ )
+
+ assert resolved == target.resolve()
+
+
+def test_resolve_browse_target_rejects_outside_allowlist(tmp_path):
+ allowed = tmp_path / "allowed"
+ outside = tmp_path / "outside"
+ allowed.mkdir()
+ outside.mkdir()
+
+ with pytest.raises(HTTPException) as exc_info:
+ folder_browser._resolve_browse_target(str(outside), [allowed])
+
+ assert exc_info.value.status_code == 403
+
+
+def test_resolve_browse_target_rejects_sensitive_dir(tmp_path):
+ home = tmp_path / "home"
+ ssh = home / ".ssh"
+ ssh.mkdir(parents = True)
+
+ with pytest.raises(HTTPException) as exc_info:
+ folder_browser._resolve_browse_target(str(ssh), [home])
+
+ assert exc_info.value.status_code == 403
+
+
+def test_browse_folders_hides_sensitive_dirs(monkeypatch, tmp_path):
+ home = tmp_path / "home"
+ (home / ".ssh").mkdir(parents = True)
+ (home / "models").mkdir()
+ monkeypatch.setattr(folder_browser, "_build_browse_allowlist", lambda: [home])
+
+ response = folder_browser.browse_folders_response(str(home), show_hidden = True)
+
+ names = {entry.name for entry in response.entries}
+ assert "models" in names
+ assert ".ssh" not in names
+
+
+def test_contained_link_path_confines_to_link_dir(tmp_path):
+ link_dir = tmp_path / "ollama" / ".studio_links" / "abc123"
+
+ legit = ollama._contained_link_path(link_dir, "llama3-latest-Q4_K_M.gguf")
+ assert legit == link_dir / "llama3-latest-Q4_K_M.gguf"
+
+ for unsafe in (
+ "",
+ ".",
+ "..",
+ "a/b.gguf",
+ "../evil.gguf",
+ "/etc/passwd",
+ "model-tag-../../../pwned.gguf",
+ ):
+ assert ollama._contained_link_path(link_dir, unsafe) is None
+
+
+def test_make_ollama_blob_link_refuses_escaping_name(tmp_path):
+ root = tmp_path / "ollama"
+ link_dir = root / ".studio_links" / "abc123"
+ blob = root / "blobs" / "sha256-deadbeef"
+ blob.parent.mkdir(parents = True)
+ blob.write_bytes(b"weights")
+
+ escaped = ollama._make_ollama_blob_link(link_dir, "model-tag-../../../pwned.gguf", blob)
+ assert escaped is None
+ assert not list(tmp_path.rglob("pwned.gguf"))
+
+ safe = ollama._make_ollama_blob_link(link_dir, "model-tag.gguf", blob)
+ assert safe == str(link_dir / "model-tag.gguf")
+ assert (link_dir / "model-tag.gguf").exists()
+
+
+def test_cached_gguf_scan_dedupes_and_excludes_mmproj_only(monkeypatch, tmp_path):
+ smaller = _repo("Org/Dupe", [_file("Q4_K_M.gguf", 100)], tmp_path / "small")
+ larger = _repo(
+ "org/dupe",
+ [_file("Q4_K_M.gguf", 300), _file("Q8_0.gguf", 200)],
+ tmp_path / "large",
+ )
+ mmproj_only = _repo("Org/VisionAdapter", [_file("mmproj-F16.gguf", 900)], tmp_path / "mmproj")
+ monkeypatch.setattr(
+ cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [smaller, larger, mmproj_only])],
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_gguf_repo_partial",
+ lambda _repo_id, _path: False,
+ )
+
+ result = {"cached": cache_inventory._scan_cached_gguf()}
+
+ assert [row["repo_id"] for row in result["cached"]] == ["org/dupe"]
+ assert result["cached"][0]["size_bytes"] == 500
+ assert result["cached"][0]["model_format"] == "gguf"
+ assert result["cached"][0]["capabilities"]["requires_variant"] is True
+
+
+def test_cached_gguf_scan_preserves_partial_flag(monkeypatch, tmp_path):
+ partial = _repo("Org/Partial", [_file("Q4_K_M.gguf", 100)], tmp_path / "partial")
+ monkeypatch.setattr(
+ cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [partial])],
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_gguf_repo_partial",
+ lambda _repo_id, _path: True,
+ )
+
+ result = {"cached": cache_inventory._scan_cached_gguf()}
+ row = result["cached"][0]
+
+ assert row["partial"] is True
+ assert row["partial_transport"] is None
+ assert row["capabilities"]["can_chat"] is False
+
+
+def test_cached_gguf_scan_includes_variant_state_without_completed_gguf(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ repo_path = tmp_path / "hub" / "models--Org--PartialGguf"
+ repo_path.mkdir(parents = True)
+ partial = _repo(
+ "Org/PartialGguf",
+ [_file("config.json", 12)],
+ repo_path,
+ )
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/PartialGguf",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 4096)],
+ "http",
+ )
+ assert download_manifest.write_cancel_marker("model", "Org/PartialGguf", "Q4_K_M", "http")
+ monkeypatch.setattr(
+ cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [partial])],
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_gguf_repo_partial",
+ lambda _repo_id, _path: True,
+ )
+
+ result = {"cached": cache_inventory._scan_cached_gguf()}
+ row = result["cached"][0]
+
+ assert row["repo_id"] == "Org/PartialGguf"
+ assert row["model_format"] == "gguf"
+ assert row["size_bytes"] == 4096
+ assert row["partial"] is True
+ assert row["capabilities"]["requires_variant"] is True
+
+
+def test_gguf_variant_requirements_include_split_files_and_preferred_mmproj():
+ requirements = gguf_variants._build_gguf_variant_requirements(
+ [
+ _sibling("model-Q4_K_M-00001-of-00002.gguf", 10, "main-a"),
+ _sibling("model-Q4_K_M-00002-of-00002.gguf", 20, "main-b"),
+ _sibling("mmproj-BF16.gguf", 7, "mm-bf16"),
+ _sibling("mmproj-F16.gguf", 5, "mm-f16"),
+ ]
+ )
+
+ req = requirements["q4_k_m"]
+
+ assert req.main_size_bytes == 30
+ assert req.download_size_bytes == 35
+ assert req.main_hashes == frozenset({"main-a", "main-b"})
+ assert req.required_hashes == frozenset({"main-a", "main-b", "mm-f16"})
+ assert req.companion_hashes == frozenset({"mm-f16"})
+ assert req.mmproj_hashes == frozenset({"mm-bf16", "mm-f16"})
+ assert req.target_filenames == (
+ "model-Q4_K_M-00001-of-00002.gguf",
+ "model-Q4_K_M-00002-of-00002.gguf",
+ "mmproj-F16.gguf",
+ )
+
+
+def test_worker_gguf_variant_plan_matches_service_requirement(monkeypatch):
+ siblings = [
+ _sibling("model-Q4_K_M-00001-of-00002.gguf", 10, "main-a"),
+ _sibling("model-Q4_K_M-00002-of-00002.gguf", 20, "main-b"),
+ _sibling("mmproj-BF16.gguf", 7, "mm-bf16"),
+ _sibling("mmproj-F16.gguf", 5, "mm-f16"),
+ ]
+ monkeypatch.setattr(
+ hf_download,
+ "_model_info_with_retry",
+ lambda *_args, **_kwargs: SimpleNamespace(siblings = siblings),
+ )
+
+ service_req = gguf_variants._build_gguf_variant_requirements(siblings)["q4_k_m"]
+ worker_plan = hf_download._gguf_variant_target_plan("Org/Vision", "Q4_K_M", None)
+
+ assert worker_plan == service_req
+
+
+def test_gguf_variant_blob_hashes_accept_dict_lfs_fallback(monkeypatch):
+ with gguf_variants._VARIANT_HASH_LOCK:
+ gguf_variants._VARIANT_HASH_CACHE.clear()
+ gguf_variants._VARIANT_REQUIREMENT_CACHE.clear()
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(
+ HfApi = lambda *_args, **_kwargs: SimpleNamespace(
+ model_info = lambda *_a, **_k: SimpleNamespace(
+ siblings = [
+ _sibling("model-Q4_K_M.gguf", 10, "main-dict"),
+ _sibling("model-Q8_0.gguf", 20, "other"),
+ _sibling("mmproj-F16.gguf", 5, "mmproj"),
+ ]
+ )
+ )
+ ),
+ )
+
+ result = gguf_variants.gguf_variant_blob_hashes("Org/DictLfs", "Q4_K_M", None)
+ main_only = gguf_variants.gguf_variant_blob_hashes(
+ "Org/DictLfs",
+ "Q4_K_M",
+ None,
+ include_companions = False,
+ )
+
+ assert result == frozenset({"main-dict", "mmproj"})
+ assert main_only == frozenset({"main-dict"})
+
+
+def test_gguf_variant_blob_hashes_skip_missing_rfilename(monkeypatch):
+ with gguf_variants._VARIANT_HASH_LOCK:
+ gguf_variants._VARIANT_HASH_CACHE.clear()
+ gguf_variants._VARIANT_REQUIREMENT_CACHE.clear()
+ siblings = [
+ SimpleNamespace(rfilename = None, size = 1, lfs = {"sha256": "bad"}),
+ _sibling("model-Q4_K_M.gguf", 10, "main"),
+ ]
+ monkeypatch.setattr(
+ gguf_variants,
+ "_fetch_gguf_variant_requirements",
+ lambda _repo_id, _hf_token = None: gguf_variants._build_gguf_variant_requirements(siblings),
+ )
+
+ result = gguf_variants.gguf_variant_blob_hashes("Org/Malformed", "Q4_K_M", None)
+
+ assert result == frozenset({"main"})
+
+
+def test_worker_gguf_variant_targets_skip_missing_rfilename(monkeypatch):
+ monkeypatch.setattr(
+ hf_download,
+ "_model_info_with_retry",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ siblings = [
+ SimpleNamespace(rfilename = None, size = 1),
+ _sibling("model-Q4_K_M.gguf", 10, "main"),
+ _sibling("mmproj-F16.gguf", 5, "mm"),
+ ]
+ ),
+ )
+
+ result = hf_download._gguf_variant_target_plan("Org/Malformed", "Q4_K_M", None)
+
+ assert list(result.target_filenames) == ["model-Q4_K_M.gguf", "mmproj-F16.gguf"]
+
+
+def test_download_gguf_variant_purges_only_main_quant_hashes(monkeypatch, tmp_path):
+ prepare_calls = []
+ snapshot_calls = []
+ written = []
+ verified = []
+
+ monkeypatch.setattr(
+ hf_download,
+ "_model_info_with_retry",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ siblings = [
+ _sibling("model-Q4_K_M.gguf", 10, "q4-main"),
+ _sibling("model-Q8_0.gguf", 20, "q8-main"),
+ _sibling("mmproj-F16.gguf", 5, "shared-mmproj"),
+ ]
+ ),
+ )
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry,
+ "prepare_cache_for_transport",
+ lambda *args, **kwargs: prepare_calls.append((args, kwargs)) or 0,
+ )
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
+ monkeypatch.setattr(
+ download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(
+ snapshot_download = lambda **kwargs: snapshot_calls.append(kwargs) or str(tmp_path)
+ ),
+ )
+
+ hf_download._download_gguf_variant("Org/Vision", "Q4_K_M", None, "http")
+
+ assert prepare_calls == [
+ (
+ ("model", "Org/Vision", "http", "Q4_K_M"),
+ {
+ "only_blob_hashes": frozenset({"q4-main"}),
+ "companion_blob_hashes": frozenset({"shared-mmproj"}),
+ "protected_blob_hashes": frozenset(),
+ },
+ )
+ ]
+ assert [file.path for file in written[0][3]] == ["model-Q4_K_M.gguf", "mmproj-F16.gguf"]
+ assert snapshot_calls[0]["allow_patterns"] == ["model-Q4_K_M.gguf", "mmproj-F16.gguf"]
+ assert verified == [("model", "Org/Vision", "Q4_K_M", str(tmp_path))]
+
+
+def test_download_gguf_variant_manifest_resume_purges_only_main_quant_hashes(monkeypatch, tmp_path):
+ prepare_calls = []
+ snapshot_calls = []
+
+ def _metadata_unavailable(*_args, **_kwargs):
+ raise RuntimeError("metadata down")
+
+ manifest = download_manifest.Manifest(
+ repo_type = "model",
+ repo_id = "Org/Vision",
+ variant = "Q4_K_M",
+ started_at = "",
+ expected_files = (
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 10,
+ sha256 = "q4-main",
+ ),
+ download_manifest.ExpectedFile(
+ path = "mmproj-F16.gguf",
+ size = 5,
+ sha256 = "shared-mmproj",
+ ),
+ ),
+ transport = "http",
+ )
+ monkeypatch.setattr(
+ hf_download,
+ "_gguf_variant_target_plan",
+ _metadata_unavailable,
+ )
+ monkeypatch.setattr(download_manifest, "read_manifest", lambda *_args: manifest)
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
+ monkeypatch.setattr(
+ download_registry,
+ "prepare_cache_for_transport",
+ lambda *args, **kwargs: prepare_calls.append((args, kwargs)) or 0,
+ )
+ monkeypatch.setattr(hf_download, "_verify_completed_download", lambda *_args, **_kwargs: None)
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(
+ snapshot_download = lambda **kwargs: snapshot_calls.append(kwargs) or str(tmp_path)
+ ),
+ )
+
+ hf_download._download_gguf_variant("Org/Vision", "Q4_K_M", None, "http")
+
+ assert prepare_calls == [
+ (
+ ("model", "Org/Vision", "http", "Q4_K_M"),
+ {
+ "only_blob_hashes": frozenset({"q4-main"}),
+ "companion_blob_hashes": frozenset({"shared-mmproj"}),
+ "protected_blob_hashes": frozenset(),
+ },
+ )
+ ]
+ assert snapshot_calls[0]["allow_patterns"] == ["model-Q4_K_M.gguf", "mmproj-F16.gguf"]
+
+
+def test_download_snapshot_recovers_manifest_after_metadata_fallback(monkeypatch, tmp_path):
+ metadata_calls = []
+ written = []
+ cleared = []
+ verified = []
+
+ def _metadata(*_args, **_kwargs):
+ metadata_calls.append(True)
+ if len(metadata_calls) == 1:
+ raise RuntimeError("metadata down")
+ return SimpleNamespace(siblings = [SimpleNamespace(rfilename = "config.json", size = 12)])
+
+ monkeypatch.setattr(hf_download, "_model_info_with_retry", _metadata)
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ )
+ monkeypatch.setattr(
+ download_manifest, "clear_cancel_marker", lambda *args: cleared.append(args)
+ )
+ monkeypatch.setattr(
+ download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
+ )
+
+ hf_download._download_snapshot("Org/Model", None, "http")
+
+ assert len(metadata_calls) == 2
+ assert cleared == [("model", "Org/Model", None)]
+ assert written[0][0:3] == ("model", "Org/Model", None)
+ assert written[0][3][0].path == "config.json"
+ assert verified == [("model", "Org/Model", None, str(tmp_path))]
+
+
+def test_download_dataset_continues_without_metadata_manifest(monkeypatch, tmp_path):
+ metadata_calls = []
+ snapshot_calls = []
+ written = []
+ cleared = []
+ verified = []
+
+ def _metadata(*_args, **_kwargs):
+ metadata_calls.append(True)
+ raise RuntimeError("metadata down")
+
+ monkeypatch.setattr(hf_download, "_dataset_info_with_retry", _metadata)
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ )
+ monkeypatch.setattr(
+ download_manifest, "clear_cancel_marker", lambda *args: cleared.append(args)
+ )
+ monkeypatch.setattr(
+ download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ )
+ monkeypatch.setattr(
+ hf_cache_state, "has_active_incomplete_blobs", lambda *_args, **_kwargs: False
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(
+ snapshot_download = lambda **kwargs: snapshot_calls.append(kwargs) or str(tmp_path)
+ ),
+ )
+
+ hf_download._download_dataset("Org/Data", None, "http")
+
+ assert len(metadata_calls) == 2
+ assert cleared == [("dataset", "Org/Data", None)]
+ assert written == []
+ assert snapshot_calls == [
+ {
+ "repo_id": "Org/Data",
+ "token": False,
+ "repo_type": "dataset",
+ "max_workers": 1,
+ }
+ ]
+ assert verified == [("dataset", "Org/Data", None, str(tmp_path))]
+
+
+def test_download_snapshot_fails_when_metadata_unavailable_and_partial_remains(
+ monkeypatch, tmp_path
+):
+ """No prior manifest + metadata unavailable + leftover .incomplete blobs means
+ a cached partial was returned without downloading: the worker must exit 1, not
+ derive a self-certifying manifest from the finalized subset."""
+ written = []
+ verified = []
+
+ def _metadata(*_args, **_kwargs):
+ raise RuntimeError("metadata down")
+
+ monkeypatch.setattr(hf_download, "_model_info_with_retry", _metadata)
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ )
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
+ monkeypatch.setattr(download_manifest, "read_manifest", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(
+ download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ )
+ monkeypatch.setattr(
+ hf_cache_state, "has_active_incomplete_blobs", lambda *_args, **_kwargs: True
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
+ )
+
+ with pytest.raises(SystemExit) as excinfo:
+ hf_download._download_snapshot("Org/Model", None, "http")
+
+ assert excinfo.value.code == 1
+ assert written == []
+ assert verified == []
+
+
+def test_purge_repo_cache_dirs_skips_top_level_symlink(monkeypatch, tmp_path):
+ root = tmp_path / "hub"
+ target = tmp_path / "target"
+ root.mkdir()
+ target.mkdir()
+ link = root / "models--Org--Repo"
+ link.symlink_to(target, target_is_directory = True)
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [root])
+
+ removed = hf_cache_state.purge_repo_cache_dirs("model", "Org/Repo")
+
+ assert removed is False
+ assert link.is_symlink()
+ assert target.is_dir()
+
+
+def test_gguf_download_progress_fallback_logs_warning(monkeypatch):
+ token = "hf_12345678901234567890"
+ logger = _RecordingLogger()
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ def _raise_permission_error(*_args, **_kwargs):
+ raise PermissionError(f"denied {token}")
+
+ monkeypatch.setattr(snapshot_progress, "logger", logger)
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: None,
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda *_args, **_kwargs: frozenset(),
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ _raise_permission_error,
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "running")),
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model",
+ variant = "Q4_K_M",
+ expected_bytes = -1,
+ hf_token = token,
+ )
+ )
+
+ assert result == {
+ "downloaded_bytes": 0,
+ "completed_bytes": 0,
+ "complete_on_disk": False,
+ "expected_bytes": 0,
+ "progress": 0,
+ "cache_path": None,
+ }
+ assert logger.warnings
+ args, kwargs = logger.warnings[0]
+ assert args[:4] == (
+ "Error checking %s download progress for %s: %s: %s",
+ "model",
+ "Org/Model",
+ "PermissionError",
+ )
+ assert token not in args[4]
+ assert "***" in args[4]
+ assert kwargs == {}
+
+
+def test_gguf_progress_counts_completed_mmproj_with_expected_bytes(monkeypatch, tmp_path):
+ """A finished mmproj companion keeps counting toward progress once the caller
+ supplies expected bytes; resolving the variant requirement credits it."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (snap / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ (snap / "mmproj-F16.gguf").write_bytes(b"y" * 30)
+ (blobs / "mainhash").write_bytes(b"x" * 100)
+ (blobs / "mmprojhash").write_bytes(b"y" * 30)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ download_manifest.ExpectedFile(
+ path = "mmproj-F16.gguf",
+ size = 30,
+ sha256 = "mmprojhash",
+ ),
+ ],
+ "http",
+ )
+
+ requirement = gguf_variants._GgufVariantRequirement(
+ main_filenames = frozenset({"model-Q4_K_M.gguf"}),
+ target_filenames = ("model-Q4_K_M.gguf", "mmproj-F16.gguf"),
+ main_hashes = frozenset({"mainhash"}),
+ required_hashes = frozenset({"mainhash", "mmprojhash"}),
+ companion_hashes = frozenset({"mmprojhash"}),
+ mmproj_filenames = frozenset({"mmproj-F16.gguf"}),
+ mmproj_hashes = frozenset({"mmprojhash"}),
+ expected_files = (
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ download_manifest.ExpectedFile(
+ path = "mmproj-F16.gguf",
+ size = 30,
+ sha256 = "mmprojhash",
+ ),
+ ),
+ main_size_bytes = 100,
+ download_size_bytes = 130,
+ )
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: requirement,
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 130,
+ )
+ )
+
+ assert result["completed_bytes"] == 130
+ assert result["downloaded_bytes"] == 130
+ assert result["complete_on_disk"] is True
+ assert result["progress"] == 1.0
+
+
+def test_gguf_progress_subtracts_new_job_completed_baseline(monkeypatch, tmp_path):
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (snap / "mmproj-F16.gguf").write_bytes(b"y" * 30)
+ (blobs / "mmprojhash").write_bytes(b"y" * 30)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ download_manifest.ExpectedFile(
+ path = "mmproj-F16.gguf",
+ size = 30,
+ sha256 = "mmprojhash",
+ ),
+ ],
+ "http",
+ )
+
+ requirement = gguf_variants._GgufVariantRequirement(
+ main_filenames = frozenset({"model-Q4_K_M.gguf"}),
+ target_filenames = ("model-Q4_K_M.gguf", "mmproj-F16.gguf"),
+ main_hashes = frozenset({"mainhash"}),
+ required_hashes = frozenset({"mainhash", "mmprojhash"}),
+ companion_hashes = frozenset({"mmprojhash"}),
+ mmproj_filenames = frozenset({"mmproj-F16.gguf"}),
+ mmproj_hashes = frozenset({"mmprojhash"}),
+ expected_files = (
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ download_manifest.ExpectedFile(
+ path = "mmproj-F16.gguf",
+ size = 30,
+ sha256 = "mmprojhash",
+ ),
+ ),
+ main_size_bytes = 100,
+ download_size_bytes = 130,
+ )
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: requirement,
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "running"),
+ get_job_metadata = lambda _key: SimpleNamespace(
+ completed_baseline_bytes = 30,
+ ),
+ ),
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 130,
+ )
+ )
+
+ assert result["completed_bytes"] == 0
+ assert result["downloaded_bytes"] == 0
+ assert result["expected_bytes"] == 100
+ assert result["complete_on_disk"] is False
+ assert result["progress"] == 0
+
+
+def test_gguf_progress_shows_main_when_companion_left_the_count(monkeypatch, tmp_path):
+ # The mmproj companion that seeded the baseline is gone, so completed_bytes
+ # is main-only and below the baseline; it must not be subtracted to 0.
+ entry = tmp_path / "models--Org--Model-GGUF"
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "mainhash").write_bytes(b"x" * 20)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+
+ requirement = gguf_variants._GgufVariantRequirement(
+ main_filenames = frozenset({"model-Q4_K_M.gguf"}),
+ target_filenames = ("model-Q4_K_M.gguf", "mmproj-F16.gguf"),
+ main_hashes = frozenset({"mainhash"}),
+ required_hashes = frozenset({"mainhash", "mmprojhash"}),
+ companion_hashes = frozenset({"mmprojhash"}),
+ mmproj_filenames = frozenset({"mmproj-F16.gguf"}),
+ mmproj_hashes = frozenset({"mmprojhash"}),
+ expected_files = (
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ download_manifest.ExpectedFile(
+ path = "mmproj-F16.gguf",
+ size = 30,
+ sha256 = "mmprojhash",
+ ),
+ ),
+ main_size_bytes = 100,
+ download_size_bytes = 130,
+ )
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: requirement,
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "running"),
+ get_job_metadata = lambda _key: SimpleNamespace(
+ completed_baseline_bytes = 30,
+ ),
+ ),
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 130,
+ )
+ )
+
+ assert result["completed_bytes"] == 20
+ assert result["downloaded_bytes"] == 20
+ assert result["expected_bytes"] == 130
+ assert result["complete_on_disk"] is False
+
+
+def test_gguf_progress_complete_on_disk_ignores_full_baseline(monkeypatch, tmp_path):
+ # A variant already complete on disk carries a baseline equal to its full
+ # size; subtracting it would report 0/0 for a finished variant (frontend
+ # evicts it as gone). Once complete_on_disk is verified, the full figures
+ # must survive.
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (snap / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ (snap / "mmproj-F16.gguf").write_bytes(b"y" * 30)
+ (blobs / "mainhash").write_bytes(b"x" * 100)
+ (blobs / "mmprojhash").write_bytes(b"y" * 30)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ download_manifest.ExpectedFile(
+ path = "mmproj-F16.gguf",
+ size = 30,
+ sha256 = "mmprojhash",
+ ),
+ ],
+ "http",
+ )
+
+ requirement = gguf_variants._GgufVariantRequirement(
+ main_filenames = frozenset({"model-Q4_K_M.gguf"}),
+ target_filenames = ("model-Q4_K_M.gguf", "mmproj-F16.gguf"),
+ main_hashes = frozenset({"mainhash"}),
+ required_hashes = frozenset({"mainhash", "mmprojhash"}),
+ companion_hashes = frozenset({"mmprojhash"}),
+ mmproj_filenames = frozenset({"mmproj-F16.gguf"}),
+ mmproj_hashes = frozenset({"mmprojhash"}),
+ expected_files = (
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ download_manifest.ExpectedFile(
+ path = "mmproj-F16.gguf",
+ size = 30,
+ sha256 = "mmprojhash",
+ ),
+ ),
+ main_size_bytes = 100,
+ download_size_bytes = 130,
+ )
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: requirement,
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "running"),
+ get_job_metadata = lambda _key: SimpleNamespace(
+ completed_baseline_bytes = 130,
+ ),
+ ),
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 130,
+ )
+ )
+
+ assert result["complete_on_disk"] is True
+ assert result["completed_bytes"] == 130
+ assert result["downloaded_bytes"] == 130
+ assert result["expected_bytes"] == 130
+ assert result["progress"] == 1.0
+
+
+def test_gguf_progress_scoped_hashes_exclude_sibling_quant(monkeypatch, tmp_path):
+ # The "instant ~900 MB" bug: a sibling quant is fully cached when a different
+ # variant starts. With this variant's hashes resolved, progress counts ONLY
+ # its in-progress blob, never the sibling's finalized bytes in the shared
+ # blobs/ dir.
+ entry = tmp_path / "models--Org--Model-GGUF"
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "siblinghash").write_bytes(b"z" * 900) # other quant, complete
+ (blobs / "mainhash.incomplete").write_bytes(b"x" * 5) # this variant, started
+
+ requirement = gguf_variants._GgufVariantRequirement(
+ main_filenames = frozenset({"model-Q4_K_M.gguf"}),
+ target_filenames = ("model-Q4_K_M.gguf",),
+ main_hashes = frozenset({"mainhash"}),
+ required_hashes = frozenset({"mainhash"}),
+ companion_hashes = frozenset(),
+ mmproj_filenames = frozenset(),
+ mmproj_hashes = frozenset(),
+ expected_files = (
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ ),
+ main_size_bytes = 100,
+ download_size_bytes = 100,
+ )
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: requirement,
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "running"),
+ get_job_metadata = lambda _key: SimpleNamespace(
+ completed_baseline_bytes = 0,
+ ),
+ ),
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
+
+ assert result["completed_bytes"] == 0
+ assert result["downloaded_bytes"] == 5
+
+
+def test_gguf_progress_unknown_hashes_does_not_count_foreign_blobs(monkeypatch, tmp_path):
+ # With a variant's hashes unresolved (metadata flaked, no manifest), the
+ # shared blobs/ dir's FINALIZED blobs must NOT be counted wholesale: a cached
+ # sibling quant (``siblinghash``) alongside is the "instant ~900 MB" bug.
+ # With no .incomplete present, downloaded must be 0.
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (blobs / "mainhash").write_bytes(b"x" * 100)
+ (blobs / "mmprojhash").write_bytes(b"y" * 30)
+ (blobs / "siblinghash").write_bytes(b"z" * 900)
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: None,
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda *_args, **_kwargs: frozenset(),
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "running")),
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 130,
+ )
+ )
+
+ assert result["completed_bytes"] == 0
+ assert result["downloaded_bytes"] == 0
+ assert result["complete_on_disk"] is False
+
+
+def test_gguf_progress_unknown_hashes_drops_unscoped_incomplete_blob(monkeypatch, tmp_path):
+ # With hashes unresolved, an .incomplete in the shared blobs/ dir can't be
+ # attributed to this variant (it may be a concurrent sibling's active write),
+ # so it is dropped, mirroring the finalized-blob guard. In production the
+ # worker writes the manifest before any .incomplete exists, so hashes resolve
+ # via the manifest backstop and this window never suppresses real progress.
+ entry = tmp_path / "models--Org--Model-GGUF"
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "activehash.incomplete").write_bytes(b"x" * 50) # unattributable
+ (blobs / "siblinghash").write_bytes(b"z" * 900) # finalized sibling
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: None,
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda *_args, **_kwargs: frozenset(),
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "running")),
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 1000,
+ )
+ )
+
+ assert result["downloaded_bytes"] == 0 # unscoped .incomplete not leaked
+ assert result["completed_bytes"] == 0 # finalized sibling still ignored
+
+
+def test_gguf_progress_unknown_hashes_no_backward_dip_when_variant_finalizes(monkeypatch, tmp_path):
+ # Regression for the two-variant dip: with hashes unresolved, the first quant
+ # finalizes while the sibling still writes its .incomplete. The sibling's
+ # bytes used to leak into this numerator, dipping the bar ~99% -> ~78% for
+ # one poll. The unscoped .incomplete must be dropped so the reading stays 0.
+ entry = tmp_path / "models--unsloth--SmolLM2-360M-Instruct-GGUF"
+ blobs = entry / "blobs"
+ snap = entry / "snapshots" / "rev0"
+ blobs.mkdir(parents = True)
+ snap.mkdir(parents = True)
+ own_total = 218_673_760 # Q2_K finished blob size (denominator)
+ sibling_total = 234_686_560 # Q3_K_M total
+
+ def _sparse_file(path: Path, size: int) -> None:
+ with path.open("wb") as handle:
+ handle.truncate(size)
+
+ own_finalized = blobs / "q2hash"
+ _sparse_file(own_finalized, own_total)
+ # ~72.7% of the sibling => sibling_partial / own_total == 0.78 pre-fix.
+ sibling_incomplete = blobs / "q3hash.incomplete"
+ _sparse_file(sibling_incomplete, int(sibling_total * 0.727))
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: None,
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda *_args, **_kwargs: frozenset(),
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "running")),
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "unsloth/SmolLM2-360M-Instruct-GGUF",
+ variant = "Q2_K",
+ expected_bytes = own_total,
+ )
+ )
+
+ assert result["downloaded_bytes"] == 0 # sibling .incomplete did not leak
+ assert result["progress"] == 0 # no ~0.78 backward dip
+
+
+def test_hf_cache_model_file_probe_is_bounded(monkeypatch, tmp_path):
+ snapshot = tmp_path / "snapshot"
+ snapshot.mkdir()
+ first = tmp_path / "README.md"
+ second = tmp_path / "notes.txt"
+ model = tmp_path / "model.safetensors"
+ first.write_text("readme", encoding = "utf-8")
+ second.write_text("notes", encoding = "utf-8")
+ model.write_bytes(b"weights")
+ entries = [first, second, model]
+
+ monkeypatch.setattr(model_common.Path, "rglob", lambda _self, _pattern: iter(entries))
+ monkeypatch.setattr(model_common, "_HF_CACHE_MODEL_FILE_PROBE_LIMIT", 2)
+
+ bounded = model_common._iter_hf_cache_model_files(snapshot)
+
+ assert bounded == [first, second]
+
+ monkeypatch.setattr(model_common, "_HF_CACHE_MODEL_FILE_PROBE_LIMIT", 3)
+
+ unbounded = model_common._iter_hf_cache_model_files(snapshot)
+
+ assert unbounded == [first, second, model]
+
+
+def test_download_state_lookup_is_repo_case_insensitive(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
+
+ assert download_manifest.write_manifest(
+ "model",
+ "Owner/Repo",
+ None,
+ [download_manifest.ExpectedFile(path = "config.json", size = 12)],
+ )
+ assert download_manifest.write_cancel_marker("model", "Owner/Repo", "Q4_K_M", "http")
+
+ manifest = download_manifest.read_manifest("model", "owner/repo", None)
+
+ assert manifest is not None
+ assert manifest.repo_id == "Owner/Repo"
+ assert manifest.expected_files[0].path == "config.json"
+ assert download_manifest.has_cancel_marker("model", "owner/repo", "Q4_K_M")
+ assert (
+ download_manifest.read_cancel_marker_transport(
+ "model",
+ "owner/repo",
+ "Q4_K_M",
+ )
+ == "http"
+ )
+ assert [
+ variant
+ for variant, _path in download_manifest.iter_variant_markers(
+ "model",
+ "owner/repo",
+ )
+ ] == ["Q4_K_M"]
+ assert download_manifest.purge_all_state_for_repo("model", "owner/repo") == 2
+ assert download_manifest.read_manifest("model", "owner/repo", None) is None
+
+
+def test_hf_cache_scan_fallback_row_uses_local_model_info_alias(monkeypatch, tmp_path):
+ cache_dir = tmp_path / "hub"
+ repo_dir = cache_dir / "models--Org--Broken"
+ blobs_dir = repo_dir / "blobs"
+ blobs_dir.mkdir(parents = True)
+ (blobs_dir / "blob").write_bytes(b"content")
+ monkeypatch.setattr(local_inventory, "_classify_local_path", lambda *_args, **_kwargs: [])
+ monkeypatch.setattr(
+ local_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(
+ local_inventory.hf_cache_scan,
+ "is_gguf_repo_partial",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(
+ local_inventory.hf_cache_scan,
+ "resolve_hf_cache_realpath",
+ lambda *_args, **_kwargs: None,
+ )
+
+ rows = local_inventory._scan_hf_cache(cache_dir)
+
+ assert len(rows) == 1
+ assert rows[0].model_id == "Org/Broken"
+ assert rows[0].source == "hf_cache"
+ assert rows[0].model_format == "unknown"
+
+
+def test_hf_cache_scan_uses_gguf_partial_row_for_variant_state(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ cache_dir = tmp_path / "hub"
+ repo_dir = cache_dir / "models--Org--PartialGguf"
+ blobs_dir = repo_dir / "blobs"
+ blobs_dir.mkdir(parents = True)
+ (blobs_dir / "partial").write_bytes(b"content")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/PartialGguf",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 8192)],
+ "http",
+ )
+ assert download_manifest.write_cancel_marker("model", "Org/PartialGguf", "Q4_K_M", "http")
+ monkeypatch.setattr(local_inventory, "_classify_local_path", lambda *_args, **_kwargs: [])
+ monkeypatch.setattr(
+ local_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(
+ local_inventory.hf_cache_scan,
+ "is_gguf_repo_partial",
+ lambda *_args, **_kwargs: True,
+ )
+ monkeypatch.setattr(
+ local_inventory.hf_cache_scan,
+ "resolve_hf_cache_realpath",
+ lambda *_args, **_kwargs: None,
+ )
+
+ rows = local_inventory._scan_hf_cache(cache_dir)
+
+ assert len(rows) == 1
+ assert rows[0].model_id == "Org/PartialGguf"
+ assert rows[0].source == "hf_cache"
+ assert rows[0].model_format == "gguf"
+ assert rows[0].partial is True
+ assert rows[0].size_bytes == 8192
+ assert rows[0].capabilities.requires_variant is True
+
+
+def test_model_download_job_helpers_preserve_idle_shape():
+ key = downloads._download_job_key("Org/Model", None)
+ status = downloads._job_status(key)
+
+ assert key == "org/model::"
+ assert status.state == "idle"
+ assert status.error is None
+
+
+def test_gguf_repo_partial_treats_completed_disk_variant_as_clean(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ snapshot = tmp_path / "cache" / "models--Org--Repo" / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ (snapshot / "model-Q8_0.gguf").write_bytes(b"complete")
+ assert download_manifest.write_cancel_marker("model", "Org/Repo", "Q4_K_M", "xet")
+ monkeypatch.setattr(
+ inventory_scan,
+ "resolve_snapshot_dir_for_scan",
+ lambda *_args: snapshot,
+ )
+
+ assert inventory_scan.is_gguf_repo_partial("Org/Repo", snapshot.parents[1]) is False
+
+
+def test_gguf_repo_partial_flags_vision_variant_missing_mmproj(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ snapshot = tmp_path / "cache" / "models--Org--Vision" / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ (snapshot / "model-Q4_K_M.gguf").write_bytes(b"complete-weight")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Vision",
+ "Q4_K_M",
+ [
+ download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 15),
+ download_manifest.ExpectedFile(path = "mmproj-F16.gguf", size = 8),
+ ],
+ "http",
+ )
+ monkeypatch.setattr(
+ inventory_scan,
+ "resolve_snapshot_dir_for_scan",
+ lambda *_args: snapshot,
+ )
+
+ assert inventory_scan.is_gguf_repo_partial("Org/Vision") is True
+
+
+def test_cancel_worker_leaves_exited_process_to_watcher():
+ calls: list = []
+
+ class _Registry:
+ def get_process(self, _key):
+ return SimpleNamespace(poll = lambda: 1)
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running")
+
+ def mark_pending_cancel(self, key, generation):
+ calls.append(("pending", key, generation))
+ return True
+
+ def request_cancel(self, key, proc, generation):
+ calls.append(("request", key, generation))
+ return True
+
+ def cancel_requested(self, _key):
+ return False
+
+ state = download_lifecycle.cancel_worker(
+ _Registry(),
+ "org/model::",
+ generation = 3,
+ label = "Org/Model",
+ logger = SimpleNamespace(warning = lambda *_a, **_k: None),
+ )
+
+ assert state == "running"
+ assert calls == []
+
+
+def test_completed_gguf_split_variant_requires_all_shards(tmp_path):
+ snapshot = tmp_path / "snapshot"
+ snapshot.mkdir()
+ first = snapshot / "model-Q8_0-00001-of-00002.gguf"
+ second = snapshot / "model-Q8_0-00002-of-00002.gguf"
+ first.write_bytes(b"first")
+
+ assert "Q8_0" not in inventory_scan._completed_gguf_variants(snapshot)
+
+ second.write_bytes(b"second")
+ assert "Q8_0" in inventory_scan._completed_gguf_variants(snapshot)
+
+
+def test_variant_partial_accepts_variant_filtered_legacy_hashes(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
+
+ assert inventory_scan.is_variant_partial(
+ "Org/Repo",
+ "Q4_K_M",
+ incomplete_blob_hashes = {"main-q4", "main-q8"},
+ variant_blob_hashes = frozenset({"main-q4"}),
+ )
+ assert not inventory_scan.is_variant_partial(
+ "Org/Repo",
+ "Q5_K_M",
+ incomplete_blob_hashes = {"main-q4"},
+ variant_blob_hashes = frozenset({"main-q5"}),
+ )
+
+
+def test_gguf_variants_partial_marker_overrides_size_only_downloaded(monkeypatch, tmp_path):
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(gguf_variants.asyncio, "to_thread", _run_inline)
+ assert download_manifest.write_cancel_marker("model", "Org/PartialRepo", "Q4_K_M", "http")
+ snapshot = tmp_path / "cache" / "models--Org--PartialRepo" / "snapshots" / "rev0"
+ snapshot.mkdir(parents = True)
+ (snapshot / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+
+ monkeypatch.setattr(
+ gguf_variants,
+ "list_gguf_variants",
+ lambda *_args, **_kwargs: (
+ [
+ SimpleNamespace(
+ filename = "model-Q4_K_M.gguf",
+ quant = "Q4_K_M",
+ display_label = None,
+ size_bytes = 100,
+ )
+ ],
+ False,
+ None,
+ ),
+ )
+ monkeypatch.setattr(
+ gguf_variants,
+ "iter_hf_cache_snapshots",
+ lambda _repo_id: [snapshot],
+ )
+ monkeypatch.setattr(
+ gguf_variants,
+ "_gguf_all_variant_requirements",
+ lambda *_args, **_kwargs: {},
+ )
+ monkeypatch.setattr(
+ gguf_variants.download_registry,
+ "incomplete_blob_hashes",
+ lambda *_args, **_kwargs: set(),
+ )
+
+ result = asyncio.run(gguf_variants.get_gguf_variants_response("Org/PartialRepo"))
+
+ assert result.variants[0].downloaded is False
+ assert result.variants[0].partial is True
+
+
+def test_download_registry_repo_keys_are_case_insensitive():
+ registry = download_registry.DownloadRegistry()
+
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ )
+ # The same variant under a different-cased repo id resolves to the same
+ # job, so the second claim attaches to the running one instead of starting
+ # a duplicate.
+ duplicate_claimed, duplicate_state = registry.claim(
+ "org/repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "org/repo",
+ variant = "Q8_0",
+ )
+
+ assert claimed is True
+ assert state == "running"
+ assert duplicate_claimed is False
+ assert duplicate_state == "running"
+ assert registry.active_jobs("ORG/REPO") == {"org/repo::Q8_0": "running"}
+
+
+def test_download_registry_allows_disjoint_gguf_variant_downloads():
+ registry = download_registry.DownloadRegistry()
+
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ blob_hashes = frozenset({"q8-main"}),
+ progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
+ )
+ second_claimed, second_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ blob_hashes = frozenset({"q4-main"}),
+ progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
+ )
+
+ assert claimed is True
+ assert state == "running"
+ assert second_claimed is True
+ assert second_state == "running"
+ assert registry.active_jobs("org/repo") == {
+ "org/repo::Q8_0": "running",
+ "org/repo::Q4_K_M": "running",
+ }
+
+
+def test_download_registry_allows_overlapping_same_transport_variant_downloads():
+ # Two variants sharing one mmproj blob still download together on one
+ # transport: huggingface_hub's per-blob lock serializes the shared write and
+ # prepare_cache_for_transport never purges a blob a peer is writing.
+ registry = download_registry.DownloadRegistry()
+
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ blob_hashes = frozenset({"q8-main"}),
+ progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
+ )
+ second_claimed, second_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ blob_hashes = frozenset({"q4-main"}),
+ progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
+ )
+
+ assert claimed is True
+ assert state == "running"
+ assert second_claimed is True
+ assert second_state == "running"
+
+
+def test_download_registry_variant_delete_does_not_block_sibling_download():
+ # Deleting one quant's partial must be allowed while a different quant of the
+ # same repo is downloading, and must protect every blob the live sibling is
+ # writing (including a shared mmproj companion).
+ registry = download_registry.DownloadRegistry()
+ registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ blob_hashes = frozenset({"q8-main"}),
+ progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
+ )
+
+ # A sibling variant delete is allowed; deleting the in-flight variant is not.
+ assert registry.begin_delete("Org/Repo", "Q4_K_M") is True
+ assert registry.begin_delete("Org/Repo", "Q8_0") is False
+ # A whole-repo delete still waits for every active download.
+ assert registry.begin_delete("Org/Repo") is False
+
+ # The live sibling is detected so the delete keeps the shared companion.
+ assert registry.has_active_peer_variant("Org/Repo", "Q4_K_M") is True
+ assert registry.has_active_peer_variant("Org/Repo", "Q8_0") is False
+
+ # While Q4_K_M is being deleted, re-downloading it is blocked but an
+ # untouched third variant may still start.
+ blocked, blocked_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ )
+ assert blocked is False
+ assert blocked_state == "deleting"
+ started, started_state = registry.claim(
+ "Org/Repo::Q5_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q5_K_M",
+ )
+ assert started is True
+ assert started_state == "running"
+
+ registry.end_delete("Org/Repo", "Q4_K_M")
+ assert registry.begin_delete("Org/Repo", "Q4_K_M") is True
+
+
+def test_partial_gguf_reconstruction_dedupes_variant_casing(monkeypatch):
+ # The manifest keeps original casing while the marker is lowercased; offline
+ # reconstruction must collapse them to ONE entry (manifest's casing), not two.
+ monkeypatch.setattr(
+ download_manifest,
+ "iter_variant_manifests",
+ lambda _repo_type, _repo_id: iter([("Q4_K_M", Path("manifest.json"))]),
+ )
+ monkeypatch.setattr(
+ download_manifest,
+ "iter_variant_markers",
+ lambda _repo_type, _repo_id: iter([("q4_k_m", Path("marker.json"))]),
+ )
+ monkeypatch.setattr(download_manifest, "read_manifest", lambda *_a, **_k: None)
+
+ result = gguf.list_partial_gguf_variants_from_state("Org/Repo")
+
+ assert result is not None
+ variants, _has_vision = result
+ assert [variant.quant for variant in variants] == ["Q4_K_M"]
+
+
+def test_download_registry_serializes_cross_transport_variant_downloads():
+ # An HTTP append-resume and an XET rewrite of the same shared blob would
+ # corrupt each other, so different-transport variants are serialized.
+ registry = download_registry.DownloadRegistry()
+
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ blob_hashes = frozenset({"q8-main"}),
+ progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
+ )
+ second_claimed, second_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_XET,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ blob_hashes = frozenset({"q4-main"}),
+ progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
+ )
+
+ assert claimed is True
+ assert state == "running"
+ assert second_claimed is False
+ assert second_state == "running"
+
+
+def test_download_registry_allows_unknown_hash_gguf_variant_downloads():
+ # Resolved blob hashes are NOT required to run two same-transport variants
+ # concurrently: on-disk safety comes from each worker purging only its own
+ # main-quant blobs plus huggingface_hub's per-etag lock. Requiring them here
+ # used to reject the second variant whenever a metadata fetch flaked.
+ registry = download_registry.DownloadRegistry()
+
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ )
+ second_claimed, second_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ blob_hashes = frozenset({"q4-main"}),
+ progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
+ )
+
+ assert claimed is True
+ assert state == "running"
+ assert second_claimed is True
+ assert second_state == "running"
+ assert registry.active_jobs("org/repo") == {
+ "org/repo::Q8_0": "running",
+ "org/repo::Q4_K_M": "running",
+ }
+
+
+def test_finalize_worker_exit_never_kills_a_healthy_worker(monkeypatch, tmp_path):
+ # finalize_worker_exit relies solely on the worker's exit code and never kills
+ # a live process: huggingface_hub already bounds reads with timeouts, so a
+ # liveness kill could only false-cancel a healthy download.
+ import inspect
+ import io
+ import logging
+
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+
+ class _Proc:
+ pid = 4242
+
+ def __init__(self):
+ self.killed = False
+ self.stderr = io.BytesIO(b"")
+
+ def poll(self):
+ return 0
+
+ def wait(self, timeout = None):
+ return 0
+
+ def kill(self):
+ self.killed = True
+
+ registry = download_registry.DownloadRegistry()
+ proc = _Proc()
+ key = "Org/Repo::Q4_K_M"
+ registry.claim(
+ key,
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ )
+ registry.register_process(key, proc)
+
+ download_lifecycle.finalize_worker_exit(
+ registry,
+ key,
+ proc,
+ hf_token = None,
+ label = "Org/Repo [Q4_K_M]",
+ log_prefix = "Download",
+ logger = logging.getLogger("test"),
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ transport = "http",
+ )
+
+ assert proc.killed is False
+ assert registry.get_job(key).state == "complete"
+ # The stall-watchdog knob is gone entirely; no caller may re-enable it.
+ assert (
+ "enable_stall_watchdog"
+ not in inspect.signature(download_lifecycle.finalize_worker_exit).parameters
+ )
+
+
+def test_prepare_cache_for_transport_purges_only_requested_hashes(monkeypatch, tmp_path):
+ root = tmp_path / "hub"
+ blobs = root / "models--Org--Repo" / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "variant-main.incomplete").write_bytes(b"x")
+ (blobs / "shared-mmproj.incomplete").write_bytes(b"y")
+ monkeypatch.setattr(download_registry, "hf_cache_root", lambda create = False: root)
+
+ purged = download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Repo",
+ download_registry.TRANSPORT_XET,
+ "Q4_K_M",
+ frozenset({"variant-main"}),
+ )
+
+ assert purged == 1
+ assert not (blobs / "variant-main.incomplete").exists()
+ assert (blobs / "shared-mmproj.incomplete").exists()
+
+
+def _vision_cache_root(monkeypatch, tmp_path):
+ root = tmp_path / "hub"
+ blobs = root / "models--Org--Vision" / "blobs"
+ blobs.mkdir(parents = True)
+ monkeypatch.setattr(download_registry, "hf_cache_root", lambda create = False: root)
+ return blobs
+
+
+def test_prepare_cache_for_transport_purges_cross_transport_companion(monkeypatch, tmp_path):
+ blobs = _vision_cache_root(monkeypatch, tmp_path)
+ companion = frozenset({"shared-mmproj"})
+
+ # An interrupted XET download stamps the companion marker "xet" and leaves a
+ # sparse partial. A later HTTP download of a different variant must purge it,
+ # else the HTTP resumer appends to the sparse bytes and corrupts the blob.
+ download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_XET,
+ "Q4_K_M",
+ only_blob_hashes = frozenset({"q4-main"}),
+ companion_blob_hashes = companion,
+ )
+ (blobs / "shared-mmproj.incomplete").write_bytes(b"sparse")
+
+ purged = download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_HTTP,
+ "Q8_0",
+ only_blob_hashes = frozenset({"q8-main"}),
+ companion_blob_hashes = companion,
+ )
+
+ assert purged == 1
+ assert not (blobs / "shared-mmproj.incomplete").exists()
+
+
+def test_prepare_cache_for_transport_preserves_same_transport_companion(monkeypatch, tmp_path):
+ blobs = _vision_cache_root(monkeypatch, tmp_path)
+ companion = frozenset({"shared-mmproj"})
+
+ download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_HTTP,
+ "Q4_K_M",
+ only_blob_hashes = frozenset({"q4-main"}),
+ companion_blob_hashes = companion,
+ )
+ (blobs / "shared-mmproj.incomplete").write_bytes(b"resumable")
+
+ purged = download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_HTTP,
+ "Q4_K_M",
+ only_blob_hashes = frozenset({"q4-main"}),
+ companion_blob_hashes = companion,
+ )
+
+ assert purged == 0
+ assert (blobs / "shared-mmproj.incomplete").exists()
+
+
+def test_prepare_cache_for_transport_protects_peer_companion(monkeypatch, tmp_path):
+ blobs = _vision_cache_root(monkeypatch, tmp_path)
+ companion = frozenset({"shared-mmproj"})
+
+ download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_XET,
+ "Q4_K_M",
+ only_blob_hashes = frozenset({"q4-main"}),
+ companion_blob_hashes = companion,
+ )
+ (blobs / "shared-mmproj.incomplete").write_bytes(b"sparse")
+
+ purged = download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_HTTP,
+ "Q8_0",
+ only_blob_hashes = frozenset({"q8-main"}),
+ companion_blob_hashes = companion,
+ protected_blob_hashes = companion,
+ )
+
+ assert purged == 0
+ assert (blobs / "shared-mmproj.incomplete").exists()
+
+
+def test_model_download_records_completed_baseline_for_new_gguf_variant(monkeypatch, tmp_path):
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, repo_type = "model": repo_id,
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda _repo, _variant, _token = None, include_companions = True, **_kwargs: (
+ frozenset({"mainhash", "mmprojhash"}) if include_companions else frozenset({"mainhash"})
+ ),
+ )
+ monkeypatch.setattr(
+ downloads.download_registry,
+ "completed_blob_bytes",
+ lambda *_args, **_kwargs: 30,
+ )
+
+ class _Registry:
+ claim_kwargs = None
+
+ def claim(self, _key, _transport, **kwargs):
+ self.claim_kwargs = kwargs
+ return True, "running"
+
+ def current_generation(self, _key):
+ return 1
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running")
+
+ def register_process(self, _key, _proc):
+ return False
+
+ def peer_blob_hashes(self, _key):
+ return frozenset()
+
+ class _Proc:
+ pid = 123
+ stderr = None
+
+ def poll(self):
+ return None
+
+ def kill(self):
+ return None
+
+ def wait(self, timeout = None):
+ return 0
+
+ registry = _Registry()
+ monkeypatch.setattr(downloads, "_registry", registry)
+ monkeypatch.setattr(downloads, "_spawn_download_worker", lambda *_args, **_kwargs: _Proc())
+
+ asyncio.run(
+ downloads.download_model_response(
+ SimpleNamespace(repo_id = "Org/Model", gguf_variant = "Q4_K_M", use_xet = False)
+ )
+ )
+
+ assert registry.claim_kwargs["blob_hashes"] == frozenset({"mainhash"})
+ assert registry.claim_kwargs["progress_blob_hashes"] == frozenset({"mainhash", "mmprojhash"})
+ assert registry.claim_kwargs["completed_baseline_bytes"] == 30
+
+
+def test_gguf_model_download_skips_completed_baseline_for_variant_resume_state(
+ monkeypatch, tmp_path
+):
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model",
+ "Q4_K_M",
+ [
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ )
+ ],
+ "http",
+ )
+ monkeypatch.setattr(
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, repo_type = "model": repo_id,
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda _repo, _variant, _token = None, include_companions = True, **_kwargs: (
+ frozenset({"mainhash", "mmprojhash"}) if include_companions else frozenset({"mainhash"})
+ ),
+ )
+ monkeypatch.setattr(
+ downloads.download_registry,
+ "completed_blob_bytes",
+ lambda *_args, **_kwargs: 30,
+ )
+
+ class _Registry:
+ claim_kwargs = None
+
+ def claim(self, _key, _transport, **kwargs):
+ self.claim_kwargs = kwargs
+ return True, "running"
+
+ def current_generation(self, _key):
+ return 1
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running")
+
+ def register_process(self, _key, _proc):
+ return False
+
+ def peer_blob_hashes(self, _key):
+ return frozenset()
+
+ class _Proc:
+ pid = 123
+ stderr = None
+
+ def poll(self):
+ return None
+
+ def kill(self):
+ return None
+
+ def wait(self, timeout = None):
+ return 0
+
+ registry = _Registry()
+ monkeypatch.setattr(downloads, "_registry", registry)
+ monkeypatch.setattr(downloads, "_spawn_download_worker", lambda *_args, **_kwargs: _Proc())
+
+ asyncio.run(
+ downloads.download_model_response(
+ SimpleNamespace(repo_id = "Org/Model", gguf_variant = "Q4_K_M", use_xet = False)
+ )
+ )
+
+ assert registry.claim_kwargs["completed_baseline_bytes"] == 0
+
+
+def test_model_idle_status_uses_cancel_marker_after_restart(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
+ monkeypatch.setattr(downloads, "_registry", download_registry.DownloadRegistry())
+ assert download_manifest.write_cancel_marker("model", "Owner/Repo", "Q4_K_M", "http")
+
+ status = asyncio.run(downloads.get_download_status_response("owner/repo", "Q4_K_M"))
+
+ assert status.state == "cancelled"
+ assert status.error is None
+
+
+def test_shutdown_kills_all_workers_before_shared_deadline_reap(monkeypatch):
+ events = []
+ now = [100.0]
+
+ class _Proc:
+ def __init__(self, name):
+ self.name = name
+
+ def poll(self):
+ return None
+
+ def kill(self):
+ events.append(("kill", self.name))
+
+ def wait(self, timeout):
+ events.append(("wait", self.name, timeout))
+ now[0] += 7.0
+
+ registry = download_registry.DownloadRegistry()
+ proc_a = _Proc("a")
+ proc_b = _Proc("b")
+ registry.claim(
+ "Org/A",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "dataset",
+ repo_id = "Org/A",
+ )
+ registry.claim(
+ "Org/B",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "dataset",
+ repo_id = "Org/B",
+ )
+ assert registry.register_process("org/a", proc_a)
+ assert registry.register_process("org/b", proc_b)
+ monkeypatch.setattr(
+ download_registry,
+ "persist_cancel_marker",
+ lambda *args, **kwargs: events.append(("marker", args[1])),
+ )
+ monkeypatch.setattr(download_registry.time, "monotonic", lambda: now[0])
+
+ registry.terminate_all("dataset download")
+
+ assert events == [
+ ("kill", "a"),
+ ("kill", "b"),
+ ("wait", "a", 10.0),
+ ("marker", "Org/A"),
+ ("wait", "b", 3.0),
+ ("marker", "Org/B"),
+ ]
+
+
+def test_shutdown_skips_marker_for_worker_that_exits_cleanly(monkeypatch):
+ markers = []
+
+ class _Proc:
+ def __init__(self, final_rc):
+ self._final_rc = final_rc
+ self._exited = False
+
+ def poll(self):
+ return self._final_rc if self._exited else None
+
+ def kill(self):
+ pass
+
+ def wait(self, timeout):
+ self._exited = True
+
+ registry = download_registry.DownloadRegistry()
+ clean = _Proc(0)
+ interrupted = _Proc(-9)
+ registry.claim(
+ "Org/Clean",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "dataset",
+ repo_id = "Org/Clean",
+ )
+ registry.claim(
+ "Org/Cut",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "dataset",
+ repo_id = "Org/Cut",
+ )
+ assert registry.register_process("org/clean", clean)
+ assert registry.register_process("org/cut", interrupted)
+ monkeypatch.setattr(
+ download_registry,
+ "persist_cancel_marker",
+ lambda *args, **kwargs: markers.append(args[1]),
+ )
+
+ registry.terminate_all("dataset download")
+
+ assert markers == ["Org/Cut"]
+
+
+def test_model_claim_register_cancel_uses_registry_marker_owner(monkeypatch):
+ killed = []
+
+ class _Registry:
+ def claim(self, *_args, **_kwargs):
+ return True, "running"
+
+ def current_generation(self, _key):
+ return 1
+
+ def register_process(self, _key, _proc):
+ return False
+
+ def persist_cancel_for_key(self, *_args, **_kwargs):
+ raise AssertionError("register_process owns pending-cancel markers")
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "cancelled", error = None)
+
+ monkeypatch.setattr(downloads, "_registry", _Registry())
+ monkeypatch.setattr(
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
+ )
+ monkeypatch.setattr(
+ downloads.download_registry,
+ "download_transport_unavailable_reason",
+ lambda _transport: None,
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_spawn_download_worker",
+ lambda *_args, **_kwargs: object(),
+ )
+ monkeypatch.setattr(
+ downloads.download_lifecycle,
+ "kill_and_reap_process",
+ lambda proc, **_kwargs: killed.append(proc),
+ )
+
+ result = asyncio.run(
+ downloads.download_model_response(
+ SimpleNamespace(repo_id = "Org/Model", gguf_variant = None, use_xet = False)
+ )
+ )
+
+ assert result["state"] == "cancelled"
+ assert killed
+
+
+def test_model_cancel_registered_worker_requests_and_kills(monkeypatch):
+ events = []
+
+ class _Proc:
+ def poll(self):
+ return None
+
+ def kill(self):
+ events.append(("kill",))
+
+ class _Registry:
+ def get_process(self, _key):
+ return _Proc()
+
+ def request_cancel(self, key, _proc, generation):
+ events.append(("request", key, generation))
+ return True
+
+ def persist_cancel_for_key(self, *_args, **_kwargs):
+ raise AssertionError(
+ "cancel_worker must leave marker persistence to the exit watcher; "
+ "an eager persist races a clean completion and strands a stale marker"
+ )
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running")
+
+ monkeypatch.setattr(downloads, "_registry", _Registry())
+ monkeypatch.setattr(
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
+ )
+
+ result = asyncio.run(
+ downloads.cancel_download_model_response(
+ SimpleNamespace(repo_id = "Org/Model", gguf_variant = "Q4_K_M", generation = 7)
+ )
+ )
+
+ assert result == {
+ "job_key": downloads._download_job_key("Org/Model", "Q4_K_M"),
+ "state": "cancelling",
+ }
+ assert events == [
+ ("request", downloads._download_job_key("Org/Model", "Q4_K_M"), 7),
+ ("kill",),
+ ]
+
+
+def test_model_download_watcher_invalidates_hf_cache_scan(monkeypatch):
+ invalidated = []
+
+ class _Registry:
+ def claim(self, *_args, **_kwargs):
+ return True, "running"
+
+ def current_generation(self, _key):
+ return 1
+
+ def register_process(self, _key, _proc):
+ return True
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "complete", error = None)
+
+ class _ImmediateThread:
+ def __init__(self, *, target, **_kwargs):
+ self._target = target
+
+ def start(self):
+ self._target()
+
+ monkeypatch.setattr(downloads, "_registry", _Registry())
+ monkeypatch.setattr(
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
+ )
+ monkeypatch.setattr(
+ downloads.download_registry,
+ "download_transport_unavailable_reason",
+ lambda _transport: None,
+ )
+ monkeypatch.setattr(
+ downloads.download_lifecycle,
+ "finalize_worker_exit",
+ lambda *_args, **_kwargs: None,
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_spawn_download_worker",
+ lambda *_args, **_kwargs: object(),
+ )
+ monkeypatch.setattr(downloads.download_lifecycle.threading, "Thread", _ImmediateThread)
+ monkeypatch.setattr(
+ downloads.hf_cache_scan,
+ "invalidate_hf_cache_scans",
+ lambda: invalidated.append(True),
+ )
+
+ async def _inline_to_thread(func, *args, **kwargs):
+ return func(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _inline_to_thread)
+
+ result = asyncio.run(
+ downloads.download_model_response(
+ SimpleNamespace(repo_id = "Org/Model", gguf_variant = None, use_xet = False)
+ )
+ )
+
+ assert result["accepted"] is True
+ assert invalidated == [True]
+
+
+def test_two_concurrent_same_repo_variants_both_complete(monkeypatch, tmp_path):
+ # End-to-end proof that two GGUF variants of ONE repo download concurrently
+ # without cancelling each other, with real registry/finalize/subprocess/watch
+ # threads exercising the claim gate, register, finalize funnel, and
+ # classify_exit under true concurrency.
+ import subprocess
+ import time
+
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ download_registry.DownloadRegistry(),
+ )
+ monkeypatch.setattr(
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_k: repo_id,
+ )
+ monkeypatch.setattr(
+ downloads.download_registry,
+ "download_transport_unavailable_reason",
+ lambda _transport: None,
+ )
+ # Per-variant blob hashes (distinct main shard, shared mmproj companion).
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda _repo, variant, _token = None, include_companions = True, **_k: (
+ frozenset({f"{variant.lower()}-main", "shared-mmproj"})
+ if include_companions
+ else frozenset({f"{variant.lower()}-main"})
+ ),
+ )
+ monkeypatch.setattr(
+ downloads.download_registry,
+ "completed_blob_bytes",
+ lambda *_a, **_k: 0,
+ )
+ monkeypatch.setattr(
+ downloads.hf_cache_scan,
+ "invalidate_hf_cache_scans",
+ lambda: None,
+ )
+ # Real subprocess that exits 0 immediately, with a stderr pipe to drain.
+ spawned: list[subprocess.Popen] = []
+
+ def _fake_spawn(*_args, **_kwargs):
+ proc = subprocess.Popen(
+ [sys.executable, "-c", "import sys; sys.exit(0)"],
+ stderr = subprocess.PIPE,
+ )
+ spawned.append(proc)
+ return proc
+
+ monkeypatch.setattr(downloads, "_spawn_download_worker", _fake_spawn)
+
+ async def _run_both():
+ return await asyncio.gather(
+ downloads.download_model_response(
+ SimpleNamespace(
+ repo_id = "Org/Model",
+ gguf_variant = "Q4_K_M",
+ use_xet = False,
+ )
+ ),
+ downloads.download_model_response(
+ SimpleNamespace(
+ repo_id = "Org/Model",
+ gguf_variant = "Q8_0",
+ use_xet = False,
+ )
+ ),
+ )
+
+ results = asyncio.run(_run_both())
+ assert all(r["accepted"] is True for r in results), results
+
+ registry = downloads._registry
+ key_q4 = downloads._download_job_key("Org/Model", "Q4_K_M")
+ key_q8 = downloads._download_job_key("Org/Model", "Q8_0")
+ deadline = time.monotonic() + 10.0
+ while time.monotonic() < deadline:
+ s4 = registry.get_job(key_q4).state
+ s8 = registry.get_job(key_q8).state
+ if s4 in download_registry.TERMINAL_STATES and s8 in download_registry.TERMINAL_STATES:
+ break
+ time.sleep(0.02)
+
+ for p in spawned:
+ try:
+ p.wait(timeout = 5)
+ except Exception:
+ pass
+
+ assert registry.get_job(key_q4).state == "complete"
+ assert registry.get_job(key_q8).state == "complete"
+
+
+def test_download_registry_factories_reuse_service_singletons():
+ registry_module = downloads.download_registry
+ before_count = len(registry_module._REGISTRIES)
+
+ assert registry_module.get_models_registry() is downloads.registry
+ assert registry_module.get_models_registry() is downloads.registry
+ assert registry_module.get_datasets_registry() is dataset_downloads.registry
+ assert registry_module.get_datasets_registry() is dataset_downloads.registry
+ assert len(registry_module._REGISTRIES) == before_count
+
+
+def test_hub_hf_token_header_uses_namespaced_header_only():
+ assert get_hf_token("new-token") == "new-token"
+ assert get_hf_token(None) is None
+
+
+def test_scan_folder_rejects_credential_directories(tmp_path):
+ sensitive_dir = tmp_path / ".ssh" / "models"
+ sensitive_dir.mkdir(parents = True)
+
+ with pytest.raises(ValueError, match = "Credential or configuration"):
+ scan_folders.add_scan_folder(str(sensitive_dir))
+
+
+def _build_variant_cache_repo(repo_dir, blob_specs, snapshot_links):
+ """Build a HF cache repo dir with blobs + snapshot symlinks for the
+ per-variant deletion path. blob_specs: {blob_name: bytes_payload};
+ snapshot_links: list of (revision, filename, blob_name)."""
+ blobs_dir = repo_dir / "blobs"
+ blobs_dir.mkdir(parents = True)
+ for blob_name, payload in blob_specs.items():
+ (blobs_dir / blob_name).write_bytes(payload)
+
+ files = []
+ for revision, filename, blob_name in snapshot_links:
+ snap_dir = repo_dir / "snapshots" / revision
+ snap_dir.mkdir(parents = True, exist_ok = True)
+ blob = blobs_dir / blob_name
+ link = snap_dir / filename
+ link.symlink_to(blob)
+ files.append(
+ SimpleNamespace(
+ file_name = filename,
+ file_path = str(link),
+ blob_path = str(blob),
+ size_on_disk = blob.stat().st_size,
+ )
+ )
+ repo = SimpleNamespace(
+ repo_id = "Org/Repo-GGUF",
+ repo_type = "model",
+ repo_path = repo_dir,
+ revisions = [SimpleNamespace(commit_hash = "rev1", files = files)],
+ )
+ return repo
+
+
+def _patch_variant_delete_side_effects(monkeypatch):
+ monkeypatch.setattr(
+ deletion.download_manifest,
+ "purge_state",
+ lambda *_args, **_kwargs: False,
+ )
+
+
+def test_snapshot_progress_filters_stale_blobs(monkeypatch, tmp_path):
+ """Exclude superseded-revision blobs; count an in-progress blob only when its
+ hash belongs to the target."""
+ entry = tmp_path / "datasets--Org--Data"
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "keep1").write_bytes(b"a" * 100)
+ (blobs / "stale").write_bytes(b"b" * 500)
+ (blobs / "keep2.incomplete").write_bytes(b"c" * 40)
+
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda _repo_type, _repo_id, force_active = False: [entry],
+ )
+
+ result = snapshot_progress.compute_snapshot_progress(
+ repo_type = "dataset",
+ repo_id = "Org/Data",
+ job_key = "org/data",
+ expected_bytes = 0,
+ hf_token = None,
+ registry = SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "running"),
+ ),
+ metadata_resolver = lambda _repo_id, _hf_token: (
+ 140,
+ frozenset({"keep1", "keep2"}),
+ ),
+ )
+
+ assert result["completed_bytes"] == 100
+ assert result["downloaded_bytes"] == 140
+ assert result["complete_on_disk"] is False
+ assert result["expected_bytes"] == 140
+
+
+def test_snapshot_progress_confirms_complete_only_with_verified_snapshot(monkeypatch, tmp_path):
+ entry = tmp_path / "models--Org--Model"
+ blobs = entry / "blobs"
+ snap = entry / "snapshots" / "rev0"
+ blobs.mkdir(parents = True)
+ snap.mkdir(parents = True)
+ (blobs / "keep1").write_bytes(b"a" * 100)
+ (snap / "model.safetensors").write_bytes(b"a" * 100)
+
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda _repo_type, _repo_id, force_active = False: [entry],
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "has_cancel_marker",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "read_manifest",
+ lambda *_args, **_kwargs: SimpleNamespace(),
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "verify_against_disk",
+ lambda *_args, **_kwargs: SimpleNamespace(ok = True),
+ )
+
+ result = snapshot_progress.compute_snapshot_progress(
+ repo_type = "model",
+ repo_id = "Org/Model",
+ job_key = "org/model::",
+ expected_bytes = 100,
+ hf_token = None,
+ registry = SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "idle"),
+ ),
+ metadata_resolver = lambda _repo_id, _hf_token: (
+ 100,
+ frozenset({"keep1"}),
+ ),
+ )
+
+ assert result["completed_bytes"] == 100
+ assert result["complete_on_disk"] is True
+
+
+def test_expected_files_from_snapshot_dir_records_relative_paths_and_sizes(tmp_path):
+ snap = tmp_path / "snapshots" / "rev0"
+ (snap / "nested").mkdir(parents = True)
+ (snap / "model.safetensors").write_bytes(b"a" * 12)
+ (snap / "nested" / "config.json").write_bytes(b"b" * 3)
+
+ files = download_manifest.expected_files_from_snapshot_dir(snap)
+
+ by_path = {f.path: f for f in files}
+ assert by_path["model.safetensors"].size == 12
+ assert by_path["nested/config.json"].size == 3
+ assert all(f.sha256 is None for f in files)
+
+
+def test_snapshot_progress_complete_with_manifest_synthesized_from_disk(monkeypatch, tmp_path):
+ """A finished snapshot whose only manifest was synthesized from on-disk files
+ still verifies as complete, so a refresh finalizes it instead of capping at
+ 99% and evicting it as gone."""
+ entry = tmp_path / "models--Org--Model"
+ blobs = entry / "blobs"
+ snap = entry / "snapshots" / "rev0"
+ blobs.mkdir(parents = True)
+ snap.mkdir(parents = True)
+ (blobs / "keep1").write_bytes(b"a" * 100)
+ (snap / "model.safetensors").write_bytes(b"a" * 100)
+
+ synthesized = download_manifest.expected_files_from_snapshot_dir(snap)
+ manifest = download_manifest.Manifest(
+ repo_type = "model",
+ repo_id = "Org/Model",
+ variant = None,
+ started_at = "",
+ expected_files = tuple(synthesized),
+ )
+
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda _repo_type, _repo_id, force_active = False: [entry],
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "has_cancel_marker",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "read_manifest",
+ lambda *_args, **_kwargs: manifest,
+ )
+
+ result = snapshot_progress.compute_snapshot_progress(
+ repo_type = "model",
+ repo_id = "Org/Model",
+ job_key = "org/model::",
+ expected_bytes = 100,
+ hf_token = None,
+ registry = SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "idle"),
+ ),
+ metadata_resolver = lambda _repo_id, _hf_token: (
+ 100,
+ frozenset({"keep1"}),
+ ),
+ )
+
+ assert result["complete_on_disk"] is True
+ assert result["progress"] == 1.0
+
+
+def test_delete_variant_keeps_blob_shared_with_other_snapshot(monkeypatch, tmp_path):
+ """A blob still referenced by a non-target snapshot symlink survives so that
+ symlink doesn't dangle (which the scanner reports as partial)."""
+ repo_dir = tmp_path / "models--Org--Repo-GGUF"
+ repo = _build_variant_cache_repo(
+ repo_dir,
+ blob_specs = {"sharedblob": b"x" * 200, "q8blob": b"y" * 300},
+ snapshot_links = [
+ ("rev1", "model-Q4_K_M.gguf", "sharedblob"),
+ ("rev1", "model-Q8_0.gguf", "q8blob"),
+ # An unrelated file that happens to share Q4's blob content.
+ ("rev1", "extra-copy.gguf", "sharedblob"),
+ ],
+ )
+ monkeypatch.setattr(
+ deletion.cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [repo])],
+ )
+ _patch_variant_delete_side_effects(monkeypatch)
+
+ result = deletion._delete_cached_model_blocking("Org/Repo-GGUF", "Q4_K_M", None)
+
+ assert result["status"] == "deleted"
+ # Q4 snapshot link gone, but its blob survives (extra-copy still links it).
+ assert not (repo_dir / "snapshots" / "rev1" / "model-Q4_K_M.gguf").exists()
+ assert (repo_dir / "blobs" / "sharedblob").exists()
+ extra = repo_dir / "snapshots" / "rev1" / "extra-copy.gguf"
+ assert extra.is_symlink() and extra.exists() # not dangling
+
+
+def test_delete_variant_unlinks_unshared_blob(monkeypatch, tmp_path):
+ repo_dir = tmp_path / "models--Org--Repo-GGUF"
+ repo = _build_variant_cache_repo(
+ repo_dir,
+ blob_specs = {"q4blob": b"x" * 200, "q8blob": b"y" * 300},
+ snapshot_links = [
+ ("rev1", "model-Q4_K_M.gguf", "q4blob"),
+ ("rev1", "model-Q8_0.gguf", "q8blob"),
+ ],
+ )
+ monkeypatch.setattr(
+ deletion.cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [repo])],
+ )
+ _patch_variant_delete_side_effects(monkeypatch)
+
+ result = deletion._delete_cached_model_blocking("Org/Repo-GGUF", "Q4_K_M", None)
+
+ assert result["status"] == "deleted"
+ assert not (repo_dir / "blobs" / "q4blob").exists()
+ # Untouched sibling variant remains fully intact.
+ assert (repo_dir / "blobs" / "q8blob").exists()
+ q8 = repo_dir / "snapshots" / "rev1" / "model-Q8_0.gguf"
+ assert q8.is_symlink() and q8.exists()
+
+
+def test_delete_variant_surfaces_locked_file_as_conflict(monkeypatch, tmp_path):
+ """A blob unlink that fails (e.g. a Windows file lock on a loaded model)
+ must raise a clear 409, not report a misleading success."""
+ repo_dir = tmp_path / "models--Org--Repo-GGUF"
+ repo = _build_variant_cache_repo(
+ repo_dir,
+ blob_specs = {"lockedblob": b"x" * 200},
+ snapshot_links = [("rev1", "model-Q4_K_M.gguf", "lockedblob")],
+ )
+ monkeypatch.setattr(
+ deletion.cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [repo])],
+ )
+ _patch_variant_delete_side_effects(monkeypatch)
+
+ real_unlink = Path.unlink
+
+ def fake_unlink(self, *args, **kwargs):
+ if self.name == "lockedblob":
+ raise PermissionError("file in use")
+ return real_unlink(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "unlink", fake_unlink)
+
+ with pytest.raises(HTTPException) as exc_info:
+ deletion._delete_cached_model_blocking("Org/Repo-GGUF", "Q4_K_M", None)
+
+ assert exc_info.value.status_code == 409
+
+
+def test_download_snapshot_writes_manifest_for_xet(monkeypatch, tmp_path):
+ written = []
+ verified = []
+
+ monkeypatch.setattr(
+ hf_download,
+ "_model_info_with_retry",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ siblings = [SimpleNamespace(rfilename = "config.json", size = 12)]
+ ),
+ )
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ )
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
+ monkeypatch.setattr(
+ download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
+ )
+
+ hf_download._download_snapshot("Org/Model", None, "xet")
+
+ assert written, "XET snapshot download must still record a manifest"
+ assert written[0][0:3] == ("model", "Org/Model", None)
+ assert written[0][3][0].path == "config.json"
+ assert verified == [("model", "Org/Model", None, str(tmp_path))]
+
+
+def test_download_gguf_variant_writes_manifest_for_xet(monkeypatch, tmp_path):
+ written = []
+ verified = []
+
+ monkeypatch.setattr(
+ hf_download,
+ "_model_info_with_retry",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ siblings = [_sibling("model-Q4_K_M.gguf", 10, "main")]
+ ),
+ )
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ )
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
+ monkeypatch.setattr(
+ download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
+ )
+
+ hf_download._download_gguf_variant("Org/Model", "Q4_K_M", None, "xet")
+
+ assert written, "XET GGUF variant download must still record a manifest"
+ assert written[0][0:3] == ("model", "Org/Model", "Q4_K_M")
+ assert written[0][3][0].path == "model-Q4_K_M.gguf"
+ assert verified == [("model", "Org/Model", "Q4_K_M", str(tmp_path))]
+
+
+def test_download_dataset_writes_manifest_for_xet(monkeypatch, tmp_path):
+ written = []
+ verified = []
+
+ monkeypatch.setattr(
+ hf_download,
+ "_dataset_info_with_retry",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ siblings = [SimpleNamespace(rfilename = "data.parquet", size = 30)]
+ ),
+ )
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ )
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
+ monkeypatch.setattr(
+ download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
+ )
+
+ hf_download._download_dataset("Org/Data", None, "xet")
+
+ assert written, "XET dataset download must still record a manifest"
+ assert written[0][0:3] == ("dataset", "Org/Data", None)
+ assert written[0][3][0].path == "data.parquet"
+ assert verified == [("dataset", "Org/Data", None, str(tmp_path))]
+
+
+def test_dataset_status_includes_generation(monkeypatch):
+ class _Registry:
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running", error = None)
+
+ def current_generation(self, _key):
+ return 4
+
+ monkeypatch.setattr(dataset_downloads, "_registry", _Registry())
+ monkeypatch.setattr(
+ dataset_downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
+ )
+
+ result = asyncio.run(dataset_downloads.get_dataset_download_status_response("Org/Data"))
+
+ assert result.state == "running"
+ assert result.generation == 4
diff --git a/studio/backend/hub/utils/__init__.py b/studio/backend/hub/utils/__init__.py
new file mode 100644
index 00000000000..32014236c6a
--- /dev/null
+++ b/studio/backend/hub/utils/__init__.py
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
diff --git a/studio/backend/hub/utils/dataset_cache.py b/studio/backend/hub/utils/dataset_cache.py
new file mode 100644
index 00000000000..1a7a90d8a57
--- /dev/null
+++ b/studio/backend/hub/utils/dataset_cache.py
@@ -0,0 +1,145 @@
+# 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 re
+from pathlib import Path
+from typing import Optional
+
+from hub.utils.hf_cache_state import iter_repo_cache_dirs
+
+
+TRAINING_DATA_EXTS = (".parquet", ".json", ".jsonl", ".csv")
+
+
+def _rel_lower(snapshot: Path, path: Path) -> str:
+ return path.relative_to(snapshot).as_posix().lower()
+
+
+_SPLIT_ALIASES = {
+ "validation": frozenset({"validation", "valid", "val"}),
+ "valid": frozenset({"validation", "valid", "val"}),
+ "val": frozenset({"validation", "valid", "val"}),
+ "eval": frozenset({"eval", "validation", "valid", "val"}),
+}
+
+
+def _label_tokens(text: str) -> set[str]:
+ return {token for token in re.split(r"[^a-z0-9]+", text.lower()) if token}
+
+
+def split_label_matches(text: str, split: str) -> bool:
+ """Match a split name against a file path's tokens, expanding split aliases
+ (validation/valid/val, eval) so cached and remote selection agree."""
+ normalized = split.strip().lower()
+ if not normalized:
+ return False
+ labels = _SPLIT_ALIASES.get(normalized, frozenset({normalized}))
+ return bool(labels.intersection(_label_tokens(text)))
+
+
+def _matches_label(snapshot: Path, path: Path, label: str) -> bool:
+ label = label.strip().lower()
+ if not label:
+ return False
+ rel = _rel_lower(snapshot, path)
+ tokens = [token for token in re.split(r"[^a-z0-9]+", rel) if token]
+ if label in tokens:
+ return True
+ if label in {"train", "test", "validation", "valid", "val", "eval"}:
+ return False
+ return label in rel
+
+
+def dataset_snapshot_from_cache_path(local_path: Optional[str], repo_id: str) -> Optional[Path]:
+ if not local_path or not repo_id:
+ return None
+ try:
+ root = Path(local_path).expanduser()
+ if not root.exists():
+ return None
+ expected_repo_dir = f"datasets--{repo_id.replace('/', '--')}".lower()
+ if expected_repo_dir not in {part.lower() for part in root.parts}:
+ return None
+ if root.is_dir() and root.parent.name == "snapshots":
+ return root.resolve()
+ snapshots = root / "snapshots" if root.is_dir() else None
+ if snapshots is None or not snapshots.is_dir():
+ return None
+ candidates = [p for p in snapshots.iterdir() if p.is_dir()]
+ if not candidates:
+ return None
+ candidates.sort(
+ key = lambda path: path.stat().st_mtime if path.exists() else 0,
+ reverse = True,
+ )
+ return candidates[0].resolve()
+ except Exception:
+ return None
+
+
+def latest_cached_dataset_snapshot(
+ repo_id: str, local_path: Optional[str] = None
+) -> Optional[Path]:
+ local_snapshot = dataset_snapshot_from_cache_path(local_path, repo_id)
+ if local_snapshot is not None:
+ return local_snapshot
+
+ newest: Optional[Path] = None
+ newest_mtime = -1.0
+ for entry in iter_repo_cache_dirs("dataset", repo_id):
+ snapshots = entry / "snapshots"
+ if not snapshots.is_dir():
+ continue
+ try:
+ candidates = [s for s in snapshots.iterdir() if s.is_dir()]
+ except OSError:
+ continue
+ for snap in candidates:
+ try:
+ mtime = snap.stat().st_mtime
+ except OSError:
+ continue
+ if mtime > newest_mtime:
+ newest = snap
+ newest_mtime = mtime
+ return newest
+
+
+def cached_dataset_candidates(
+ snapshot: Path,
+ *,
+ subset: Optional[str],
+ train_split: str,
+ extensions: tuple[str, ...],
+ preferred_extensions: tuple[str, ...] = TRAINING_DATA_EXTS,
+) -> list[Path]:
+ try:
+ files = [
+ p for p in snapshot.rglob("*") if p.is_file() and p.name.lower().endswith(extensions)
+ ]
+ except OSError:
+ return []
+ if not files:
+ return []
+
+ subset_lower = subset.lower() if subset else ""
+ split_lower = train_split.lower()
+
+ def score(path: Path) -> tuple[int, int, str]:
+ rel = _rel_lower(snapshot, path)
+ subset_match = bool(subset_lower and _matches_label(snapshot, path, subset_lower))
+ split_match = bool(split_lower and split_label_matches(rel, split_lower))
+ location_rank = 3
+ if split_match and (not subset_lower or subset_match):
+ location_rank = 0
+ elif split_match:
+ location_rank = 1
+ elif subset_match:
+ location_rank = 2
+ return (
+ 0 if path.name.lower().endswith(preferred_extensions) else 1,
+ location_rank,
+ rel,
+ )
+
+ return sorted(files, key = score)
diff --git a/studio/backend/hub/utils/dataset_format.py b/studio/backend/hub/utils/dataset_format.py
new file mode 100644
index 00000000000..df020353654
--- /dev/null
+++ b/studio/backend/hub/utils/dataset_format.py
@@ -0,0 +1,749 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import re
+from typing import Any, Optional
+
+
+def _first_row(dataset) -> Optional[dict]:
+ try:
+ row = next(iter(dataset))
+ except StopIteration:
+ return None
+ return row if isinstance(row, dict) else None
+
+
+def _column_names(dataset, sample: Optional[dict] = None) -> list[str]:
+ names = getattr(dataset, "column_names", None)
+ if names is not None:
+ return list(names)
+ return list((sample or {}).keys())
+
+
+def _keyword_in_column(keyword: str, col_name: str) -> bool:
+ return re.search(r"\b" + re.escape(keyword) + r"\b", col_name, re.IGNORECASE) is not None
+
+
+def _unknown_dataset_format(
+ chat_column: Optional[str] = None, sample_keys: Optional[list[str]] = None
+) -> dict:
+ return {
+ "format": "unknown",
+ "chat_column": chat_column,
+ "needs_standardization": None,
+ "sample_keys": sample_keys or [],
+ }
+
+
+def detect_dataset_format(dataset) -> dict:
+ sample = _first_row(dataset)
+ if sample is None:
+ return _unknown_dataset_format()
+ column_names = set(sample.keys())
+ if {"instruction", "output"}.issubset(column_names):
+ return {
+ "format": "alpaca",
+ "chat_column": None,
+ "needs_standardization": False,
+ "sample_keys": [],
+ }
+
+ chat_column = None
+ if "messages" in column_names:
+ chat_column = "messages"
+ elif "conversations" in column_names:
+ chat_column = "conversations"
+ elif "texts" in column_names:
+ chat_column = "texts"
+
+ if not chat_column:
+ return _unknown_dataset_format()
+
+ chat_data = sample.get(chat_column)
+ if not isinstance(chat_data, (list, tuple)) or not chat_data:
+ return _unknown_dataset_format(chat_column)
+ first_msg = chat_data[0]
+ if not isinstance(first_msg, dict):
+ return _unknown_dataset_format(chat_column)
+ msg_keys = set(first_msg.keys())
+ sample_keys = [str(key) for key in msg_keys]
+ if "from" in msg_keys or "value" in msg_keys:
+ return {
+ "format": "sharegpt",
+ "chat_column": chat_column,
+ "needs_standardization": True,
+ "sample_keys": sample_keys,
+ }
+ if "role" in msg_keys and "content" in msg_keys:
+ return {
+ "format": "chatml",
+ "chat_column": chat_column,
+ "needs_standardization": False,
+ "sample_keys": sample_keys,
+ }
+ return _unknown_dataset_format(chat_column, sample_keys)
+
+
+def detect_custom_format_heuristic(dataset):
+ sample = _first_row(dataset)
+ if sample is None:
+ return None
+ all_columns = list(sample.keys())
+ mapping = {}
+ assistant_words = [
+ "output",
+ "answer",
+ "response",
+ "assistant",
+ "completion",
+ "expected",
+ "recommendation",
+ "reply",
+ "result",
+ "target",
+ "solution",
+ "explanation",
+ "solve",
+ ]
+ user_words_high_priority = [
+ "input",
+ "question",
+ "query",
+ "prompt",
+ "instruction",
+ "request",
+ "snippet",
+ "user",
+ "text",
+ "problem",
+ "exercise",
+ ]
+ user_words_low_priority = ["task"]
+ user_words = user_words_high_priority + user_words_low_priority
+ system_words = [
+ "system",
+ "context",
+ "description",
+ "persona",
+ "role",
+ "template",
+ "task",
+ ]
+ metadata_exact_match = {
+ "id",
+ "idx",
+ "index",
+ "key",
+ "timestamp",
+ "date",
+ "metadata",
+ "source",
+ "kind",
+ "type",
+ "category",
+ "score",
+ "label",
+ "tag",
+ "inference_mode",
+ }
+ metadata_prefix_patterns = [
+ "problem_type",
+ "problem_source",
+ "generation_model",
+ "pass_rate",
+ ]
+ priority_patterns = {
+ "generated": 100,
+ "gen_": 90,
+ "model_": 80,
+ "predicted": 70,
+ "completion": 60,
+ }
+
+ def has_keyword(col_name, keywords):
+ col_lower = col_name.lower()
+ col_normalized = col_lower.replace("_", "").replace("-", "").replace(" ", "")
+ return any(keyword in col_lower or keyword in col_normalized for keyword in keywords)
+
+ def is_metadata(col_name):
+ col_lower = col_name.lower()
+ if col_lower in metadata_exact_match or col_lower in metadata_prefix_patterns:
+ return True
+ for pattern in metadata_prefix_patterns:
+ if col_lower.startswith(pattern.split("_")[0] + "_") and col_lower != pattern:
+ if "_" in col_lower:
+ prefix = col_lower.split("_")[0]
+ if prefix in ["generation", "pass", "inference"]:
+ return True
+ return len(col_lower) <= 2 and col_lower not in ["qa", "q", "a"]
+
+ def get_priority_score(col_name):
+ col_lower = col_name.lower()
+ return sum(score for pattern, score in priority_patterns.items() if pattern in col_lower)
+
+ def get_content_length(col_name):
+ try:
+ return len(str(sample[col_name])) if sample.get(col_name) else 0
+ except Exception:
+ return 0
+
+ def score_column(col_name, keywords, role_type, num_candidates):
+ if not has_keyword(col_name, keywords):
+ return 0
+ score = 10
+ if role_type == "user":
+ col_lower = col_name.lower()
+ if "task" in col_lower and not any(kw in col_lower for kw in user_words_high_priority):
+ score -= 15
+ score += get_priority_score(col_name)
+ if role_type in ["assistant", "user"]:
+ avg_length = get_content_length(col_name)
+ if num_candidates > 1:
+ if avg_length > 1000:
+ score += 50
+ elif avg_length > 200:
+ score += 30
+ elif avg_length > 50:
+ score += 10
+ elif avg_length < 50:
+ score -= 20
+ else:
+ if avg_length > 1000:
+ score += 50
+ elif avg_length > 200:
+ score += 30
+ elif avg_length > 50:
+ score += 10
+ return score
+
+ content_columns = [col for col in all_columns if not is_metadata(col)]
+ assistant_potential = [col for col in content_columns if has_keyword(col, assistant_words)]
+ user_potential = [col for col in content_columns if has_keyword(col, user_words)]
+ assistant_candidates = [
+ (col, score)
+ for col in assistant_potential
+ if (score := score_column(col, assistant_words, "assistant", len(assistant_potential))) > 0
+ ]
+ if assistant_candidates:
+ assistant_candidates.sort(key = lambda item: item[1], reverse = True)
+ assistant_col = assistant_candidates[0][0]
+ mapping[assistant_col] = "assistant"
+ else:
+ assistant_col = None
+
+ user_candidates = []
+ for col in user_potential:
+ if col == assistant_col:
+ continue
+ score = score_column(col, user_words, "user", len(user_potential))
+ if score > 0:
+ user_candidates.append((col, score))
+ if user_candidates:
+ user_candidates.sort(key = lambda item: item[1], reverse = True)
+ user_col = user_candidates[0][0]
+ mapping[user_col] = "user"
+ else:
+ user_col = None
+
+ remaining_columns = [col for col in content_columns if col not in mapping]
+ system_col = None
+ for col in remaining_columns:
+ if has_keyword(col, system_words):
+ mapping[col] = "system"
+ system_col = col
+ break
+ if system_col:
+ remaining_columns = [col for col in remaining_columns if col != system_col]
+ if remaining_columns:
+ remaining_col = remaining_columns[0]
+ if not has_keyword(remaining_col, user_words + assistant_words):
+ mapping[remaining_col] = "system"
+ elif user_col is None:
+ mapping[remaining_col] = "user"
+ else:
+ mapping[remaining_col] = "system"
+
+ has_user = any(role == "user" for role in mapping.values())
+ has_assistant = any(role == "assistant" for role in mapping.values())
+ if not has_user:
+ for col in remaining_columns:
+ if col not in mapping:
+ mapping[col] = "user"
+ has_user = True
+ break
+ return mapping if has_user and has_assistant else None
+
+
+_AUDIO_EXTENSIONS = (
+ ".wav",
+ ".mp3",
+ ".flac",
+ ".ogg",
+ ".opus",
+ ".m4a",
+ ".aac",
+ ".wma",
+ ".webm",
+)
+
+
+def _is_audio_value(value) -> bool:
+ if value is None:
+ return False
+ if isinstance(value, dict):
+ if "array" in value and "sampling_rate" in value:
+ return True
+ if "bytes" in value or "path" in value:
+ path = value.get("path") or ""
+ return isinstance(path, str) and any(
+ path.lower().endswith(ext) for ext in _AUDIO_EXTENSIONS
+ )
+ return False
+
+
+def _has_image_header(data: bytes) -> bool:
+ if len(data) < 4:
+ return False
+ return (
+ data[:2] == b"\xff\xd8"
+ or data[:4] == b"\x89PNG"
+ or data[:3] == b"GIF"
+ or (data[:4] == b"RIFF" and len(data) >= 12 and data[8:12] == b"WEBP")
+ or data[:2] == b"BM"
+ )
+
+
+def _is_image_value(value) -> bool:
+ if value is None:
+ return False
+ try:
+ from PIL.Image import Image as PILImage
+ if isinstance(value, PILImage):
+ return True
+ except ImportError:
+ pass
+ if isinstance(value, dict):
+ if "array" in value and "sampling_rate" in value:
+ return False
+ if "bytes" in value and "path" in value:
+ path = value.get("path") or ""
+ if isinstance(path, str) and any(
+ path.lower().endswith(ext) for ext in _AUDIO_EXTENSIONS
+ ):
+ return False
+ return True
+ if isinstance(value, (bytes, bytearray)):
+ return _has_image_header(value)
+ image_exts = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".svg")
+ if isinstance(value, str) and len(value) < 1000:
+ lower = value.strip().lower()
+ if lower.startswith(("http://", "https://")):
+ return any(lower.split("?")[0].endswith(ext) for ext in image_exts)
+ return any(lower.endswith(ext) for ext in image_exts)
+ return False
+
+
+def detect_multimodal_dataset(dataset):
+ sample = _first_row(dataset)
+ if sample is None:
+ return {
+ "is_image": False,
+ "multimodal_columns": [],
+ "modality_types": [],
+ "is_audio": False,
+ "audio_columns": [],
+ "detected_audio_column": None,
+ "detected_text_column": None,
+ "detected_speaker_column": None,
+ }
+ column_names = list(sample.keys())
+ image_keywords = [
+ "image",
+ "img",
+ "pixel",
+ "jpg",
+ "jpeg",
+ "png",
+ "webp",
+ "bmp",
+ "gif",
+ "tiff",
+ "svg",
+ "photo",
+ "pic",
+ "picture",
+ "visual",
+ "file_name",
+ "filename",
+ ]
+ audio_keywords = ["audio", "speech", "wav", "waveform", "sound"]
+ multimodal_columns = []
+ audio_columns = []
+ modality_types = set()
+ for col_name in column_names:
+ if any(_keyword_in_column(keyword, col_name) for keyword in image_keywords):
+ multimodal_columns.append(col_name)
+ modality_types.add("image")
+ for col_name in column_names:
+ if col_name not in multimodal_columns and _is_image_value(sample[col_name]):
+ multimodal_columns.append(col_name)
+ modality_types.add("image")
+ for col_name in column_names:
+ if any(_keyword_in_column(keyword, col_name) for keyword in audio_keywords):
+ audio_columns.append(col_name)
+ modality_types.add("audio")
+ for col_name in column_names:
+ if col_name not in audio_columns and _is_audio_value(sample[col_name]):
+ audio_columns.append(col_name)
+ modality_types.add("audio")
+ if audio_columns:
+ multimodal_columns = [col for col in multimodal_columns if col not in set(audio_columns)]
+
+ detected_text_col = None
+ if audio_columns:
+ for col_name in column_names:
+ if col_name.lower() in [
+ "text",
+ "sentence",
+ "transcript",
+ "transcription",
+ "label",
+ ]:
+ detected_text_col = col_name
+ break
+ detected_speaker_col = None
+ if audio_columns:
+ for col_name in column_names:
+ if col_name.lower() in ["source", "speaker", "speaker_id"]:
+ detected_speaker_col = col_name
+ break
+ return {
+ "is_image": len(multimodal_columns) > 0,
+ "multimodal_columns": multimodal_columns,
+ "modality_types": list(modality_types),
+ "is_audio": len(audio_columns) > 0,
+ "audio_columns": audio_columns,
+ "detected_audio_column": audio_columns[0] if audio_columns else None,
+ "detected_text_column": detected_text_col,
+ "detected_speaker_column": detected_speaker_col,
+ }
+
+
+def detect_vlm_dataset_structure(dataset):
+ sample = _first_row(dataset)
+ if sample is None:
+ return {
+ "format": "unknown",
+ "needs_conversion": None,
+ "image_column": None,
+ "text_column": None,
+ "messages_column": None,
+ }
+ column_names = set(sample.keys())
+ if "messages" in column_names:
+ messages = sample["messages"]
+ if messages and len(messages) > 0:
+ first_msg = messages[0]
+ if "content" in first_msg:
+ content = first_msg["content"]
+ if (
+ isinstance(content, list)
+ and content
+ and isinstance(content[0], dict)
+ and "type" in content[0]
+ ):
+ has_index = any("index" in item for item in content if isinstance(item, dict))
+ if has_index and "images" in column_names:
+ return {
+ "format": "vlm_messages_llava",
+ "needs_conversion": True,
+ "messages_column": "messages",
+ "image_column": "images",
+ "text_column": None,
+ }
+ has_image = any("image" in item for item in content if isinstance(item, dict))
+ if has_image:
+ return {
+ "format": "vlm_messages",
+ "needs_conversion": False,
+ "messages_column": "messages",
+ "image_column": None,
+ "text_column": None,
+ }
+
+ for chat_col in ("conversations", "messages"):
+ if chat_col not in column_names:
+ continue
+ chat_data = sample[chat_col]
+ if not isinstance(chat_data, list) or not chat_data:
+ continue
+ has_image_placeholder = any(
+ "<image>" in str(message.get("value", "") or message.get("content", ""))
+ for message in chat_data
+ if isinstance(message, dict)
+ )
+ if not has_image_placeholder:
+ continue
+ image_col = next(
+ (
+ col
+ for col in column_names
+ if col != chat_col
+ and (_keyword_in_column("image", col) or _keyword_in_column("img", col))
+ ),
+ None,
+ )
+ if image_col:
+ return {
+ "format": "sharegpt_with_images",
+ "needs_conversion": True,
+ "image_column": image_col,
+ "text_column": None,
+ "messages_column": chat_col,
+ }
+
+ metadata_suffixes = (
+ "_id",
+ "_url",
+ "_name",
+ "_filename",
+ "_uri",
+ "_link",
+ "_key",
+ "_index",
+ )
+ metadata_prefixes = (
+ "id_",
+ "url_",
+ "name_",
+ "filename_",
+ "uri_",
+ "link_",
+ "key_",
+ "index_",
+ )
+ image_keywords = [
+ "image",
+ "img",
+ "photo",
+ "picture",
+ "pic",
+ "visual",
+ "scan",
+ "file_name",
+ "filename",
+ ]
+ text_keywords = [
+ "text",
+ "caption",
+ "captions",
+ "description",
+ "answer",
+ "output",
+ "response",
+ "label",
+ ]
+
+ def is_metadata_column(col_name):
+ lower = col_name.lower()
+ return any(lower.endswith(suffix) for suffix in metadata_suffixes) or any(
+ lower.startswith(prefix) for prefix in metadata_prefixes
+ )
+
+ image_candidates = []
+ for col in column_names:
+ value = sample[col]
+ if any(_keyword_in_column(keyword, col) for keyword in image_keywords) or _is_image_value(
+ value
+ ):
+ if hasattr(value, "size") and hasattr(value, "mode"):
+ score = 100
+ elif isinstance(value, dict) and ("bytes" in value or "path" in value):
+ score = 75
+ elif isinstance(value, str):
+ score = (
+ 55
+ if is_metadata_column(col)
+ else 70
+ if value.startswith(("http://", "https://"))
+ else 50
+ )
+ else:
+ score = 0
+ if score > 0:
+ image_candidates.append((col, score))
+ image_candidates.sort(key = lambda item: item[1], reverse = True)
+
+ text_candidates = []
+ for col in column_names:
+ if is_metadata_column(col) or not any(
+ _keyword_in_column(keyword, col) for keyword in text_keywords
+ ):
+ continue
+ value = sample[col]
+ if isinstance(value, str) and value:
+ text_candidates.append((col, min(len(value), 1000)))
+ elif isinstance(value, list) and value and isinstance(value[0], str):
+ text_candidates.append((col, min(len(value[0]), 1000) // 2))
+ text_candidates.sort(key = lambda item: item[1], reverse = True)
+
+ found_image = image_candidates[0][0] if image_candidates else None
+ found_text = text_candidates[0][0] if text_candidates else None
+ if found_image and found_text:
+ return {
+ "format": "simple_image_text",
+ "needs_conversion": True,
+ "image_column": found_image,
+ "text_column": found_text,
+ "messages_column": None,
+ }
+ return {
+ "format": "unknown",
+ "needs_conversion": None,
+ "image_column": found_image,
+ "text_column": found_text,
+ "messages_column": None,
+ }
+
+
+def check_dataset_format(dataset, is_vlm: bool = False) -> dict:
+ sample = _first_row(dataset)
+ columns = _column_names(dataset, sample)
+ multimodal_info = detect_multimodal_dataset(dataset)
+ is_audio = multimodal_info.get("is_audio", False)
+ audio_fields = {
+ "is_audio": is_audio,
+ "detected_audio_column": multimodal_info.get("detected_audio_column"),
+ "detected_speaker_column": multimodal_info.get("detected_speaker_column"),
+ }
+
+ if is_vlm:
+ vlm_structure = detect_vlm_dataset_structure(dataset)
+ requires_mapping = vlm_structure["format"] == "unknown"
+ warning = None
+ if requires_mapping:
+ missing = []
+ if not vlm_structure.get("image_column"):
+ missing.append("image")
+ if not vlm_structure.get("text_column"):
+ missing.append("text")
+ if missing:
+ warning = (
+ f"Could not auto-detect {' or '.join(missing)} column. "
+ "Please assign image and text columns manually."
+ )
+ return {
+ "requires_manual_mapping": requires_mapping,
+ "detected_format": vlm_structure["format"],
+ "columns": columns,
+ "suggested_mapping": None,
+ "detected_image_column": vlm_structure.get("image_column"),
+ "detected_text_column": vlm_structure.get("text_column"),
+ "is_image": multimodal_info["is_image"],
+ "multimodal_columns": multimodal_info.get("multimodal_columns"),
+ "warning": warning,
+ **audio_fields,
+ }
+
+ if is_audio:
+ detected_audio = multimodal_info.get("detected_audio_column")
+ detected_text = multimodal_info.get("detected_text_column")
+ return {
+ "requires_manual_mapping": not detected_audio or not detected_text,
+ "detected_format": "audio",
+ "columns": columns,
+ "suggested_mapping": None,
+ "detected_image_column": None,
+ "detected_text_column": detected_text,
+ "is_image": False,
+ "multimodal_columns": multimodal_info.get("audio_columns"),
+ **audio_fields,
+ }
+
+ detected = detect_dataset_format(dataset)
+ if detected["format"] == "unknown":
+ heuristic_mapping = detect_custom_format_heuristic(dataset)
+ if heuristic_mapping:
+ return {
+ "requires_manual_mapping": False,
+ "detected_format": "custom_heuristic",
+ "columns": columns,
+ "suggested_mapping": heuristic_mapping,
+ "detected_image_column": None,
+ "detected_text_column": None,
+ "is_image": multimodal_info["is_image"],
+ "multimodal_columns": multimodal_info.get("multimodal_columns"),
+ **audio_fields,
+ }
+ return {
+ "requires_manual_mapping": True,
+ "detected_format": "unknown",
+ "columns": columns,
+ "suggested_mapping": None,
+ "detected_image_column": None,
+ "detected_text_column": None,
+ "is_image": multimodal_info["is_image"],
+ "multimodal_columns": multimodal_info.get("multimodal_columns"),
+ "warning": (
+ f"Could not auto-detect column roles for columns: {columns}. "
+ "Please assign roles manually, or use AI Assist."
+ ),
+ **audio_fields,
+ }
+
+ return {
+ "requires_manual_mapping": False,
+ "detected_format": detected["format"],
+ "columns": columns,
+ "suggested_mapping": None,
+ "detected_image_column": None,
+ "detected_text_column": None,
+ "is_image": multimodal_info["is_image"],
+ "multimodal_columns": multimodal_info.get("multimodal_columns"),
+ **audio_fields,
+ }
+
+
+_ROLE_MAP = {
+ "human": "user",
+ "user": "user",
+ "input": "user",
+ "gpt": "assistant",
+ "assistant": "assistant",
+ "output": "assistant",
+ "system": "system",
+}
+
+
+def _standardize_sharegpt_row(row: dict[str, Any], chat_column: str) -> dict[str, Any]:
+ chat_data = row.get(chat_column)
+ if not isinstance(chat_data, list):
+ return row
+ messages = []
+ for message in chat_data:
+ if not isinstance(message, dict):
+ continue
+ role = message.get("role") or message.get("from")
+ content = message.get("content") if "content" in message else message.get("value")
+ messages.append(
+ {
+ "role": _ROLE_MAP.get(str(role), str(role or "user")),
+ "content": "" if content is None else content,
+ }
+ )
+ return {chat_column: messages}
+
+
+def format_dataset_preview(dataset):
+ detected = detect_dataset_format(dataset)
+ if detected.get("format") != "sharegpt":
+ return dataset
+ chat_column = detected.get("chat_column")
+ if not isinstance(chat_column, str):
+ return dataset
+
+ if hasattr(dataset, "map"):
+ return dataset.map(lambda row: _standardize_sharegpt_row(row, chat_column))
+ return dataset
diff --git a/studio/backend/hub/utils/download_manifest.py b/studio/backend/hub/utils/download_manifest.py
new file mode 100644
index 00000000000..53666892960
--- /dev/null
+++ b/studio/backend/hub/utils/download_manifest.py
@@ -0,0 +1,487 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hub download manifest + cancel-marker primitives.
+
+Manifests record what a download was supposed to fetch (path + declared
+size per expected file). Consumed by:
+ - the worker post-download, to verify on-disk sizes match what HF
+ declared, so a resume that no-ops doesn't get classified as success;
+ - the inventory scanner, to mark a row partial when expected files
+ are absent or undersized, so a half-finished GGUF/dataset doesn't
+ masquerade as a complete on-device row.
+
+Cancel markers record that a user-initiated cancel landed for a
+(repo_type, repo_id, variant) triple. *Existence* is the signal the
+scanner reads; the body carries debuggability metadata. Markers are
+cleared at the start of a new download attempt (supersedes prior cancel)
+and on successful completion (defensive, in case the start clear failed).
+
+I/O contracts:
+ - Writes are atomic via ``tmp + os.replace``: a SIGKILL mid-write
+ cannot leave a half-written file readable to the next reader.
+ - Manifest reads fail *open*: missing/corrupt/schema-mismatched
+ manifests return ``None`` and the scanner falls through to the
+ legacy on-disk-only check (matches HF-cache imports and pre-fix
+ downloads that never wrote a manifest).
+ - Cancel-marker reads fail *closed*: file existence is the signal
+ regardless of body parseability, so a corrupt marker still
+ suppresses the "on device" classification.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import uuid
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Iterator, Optional, Sequence
+
+from loggers import get_logger
+
+from hub.utils.state_dir import (
+ RepoType,
+ cancelled_dir,
+ manifest_path,
+ manifests_dir,
+ marker_path,
+ variant_filename_prefix,
+)
+
+logger = get_logger(__name__)
+
+
+_MANIFEST_VERSION = 1
+_MARKER_VERSION = 2
+_LEGACY_MARKER_VERSION = 1
+
+# Verbatim phrase the worker emits on a degraded completion and the download
+# lifecycle escalates to a warning log. Shared so the emit and match stay coupled.
+MANIFEST_DEGRADED_MARKER = "completed without a manifest so partial detection is degraded"
+
+
+@dataclass(frozen = True)
+class ExpectedFile:
+ path: str
+ size: int
+ sha256: Optional[str] = None
+
+
+@dataclass(frozen = True)
+class Manifest:
+ repo_type: RepoType
+ repo_id: str
+ variant: Optional[str]
+ started_at: str
+ expected_files: tuple[ExpectedFile, ...]
+ transport: Optional[str] = None
+
+
+@dataclass(frozen = True)
+class VerifyResult:
+ ok: bool
+ missing: tuple[str, ...]
+ size_mismatched: tuple[str, ...]
+
+
+def _atomic_write_json(path: Path, payload: dict) -> bool:
+ # Per-write uuid suffix so a concurrent caller or a stale tmp from a
+ # previous crash cannot collide with the in-flight write.
+ tmp = path.with_name(f".{path.name}.tmp-{uuid.uuid4().hex[:8]}")
+ try:
+ with tmp.open("w", encoding = "utf-8") as handle:
+ handle.write(json.dumps(payload, indent = 2))
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp, path)
+ except OSError as exc:
+ logger.debug("Atomic write failed for %s: %s", path, exc)
+ try:
+ tmp.unlink(missing_ok = True)
+ except OSError:
+ pass
+ return False
+ if os.name != "nt":
+ try:
+ flags = os.O_RDONLY
+ if hasattr(os, "O_DIRECTORY"):
+ flags |= os.O_DIRECTORY
+ parent_fd = os.open(path.parent, flags)
+ try:
+ os.fsync(parent_fd)
+ finally:
+ os.close(parent_fd)
+ except OSError as exc:
+ logger.debug("Parent dir fsync failed for %s: %s", path, exc)
+ return True
+
+
+def write_manifest(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str],
+ expected_files: Sequence[ExpectedFile],
+ transport: Optional[str] = None,
+) -> bool:
+ """Write/overwrite the manifest for this triple. Best-effort.
+
+ ``False`` on write failure must not be treated as fatal: the
+ worst-case fallback is the pre-fix scanner behavior (one missed
+ partial detection), which is no regression.
+ """
+ path = manifest_path(repo_type, repo_id, variant)
+ if path is None:
+ return False
+ payload = {
+ "version": _MANIFEST_VERSION,
+ "repo_type": repo_type,
+ "repo_id": repo_id,
+ "variant": variant,
+ "started_at": datetime.now(timezone.utc).isoformat(),
+ "expected_files": [
+ {
+ "path": f.path,
+ "size": int(f.size),
+ **({"sha256": f.sha256} if f.sha256 else {}),
+ }
+ for f in expected_files
+ ],
+ "transport": transport,
+ }
+ return _atomic_write_json(path, payload)
+
+
+def read_manifest(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> Optional[Manifest]:
+ """Return the manifest if present and parseable; ``None`` otherwise.
+
+ Treats missing-file, parse-error, and any schema mismatch all as
+ ``None`` (fail-open). Scanner callers fall through to on-disk-only
+ behavior on ``None`` so this never regresses legacy/imported repos
+ that have no manifest.
+
+ Forward-compat: accepts only ``version == 1``; an unknown version is
+ treated as no manifest. A future v2 schema MUST either keep v1's
+ ``expected_files`` shape on the same filename (bump
+ ``_MANIFEST_VERSION`` and widen this check) or live under a different
+ filename, so an incompatible payload can never mis-classify rows.
+ """
+ path = manifest_path(repo_type, repo_id, variant)
+ if path is None or not path.is_file():
+ return None
+ try:
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ except (OSError, ValueError) as exc:
+ logger.debug("Could not read manifest %s: %s", path, exc)
+ return None
+ if not isinstance(data, dict):
+ return None
+ if data.get("version") != _MANIFEST_VERSION:
+ logger.debug(
+ "Manifest %s has unknown version %r; ignoring.",
+ path,
+ data.get("version"),
+ )
+ return None
+ raw_files = data.get("expected_files")
+ if not isinstance(raw_files, list):
+ return None
+ expected: list[ExpectedFile] = []
+ for item in raw_files:
+ if not isinstance(item, dict):
+ return None
+ file_path = item.get("path")
+ size = item.get("size")
+ if not isinstance(file_path, str) or not isinstance(size, int):
+ return None
+ sha256 = item.get("sha256")
+ expected.append(
+ ExpectedFile(
+ path = file_path,
+ size = size,
+ sha256 = sha256 if isinstance(sha256, str) and sha256 else None,
+ )
+ )
+ raw_variant = data.get("variant")
+ transport = data.get("transport")
+ return Manifest(
+ repo_type = repo_type,
+ repo_id = str(data.get("repo_id", repo_id)),
+ variant = raw_variant if raw_variant else None,
+ started_at = str(data.get("started_at", "")),
+ expected_files = tuple(expected),
+ transport = transport if transport in ("http", "xet") else None,
+ )
+
+
+def verify_against_disk(manifest: Manifest, snapshot_dir: Path) -> VerifyResult:
+ """Check every expected file is present in *snapshot_dir* at its declared size.
+
+ Presence + size only, not content integrity: it converts a
+ no-op-on-cached ``snapshot_download`` into a clear error when shards are
+ missing or truncated, and marks a scanner row partial when expected bytes
+ aren't on disk. Byte-level integrity is already covered upstream by
+ ``huggingface_hub`` (size check on HTTP, content-addressed chunk hashes on
+ XET), so re-hashing finalized multi-GB weights here would only duplicate
+ that at a large cost. ``Path.stat()`` follows symlinks, so HF's symlink and
+ Windows copy cache layouts both verify correctly.
+ """
+ missing: list[str] = []
+ mismatched: list[str] = []
+ for expected in manifest.expected_files:
+ target = snapshot_dir / expected.path
+ try:
+ actual_size = target.stat().st_size
+ except OSError:
+ missing.append(expected.path)
+ continue
+ # expected.size == 0 means HF metadata had no declared size: verify
+ # existence only rather than flagging every such file as mismatched.
+ if expected.size > 0 and actual_size != expected.size:
+ mismatched.append(expected.path)
+ return VerifyResult(
+ ok = not missing and not mismatched,
+ missing = tuple(missing),
+ size_mismatched = tuple(mismatched),
+ )
+
+
+def expected_files_from_snapshot_dir(snapshot_dir: Path) -> list[ExpectedFile]:
+ """Derive expected-file entries from a completed snapshot directory.
+
+ Last-resort manifest source for when HF metadata was unreachable for the
+ whole download. ``snapshot_download`` has already exited cleanly, so every
+ regular file is a finished, correctly-sized blob; recording them keeps the
+ scanner's completion check in agreement with the worker's exit-0 success
+ instead of leaving a finished repo perpetually partial. ``stat()`` follows
+ HF's symlink layout and Windows copies, so the recorded sizes match what
+ ``verify_against_disk`` later reads.
+ """
+ out: list[ExpectedFile] = []
+ try:
+ entries = sorted(snapshot_dir.rglob("*"))
+ except OSError:
+ return out
+ for path in entries:
+ try:
+ if not path.is_file():
+ continue
+ relative = path.relative_to(snapshot_dir).as_posix()
+ out.append(
+ ExpectedFile(
+ path = relative,
+ size = path.stat().st_size,
+ sha256 = None,
+ )
+ )
+ except OSError:
+ continue
+ return out
+
+
+def write_cancel_marker(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+ transport: Optional[str] = None,
+) -> bool:
+ """Record that this triple was cancelled. Idempotent across repeated cancels.
+
+ ``transport`` ("http"/"xet") is surfaced via partial_transport on
+ inventory rows so the UI labels HTTP retries as continuable and XET
+ retries as full redownloads. None is accepted for forward-compat.
+ """
+ path = marker_path(repo_type, repo_id, variant)
+ if path is None:
+ return False
+ payload = {
+ "version": _MARKER_VERSION,
+ "repo_type": repo_type,
+ "repo_id": repo_id,
+ "variant": variant,
+ "transport": transport,
+ "cancelled_at": datetime.now(timezone.utc).isoformat(),
+ }
+ return _atomic_write_json(path, payload)
+
+
+def read_cancel_marker_transport(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> Optional[str]:
+ """Return the transport recorded in the cancel marker, or ``None`` if no
+ marker exists or it is unreadable.
+
+ Cases:
+
+ * No marker on disk → ``None``.
+ * Legacy v1 marker → ``"http"``: v1 markers were only written by the
+ HTTP path, so the transport is unambiguous despite the absent field.
+ * v2 marker with a valid ``"http"`` / ``"xet"`` transport → that value.
+ * Corrupt, non-dict, or v2-with-missing-transport marker → ``None``.
+ Defaulting these to ``"http"`` misled the UI into showing a
+ byte-resume "Continue" label for what may have been an XET cancel;
+ ``None`` keeps the neutral "Retry" label.
+ * Unknown future versions → ``None`` (unknown layout, unknown transport).
+ """
+ path = marker_path(repo_type, repo_id, variant)
+ if path is None or not path.is_file():
+ return None
+ try:
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ except (OSError, ValueError) as exc:
+ logger.debug("Could not read cancel marker %s: %s", path, exc)
+ return None
+ if not isinstance(data, dict):
+ return None
+ version = data.get("version")
+ if version == _LEGACY_MARKER_VERSION:
+ return "http"
+ if version != _MARKER_VERSION:
+ return None
+ transport = data.get("transport")
+ if isinstance(transport, str) and transport in ("http", "xet"):
+ return transport
+ return None
+
+
+def clear_cancel_marker(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> None:
+ """Remove the cancel marker for this triple if present.
+
+ Idempotent: a missing marker is not an error. Called at
+ download-start (a fresh attempt supersedes prior cancel state) and
+ again at successful completion (cleans up if the start clear failed).
+ """
+ path = marker_path(repo_type, repo_id, variant)
+ if path is None:
+ return
+ try:
+ path.unlink(missing_ok = True)
+ except OSError as exc:
+ logger.debug("Could not clear cancel marker %s: %s", path, exc)
+
+
+def has_cancel_marker(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> bool:
+ """File-existence check only. Body is never read.
+
+ Fail-closed: a corrupt marker still returns ``True`` because the
+ file's existence is the signal (the user once cancelled this
+ triple, even if the body is unreadable).
+ """
+ path = marker_path(repo_type, repo_id, variant)
+ if path is None:
+ return False
+ try:
+ return path.is_file()
+ except OSError:
+ return False
+
+
+def delete_manifest(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> bool:
+ path = manifest_path(repo_type, repo_id, variant)
+ if path is None:
+ return False
+ try:
+ if not path.is_file():
+ return False
+ path.unlink()
+ return True
+ except OSError as exc:
+ logger.debug("Could not delete manifest %s: %s", path, exc)
+ return False
+
+
+def purge_state(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> bool:
+ """Remove manifest + cancel marker for this triple. Returns ``True``
+ when anything was present on disk before the call. Idempotent."""
+ marker_existed = has_cancel_marker(repo_type, repo_id, variant)
+ manifest_removed = delete_manifest(repo_type, repo_id, variant)
+ clear_cancel_marker(repo_type, repo_id, variant)
+ return marker_existed or manifest_removed
+
+
+def purge_all_state_for_repo(repo_type: RepoType, repo_id: str) -> int:
+ """Remove the snapshot-level manifest + marker AND every variant-keyed
+ manifest + marker for this repo. Used by the route delete handlers so
+ scanner state never outlives the cache it described. Returns the count
+ of (repo, variant) triples that had any state on disk."""
+ removed = 0
+ if purge_state(repo_type, repo_id, None):
+ removed += 1
+ variants: set[str] = set()
+ for variant, _ in iter_variant_manifests(repo_type, repo_id):
+ variants.add(variant)
+ for variant, _ in iter_variant_markers(repo_type, repo_id):
+ variants.add(variant)
+ for variant in variants:
+ if purge_state(repo_type, repo_id, variant):
+ removed += 1
+ return removed
+
+
+def _variant_from_state_file(path: Path, fallback: str) -> str:
+ try:
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ return fallback
+ if not isinstance(data, dict):
+ return fallback
+ variant = data.get("variant")
+ return variant if isinstance(variant, str) and variant else fallback
+
+
+def _iter_variant_state_files(
+ parent: Optional[Path], repo_type: RepoType, repo_id: str
+) -> Iterator[tuple[str, Path]]:
+ if parent is None:
+ return
+ prefix = variant_filename_prefix(repo_type, repo_id)
+ try:
+ entries = list(parent.iterdir())
+ except OSError:
+ return
+ for entry in entries:
+ if not entry.is_file() or not entry.name.endswith(".json"):
+ continue
+ stem = entry.name[: -len(".json")]
+ if not stem.lower().startswith(prefix):
+ continue
+ variant = stem[len(prefix) :]
+ if variant:
+ yield _variant_from_state_file(entry, variant), entry
+
+
+def iter_variant_manifests(repo_type: RepoType, repo_id: str) -> Iterator[tuple[str, Path]]:
+ """Yield (variant, manifest_path) for every variant-keyed manifest
+ written for this repo. Used by is_gguf_repo_partial to enumerate all
+ variants present on disk so the all-variants-broken gate can run."""
+ yield from _iter_variant_state_files(manifests_dir(), repo_type, repo_id)
+
+
+def iter_variant_markers(repo_type: RepoType, repo_id: str) -> Iterator[tuple[str, Path]]:
+ """Yield (variant, marker_path) for every variant-keyed cancel marker.
+ Companion to iter_variant_manifests: catches variants cancelled
+ before download-start ever wrote a manifest (very early failures)."""
+ yield from _iter_variant_state_files(cancelled_dir(), repo_type, repo_id)
diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.py
new file mode 100644
index 00000000000..777d63e1b5b
--- /dev/null
+++ b/studio/backend/hub/utils/download_registry.py
@@ -0,0 +1,1263 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""HF cache inspection, download registry state, and orphan-worker reaping.
+
+Worker spawning and exit handling live in
+:mod:`hub.services.download_lifecycle`; this module owns the registry state
+machine plus the cache/marker inspection those workers depend on.
+
+Resume model
+------------
+Only the HTTP transport supports true partial-file resume:
+huggingface_hub's HTTP resumer opens ``<etag>.incomplete`` in append mode
+and sends ``Range: bytes={resume_size}-`` to continue from disk.
+
+The XET transport CANNOT resume from a ``.incomplete`` partial:
+``hf_xet.download_files`` rewrites the destination from scratch.
+Network-level dedup still happens, but through the separate chunk cache at
+``~/.cache/huggingface/xet/chunk-cache``, which these helpers never touch.
+
+Cross-transport corruption: a partial written by XET (or ``hf_transfer``'s
+parallel-Range writer) can be sparse — high reported size, zero-filled
+gaps below. Feeding it to the HTTP resumer would produce a correct-sized
+blob whose internal bytes are silently wrong. To prevent that, we keep
+transport markers at the download's scope (repo for snapshots/datasets,
+variant for GGUF) and refuse to inherit an HTTP partial unless the marker
+proves the previous writer was the same single-stream sequential writer.
+
+Marker writes go through tmp+rename in :func:`prepare_cache_for_transport`
+before the worker hands off to ``snapshot_download``, so the next process
+always sees a consistent provenance signal.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import os
+import re
+import shlex
+import signal
+import subprocess
+import sys
+import threading
+import time
+import weakref
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Iterator, Literal, Optional
+
+from loggers import get_logger
+
+from hub.utils import state_dir
+from hub.utils.state_dir import RepoType
+
+logger = get_logger(__name__)
+
+from hub.utils.hf_cache_state import (
+ INCOMPLETE_SUFFIX,
+ TRANSPORT_HTTP,
+ TRANSPORT_XET,
+ TRANSPORT_MARKER_NAME,
+ VALID_TRANSPORTS,
+ has_active_incomplete_blobs,
+ iter_repo_cache_dirs,
+ iter_active_repo_cache_dirs,
+ repo_cache_dir_name,
+ target_dir_name,
+ hf_cache_root,
+)
+
+
+@dataclass(frozen = True)
+class DownloadTransportCapability:
+ available: bool
+ reason: Optional[str] = None
+
+
+@dataclass(frozen = True)
+class DownloadTransportCapabilities:
+ http: DownloadTransportCapability
+ xet: DownloadTransportCapability
+
+
+def get_download_transport_capabilities() -> DownloadTransportCapabilities:
+ xet_available = importlib.util.find_spec("hf_xet") is not None
+ return DownloadTransportCapabilities(
+ http = DownloadTransportCapability(available = True),
+ xet = DownloadTransportCapability(
+ available = xet_available,
+ reason = None
+ if xet_available
+ else "Xet transport is unavailable because hf_xet is not installed.",
+ ),
+ )
+
+
+def download_transport_unavailable_reason(transport: str) -> Optional[str]:
+ if transport == TRANSPORT_HTTP:
+ return None
+ if transport == TRANSPORT_XET:
+ caps = get_download_transport_capabilities().xet
+ return None if caps.available else caps.reason
+ return f"Unsupported download transport: {transport}"
+
+
+def _worker_breadcrumb_path(key: str) -> Optional[Path]:
+ parent = state_dir.workers_dir()
+ if parent is None:
+ return None
+ safe = hashlib.sha256(key.encode("utf-8")).hexdigest()[:32]
+ return parent / f"{safe}.json"
+
+
+def write_worker_breadcrumb(key: str, pid: int, metadata: Optional["DownloadMetadata"]) -> None:
+ """Record a live worker's PID so a restarted backend can reap it. Best
+ effort: a write failure only forfeits boot-time reaping for this worker,
+ still covered by the worker's own parent-death watchdog."""
+ path = _worker_breadcrumb_path(key)
+ if path is None:
+ return
+ payload = {
+ "pid": int(pid),
+ "repo_type": metadata.repo_type if metadata is not None else None,
+ "repo_id": metadata.repo_id if metadata is not None else None,
+ "variant": metadata.variant if metadata is not None else None,
+ "transport": metadata.transport if metadata is not None else None,
+ }
+ tmp = path.with_name(f".{path.name}.tmp-{pid}")
+ try:
+ tmp.write_text(json.dumps(payload), encoding = "utf-8")
+ os.replace(tmp, path)
+ except OSError as exc:
+ logger.debug("Could not write worker breadcrumb %s: %s", path, exc)
+ try:
+ tmp.unlink(missing_ok = True)
+ except OSError:
+ pass
+
+
+def remove_worker_breadcrumb(key: str) -> None:
+ path = _worker_breadcrumb_path(key)
+ if path is None:
+ return
+ _safe_unlink(path)
+
+
+def _safe_unlink(path: Path) -> None:
+ try:
+ path.unlink(missing_ok = True)
+ except OSError as exc:
+ logger.debug("Could not remove %s: %s", path, exc)
+
+
+def _process_alive(pid: int) -> bool:
+ if sys.platform == "win32":
+ import ctypes
+ from ctypes import wintypes
+
+ SYNCHRONIZE = 0x00100000
+ ERROR_INVALID_PARAMETER = 87
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ kernel32.OpenProcess.restype = wintypes.HANDLE
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+ ctypes.set_last_error(0)
+ handle = kernel32.OpenProcess(SYNCHRONIZE, False, pid)
+ if not handle:
+ return ctypes.get_last_error() != ERROR_INVALID_PARAMETER
+ kernel32.CloseHandle(handle)
+ return True
+ try:
+ os.kill(pid, 0)
+ return True
+ except ProcessLookupError:
+ return False
+ except OSError:
+ return True
+
+
+def _read_process_cmdline(pid: int) -> Optional[str]:
+ proc_cmdline = Path(f"/proc/{pid}/cmdline")
+ try:
+ if proc_cmdline.exists():
+ raw = proc_cmdline.read_bytes()
+ return raw.replace(b"\x00", b" ").decode("utf-8", "replace")
+ except OSError:
+ pass
+ try:
+ import psutil
+ return " ".join(psutil.Process(pid).cmdline())
+ except Exception:
+ return None
+
+
+def _cmdline_repo_id(cmdline: str) -> Optional[str]:
+ try:
+ args = shlex.split(cmdline)
+ except ValueError:
+ args = cmdline.split()
+ for i, arg in enumerate(args):
+ if arg == "--repo-id" and i + 1 < len(args):
+ return args[i + 1]
+ if arg.startswith("--repo-id="):
+ return arg.split("=", 1)[1]
+ return None
+
+
+def _is_our_worker(pid: int, repo_id: Optional[str]) -> bool:
+ cmdline = _read_process_cmdline(pid)
+ if cmdline is None:
+ return False
+ if "hub.workers.hf_download" not in cmdline:
+ return False
+ # Exact --repo-id match: a substring match would let a stale breadcrumb for
+ # Org/Model reap a live worker for Org/Model-v2.
+ if isinstance(repo_id, str) and repo_id:
+ return _cmdline_repo_id(cmdline) == repo_id
+ return True
+
+
+def _kill_orphan(pid: int) -> None:
+ try:
+ os.kill(pid, signal.SIGTERM if sys.platform == "win32" else signal.SIGKILL)
+ except OSError:
+ pass
+
+
+def _settle_orphaned_download(
+ repo_type: Optional[str],
+ repo_id: Optional[str],
+ variant: Optional[str],
+ transport: Optional[str],
+) -> None:
+ """Persist a cancel marker for a reaped orphan still mid-download so the next
+ launch settles it to a resumable "cancelled" state instead of a phantom-running
+ row.
+
+ Gated on surviving partial state and on the recorded manifest not already
+ verifying against an active snapshot, so a download that finished before its
+ breadcrumb was cleaned up is never mislabeled cancelled. For a GGUF variant
+ manifest with blob hashes, the partial-state check is scoped to those hashes so
+ a sibling variant cannot contaminate this orphan's state. The recorded
+ transport is preserved so the resume affordance stays accurate."""
+ if repo_type not in ("model", "dataset") or not repo_id:
+ return
+ from hub.utils import download_manifest
+
+ manifest = download_manifest.read_manifest(repo_type, repo_id, variant)
+ if repo_type == "model" and variant and manifest is None:
+ return
+ if manifest is None:
+ if not has_active_incomplete_blobs(repo_type, repo_id):
+ return
+ else:
+ if _manifest_verifies_against_active_cache(repo_type, repo_id, manifest):
+ return
+ if not _manifest_has_active_incomplete_blobs(repo_type, repo_id, manifest):
+ return
+ persist_cancel_marker(repo_type, repo_id, variant, transport, logger = logger)
+
+
+def reap_orphan_workers() -> None:
+ """Kill download workers left running by a previous backend instance.
+
+ Verifies each breadcrumb's PID is alive AND its command line is one of our
+ workers before terminating, so a recycled PID can't take down an unrelated
+ process. Partial blobs are never touched, so a reaped download stays
+ resumable; an interrupted one with bytes on disk is settled to a cancelled
+ marker (see :func:`_settle_orphaned_download`) so its resume affordance
+ survives a hard crash like a graceful shutdown's does. Runs once at startup
+ and never raises."""
+ parent = state_dir.workers_dir()
+ if parent is None:
+ return
+ try:
+ entries = list(parent.iterdir())
+ except OSError:
+ return
+ for entry in entries:
+ if not entry.is_file() or not entry.name.endswith(".json"):
+ continue
+ try:
+ data = json.loads(entry.read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ _safe_unlink(entry)
+ continue
+ pid = data.get("pid") if isinstance(data, dict) else None
+ repo_id = data.get("repo_id") if isinstance(data, dict) else None
+ if not isinstance(pid, int) or pid <= 0:
+ _safe_unlink(entry)
+ continue
+ try:
+ if _process_alive(pid) and _is_our_worker(pid, repo_id):
+ _kill_orphan(pid)
+ logger.warning(
+ "Reaped orphaned download worker pid=%s repo=%s from a "
+ "previous backend instance.",
+ pid,
+ repo_id,
+ )
+ _settle_orphaned_download(
+ data.get("repo_type"),
+ repo_id,
+ data.get("variant"),
+ data.get("transport"),
+ )
+ except Exception as exc:
+ logger.debug("Reaper failed for breadcrumb %s: %s", entry, exc)
+ _safe_unlink(entry)
+
+
+def _purge_incomplete_blobs(
+ entry: Path,
+ only_hashes: Optional[frozenset[str]] = None,
+ protected_hashes: Optional[frozenset[str]] = None,
+) -> int:
+ """Delete matching ``*.incomplete`` blobs beneath *entry*; return the count
+ removed. Per-file failures are swallowed.
+
+ ``only_hashes`` whitelists which partials may be purged; ``None`` means
+ every partial (full-repo snapshot/dataset). ``protected_hashes`` is honoured
+ unconditionally, even when ``only_hashes`` is ``None``, so a blob a
+ concurrent same-repo peer is writing is never purged from under it."""
+ blobs_dir = entry / "blobs"
+ if not blobs_dir.is_dir():
+ return 0
+ removed = 0
+ try:
+ candidates = list(blobs_dir.iterdir())
+ except OSError:
+ return 0
+ for blob in candidates:
+ try:
+ if not blob.is_file():
+ continue
+ if not blob.name.endswith(INCOMPLETE_SUFFIX):
+ continue
+ blob_hash = blob.name[: -len(INCOMPLETE_SUFFIX)]
+ if protected_hashes and blob_hash in protected_hashes:
+ continue
+ if only_hashes is not None and blob_hash not in only_hashes:
+ continue
+ blob.unlink()
+ removed += 1
+ except OSError:
+ # Swallow; downstream snapshot_download surfaces a precise error if
+ # it actually can't proceed.
+ continue
+ return removed
+
+
+def _iter_active_snapshot_dirs(repo_type: str, repo_id: str) -> Iterator[Path]:
+ for entry in iter_active_repo_cache_dirs(repo_type, repo_id):
+ snapshots_dir = entry / "snapshots"
+ if not snapshots_dir.is_dir():
+ continue
+ try:
+ snapshots = list(snapshots_dir.iterdir())
+ except OSError:
+ continue
+ for snapshot in snapshots:
+ if snapshot.is_dir():
+ yield snapshot
+
+
+def _manifest_verifies_against_active_cache(repo_type: str, repo_id: str, manifest) -> bool:
+ from hub.utils import download_manifest
+ for snapshot_dir in _iter_active_snapshot_dirs(repo_type, repo_id):
+ if download_manifest.verify_against_disk(manifest, snapshot_dir).ok:
+ return True
+ return False
+
+
+def _manifest_has_active_incomplete_blobs(repo_type: str, repo_id: str, manifest) -> bool:
+ if not getattr(manifest, "variant", None):
+ return has_active_incomplete_blobs(repo_type, repo_id)
+ expected_hashes = frozenset(
+ expected.sha256 for expected in manifest.expected_files if expected.sha256
+ )
+ if not expected_hashes:
+ return has_active_incomplete_blobs(repo_type, repo_id)
+ return bool(
+ incomplete_blob_hashes(repo_type, repo_id, active_only = True).intersection(expected_hashes)
+ )
+
+
+def _marker_path(entry: Path, variant: Optional[str] = None) -> Path:
+ if not variant:
+ return entry / TRANSPORT_MARKER_NAME
+ digest = hashlib.sha256(variant.strip().lower().encode("utf-8")).hexdigest()[:24]
+ return entry / f"{TRANSPORT_MARKER_NAME}.gguf-{digest}"
+
+
+def _is_transport_marker_file(path: Path) -> bool:
+ # Matches ".transport", its tmps, and variant-scoped ".transport.gguf-*".
+ # Real HF cache entries (blobs/refs/snapshots/.no_exist) never start with
+ # ".transport.".
+ return path.name == TRANSPORT_MARKER_NAME or path.name.startswith(f"{TRANSPORT_MARKER_NAME}.")
+
+
+def _companion_marker_path(entry: Path) -> Path:
+ return entry / f"{TRANSPORT_MARKER_NAME}.companion"
+
+
+def _read_marker_value(marker: Path) -> Optional[str]:
+ try:
+ if not marker.exists():
+ return None
+ value = marker.read_text().strip()
+ except OSError:
+ return None
+ return value if value in VALID_TRANSPORTS else None
+
+
+def _write_marker_value(marker: Path, mode: str) -> None:
+ try:
+ # tmp + rename so a SIGKILL mid-write can't leave a half-written marker.
+ # The tmp name is per-process so concurrent writers don't clobber tmps.
+ tmp = marker.with_name(f"{marker.name}.tmp-{os.getpid()}")
+ tmp.write_text(mode)
+ os.replace(tmp, marker)
+ except OSError:
+ # Best-effort: a missing marker next run purges the partial defensively,
+ # the safe failure mode.
+ pass
+
+
+def _read_marker(entry: Path, variant: Optional[str] = None) -> Optional[str]:
+ return _read_marker_value(_marker_path(entry, variant))
+
+
+def _write_marker(
+ entry: Path,
+ mode: str,
+ variant: Optional[str] = None,
+) -> None:
+ _write_marker_value(_marker_path(entry, variant), mode)
+
+
+def _read_companion_marker(entry: Path) -> Optional[str]:
+ return _read_marker_value(_companion_marker_path(entry))
+
+
+def _write_companion_marker(entry: Path, mode: str) -> None:
+ _write_marker_value(_companion_marker_path(entry), mode)
+
+
+def prepare_cache_for_transport(
+ repo_type: str,
+ repo_id: str,
+ mode: str,
+ variant: Optional[str] = None,
+ only_blob_hashes: Optional[frozenset[str]] = None,
+ companion_blob_hashes: Optional[frozenset[str]] = None,
+ protected_blob_hashes: Optional[frozenset[str]] = None,
+) -> int:
+ """Guarantee any pre-existing ``.incomplete`` blobs are SAFE to resume under
+ *mode*. Returns the number of partial blobs purged for untrusted provenance.
+
+ Two marker scopes govern GGUF downloads. ``only_blob_hashes`` are the
+ variant's own (main quant) blobs, judged by the ``variant``-scoped marker;
+ ``None`` widens the scope to every partial for full-repo snapshots/datasets.
+ ``companion_blob_hashes`` are blobs shared across sibling variants (a vision
+ mmproj), judged by a separate repo-scoped companion marker — so a companion
+ partial is trusted against the transport that wrote it, not against
+ whichever sibling variant resumes next.
+
+ The contract:
+ - HTTP mode: a partial is trusted ONLY when its governing marker equals
+ ``"http"``. Any other case (missing/unreadable/mismatched marker) purges,
+ since the HTTP resumer would otherwise append to a sparse
+ XET/parallel-Range partial and silently produce a corrupt blob.
+ - XET mode: incomplete blobs are purged (``hf_xet.download_files`` rewrites
+ from scratch, so this only fixes UI accounting — bytes already in CAS are
+ reused via the chunk-cache). Scoped to ``only_blob_hashes``: companion
+ blobs fall outside that set and survive (shared, and XET overwrites them).
+
+ ``protected_blob_hashes`` are blobs a concurrent same-repo peer is writing;
+ they are excluded from every purge so a shared companion is never deleted
+ mid-write.
+
+ Scope: only the active ``HF_HUB_CACHE`` root is inspected. That suffices for
+ resume safety because ``snapshot_download`` runs without a ``cache_dir``
+ override and so can only read or resume a ``.incomplete`` under this same
+ active root. Markers are written for the new mode before returning.
+ """
+ if mode not in VALID_TRANSPORTS:
+ raise ValueError(f"Invalid transport mode: {mode!r}")
+ root = hf_cache_root(create = True)
+ if root is None:
+ return 0
+ target = target_dir_name(repo_type, repo_id)
+ try:
+ entries = [e for e in root.iterdir() if e.name.lower() == target]
+ except OSError:
+ return 0
+ if not entries:
+ # First download: pre-create the repo dir so the marker lands before the
+ # worker writes any bytes. Otherwise a SIGKILL mid-download leaves a
+ # partial with no marker that the resume then purges.
+ canonical = repo_cache_dir_name(repo_type, repo_id)
+ new_entry = root / canonical
+ try:
+ new_entry.mkdir(exist_ok = True)
+ except OSError:
+ return 0
+ entries = [new_entry]
+ protected = protected_blob_hashes or frozenset()
+ has_companion = bool(companion_blob_hashes)
+ total_purged = 0
+ for entry in entries:
+ if mode == TRANSPORT_XET:
+ total_purged += _purge_incomplete_blobs(entry, only_blob_hashes, protected)
+ else:
+ if _read_marker(entry, variant) != mode:
+ total_purged += _purge_incomplete_blobs(entry, only_blob_hashes, protected)
+ if companion_blob_hashes and _read_companion_marker(entry) != mode:
+ total_purged += _purge_incomplete_blobs(entry, companion_blob_hashes, protected)
+ _write_marker(entry, mode, variant)
+ if has_companion:
+ _write_companion_marker(entry, mode)
+ return total_purged
+
+
+_HF_TOKEN_RE = re.compile(r"hf_[A-Za-z0-9]{20,}")
+_BEARER_RE = re.compile(r"(?i)bearer\s+[A-Za-z0-9._\-]+")
+
+
+def scrub_secrets(text: str, *, hf_token: Optional[str] = None) -> str:
+ if not text:
+ return text
+ cleaned = text
+ if hf_token:
+ cleaned = cleaned.replace(hf_token, "***")
+ cleaned = _BEARER_RE.sub("Bearer ***", cleaned)
+ cleaned = _HF_TOKEN_RE.sub("hf_***", cleaned)
+ return cleaned
+
+
+def purge_empty_marker_dir(
+ repo_type: str,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> bool:
+ """Remove the failed download's own transport marker from a marker-only dir.
+
+ ``prepare_cache_for_transport`` pre-creates the dir + marker before any
+ download; a failure during validation/auth/network setup leaves the dir as
+ marker-only litter. Only the failed download's OWN marker is removed (the
+ repo-scope ``.transport`` or the variant-scoped ``.transport.gguf-*`` plus
+ its ``.tmp-*`` siblings); a sibling variant's marker and the shared
+ ``.transport.companion`` are left intact, so cancelling one quant never
+ strips a peer's provenance. A dir holding ``blobs/``/``snapshots/``/``refs/``
+ won't match and is left untouched, so a resumable partial isn't blown away.
+ """
+ cleaned = False
+ for entry in iter_repo_cache_dirs(repo_type, repo_id):
+ try:
+ contents = list(entry.iterdir())
+ except OSError:
+ continue
+ if not contents or not all(_is_transport_marker_file(item) for item in contents):
+ continue
+ own_name = _marker_path(entry, variant).name
+ own_markers = [
+ item
+ for item in contents
+ if item.name == own_name or item.name.startswith(f"{own_name}.tmp")
+ ]
+ if not own_markers:
+ continue
+ try:
+ for marker in own_markers:
+ marker.unlink()
+ except OSError:
+ continue
+ cleaned = True
+ try:
+ entry.rmdir()
+ except OSError:
+ continue
+ return cleaned
+
+
+def read_active_transport_marker(
+ repo_type: str,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> Optional[str]:
+ for entry in iter_active_repo_cache_dirs(repo_type, repo_id):
+ value = _read_marker(entry, variant)
+ if value is not None:
+ return value
+ return None
+
+
+def is_resumable_partial(
+ repo_type: str,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> bool:
+ """True only when a partial exists AND was produced by a byte-resumable
+ writer (the HTTP transport). XET partials exist on disk but are discarded on
+ the next download attempt."""
+ if not has_active_incomplete_blobs(repo_type, repo_id):
+ return False
+ return read_active_transport_marker(repo_type, repo_id, variant) == TRANSPORT_HTTP
+
+
+def incomplete_blob_hashes(
+ repo_type: str,
+ repo_id: str,
+ *,
+ active_only: bool = False,
+) -> set[str]:
+ out: set[str] = set()
+ entries = (
+ iter_active_repo_cache_dirs(repo_type, repo_id)
+ if active_only
+ else iter_repo_cache_dirs(repo_type, repo_id)
+ )
+ for entry in entries:
+ blobs_dir = entry / "blobs"
+ if not blobs_dir.is_dir():
+ continue
+ try:
+ for blob in blobs_dir.iterdir():
+ if blob.is_file() and blob.name.endswith(INCOMPLETE_SUFFIX):
+ out.add(blob.name[: -len(INCOMPLETE_SUFFIX)])
+ except OSError:
+ continue
+ return out
+
+
+def completed_blob_bytes(repo_type: str, repo_id: str, blob_hashes: frozenset[str]) -> int:
+ """Sum finalized blob bytes for *blob_hashes* in the active HF cache root.
+
+ A worker only writes to the active ``HF_HUB_CACHE`` root, so a baseline must
+ ignore legacy/default roots that ``snapshot_download`` won't reuse this run.
+ """
+ if not blob_hashes:
+ return 0
+ total = 0
+ for entry in iter_active_repo_cache_dirs(repo_type, repo_id):
+ blobs_dir = entry / "blobs"
+ if not blobs_dir.is_dir():
+ continue
+ for blob_hash in blob_hashes:
+ blob = blobs_dir / blob_hash
+ try:
+ if blob.is_file():
+ total += max(0, int(blob.stat().st_size))
+ except OSError:
+ continue
+ return total
+
+
+def existing_blob_bytes(repo_type: str, repo_id: str, blob_hashes: frozenset[str]) -> int:
+ """Bytes already on disk (finalized + ``.incomplete``) for *blob_hashes* in
+ the active HF cache root. A blob is in exactly one state, so summing both
+ candidate names never double-counts. Used to size what a (possibly resumed)
+ download still needs to write before the run starts."""
+ if not blob_hashes:
+ return 0
+ total = 0
+ for entry in iter_active_repo_cache_dirs(repo_type, repo_id):
+ blobs_dir = entry / "blobs"
+ if not blobs_dir.is_dir():
+ continue
+ for blob_hash in blob_hashes:
+ for name in (blob_hash, f"{blob_hash}{INCOMPLETE_SUFFIX}"):
+ blob = blobs_dir / name
+ try:
+ if blob.is_file():
+ total += max(0, int(blob.stat().st_size))
+ except OSError:
+ continue
+ return total
+
+
+JobState = Literal["idle", "running", "cancelling", "cancelled", "complete", "error"]
+
+TERMINAL_STATES = frozenset({"complete", "cancelled", "error"})
+_ACTIVE_STATES = frozenset({"running", "cancelling"})
+
+
+@dataclass(frozen = True)
+class DownloadState:
+ state: JobState
+ error: Optional[str] = None
+
+
+@dataclass(frozen = True)
+class DownloadMetadata:
+ repo_type: RepoType
+ repo_id: str
+ variant: Optional[str]
+ transport: Optional[str]
+ # GGUF variant main/writable hashes, identifying the variant-specific shards
+ # for concurrency decisions.
+ blob_hashes: frozenset[str] = field(default_factory = frozenset)
+ # Full required hash set for progress/completion (includes the shared mmproj
+ # companion for vision GGUF repos).
+ progress_blob_hashes: frozenset[str] = field(default_factory = frozenset)
+ # Bytes already complete before this job started; not counted as this run's
+ # progress.
+ completed_baseline_bytes: int = 0
+
+
+@dataclass(frozen = True)
+class ActiveDownloadRef:
+ key: str
+ state: str
+ metadata: Optional[DownloadMetadata]
+ generation: int
+
+
+def normalize_repo_key(repo_id: str) -> str:
+ return repo_id.strip().lower()
+
+
+def normalize_job_key(key: str) -> str:
+ repo, sep, variant = key.partition("::")
+ repo_key = normalize_repo_key(repo)
+ return f"{repo_key}{sep}{variant.strip().lower()}" if sep else repo_key
+
+
+def _repo_of_key(key: str) -> str:
+ return normalize_repo_key(key.split("::", 1)[0])
+
+
+def variant_from_key(key: str) -> Optional[str]:
+ """Parse the variant suffix from a 'repo_id::variant' key. Empty
+ variant returns None — matches the manifest/marker calling
+ convention for full-snapshot models and datasets."""
+ if "::" not in key:
+ return None
+ _, _, variant = key.partition("::")
+ return variant or None
+
+
+def persist_cancel_marker(
+ repo_type: Optional[RepoType],
+ repo_id: Optional[str],
+ variant: Optional[str],
+ transport: Optional[str],
+ *,
+ logger = logger,
+) -> None:
+ if not repo_type or not repo_id:
+ return
+ try:
+ from hub.utils.download_manifest import write_cancel_marker
+ if not write_cancel_marker(
+ repo_type,
+ repo_id,
+ variant,
+ transport = transport,
+ ):
+ logger.debug("write_cancel_marker returned False for %s", repo_id)
+ except Exception as exc:
+ logger.debug("write_cancel_marker failed for %s: %s", repo_id, exc)
+
+
+_REGISTRIES: "weakref.WeakSet[DownloadRegistry]" = weakref.WeakSet()
+_NAMED_REGISTRIES: dict[str, "DownloadRegistry"] = {}
+_NAMED_REGISTRIES_LOCK = threading.Lock()
+
+
+def terminate_active_downloads() -> None:
+ """Best-effort shutdown hook called from the FastAPI lifespan.
+
+ Walks every live DownloadRegistry instance and SIGKILLs any in-flight
+ workers so the parent exit path doesn't leak zombies. The WeakSet drops
+ ad-hoc registries (e.g. test fixtures) automatically once their last
+ strong reference is gone; the long-lived named registries stay reachable
+ via ``_NAMED_REGISTRIES``. Quiet on its own failures: shutdown must not
+ raise.
+ """
+ for registry in list(_REGISTRIES):
+ try:
+ registry.terminate_all("download")
+ except Exception as exc:
+ logger.warning("terminate_active_downloads: %s", exc)
+
+
+class DownloadRegistry:
+ """Thread-safe state machine for background HF download jobs.
+
+ One instance backs model downloads (keys ``repo_id::variant``) and another
+ backs dataset downloads (keys ``repo_id``). Repo-scoped tracking serializes
+ full snapshots, datasets, cross-transport work, and deletes; same-transport
+ GGUF variants may run concurrently.
+ """
+
+ def __init__(self, max_terminal: int = 64) -> None:
+ self._jobs: dict[str, DownloadState] = {}
+ self._processes: dict[str, subprocess.Popen] = {}
+ self._repo_active: dict[str, set[str]] = {}
+ self._metadata: dict[str, DownloadMetadata] = {}
+ self._pending_cancel: dict[str, Optional[int]] = {}
+ self._generations: dict[str, int] = {}
+ # Monotonic across keys so an evicted then re-claimed key never reuses a
+ # prior generation (which would let a stale cancel match a new run).
+ self._generation_seq = 0
+ self._deleting: dict[str, set[Optional[str]]] = {}
+ self._lock = threading.Lock()
+ _REGISTRIES.add(self)
+ self._max_terminal = max_terminal
+
+ def _put_terminal_job_locked(
+ self,
+ key: str,
+ state: JobState,
+ error: Optional[str] = None,
+ ) -> None:
+ self._jobs.pop(key, None)
+ self._jobs[key] = DownloadState(state, error)
+ if len(self._jobs) > self._max_terminal:
+ for stale_key, stale in list(self._jobs.items()):
+ if stale.state in TERMINAL_STATES and stale_key != key:
+ self._jobs.pop(stale_key, None)
+ self._metadata.pop(stale_key, None)
+ self._generations.pop(stale_key, None)
+ if len(self._jobs) <= self._max_terminal:
+ break
+
+ def set_job(
+ self,
+ key: str,
+ state: JobState,
+ error: Optional[str] = None,
+ ) -> None:
+ key = normalize_job_key(key)
+ with self._lock:
+ if state in TERMINAL_STATES:
+ self._put_terminal_job_locked(key, state, error)
+ self._pending_cancel.pop(key, None)
+ repo = _repo_of_key(key)
+ active = self._repo_active.get(repo)
+ if active is not None:
+ active.discard(key)
+ if not active:
+ self._repo_active.pop(repo, None)
+ else:
+ self._jobs[key] = DownloadState(state, error)
+
+ def get_job(self, key: str) -> DownloadState:
+ key = normalize_job_key(key)
+ with self._lock:
+ return self._jobs.get(key, DownloadState("idle"))
+
+ def current_generation(self, key: str) -> int:
+ key = normalize_job_key(key)
+ with self._lock:
+ return self._generations.get(key, 0)
+
+ def get_job_metadata(self, key: str) -> Optional[DownloadMetadata]:
+ key = normalize_job_key(key)
+ with self._lock:
+ return self._metadata.get(key)
+
+ def _generation_matches_locked(self, key: str, generation: Optional[int]) -> bool:
+ key = normalize_job_key(key)
+ return generation is None or self._generations.get(key, 0) == generation
+
+ def register_process(self, key: str, proc: subprocess.Popen) -> bool:
+ """Register *proc* for *key*. Returns ``False`` when a cancel was
+ requested during the claim→register window (the caller must kill
+ *proc* immediately); ``True`` otherwise."""
+ key = normalize_job_key(key)
+ metadata_to_persist: Optional[DownloadMetadata] = None
+ registered = False
+ breadcrumb_metadata: Optional[DownloadMetadata] = None
+ with self._lock:
+ has_pending_cancel = key in self._pending_cancel
+ pending_generation = self._pending_cancel.pop(key, None)
+ if has_pending_cancel and self._generation_matches_locked(
+ key,
+ pending_generation,
+ ):
+ self._put_terminal_job_locked(key, "cancelled")
+ metadata_to_persist = self._metadata.pop(key, None)
+ repo = _repo_of_key(key)
+ active = self._repo_active.get(repo)
+ if active is not None:
+ active.discard(key)
+ if not active:
+ self._repo_active.pop(repo, None)
+ else:
+ self._processes[key] = proc
+ breadcrumb_metadata = self._metadata.get(key)
+ registered = True
+ if registered:
+ try:
+ write_worker_breadcrumb(key, proc.pid, breadcrumb_metadata)
+ except Exception as exc:
+ logger.debug("Could not record worker breadcrumb: %s", exc)
+ return True
+ if metadata_to_persist is not None:
+ persist_cancel_marker(
+ metadata_to_persist.repo_type,
+ metadata_to_persist.repo_id,
+ metadata_to_persist.variant,
+ metadata_to_persist.transport,
+ )
+ return False
+
+ def mark_pending_cancel(
+ self,
+ key: str,
+ generation: Optional[int] = None,
+ ) -> bool:
+ """Record a cancel for an active job whose worker process hasn't
+ registered yet. Returns ``True`` when the pending cancel was armed,
+ so :func:`register_process` will kill the process on arrival."""
+ key = normalize_job_key(key)
+ with self._lock:
+ if self._jobs.get(key, DownloadState("idle")).state not in _ACTIVE_STATES:
+ return False
+ if not self._generation_matches_locked(key, generation):
+ return False
+ self._pending_cancel[key] = generation
+ self._jobs[key] = DownloadState("cancelling")
+ return True
+
+ def cancel_requested(self, key: str) -> bool:
+ """True when *we* initiated a stop for *key* (a pending cancel armed
+ before the worker registered, or the job already moved to
+ ``cancelling``). Lets exit classification tell an intentional kill
+ apart from an OOM/external SIGKILL."""
+ key = normalize_job_key(key)
+ with self._lock:
+ if key in self._pending_cancel:
+ return True
+ return self._jobs.get(key, DownloadState("idle")).state == "cancelling"
+
+ def get_process(self, key: str) -> Optional[subprocess.Popen]:
+ key = normalize_job_key(key)
+ with self._lock:
+ return self._processes.get(key)
+
+ def drop_process(self, key: str, proc: subprocess.Popen) -> bool:
+ key = normalize_job_key(key)
+ with self._lock:
+ if self._processes.get(key) is not proc:
+ return False
+ self._processes.pop(key, None)
+ remove_worker_breadcrumb(key)
+ return True
+
+ def claim(
+ self,
+ key: str,
+ transport: str,
+ *,
+ repo_type: Optional[RepoType] = None,
+ repo_id: Optional[str] = None,
+ variant: Optional[str] = None,
+ blob_hashes: Optional[frozenset[str]] = None,
+ progress_blob_hashes: Optional[frozenset[str]] = None,
+ completed_baseline_bytes: int = 0,
+ ) -> tuple[bool, str]:
+ key = normalize_job_key(key)
+ repo = _repo_of_key(key)
+ requested_hashes = blob_hashes or frozenset()
+ requested_progress_hashes = progress_blob_hashes or frozenset()
+ with self._lock:
+ deleting_scopes = self._deleting.get(repo)
+ if deleting_scopes is not None and (
+ None in deleting_scopes or variant_from_key(key) in deleting_scopes
+ ):
+ return False, "deleting"
+ active = self._repo_active.get(repo, set())
+ stale_keys: list[str] = []
+ conflict_state: Optional[str] = None
+ for other_key in active:
+ if other_key == key:
+ continue
+ other_status = self._jobs.get(other_key)
+ if other_status is None or other_status.state not in _ACTIVE_STATES:
+ stale_keys.append(other_key)
+ continue
+ other_metadata = self._metadata.get(other_key)
+ # Same-transport variants of one model run concurrently: each
+ # worker purges only its own re-resolved main blobs and the
+ # shared companion is guarded by its marker. Cross-transport
+ # stays serialized so an HTTP resume and an XET rewrite never
+ # write one shared blob at once.
+ concurrent_gguf_variants = (
+ repo_type == "model"
+ and bool(variant)
+ and other_metadata is not None
+ and other_metadata.repo_type == "model"
+ and bool(other_metadata.variant)
+ and other_metadata.transport == transport
+ )
+ if concurrent_gguf_variants:
+ continue
+ conflict_state = other_status.state
+ break
+ for stale_key in stale_keys:
+ active.discard(stale_key)
+ if conflict_state is not None:
+ return False, conflict_state
+ current = self._jobs.get(key, DownloadState("idle")).state
+ if current in _ACTIVE_STATES:
+ return False, current
+ self._generation_seq += 1
+ self._generations[key] = self._generation_seq
+ self._jobs[key] = DownloadState("running")
+ self._repo_active.setdefault(repo, active).add(key)
+ if repo_type and repo_id:
+ self._metadata[key] = DownloadMetadata(
+ repo_type = repo_type,
+ repo_id = repo_id,
+ variant = variant,
+ transport = transport,
+ blob_hashes = requested_hashes,
+ progress_blob_hashes = requested_progress_hashes,
+ completed_baseline_bytes = max(
+ 0,
+ int(completed_baseline_bytes or 0),
+ ),
+ )
+ else:
+ self._metadata.pop(key, None)
+ return True, "running"
+
+ def adoptable(self, key: str) -> bool:
+ """True when *key* itself has a live job a client can attach to.
+
+ Lets a rejected claim distinguish a collision with this key's own
+ in-flight job (pollable) from one blocked by a different repo job
+ or an in-progress delete, where no job exists for this key."""
+ key = normalize_job_key(key)
+ with self._lock:
+ return self._jobs.get(key, DownloadState("idle")).state in _ACTIVE_STATES
+
+ def _active_job_variant_locked(self, key: str) -> Optional[str]:
+ metadata = self._metadata.get(key)
+ if metadata is not None:
+ return (metadata.variant or "").strip().lower() or None
+ return variant_from_key(key)
+
+ def _delete_blocked_by_active_locked(self, repo_id: str, variant: Optional[str]) -> bool:
+ """Whether an active download conflicts with deleting *repo_id*/*variant*.
+
+ A whole-repo delete (``variant is None``) conflicts with any active
+ download. A variant delete conflicts only with that same variant or a
+ whole-repo download writing the shared snapshot; other quantizations
+ download concurrently and never block it."""
+ for key in self._repo_active.get(repo_id, set()):
+ job = self._jobs.get(key)
+ if job is None or job.state not in _ACTIVE_STATES:
+ continue
+ if variant is None:
+ return True
+ other_variant = self._active_job_variant_locked(key)
+ if other_variant is None or other_variant == variant:
+ return True
+ return False
+
+ def peer_blob_hashes(self, key: str) -> frozenset[str]:
+ """Union of the writable blob hashes of every OTHER active download for
+ this key's repo. A worker excludes these from its purge so it never
+ deletes an ``.incomplete`` a concurrent same-repo variant is writing
+ (e.g. a shared mmproj bundled with two GGUF quants)."""
+ key = normalize_job_key(key)
+ repo = _repo_of_key(key)
+ out: set[str] = set()
+ with self._lock:
+ for other_key in self._repo_active.get(repo, set()):
+ if other_key == key:
+ continue
+ job = self._jobs.get(other_key)
+ if job is None or job.state not in _ACTIVE_STATES:
+ continue
+ metadata = self._metadata.get(other_key)
+ if metadata is not None:
+ out |= set(metadata.progress_blob_hashes or metadata.blob_hashes)
+ return frozenset(out)
+
+ def active_jobs(self, repo_id: str) -> dict[str, str]:
+ """Map of every active job key for *repo_id* to its state."""
+ repo_id = normalize_repo_key(repo_id)
+ with self._lock:
+ result: dict[str, str] = {}
+ for key in self._repo_active.get(repo_id, set()):
+ job = self._jobs.get(key)
+ if job is not None and job.state in _ACTIVE_STATES:
+ metadata = self._metadata.get(key)
+ display_key = (
+ f"{_repo_of_key(key)}::{metadata.variant}"
+ if metadata is not None and metadata.variant
+ else key
+ )
+ result[display_key] = job.state
+ return result
+
+ def active_job_refs(self, repo_id: Optional[str] = None) -> list[ActiveDownloadRef]:
+ repo_key = normalize_repo_key(repo_id) if repo_id else None
+ with self._lock:
+ if repo_key:
+ candidate_keys = list(self._repo_active.get(repo_key, set()))
+ else:
+ candidate_keys = [key for active in self._repo_active.values() for key in active]
+ refs: list[ActiveDownloadRef] = []
+ for key in candidate_keys:
+ job = self._jobs.get(key)
+ if job is None or job.state not in _ACTIVE_STATES:
+ continue
+ refs.append(
+ ActiveDownloadRef(
+ key = key,
+ state = job.state,
+ metadata = self._metadata.get(key),
+ generation = self._generations.get(key, 0),
+ )
+ )
+ return refs
+
+ def begin_delete(
+ self,
+ repo_id: str,
+ variant: Optional[str] = None,
+ ) -> bool:
+ """Reserve *repo_id* (or one GGUF *variant* of it) for deletion. Returns
+ ``False`` when a conflicting download is active (a whole-repo delete vs
+ any download, a variant delete vs that same variant or a whole-repo
+ download), so sibling quantizations keep downloading. On success the
+ scope is marked so :func:`claim` rejects overlapping downloads until
+ :func:`end_delete` runs, closing the check-then-delete race against a
+ concurrently spawned worker."""
+ repo_id = normalize_repo_key(repo_id)
+ variant_key = (variant or "").strip().lower() or None
+ with self._lock:
+ if self._delete_blocked_by_active_locked(repo_id, variant_key):
+ return False
+ self._deleting.setdefault(repo_id, set()).add(variant_key)
+ return True
+
+ def end_delete(
+ self,
+ repo_id: str,
+ variant: Optional[str] = None,
+ ) -> None:
+ repo_id = normalize_repo_key(repo_id)
+ variant_key = (variant or "").strip().lower() or None
+ with self._lock:
+ scopes = self._deleting.get(repo_id)
+ if scopes is None:
+ return
+ scopes.discard(variant_key)
+ if not scopes:
+ self._deleting.pop(repo_id, None)
+
+ def has_active_peer_variant(self, repo_id: str, variant: Optional[str]) -> bool:
+ """Whether a DIFFERENT quantization of *repo_id* is downloading while
+ *variant* is being deleted. When one is, the delete reclaims only this
+ variant's files and leaves the shared companion (mmproj) for the live
+ sibling. Point-in-time (a sibling may claim just after it returns), but
+ safe: the finalized companion is held by deletion's reference-count
+ walk and a sibling starting mid-delete re-fetches it, so protection
+ never depends on the sibling having resolved its blob hashes."""
+ repo_id = normalize_repo_key(repo_id)
+ target = (variant or "").strip().lower() or None
+ with self._lock:
+ for key in self._repo_active.get(repo_id, set()):
+ job = self._jobs.get(key)
+ if job is None or job.state not in _ACTIVE_STATES:
+ continue
+ if self._active_job_variant_locked(key) != target:
+ return True
+ return False
+
+ def request_cancel(
+ self,
+ key: str,
+ proc: subprocess.Popen,
+ generation: Optional[int] = None,
+ ) -> bool:
+ """Authorize a SIGKILL for the registered *proc*. Idempotent across an
+ active job's lifetime: a repeated cancel while already ``cancelling``
+ still returns ``True`` so a kill that raced and lost can be re-sent."""
+ key = normalize_job_key(key)
+ with self._lock:
+ if self._processes.get(key) is not proc:
+ return False
+ if not self._generation_matches_locked(key, generation):
+ return False
+ if self._jobs.get(key, DownloadState("idle")).state not in _ACTIVE_STATES:
+ return False
+ self._jobs[key] = DownloadState("cancelling")
+ return True
+
+ def terminate_all(self, kind: str = "download") -> None:
+ with self._lock:
+ live = [
+ (key, proc, self._metadata.get(key))
+ for key, proc in self._processes.items()
+ if proc.poll() is None
+ ]
+ # Flag as an intentional stop so the watcher's exit classification
+ # reports them cancelled rather than an OOM/crash once SIGKILL lands.
+ for key, _proc, _metadata in live:
+ if self._jobs.get(key, DownloadState("idle")).state == "running":
+ self._jobs[key] = DownloadState("cancelling")
+ reaped: list[tuple[str, subprocess.Popen, Optional[DownloadMetadata]]] = []
+ for key, proc, metadata in live:
+ try:
+ proc.kill()
+ except ProcessLookupError:
+ pass
+ except Exception as e:
+ logger.warning(f"shutdown: failed to kill {kind} worker for {key}: {e}")
+ if metadata is not None:
+ persist_cancel_marker(
+ metadata.repo_type,
+ metadata.repo_id,
+ metadata.variant,
+ metadata.transport,
+ )
+ continue
+ reaped.append((key, proc, metadata))
+ deadline = time.monotonic() + 10.0
+ for key, proc, metadata in reaped:
+ try:
+ proc.wait(timeout = max(0.0, deadline - time.monotonic()))
+ except subprocess.TimeoutExpired:
+ logger.warning(f"shutdown: {kind} worker for {key} did not exit after kill")
+ except Exception:
+ pass
+ # Mark only genuinely interrupted workers (rc != 0, or None on wait
+ # timeout); persisting before the exit is known would strand a stale
+ # marker on a worker that completed cleanly during shutdown.
+ if metadata is not None and proc.poll() != 0:
+ persist_cancel_marker(
+ metadata.repo_type,
+ metadata.repo_id,
+ metadata.variant,
+ metadata.transport,
+ )
+
+
+def _named_registry(name: str) -> DownloadRegistry:
+ with _NAMED_REGISTRIES_LOCK:
+ registry = _NAMED_REGISTRIES.get(name)
+ if registry is None:
+ registry = DownloadRegistry()
+ _NAMED_REGISTRIES[name] = registry
+ return registry
+
+
+def get_models_registry() -> DownloadRegistry:
+ return _named_registry("models")
+
+
+def get_datasets_registry() -> DownloadRegistry:
+ return _named_registry("datasets")
diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.py
new file mode 100644
index 00000000000..4bd1961c338
--- /dev/null
+++ b/studio/backend/hub/utils/gguf.py
@@ -0,0 +1,406 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""GGUF filename helpers. Quantization variants are derived from filenames, not parsed from binary GGUF headers."""
+
+from __future__ import annotations
+
+import os
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+_GGUF_MODEL_INFO_TIMEOUT_SECONDS = 5.0
+
+
+@dataclass
+class GgufVariantInfo:
+ filename: str
+ quant: str
+ size_bytes: int
+ display_label: Optional[str] = None
+ download_size_bytes: int = 0
+
+
+GGUF_QUANT_PREFERENCE = [
+ "UD-Q4_K_XL",
+ "UD-Q4_K_L",
+ "UD-Q5_K_XL",
+ "UD-Q3_K_XL",
+ "UD-Q6_K_XL",
+ "UD-Q6_K_S",
+ "UD-Q8_K_XL",
+ "UD-Q2_K_XL",
+ "UD-IQ4_NL",
+ "UD-IQ4_XS",
+ "UD-IQ3_S",
+ "UD-IQ3_XXS",
+ "UD-IQ2_M",
+ "UD-IQ2_XXS",
+ "UD-IQ1_M",
+ "UD-IQ1_S",
+ "Q4_K_M",
+ "Q4_K_S",
+ "Q5_K_M",
+ "Q5_K_S",
+ "Q6_K",
+ "Q8_0",
+ "Q3_K_M",
+ "Q3_K_L",
+ "Q3_K_S",
+ "Q2_K",
+ "Q2_K_L",
+ "IQ4_NL",
+ "IQ4_XS",
+ "IQ3_M",
+ "IQ3_XXS",
+ "IQ2_M",
+ "IQ1_M",
+ "F16",
+ "BF16",
+ "F32",
+]
+
+_GGUF_SPLIT_SUFFIX_RE = re.compile(r"-\d{3,}-of-\d{3,}", re.IGNORECASE)
+_GGUF_QUANT_RE = re.compile(
+ r"(UD-)?"
+ r"(MXFP[0-9]+(?:_[A-Z0-9]+)*"
+ r"|IQ[0-9]+_[A-Z]+(?:_[A-Z0-9]+)?"
+ r"|TQ[0-9]+_[0-9]+"
+ r"|Q[0-9]+_K_[A-Z]+"
+ r"|Q[0-9]+_[0-9]+"
+ r"|Q[0-9]+_K"
+ r"|BF16|F16|F32)",
+ re.IGNORECASE,
+)
+
+
+def is_mmproj_filename(filename: str) -> bool:
+ return "mmproj" in filename.lower()
+
+
+def is_gguf_filename(filename: str) -> bool:
+ return filename.lower().endswith(".gguf")
+
+
+# Cap recursive walks so a huge or system path cannot run unbounded.
+_MAX_LOCAL_SCAN_ENTRIES = 100_000
+
+
+def iter_gguf_files(directory: Path, recursive: bool = False):
+ if not directory.is_dir():
+ return
+ if recursive:
+ seen = 0
+ # os.walk skips unreadable subdirs instead of raising (e.g. /proc).
+ for dirpath, dirnames, filenames in os.walk(directory, onerror = lambda _e: None):
+ for name in filenames:
+ if is_gguf_filename(name):
+ yield Path(dirpath) / name
+ seen += len(dirnames) + len(filenames)
+ if seen > _MAX_LOCAL_SCAN_ENTRIES:
+ return
+ return
+ try:
+ entries = list(directory.iterdir())
+ except OSError:
+ return
+ for file in entries:
+ try:
+ if file.is_file() and is_gguf_filename(file.name):
+ yield file
+ except OSError:
+ continue
+
+
+def pick_best_gguf(filenames: list[str]) -> Optional[str]:
+ gguf_files = [
+ name for name in filenames if is_gguf_filename(name) and not is_mmproj_filename(name)
+ ]
+ if not gguf_files:
+ return None
+ by_quant: dict[str, str] = {}
+ for name in gguf_files:
+ by_quant.setdefault(extract_quant_label(name).upper(), name)
+ for quant in GGUF_QUANT_PREFERENCE:
+ filename = by_quant.get(quant.upper())
+ if filename is not None:
+ return filename
+ return gguf_files[0]
+
+
+def _gguf_stem(filename: str) -> str:
+ basename = filename.rsplit("/", 1)[-1]
+ return _GGUF_SPLIT_SUFFIX_RE.sub("", basename.rsplit(".", 1)[0]).strip()
+
+
+_FLOAT_PRECISION_QUANTS = frozenset({"BF16", "F16", "F32"})
+
+
+def _select_quant_match(text: str) -> Optional[re.Match]:
+ fallback: Optional[re.Match] = None
+ for match in _GGUF_QUANT_RE.finditer(text):
+ if match.group(2).upper() in _FLOAT_PRECISION_QUANTS:
+ if fallback is None:
+ fallback = match
+ continue
+ return match
+ return fallback
+
+
+def extract_quant_token(filename: str) -> Optional[str]:
+ stem = _gguf_stem(filename)
+ match = _select_quant_match(stem)
+ if not match and "/" in filename:
+ parents = filename.rsplit("/", 1)[0]
+ for segment in reversed(parents.split("/")):
+ parent_match = _select_quant_match(segment)
+ if parent_match:
+ match = parent_match
+ break
+ if match:
+ prefix = match.group(1) or ""
+ return f"{prefix}{match.group(2)}"
+ return None
+
+
+def _unknown_gguf_variant_key(filename: str) -> str:
+ stem = _gguf_stem(filename)
+ if "/" not in filename:
+ return stem or "gguf"
+ parents = filename.rsplit("/", 1)[0].strip("/")
+ return f"{parents}/{stem}" if parents and stem else stem or "gguf"
+
+
+def extract_quant_label(filename: str) -> str:
+ return extract_quant_token(filename) or _unknown_gguf_variant_key(filename)
+
+
+def _apply_gguf_display_labels(variants: list[GgufVariantInfo]) -> None:
+ unknown_variants = [
+ variant for variant in variants if extract_quant_token(variant.filename) is None
+ ]
+ if not unknown_variants:
+ return
+ ambiguous = len(unknown_variants) > 1
+ for variant in unknown_variants:
+ variant.display_label = f"GGUF · {variant.filename}" if ambiguous else "GGUF"
+
+
+def _env_offline() -> bool:
+ return os.environ.get("HF_HUB_OFFLINE", "").lower() in (
+ "1",
+ "true",
+ "yes",
+ ) or os.environ.get("TRANSFORMERS_OFFLINE", "").lower() in ("1", "true", "yes")
+
+
+def iter_hf_cache_snapshots(repo_id: str):
+ from hub.utils.hf_cache_state import iter_repo_cache_dirs
+
+ snapshots: list[Path] = []
+ for repo_dir in iter_repo_cache_dirs("model", repo_id):
+ snapshots_dir = repo_dir / "snapshots"
+ if not snapshots_dir.is_dir():
+ continue
+ try:
+ snapshots.extend(snap for snap in snapshots_dir.iterdir() if snap.is_dir())
+ except OSError:
+ continue
+
+ def _mtime(path: Path) -> float:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return 0.0
+
+ snapshots.sort(key = _mtime, reverse = True)
+ yield from snapshots
+
+
+def list_gguf_variants_from_hf_cache(repo_id: str) -> Optional[tuple[list[GgufVariantInfo], bool]]:
+ for snapshot in iter_hf_cache_snapshots(repo_id):
+ variants, has_vision = list_local_gguf_variants(str(snapshot))
+ if variants or has_vision:
+ return variants, has_vision
+ return None
+
+
+def list_partial_gguf_variants_from_state(
+ repo_id: str,
+) -> Optional[tuple[list[GgufVariantInfo], bool]]:
+ """Reconstruct GGUF variants from download manifests/markers alone.
+
+ Used when no completed snapshot exists (download cancelled or interrupted)
+ and the HF API is unreachable (offline/gated/private). Each variant's
+ ``quant`` is the stored variant key so a resume passes the matching
+ ``--variant`` back to the worker.
+ """
+ from hub.utils import download_manifest
+
+ # Variant identity on disk is case-insensitive (_entry_key lowercases it), so
+ # dedupe on the lowercased key. Manifests are read first to keep their
+ # original-casing label over a lowercased cancel marker for the same variant.
+ seen: set[str] = set()
+ ordered: list[str] = []
+ for source in (
+ download_manifest.iter_variant_manifests("model", repo_id),
+ download_manifest.iter_variant_markers("model", repo_id),
+ ):
+ for variant, _path in source:
+ key = variant.lower()
+ if key not in seen:
+ seen.add(key)
+ ordered.append(variant)
+ if not ordered:
+ return None
+
+ variants: list[GgufVariantInfo] = []
+ has_vision = False
+ for variant in ordered:
+ manifest = download_manifest.read_manifest("model", repo_id, variant)
+ main_filename: Optional[str] = None
+ size_bytes = 0
+ companion_bytes = 0
+ if manifest is not None:
+ for expected in manifest.expected_files:
+ if not is_gguf_filename(expected.path):
+ continue
+ if is_mmproj_filename(expected.path):
+ has_vision = True
+ companion_bytes += max(0, int(expected.size or 0))
+ continue
+ if main_filename is None:
+ main_filename = expected.path
+ size_bytes += max(0, int(expected.size or 0))
+ if main_filename is None:
+ main_filename = f"{variant}.gguf"
+ variants.append(
+ GgufVariantInfo(
+ filename = main_filename,
+ quant = variant,
+ size_bytes = size_bytes,
+ download_size_bytes = size_bytes + companion_bytes,
+ )
+ )
+
+ variants.sort(key = lambda variant: -variant.size_bytes)
+ _apply_gguf_display_labels(variants)
+ return variants, has_vision
+
+
+def list_gguf_variants(
+ repo_id: str, hf_token: Optional[str] = None
+) -> tuple[list[GgufVariantInfo], bool, Optional[list]]:
+ from huggingface_hub import HfApi
+
+ if _env_offline():
+ cached = list_gguf_variants_from_hf_cache(repo_id)
+ if cached is not None:
+ return (*cached, None)
+
+ try:
+ info = HfApi(token = hf_token).model_info(
+ repo_id,
+ files_metadata = True,
+ timeout = _GGUF_MODEL_INFO_TIMEOUT_SECONDS,
+ )
+ except Exception as exc:
+ if type(exc).__name__ in (
+ "RepositoryNotFoundError",
+ "GatedRepoError",
+ "RevisionNotFoundError",
+ "EntryNotFoundError",
+ ):
+ raise
+ cached = list_gguf_variants_from_hf_cache(repo_id)
+ if cached is not None:
+ logger.warning(
+ "HF API unreachable for %s (%s); using local cache snapshot.",
+ repo_id,
+ exc.__class__.__name__,
+ )
+ return (*cached, None)
+ raise
+
+ variants: list[GgufVariantInfo] = []
+ has_vision = False
+ quant_totals: dict[str, int] = {}
+ quant_first_file: dict[str, str] = {}
+
+ for sibling in info.siblings:
+ filename = getattr(sibling, "rfilename", None)
+ if not isinstance(filename, str) or not is_gguf_filename(filename):
+ continue
+ if is_mmproj_filename(filename):
+ has_vision = True
+ continue
+ quant = extract_quant_label(filename)
+ quant_totals[quant] = quant_totals.get(quant, 0) + int(getattr(sibling, "size", 0) or 0)
+ quant_first_file.setdefault(quant, filename)
+
+ for quant, total_size in quant_totals.items():
+ variants.append(
+ GgufVariantInfo(
+ filename = quant_first_file[quant],
+ quant = quant,
+ size_bytes = total_size,
+ )
+ )
+
+ variants.sort(key = lambda variant: -variant.size_bytes)
+ _apply_gguf_display_labels(variants)
+ return variants, has_vision, list(info.siblings)
+
+
+def _resolve_gguf_dir(path: Path) -> Optional[Path]:
+ if path.is_dir():
+ return path
+ if path.is_file() and path.suffix.lower() == ".gguf":
+ parent = path.parent
+ if (
+ (parent / "config.json").exists()
+ or (parent / "adapter_config.json").exists()
+ or (parent / "export_metadata.json").exists()
+ ):
+ return parent
+ return None
+
+
+def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], bool]:
+ root = _resolve_gguf_dir(Path(directory))
+ if root is None:
+ return [], False
+
+ quant_totals: dict[str, int] = {}
+ quant_first_file: dict[str, str] = {}
+ has_vision = False
+
+ for file in sorted(iter_gguf_files(root, recursive = True)):
+ if is_mmproj_filename(file.name):
+ has_vision = True
+ continue
+ try:
+ size = file.stat().st_size
+ except OSError:
+ size = 0
+ rel = file.relative_to(root).as_posix()
+ quant = extract_quant_label(rel)
+ quant_totals[quant] = quant_totals.get(quant, 0) + size
+ quant_first_file.setdefault(quant, rel)
+
+ variants = [
+ GgufVariantInfo(
+ filename = quant_first_file[quant],
+ quant = quant,
+ size_bytes = size,
+ )
+ for quant, size in quant_totals.items()
+ ]
+ variants.sort(key = lambda variant: -variant.size_bytes)
+ _apply_gguf_display_labels(variants)
+ return variants, has_vision
diff --git a/studio/backend/hub/utils/gguf_plan.py b/studio/backend/hub/utils/gguf_plan.py
new file mode 100644
index 00000000000..03ec847f4c6
--- /dev/null
+++ b/studio/backend/hub/utils/gguf_plan.py
@@ -0,0 +1,158 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Optional, Sequence
+
+from hub.utils.download_manifest import ExpectedFile
+from hub.utils.gguf import extract_quant_label, is_gguf_filename, is_mmproj_filename
+
+
+@dataclass(frozen = True)
+class GgufVariantPlan:
+ main_filenames: frozenset[str]
+ target_filenames: tuple[str, ...]
+ main_hashes: frozenset[str]
+ required_hashes: frozenset[str]
+ companion_hashes: frozenset[str]
+ mmproj_filenames: frozenset[str]
+ mmproj_hashes: frozenset[str]
+ expected_files: tuple[ExpectedFile, ...]
+ main_size_bytes: int
+ download_size_bytes: int
+
+
+def sibling_sha256(sibling) -> Optional[str]:
+ lfs = getattr(sibling, "lfs", None)
+ if isinstance(lfs, dict):
+ value = lfs.get("sha256")
+ else:
+ value = getattr(lfs, "sha256", None)
+ return value if isinstance(value, str) and value else None
+
+
+def sibling_size(sibling) -> int:
+ size = getattr(sibling, "size", 0) or 0
+ try:
+ return int(size)
+ except (TypeError, ValueError):
+ return 0
+
+
+def expected_file_from_sibling(sibling) -> Optional[ExpectedFile]:
+ name = getattr(sibling, "rfilename", None)
+ if not isinstance(name, str):
+ return None
+ return ExpectedFile(
+ path = name,
+ size = sibling_size(sibling),
+ sha256 = sibling_sha256(sibling),
+ )
+
+
+def is_companion_gguf_path(path: str) -> bool:
+ return is_gguf_filename(path) and is_mmproj_filename(path)
+
+
+def is_main_gguf_variant_path(path: str, variant: str) -> bool:
+ return (
+ is_gguf_filename(path)
+ and not is_mmproj_filename(path)
+ and extract_quant_label(path).lower() == variant.lower()
+ )
+
+
+def mmproj_siblings(siblings: Sequence) -> list:
+ return [
+ s
+ for s in siblings
+ if isinstance(getattr(s, "rfilename", None), str)
+ and is_companion_gguf_path(getattr(s, "rfilename"))
+ ]
+
+
+def preferred_mmproj_sibling(siblings: Sequence) -> Optional[object]:
+ candidates = mmproj_siblings(siblings)
+ if not candidates:
+ return None
+ return next(
+ (s for s in candidates if extract_quant_label(getattr(s, "rfilename")).upper() == "F16"),
+ candidates[0],
+ )
+
+
+def build_gguf_variant_plans(siblings: Sequence) -> dict[str, GgufVariantPlan]:
+ main: dict[str, list] = {}
+ all_mmproj = mmproj_siblings(siblings)
+ all_mmproj_filenames = frozenset(
+ getattr(s, "rfilename")
+ for s in all_mmproj
+ if isinstance(getattr(s, "rfilename", None), str)
+ )
+ all_mmproj_hashes = frozenset(h for h in (sibling_sha256(s) for s in all_mmproj) if h)
+ companion = preferred_mmproj_sibling(siblings)
+ companion_expected = expected_file_from_sibling(companion) if companion is not None else None
+
+ for sibling in siblings:
+ name = getattr(sibling, "rfilename", None)
+ if not isinstance(name, str) or not is_gguf_filename(name):
+ continue
+ if is_mmproj_filename(name):
+ continue
+ quant = extract_quant_label(name).lower()
+ main.setdefault(quant, []).append(sibling)
+
+ plans: dict[str, GgufVariantPlan] = {}
+ for quant, target_main_siblings in main.items():
+ main_expected = tuple(
+ file
+ for sibling in target_main_siblings
+ if (file := expected_file_from_sibling(sibling)) is not None
+ )
+ expected_files = (
+ (*main_expected, companion_expected)
+ if companion_expected is not None
+ else main_expected
+ )
+ plans[quant] = plan_from_expected_files(
+ quant,
+ expected_files,
+ all_mmproj_filenames = all_mmproj_filenames,
+ all_mmproj_hashes = all_mmproj_hashes,
+ )
+ return plans
+
+
+def plan_from_expected_files(
+ variant: str,
+ expected_files: Sequence[ExpectedFile],
+ *,
+ all_mmproj_filenames: frozenset[str] | None = None,
+ all_mmproj_hashes: frozenset[str] | None = None,
+) -> GgufVariantPlan:
+ expected = tuple(expected_files)
+ main_files = tuple(file for file in expected if is_main_gguf_variant_path(file.path, variant))
+ companion_files = tuple(file for file in expected if is_companion_gguf_path(file.path))
+ main_hashes = frozenset(file.sha256 for file in main_files if file.sha256)
+ companion_hashes = frozenset(file.sha256 for file in companion_files if file.sha256)
+ required_hashes = frozenset(file.sha256 for file in expected if file.sha256)
+ main_size = sum(max(0, int(file.size or 0)) for file in main_files)
+ download_size = sum(max(0, int(file.size or 0)) for file in expected)
+ return GgufVariantPlan(
+ main_filenames = frozenset(file.path for file in main_files),
+ target_filenames = tuple(file.path for file in expected),
+ main_hashes = main_hashes,
+ required_hashes = required_hashes,
+ companion_hashes = companion_hashes,
+ mmproj_filenames = (
+ all_mmproj_filenames
+ if all_mmproj_filenames is not None
+ else frozenset(file.path for file in companion_files)
+ ),
+ mmproj_hashes = (all_mmproj_hashes if all_mmproj_hashes is not None else companion_hashes),
+ expected_files = expected,
+ main_size_bytes = main_size,
+ download_size_bytes = download_size,
+ )
diff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.py
new file mode 100644
index 00000000000..a1ac372abbf
--- /dev/null
+++ b/studio/backend/hub/utils/hf_cache_state.py
@@ -0,0 +1,293 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import errno
+import shutil
+import sys
+from pathlib import Path
+from typing import Iterable, Iterator, Optional
+
+
+EXIT_CANCELLED = 130
+
+TRANSPORT_HTTP = "http"
+TRANSPORT_XET = "xet"
+VALID_TRANSPORTS = frozenset({TRANSPORT_HTTP, TRANSPORT_XET})
+TRANSPORT_MARKER_NAME = ".transport"
+INCOMPLETE_SUFFIX = ".incomplete"
+
+
+def hf_cache_root(*, create: bool = False) -> Optional[Path]:
+ try:
+ from huggingface_hub import constants as hf_constants
+ except ImportError:
+ return None
+ root = Path(hf_constants.HF_HUB_CACHE)
+ if create:
+ try:
+ root.mkdir(parents = True, exist_ok = True)
+ except OSError:
+ return None
+ return root
+ return root if root.is_dir() else None
+
+
+def hf_cache_roots() -> list[Path]:
+ from hub.utils.paths import hf_default_cache_dir, legacy_hf_cache_dir
+
+ roots: list[Path] = []
+ seen: set[str] = set()
+
+ def _add(path: Optional[Path]) -> None:
+ if path is None or not path.is_dir():
+ return
+ try:
+ key = str(path.resolve())
+ except OSError:
+ return
+ if key in seen:
+ return
+ seen.add(key)
+ roots.append(path)
+
+ _add(hf_cache_root())
+ _add(legacy_hf_cache_dir())
+ _add(hf_default_cache_dir())
+ return roots
+
+
+def target_dir_name(repo_type: str, repo_id: str) -> str:
+ return repo_cache_dir_name(repo_type, repo_id).lower()
+
+
+def repo_cache_dir_name(repo_type: str, repo_id: str) -> str:
+ return f"{repo_type}s--{repo_id.replace('/', '--')}"
+
+
+def resolve_destructive_case_matches(target: str, candidates: Iterable[str]) -> Optional[set[str]]:
+ values = list(candidates)
+ exact = {candidate for candidate in values if candidate == target}
+ if exact:
+ return exact
+ folded = {candidate for candidate in values if candidate.lower() == target.lower()}
+ if len(folded) <= 1:
+ return folded
+ return None
+
+
+def _blob_dir_is_partial(blobs_dir: Path) -> bool:
+ try:
+ for blob in blobs_dir.iterdir():
+ if blob.is_file() and blob.name.endswith(INCOMPLETE_SUFFIX):
+ return True
+ except OSError:
+ return False
+ return False
+
+
+def blob_bytes_present(path: Path) -> int:
+ """Sparse-aware on-disk size: XET/``hf_transfer`` ``.incomplete`` partials
+ report a full ``st_size`` while only some blocks are allocated, so prefer
+ ``st_blocks``, falling back to ``st_size`` where it is unreported (Windows,
+ some network filesystems)."""
+ st = path.stat()
+ blocks = getattr(st, "st_blocks", 0)
+ if blocks > 0:
+ return min(blocks * 512, st.st_size)
+ if sys.platform == "win32":
+ allocated = _windows_allocated_size(path)
+ if allocated is not None:
+ return min(allocated, st.st_size)
+ return st.st_size
+
+
+def _windows_allocated_size(path: Path) -> Optional[int]:
+ """Best-effort allocated-byte count for sparse files on Windows."""
+ if sys.platform != "win32":
+ return None
+ try:
+ import ctypes
+ from ctypes import wintypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ get_compressed_file_size = kernel32.GetCompressedFileSizeW
+ get_compressed_file_size.argtypes = [
+ wintypes.LPCWSTR,
+ ctypes.POINTER(wintypes.DWORD),
+ ]
+ get_compressed_file_size.restype = wintypes.DWORD
+
+ high = wintypes.DWORD(0)
+ ctypes.set_last_error(0)
+ low = get_compressed_file_size(str(path), ctypes.byref(high))
+ if low == 0xFFFFFFFF and ctypes.get_last_error() != 0:
+ return None
+ return (int(high.value) << 32) + int(low)
+ except Exception:
+ return None
+
+
+def latest_snapshot_dir(repo_dir: Path) -> Optional[Path]:
+ """Newest immediate child of ``repo_dir/snapshots`` by mtime, or None.
+
+ mtime is the signal huggingface_hub's from_pretrained resolves to, so this
+ points at whatever snapshot most recently landed on disk.
+ """
+ snapshots_dir = repo_dir / "snapshots"
+ try:
+ if not snapshots_dir.is_dir():
+ return None
+ snapshots = [entry for entry in snapshots_dir.iterdir() if entry.is_dir()]
+ if not snapshots:
+ return None
+ return max(snapshots, key = lambda entry: entry.stat().st_mtime)
+ except OSError:
+ return None
+
+
+def _repo_dir_has_broken_snapshot_symlinks(repo_dir: Path) -> bool:
+ latest = latest_snapshot_dir(repo_dir)
+ if latest is None:
+ return False
+ try:
+ for entry in latest.rglob("*"):
+ if entry.is_symlink() and not entry.exists():
+ return True
+ except OSError:
+ return False
+ return False
+
+
+def iter_repo_cache_dirs(repo_type: str, repo_id: str) -> Iterator[Path]:
+ target = target_dir_name(repo_type, repo_id)
+ for root in hf_cache_roots():
+ try:
+ for entry in root.iterdir():
+ if entry.name.lower() == target:
+ yield entry
+ except OSError:
+ continue
+
+
+def iter_destructive_repo_cache_dirs(repo_type: str, repo_id: str) -> Iterator[Path]:
+ target = repo_cache_dir_name(repo_type, repo_id)
+ folded_target = target.lower()
+ for root in hf_cache_roots():
+ try:
+ entries = [entry for entry in root.iterdir() if entry.name.lower() == folded_target]
+ except OSError:
+ continue
+ matched_names = resolve_destructive_case_matches(
+ target,
+ (entry.name for entry in entries),
+ )
+ if not matched_names:
+ continue
+ for entry in entries:
+ if entry.name in matched_names:
+ yield entry
+
+
+def iter_active_repo_cache_dirs(repo_type: str, repo_id: str) -> Iterator[Path]:
+ root = hf_cache_root()
+ if root is None:
+ return
+ target = target_dir_name(repo_type, repo_id)
+ try:
+ for entry in root.iterdir():
+ if entry.name.lower() == target:
+ yield entry
+ except OSError:
+ return
+
+
+def preferred_repo_cache_dirs(
+ repo_type: str,
+ repo_id: str,
+ *,
+ force_active: bool = False,
+) -> list[Path]:
+ active_entries = list(iter_active_repo_cache_dirs(repo_type, repo_id))
+ if active_entries:
+ return active_entries
+ if force_active:
+ root = hf_cache_root()
+ if root is not None:
+ canonical = repo_cache_dir_name(repo_type, repo_id)
+ return [root / canonical]
+ return list(iter_repo_cache_dirs(repo_type, repo_id))
+
+
+def has_incomplete_blobs(repo_type: str, repo_id: str) -> bool:
+ for entry in iter_repo_cache_dirs(repo_type, repo_id):
+ if repo_cache_dir_has_incomplete_blobs(entry):
+ return True
+ return False
+
+
+def has_active_incomplete_blobs(repo_type: str, repo_id: str) -> bool:
+ for entry in iter_active_repo_cache_dirs(repo_type, repo_id):
+ if repo_cache_dir_has_incomplete_blobs(entry):
+ return True
+ return False
+
+
+def repo_cache_dir_has_incomplete_blobs(repo_dir: Path) -> bool:
+ blobs_dir = repo_dir / "blobs"
+ return (blobs_dir.is_dir() and _blob_dir_is_partial(blobs_dir)) or (
+ _repo_dir_has_broken_snapshot_symlinks(repo_dir)
+ )
+
+
+def _prune_empty_dirs(root: Path) -> bool:
+ removed = False
+ try:
+ dirs = sorted(
+ (path for path in root.rglob("*") if path.is_dir()),
+ key = lambda path: len(path.parts),
+ reverse = True,
+ )
+ except OSError:
+ dirs = []
+ for directory in [*dirs, root]:
+ try:
+ directory.rmdir()
+ removed = True
+ except FileNotFoundError:
+ continue
+ except OSError as exc:
+ if exc.errno not in (errno.ENOTEMPTY, errno.EEXIST):
+ raise
+ return removed
+
+
+def purge_partial_repo(repo_type: str, repo_id: str) -> bool:
+ removed = False
+ for entry in iter_destructive_repo_cache_dirs(repo_type, repo_id):
+ blobs_dir = entry / "blobs"
+ if blobs_dir.is_dir():
+ for blob in blobs_dir.iterdir():
+ if blob.is_file() and blob.name.endswith(INCOMPLETE_SUFFIX):
+ try:
+ blob.unlink()
+ removed = True
+ except FileNotFoundError:
+ continue
+ if _prune_empty_dirs(entry):
+ removed = True
+ return removed
+
+
+def purge_repo_cache_dirs(repo_type: str, repo_id: str) -> bool:
+ removed = False
+ for entry in iter_destructive_repo_cache_dirs(repo_type, repo_id):
+ try:
+ if entry.is_symlink() or not entry.is_dir():
+ continue
+ shutil.rmtree(entry)
+ removed = True
+ except FileNotFoundError:
+ continue
+ return removed
diff --git a/studio/backend/hub/utils/hf_errors.py b/studio/backend/hub/utils/hf_errors.py
new file mode 100644
index 00000000000..b2569758c6f
--- /dev/null
+++ b/studio/backend/hub/utils/hf_errors.py
@@ -0,0 +1,28 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Map Hugging Face Hub client-side errors to HTTP status codes."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+
+def hf_error_status(exc: Exception) -> Optional[int]:
+ # Client-side HF errors should surface as 4xx, not a generic 500.
+ name = type(exc).__name__
+ if name in (
+ "RepositoryNotFoundError",
+ "RevisionNotFoundError",
+ "EntryNotFoundError",
+ ):
+ return 404
+ if name == "GatedRepoError":
+ return 403
+ if name == "HFValidationError":
+ return 400
+ # HfHubHTTPError subclasses carry the upstream response status.
+ code = getattr(getattr(exc, "response", None), "status_code", None)
+ if isinstance(code, int) and 400 <= code < 500:
+ return code
+ return None
diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.py
new file mode 100644
index 00000000000..a7281ad8b38
--- /dev/null
+++ b/studio/backend/hub/utils/inventory_scan.py
@@ -0,0 +1,533 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""HF cache inventory scanner.
+
+Read-only walks of the HuggingFace hub cache plus legacy/default
+cache locations. Builds the foundation that Hub inventory endpoints
+and the DownloadRegistry both consume.
+
+The worker spawn / transport-marker preparation / DownloadRegistry
+layers built on top of these primitives live in download_registry.py.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import re
+import threading
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable, Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+from hub.utils.gguf import extract_quant_label, is_gguf_filename, is_mmproj_filename
+from hub.utils.state_dir import RepoType
+
+from hub.utils.hf_cache_state import (
+ INCOMPLETE_SUFFIX,
+ has_incomplete_blobs,
+ hf_cache_root,
+ iter_repo_cache_dirs,
+ latest_snapshot_dir,
+ repo_cache_dir_has_incomplete_blobs,
+)
+
+# Inventory is invalidated explicitly on every app-driven cache mutation, so
+# this TTL only bounds staleness from out-of-band edits while skipping re-walks
+# on rapid UI navigation.
+_HF_CACHE_SCANS_TTL_SECONDS = 15.0
+_GGUF_SPLIT_RE = re.compile(r"-(\d{3,})-of-(\d{3,})(?=\.gguf$)", re.IGNORECASE)
+_hf_cache_scans_lock = threading.Lock()
+
+
+@dataclass
+class _HfCacheScanFlight:
+ event: threading.Event
+ epoch: int
+ result: Optional[list] = None
+ error: Optional[BaseException] = None
+
+
+_hf_cache_scans_flight: Optional[_HfCacheScanFlight] = None
+_hf_cache_scans_result: Optional[list] = None
+_hf_cache_scans_cached_at: float = 0.0
+# Bumped on every invalidation. A scan tags itself with the epoch it began
+# under; an invalidation mid-scan changes the epoch so the in-flight result is
+# neither cached nor served to callers that arrived after the mutation.
+_hf_cache_scans_epoch: int = 0
+
+
+def invalidate_hf_cache_scans() -> None:
+ global _hf_cache_scans_result, _hf_cache_scans_cached_at, _hf_cache_scans_epoch
+ with _hf_cache_scans_lock:
+ _hf_cache_scans_result = None
+ _hf_cache_scans_cached_at = 0.0
+ _hf_cache_scans_epoch += 1
+
+
+def all_hf_cache_scans() -> list:
+ global _hf_cache_scans_flight, _hf_cache_scans_result, _hf_cache_scans_cached_at
+
+ now = time.monotonic()
+ with _hf_cache_scans_lock:
+ if (
+ _hf_cache_scans_result is not None
+ and (now - _hf_cache_scans_cached_at) < _HF_CACHE_SCANS_TTL_SECONDS
+ ):
+ return list(_hf_cache_scans_result)
+ start_epoch = _hf_cache_scans_epoch
+ flight = _hf_cache_scans_flight
+ # Only coalesce onto an in-flight scan from the current epoch; one that
+ # began before an intervening invalidation is superseded so
+ # post-mutation callers never receive pre-mutation data.
+ if flight is None or flight.epoch != start_epoch:
+ flight = _HfCacheScanFlight(event = threading.Event(), epoch = start_epoch)
+ _hf_cache_scans_flight = flight
+ owner = True
+ else:
+ owner = False
+
+ if not owner:
+ flight.event.wait()
+ if flight.error is not None:
+ raise flight.error
+ return list(flight.result or [])
+
+ try:
+ scans = _compute_all_hf_cache_scans()
+ with _hf_cache_scans_lock:
+ flight.result = scans
+ if _hf_cache_scans_epoch == flight.epoch:
+ _hf_cache_scans_result = scans
+ _hf_cache_scans_cached_at = time.monotonic()
+ return scans
+ except Exception as exc:
+ with _hf_cache_scans_lock:
+ if _hf_cache_scans_epoch == flight.epoch:
+ _hf_cache_scans_result = None
+ _hf_cache_scans_cached_at = 0.0
+ flight.error = exc
+ raise
+ finally:
+ with _hf_cache_scans_lock:
+ if _hf_cache_scans_flight is flight:
+ _hf_cache_scans_flight = None
+ flight.event.set()
+
+
+def _compute_all_hf_cache_scans() -> list:
+ from huggingface_hub import scan_cache_dir
+ from hub.utils.paths import legacy_hf_cache_dir, hf_default_cache_dir
+
+ scans: list = []
+ seen: set[str] = set()
+ try:
+ from huggingface_hub.constants import HF_HUB_CACHE
+
+ active = Path(HF_HUB_CACHE).resolve()
+ seen.add(str(active))
+ if active.is_dir():
+ scans.append(scan_cache_dir())
+ except Exception as exc:
+ logger.warning("Could not scan active HF cache: %s", exc)
+
+ for extra_fn in (legacy_hf_cache_dir, hf_default_cache_dir):
+ extra = extra_fn()
+ if extra.is_dir() and str(extra.resolve()) not in seen:
+ seen.add(str(extra.resolve()))
+ try:
+ scans.append(scan_cache_dir(cache_dir = str(extra)))
+ except Exception as exc:
+ logger.warning("Could not scan HF cache %s: %s", extra, exc)
+ return scans
+
+
+def token_fingerprint(hf_token: Optional[str]) -> str:
+ """16-char SHA256 prefix used as a cache-key qualifier for gated repos.
+
+ Lets per-token size/snapshot caches refuse to serve a previously
+ fetched value back to a different token (a private/gated repo's
+ metadata is only valid for the credential that fetched it).
+ """
+ if not hf_token:
+ return ""
+ return hashlib.sha256(hf_token.encode()).hexdigest()[:16]
+
+
+def resolve_hf_cache_realpath(repo_dir: Path) -> Optional[str]:
+ """Pick the most useful on-disk path for a HF cache repo dir.
+
+ Prefers the most-recent snapshot dir (what ``from_pretrained``
+ actually points at). Falls back to the cache repo root. Returns the
+ resolved realpath so symlinks under ``snapshots/`` are followed back
+ to ``blobs/``.
+ """
+ try:
+ latest = latest_snapshot_dir(repo_dir)
+ if latest is not None:
+ return str(latest.resolve())
+ return str(repo_dir.resolve())
+ except Exception:
+ return None
+
+
+def resolve_snapshot_dir_for_scan(
+ repo_type: str,
+ repo_id: str,
+ repo_cache_dir: Optional[Path] = None,
+) -> Optional[Path]:
+ """Latest snapshot dir for a cache row, or the first populated HF cache root.
+
+ Scanner-side counterpart to snapshot_download()'s return value (which the
+ scanner cannot access). With a *repo_cache_dir*, returns its newest
+ snapshot. Otherwise scans roots in priority order (active, legacy, default)
+ and returns the newest snapshot in the first root that holds one; active is
+ where snapshot_download writes, so it is authoritative. Within a root,
+ picks by mtime (what from_pretrained resolves to) rather than refs/main,
+ since the user may have downloaded a non-main commit.
+ """
+ if repo_cache_dir is not None:
+ latest = latest_snapshot_dir(repo_cache_dir)
+ if latest is None:
+ return None
+ try:
+ return latest.resolve()
+ except OSError:
+ return None
+ for repo_dir in iter_repo_cache_dirs(repo_type, repo_id):
+ latest = latest_snapshot_dir(repo_dir)
+ if latest is None:
+ continue
+ try:
+ return latest.resolve()
+ except OSError:
+ continue
+ return None
+
+
+def _compose_partial(*signals: Callable[[], bool]) -> bool:
+ return any(signal() for signal in signals)
+
+
+def _state_applies_to_repo_cache_dir(repo_cache_dir: Optional[Path]) -> bool:
+ if repo_cache_dir is None:
+ return True
+ root = hf_cache_root()
+ if root is None:
+ return False
+ try:
+ return repo_cache_dir.resolve().parent == root.resolve()
+ except OSError:
+ return False
+
+
+def _legacy_partial(
+ repo_type: str,
+ repo_id: str,
+ repo_cache_dir: Optional[Path] = None,
+) -> bool:
+ if repo_cache_dir is not None:
+ return repo_cache_dir_has_incomplete_blobs(repo_cache_dir)
+ return has_incomplete_blobs(repo_type, repo_id)
+
+
+def _repo_cache_dir_incomplete_hashes(repo_cache_dir: Path) -> set[str]:
+ blobs_dir = repo_cache_dir / "blobs"
+ if not blobs_dir.is_dir():
+ return set()
+ hashes: set[str] = set()
+ try:
+ entries = list(blobs_dir.iterdir())
+ except OSError:
+ return hashes
+ for blob in entries:
+ try:
+ if blob.is_file() and blob.name.endswith(INCOMPLETE_SUFFIX):
+ hashes.add(blob.name[: -len(INCOMPLETE_SUFFIX)])
+ except OSError:
+ continue
+ return hashes
+
+
+def _repo_cache_dir_has_non_gguf_broken_snapshot_symlinks(repo_cache_dir: Path) -> bool:
+ latest = latest_snapshot_dir(repo_cache_dir)
+ if latest is None:
+ return False
+ try:
+ entries = list(latest.rglob("*"))
+ except OSError:
+ return False
+ for entry in entries:
+ try:
+ if not entry.is_symlink() or entry.exists():
+ continue
+ rel = entry.relative_to(latest).as_posix()
+ if is_gguf_filename(rel):
+ continue
+ return True
+ except OSError:
+ continue
+ return False
+
+
+def _gguf_variant_manifest_blob_hashes(repo_id: str) -> frozenset[str]:
+ from hub.utils import download_manifest
+
+ hashes: set[str] = set()
+ for variant, _path in download_manifest.iter_variant_manifests("model", repo_id):
+ manifest = download_manifest.read_manifest("model", repo_id, variant)
+ if manifest is None:
+ continue
+ for expected in manifest.expected_files:
+ if expected.sha256 and is_gguf_filename(expected.path):
+ hashes.add(expected.sha256)
+ return frozenset(hashes)
+
+
+def _repo_cache_dir_has_snapshot_legacy_partial(
+ repo_cache_dir: Path, *, ignored_blob_hashes: frozenset[str]
+) -> bool:
+ incomplete_hashes = _repo_cache_dir_incomplete_hashes(repo_cache_dir)
+ if any(blob_hash not in ignored_blob_hashes for blob_hash in incomplete_hashes):
+ return True
+ return _repo_cache_dir_has_non_gguf_broken_snapshot_symlinks(repo_cache_dir)
+
+
+def _snapshot_legacy_partial(
+ repo_type: str,
+ repo_id: str,
+ repo_cache_dir: Optional[Path] = None,
+) -> bool:
+ if repo_type != "model":
+ return _legacy_partial(repo_type, repo_id, repo_cache_dir)
+ ignored_hashes = _gguf_variant_manifest_blob_hashes(repo_id)
+ if repo_cache_dir is not None:
+ return _repo_cache_dir_has_snapshot_legacy_partial(
+ repo_cache_dir,
+ ignored_blob_hashes = ignored_hashes,
+ )
+ return any(
+ _repo_cache_dir_has_snapshot_legacy_partial(
+ entry,
+ ignored_blob_hashes = ignored_hashes,
+ )
+ for entry in iter_repo_cache_dirs(repo_type, repo_id)
+ )
+
+
+def _completed_gguf_variants(snapshot_dir: Optional[Path]) -> set[str]:
+ if snapshot_dir is None:
+ return set()
+ complete: set[str] = set()
+ split_groups: dict[str, dict[int, set[int]]] = {}
+ try:
+ paths = list(snapshot_dir.rglob("*"))
+ except OSError:
+ return set()
+ for path in paths:
+ try:
+ if not path.is_file() or path.stat().st_size <= 0:
+ continue
+ except OSError:
+ continue
+ rel = path.relative_to(snapshot_dir).as_posix()
+ if not is_gguf_filename(rel) or is_mmproj_filename(rel):
+ continue
+ quant = extract_quant_label(rel)
+ split = _GGUF_SPLIT_RE.search(path.name)
+ if split is None:
+ complete.add(quant)
+ continue
+ index = int(split.group(1))
+ total = int(split.group(2))
+ if index <= 0 or total <= 0 or index > total:
+ continue
+ split_groups.setdefault(quant, {}).setdefault(total, set()).add(index)
+ for quant, groups in split_groups.items():
+ for total, indices in groups.items():
+ if indices == set(range(1, total + 1)):
+ complete.add(quant)
+ break
+ return complete
+
+
+def _manifest_partial(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+ snapshot_dir: Optional[Path] = None,
+ repo_cache_dir: Optional[Path] = None,
+) -> bool:
+ from hub.utils import download_manifest
+
+ if not _state_applies_to_repo_cache_dir(repo_cache_dir):
+ return False
+ manifest = download_manifest.read_manifest(repo_type, repo_id, variant)
+ if manifest is None:
+ return False
+ resolved = (
+ snapshot_dir
+ if snapshot_dir is not None
+ else resolve_snapshot_dir_for_scan(repo_type, repo_id, repo_cache_dir)
+ )
+ if resolved is None:
+ return True
+ return not download_manifest.verify_against_disk(manifest, resolved).ok
+
+
+def is_snapshot_partial(
+ repo_type: RepoType,
+ repo_id: str,
+ repo_cache_dir: Optional[Path] = None,
+) -> bool:
+ """Repo-row partial flag for snapshot-style downloads (full-snapshot
+ models — safetensors/adapter/checkpoint — and all datasets).
+
+ Composes three signals, cheapest first:
+ 1. Cancel marker (single stat).
+ 2. Snapshot-attributed legacy .incomplete blob / broken-symlink check.
+ 3. Manifest walk (stat per expected file under the latest snapshot).
+
+ A manifest without a resolvable snapshot is partial: the worker got
+ far enough to record expectations but did not leave a usable snapshot."""
+ from hub.utils import download_manifest
+
+ state_applies = _state_applies_to_repo_cache_dir(repo_cache_dir)
+ return _compose_partial(
+ lambda: state_applies and download_manifest.has_cancel_marker(repo_type, repo_id, None),
+ lambda: _snapshot_legacy_partial(repo_type, repo_id, repo_cache_dir),
+ lambda: _manifest_partial(
+ repo_type,
+ repo_id,
+ None,
+ None,
+ repo_cache_dir,
+ ),
+ )
+
+
+def is_variant_partial(
+ repo_id: str,
+ variant: str,
+ snapshot_dir: Optional[Path] = None,
+ *,
+ incomplete_blob_hashes: Optional[set[str]] = None,
+ variant_blob_hashes: Optional[frozenset[str]] = None,
+ repo_cache_dir: Optional[Path] = None,
+) -> bool:
+ """Per-variant partial detection. Owns its manifest, owns its marker.
+ Used by the GGUF variants endpoint to flag a specific quant as broken
+ without contaminating other quants in the same repo.
+
+ snapshot_dir is an optional hint to avoid re-walking the cache when a
+ caller is checking many variants of the same repo (see
+ is_gguf_repo_partial for that usage)."""
+ from hub.utils import download_manifest
+
+ state_applies = _state_applies_to_repo_cache_dir(repo_cache_dir)
+ return _compose_partial(
+ lambda: state_applies and download_manifest.has_cancel_marker("model", repo_id, variant),
+ lambda: bool(
+ incomplete_blob_hashes
+ and variant_blob_hashes
+ and incomplete_blob_hashes.intersection(variant_blob_hashes)
+ ),
+ lambda: _manifest_partial(
+ "model",
+ repo_id,
+ variant,
+ snapshot_dir,
+ repo_cache_dir,
+ ),
+ )
+
+
+def is_gguf_repo_partial(repo_id: str, repo_cache_dir: Optional[Path] = None) -> bool:
+ """Repo-row partial flag for a GGUF repo. The inventory shows ONE row per
+ GGUF repo (requires_variant=True); per-variant detail lives in
+ GET /api/models/gguf-variants and uses is_variant_partial.
+
+ *** DO NOT simplify this to "any variant partial -> repo partial" ***
+
+ Tripwire scenario: user downloads Q8_0 fully, then starts Q4_K_M and
+ cancels. Both variants share ONE inventory row. If row.partial flips True,
+ _capabilities_for_format flips can_chat=False, so the user can no longer
+ chat with the perfectly-good Q8_0 because of an unrelated cancelled Q4_K_M.
+
+ Correct semantics: partial=True only when at least one variant is broken
+ AND no other variant is clean. "Simplifying" to the obvious "any broken"
+ form re-introduces this Q8+Q4 mixed-state regression.
+
+ Composes signals:
+ 1. Cheap legacy fast-path (.incomplete blobs / broken symlinks).
+ 2. Per-variant manifest + marker enumeration, gated on "all broken".
+ """
+ from hub.utils import download_manifest
+
+ has_legacy_partial = _legacy_partial("model", repo_id, repo_cache_dir)
+ state_applies = _state_applies_to_repo_cache_dir(repo_cache_dir)
+ snapshot_dir = resolve_snapshot_dir_for_scan(
+ "model",
+ repo_id,
+ repo_cache_dir,
+ )
+ variants: set[str] = set(_completed_gguf_variants(snapshot_dir))
+ if state_applies:
+ for variant, _path in download_manifest.iter_variant_manifests(
+ "model",
+ repo_id,
+ ):
+ variants.add(variant)
+ for variant, _path in download_manifest.iter_variant_markers(
+ "model",
+ repo_id,
+ ):
+ variants.add(variant)
+ if not variants:
+ return has_legacy_partial
+ has_clean = False
+ has_broken = has_legacy_partial
+ for variant in variants:
+ if is_variant_partial(
+ repo_id,
+ variant,
+ snapshot_dir,
+ repo_cache_dir = repo_cache_dir,
+ ):
+ has_broken = True
+ else:
+ has_clean = True
+ return has_broken and not has_clean
+
+
+def partial_transport_for(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+ repo_cache_dir: Optional[Path] = None,
+) -> Optional[str]:
+ """Transport to surface on a partial row's resume affordance.
+
+ Prefers the cancel marker's transport, then the manifest's. The fallback
+ matters for rows partial without a marker (an errored/interrupted download
+ leaves the manifest but no marker) so the UI can still show HTTP-resume vs
+ XET-redownload instead of the neutral retry label. ``None`` when neither is
+ available."""
+ from hub.utils import download_manifest
+
+ if not _state_applies_to_repo_cache_dir(repo_cache_dir):
+ return None
+ marker_transport = download_manifest.read_cancel_marker_transport(
+ repo_type,
+ repo_id,
+ variant,
+ )
+ if marker_transport is not None:
+ return marker_transport
+ manifest = download_manifest.read_manifest(repo_type, repo_id, variant)
+ return manifest.transport if manifest is not None else None
diff --git a/studio/backend/hub/utils/llm_assist.py b/studio/backend/hub/utils/llm_assist.py
new file mode 100644
index 00000000000..00edb204c5a
--- /dev/null
+++ b/studio/backend/hub/utils/llm_assist.py
@@ -0,0 +1,440 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import textwrap
+import time
+from typing import Any, Optional
+
+from loggers import get_logger
+
+from hub.utils import download_registry
+
+logger = get_logger(__name__)
+
+DEFAULT_HELPER_MODEL_REPO = "unsloth/gemma-4-E2B-it-GGUF"
+DEFAULT_HELPER_MODEL_VARIANT = "UD-Q4_K_XL"
+README_MAX_CHARS = 1500
+
+
+def _helper_disabled() -> bool:
+ return os.environ.get("UNSLOTH_HELPER_MODEL_DISABLE", "").strip().lower() in {
+ "1",
+ "true",
+ }
+
+
+def _strip_think_tags(text: str) -> str:
+ if "<think>" not in text:
+ return text
+ stripped = re.sub(r"<think>.*?</think>\s*", "", text, flags = re.DOTALL).strip()
+ if stripped:
+ return stripped
+ matches = re.findall(r"<think>(.*?)</think>", text, flags = re.DOTALL)
+ return matches[-1].strip() if matches else text
+
+
+def _parse_json_response(text: str) -> Optional[dict[str, Any]]:
+ cleaned = (text or "").strip()
+ if not cleaned:
+ return None
+ if cleaned.startswith("```"):
+ lines = cleaned.splitlines()
+ end = -1 if lines and lines[-1].strip().startswith("```") else len(lines)
+ cleaned = "\n".join(lines[1:end]).strip()
+ try:
+ parsed = json.loads(cleaned)
+ return parsed if isinstance(parsed, dict) else None
+ except json.JSONDecodeError:
+ pass
+ match = re.search(r"\{.*\}", cleaned, re.DOTALL)
+ if not match:
+ return None
+ try:
+ parsed = json.loads(match.group())
+ except json.JSONDecodeError:
+ return None
+ return parsed if isinstance(parsed, dict) else None
+
+
+def _generate_with_backend(backend, messages: list[dict[str, str]], max_tokens: int) -> str:
+ cumulative = ""
+ for chunk in backend.generate_chat_completion(
+ messages = messages,
+ temperature = 0.1,
+ top_p = 0.9,
+ top_k = 20,
+ max_tokens = max_tokens,
+ repetition_penalty = 1.0,
+ enable_thinking = False,
+ ):
+ if isinstance(chunk, dict):
+ continue
+ cumulative = chunk
+ return _strip_think_tags(cumulative.strip())
+
+
+def _fetch_hf_dataset_card(
+ dataset_name: str, hf_token: Optional[str]
+) -> tuple[Optional[str], Optional[dict[str, Any]]]:
+ try:
+ from huggingface_hub import DatasetCard
+
+ card = DatasetCard.load(dataset_name, token = hf_token)
+ readme = card.text or ""
+ if len(readme) > README_MAX_CHARS:
+ cut = readme[:README_MAX_CHARS].rfind(".")
+ if cut > README_MAX_CHARS // 2:
+ readme = readme[: cut + 1] + "\n[...truncated]"
+ else:
+ readme = readme[:README_MAX_CHARS] + "\n[...truncated]"
+ metadata: dict[str, Any] = {}
+ if card.data:
+ for key in (
+ "task_categories",
+ "task_ids",
+ "language",
+ "size_categories",
+ "tags",
+ "license",
+ "pretty_name",
+ ):
+ value = getattr(card.data, key, None)
+ if value is not None:
+ metadata[key] = value
+ return readme, metadata
+ except Exception as exc:
+ logger.warning(
+ "Could not fetch dataset card for %s: %s",
+ dataset_name,
+ download_registry.scrub_secrets(str(exc), hf_token = hf_token),
+ )
+ return None, None
+
+
+def _is_gemma_3n(model_name: Optional[str]) -> bool:
+ normalized = (model_name or "").lower().replace("_", "-")
+ return "gemma-3n" in normalized or "gemma3n" in normalized
+
+
+def _sample_text(columns: list[str], samples: list[dict[str, Any]]) -> str:
+ rows: list[str] = []
+ for index, row in enumerate(samples[:5], 1):
+ parts = [f" {col}: {str(row.get(col, ''))[:200]}" for col in columns]
+ rows.append(f"Row {index}:\n" + "\n".join(parts))
+ return "\n".join(rows)
+
+
+def _target_hints(model_name: Optional[str], model_type: Optional[str]) -> str:
+ if model_type == "audio" and not _is_gemma_3n(model_name):
+ return (
+ "\n\nHINT: The user is training an AUDIO model. The dataset must contain "
+ "a column with audio files or paths and one such column should be selected "
+ "as part of the input."
+ )
+ if model_type == "embeddings":
+ return (
+ "\n\nHINT: The user is training an EMBEDDING model. Prefer dataset formats "
+ "such as text pairs for STS, premise/hypothesis/label for NLI, or query "
+ "and document columns for retrieval."
+ )
+ return ""
+
+
+def _run_multi_pass_advisor(
+ *,
+ columns: list[str],
+ samples: list[dict[str, Any]],
+ dataset_name: Optional[str],
+ dataset_card: Optional[str],
+ dataset_metadata: Optional[dict[str, Any]],
+ model_name: Optional[str],
+ model_type: Optional[str],
+) -> Optional[dict[str, Any]]:
+ if _helper_disabled():
+ return None
+
+ repo = os.environ.get("UNSLOTH_HELPER_MODEL_REPO", DEFAULT_HELPER_MODEL_REPO)
+ variant = os.environ.get("UNSLOTH_HELPER_MODEL_VARIANT", DEFAULT_HELPER_MODEL_VARIANT)
+ backend = None
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = LlamaCppBackend()
+ started = time.monotonic()
+ if not backend.load_model(
+ hf_repo = repo,
+ hf_variant = variant,
+ model_identifier = f"hub-advisor:{repo}:{variant}",
+ is_vision = False,
+ n_ctx = 2048,
+ n_gpu_layers = -1,
+ ):
+ return None
+ logger.info("Hub advisor model loaded in %.1fs", time.monotonic() - started)
+
+ samples_text = _sample_text(columns, samples)
+ metadata_text = (
+ json.dumps(dataset_metadata, indent = 2, default = str)[:500] if dataset_metadata else "N/A"
+ )
+ card_excerpt = (dataset_card or "")[:1200] or "N/A"
+ hints = _target_hints(model_name, model_type)
+
+ pass1_raw = _generate_with_backend(
+ backend,
+ [
+ {
+ "role": "system",
+ "content": (
+ "You are a dataset analyst. Classify the dataset and respond "
+ "with only a valid JSON object."
+ f"{hints}"
+ ),
+ },
+ {
+ "role": "user",
+ "content": textwrap.dedent(f"""\
+ Dataset: {dataset_name or "unknown"}
+
+ DATASET CARD:
+ {card_excerpt}
+
+ METADATA:
+ {metadata_text}
+
+ COLUMNS: {columns}
+
+ SAMPLE DATA:
+ {samples_text}
+
+ Return this JSON shape:
+ {{
+ "dataset_type": "<summarization|question_answering|translation|classification|natural_language_inference|instruction_following|conversational|code_generation|other>",
+ "is_conversational": <boolean>,
+ "needs_conversion": <boolean>,
+ "description": "<one sentence>",
+ "task_description": "<one sentence>"
+ }}"""),
+ },
+ ],
+ 256,
+ )
+ pass1 = _parse_json_response(pass1_raw)
+ if not pass1:
+ return None
+
+ if pass1.get("is_conversational") and not pass1.get("needs_conversion"):
+ return {
+ "success": True,
+ "dataset_type": pass1.get("dataset_type"),
+ "is_conversational": True,
+ "user_notification": (
+ "This dataset is already in conversational format. No conversion is needed."
+ ),
+ }
+
+ pass2_raw = _generate_with_backend(
+ backend,
+ [
+ {
+ "role": "system",
+ "content": (
+ "Assign each dataset column to user, assistant, or skip for "
+ "LLM fine-tuning. The target/output/answer/label column must be "
+ "assistant. Return only valid JSON."
+ f"{hints}"
+ ),
+ },
+ {
+ "role": "user",
+ "content": textwrap.dedent(f"""\
+ CLASSIFICATION:
+ {json.dumps(pass1, indent = 2)}
+
+ COLUMNS: {columns}
+
+ SAMPLE DATA:
+ {samples_text}
+
+ Return this JSON shape:
+ {{
+ "column_roles": {{"<column_name>": "<user|assistant|skip>"}},
+ "label_mapping": null,
+ "notes": "<short reason>"
+ }}"""),
+ },
+ ],
+ 512,
+ )
+ pass2 = _parse_json_response(pass2_raw)
+ if not pass2:
+ return None
+ column_roles = pass2.get("column_roles")
+ if not isinstance(column_roles, dict):
+ return None
+ roles_present = set(column_roles.values())
+ if "user" not in roles_present or "assistant" not in roles_present:
+ return None
+
+ label_mapping = pass2.get("label_mapping") or None
+ system_prompt = ""
+ if not pass1.get("is_conversational"):
+ user_cols = [col for col, role in column_roles.items() if role == "user"]
+ assistant_cols = [col for col, role in column_roles.items() if role == "assistant"]
+ prompt_raw = _generate_with_backend(
+ backend,
+ [
+ {
+ "role": "user",
+ "content": textwrap.dedent(f"""\
+ Write a concise system prompt for fine-tuning.
+
+ Dataset type: {pass1.get("dataset_type", "other")}
+ Task: {pass1.get("task_description") or pass1.get("description") or ""}
+ User input columns: {user_cols}
+ Assistant output columns: {assistant_cols}
+
+ Write only the system prompt text."""),
+ },
+ ],
+ 256,
+ )
+ cleaned = prompt_raw.strip().strip('"').strip("'").strip()
+ if 20 <= len(cleaned) <= 800 and cleaned.lower() not in {"null", "none"}:
+ system_prompt = cleaned
+
+ suggested_mapping = {
+ col: role
+ for col, role in column_roles.items()
+ if col in columns and role in {"user", "assistant", "system"}
+ }
+ if (
+ "user" not in suggested_mapping.values()
+ or "assistant" not in suggested_mapping.values()
+ ):
+ return None
+
+ dtype = str(pass1.get("dataset_type") or "other")
+ notification_parts = [f"This is a {dtype} dataset."]
+ description = pass1.get("task_description") or pass1.get("description")
+ if description:
+ notification_parts.append(str(description))
+ notification_parts.append("Columns were mapped to conversation roles.")
+
+ return {
+ "success": True,
+ "suggested_mapping": suggested_mapping,
+ "system_prompt": system_prompt,
+ "label_mapping": label_mapping if isinstance(label_mapping, dict) else None,
+ "dataset_type": dtype,
+ "is_conversational": bool(pass1.get("is_conversational")),
+ "user_notification": " ".join(notification_parts),
+ }
+ except Exception as exc:
+ logger.warning("Hub advisor failed: %s", exc)
+ return None
+ finally:
+ if backend is not None:
+ try:
+ backend.unload_model()
+ except Exception:
+ pass
+
+
+def _heuristic_mapping(columns: list[str]) -> Optional[dict[str, str]]:
+ if not columns:
+ return None
+ lowered = {col: col.lower().replace("-", "_") for col in columns}
+ metadata_terms = ("id", "uuid", "url", "source", "date", "time", "score", "index")
+ assistant_terms = (
+ "assistant",
+ "answer",
+ "response",
+ "output",
+ "completion",
+ "target",
+ "label",
+ "summary",
+ "translation",
+ )
+ user_terms = (
+ "user",
+ "human",
+ "prompt",
+ "instruction",
+ "input",
+ "question",
+ "query",
+ "context",
+ "document",
+ "article",
+ "problem",
+ "text",
+ )
+ mapping: dict[str, str] = {}
+ for col, name in lowered.items():
+ if any(term == name or name.endswith(f"_{term}") for term in metadata_terms):
+ continue
+ if any(term in name for term in assistant_terms):
+ mapping[col] = "assistant"
+ elif any(term in name for term in user_terms):
+ mapping[col] = "user"
+
+ if "assistant" not in mapping.values():
+ candidates = [col for col in columns if col not in mapping]
+ if candidates:
+ mapping[candidates[-1]] = "assistant"
+ elif columns:
+ mapping[columns[-1]] = "assistant"
+ if "user" not in mapping.values():
+ for col in columns:
+ if mapping.get(col) != "assistant":
+ mapping[col] = "user"
+ break
+ if "user" not in mapping.values() or "assistant" not in mapping.values():
+ return None
+ return mapping
+
+
+def llm_conversion_advisor(
+ column_names: list[str],
+ samples: list[dict[str, Any]],
+ dataset_name: Optional[str] = None,
+ hf_token: Optional[str] = None,
+ model_name: Optional[str] = None,
+ model_type: Optional[str] = None,
+) -> Optional[dict[str, Any]]:
+ dataset_card = None
+ dataset_metadata = None
+ if dataset_name and "/" in dataset_name:
+ dataset_card, dataset_metadata = _fetch_hf_dataset_card(dataset_name, hf_token)
+
+ result = _run_multi_pass_advisor(
+ columns = column_names,
+ samples = samples,
+ dataset_name = dataset_name,
+ dataset_card = dataset_card,
+ dataset_metadata = dataset_metadata,
+ model_name = model_name,
+ model_type = model_type,
+ )
+ if result and result.get("success"):
+ return result
+
+ mapping = _heuristic_mapping(column_names)
+ if mapping:
+ return {
+ "success": True,
+ "suggested_mapping": mapping,
+ "dataset_type": None,
+ "is_conversational": None,
+ "warning": (
+ "The helper model was unavailable, so Hub used column-name heuristics. "
+ "Review the suggested mapping before training."
+ ),
+ }
+ return None
diff --git a/studio/backend/hub/utils/paths.py b/studio/backend/hub/utils/paths.py
new file mode 100644
index 00000000000..afcb0b41dc5
--- /dev/null
+++ b/studio/backend/hub/utils/paths.py
@@ -0,0 +1,522 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Path validators and storage roots for the Hub layer."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import sys
+import tempfile
+import threading
+from collections import OrderedDict
+from pathlib import Path
+from typing import Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+
+def _infer_studio_home_from_venv() -> Optional[Path]:
+ try:
+ prefix = Path(sys.prefix).resolve()
+ except (OSError, ValueError):
+ return None
+ if prefix.name != "unsloth_studio":
+ return None
+ candidate = prefix.parent
+ shim_name = "unsloth.exe" if os.name == "nt" else "unsloth"
+ try:
+ if (candidate / "share" / "studio.conf").is_file() or (
+ candidate / "bin" / shim_name
+ ).is_file():
+ return candidate
+ except OSError:
+ return None
+ return None
+
+
+def studio_root() -> Path:
+ override = (os.environ.get("UNSLOTH_STUDIO_HOME") or "").strip()
+ if not override:
+ override = (os.environ.get("STUDIO_HOME") or "").strip()
+ if override:
+ try:
+ return Path(override).expanduser().resolve()
+ except (OSError, ValueError):
+ return Path(override).expanduser()
+ inferred = _infer_studio_home_from_venv()
+ if inferred is not None:
+ return inferred
+ return Path.home() / ".unsloth" / "studio"
+
+
+def cache_root() -> Path:
+ return studio_root() / "cache"
+
+
+def assets_root() -> Path:
+ return studio_root() / "assets"
+
+
+def datasets_root() -> Path:
+ return assets_root() / "datasets"
+
+
+def dataset_uploads_root() -> Path:
+ return datasets_root() / "uploads"
+
+
+def recipe_datasets_root() -> Path:
+ return datasets_root() / "recipes"
+
+
+def outputs_root() -> Path:
+ return studio_root() / "outputs"
+
+
+def exports_root() -> Path:
+ return studio_root() / "exports"
+
+
+def tmp_root() -> Path:
+ return Path(tempfile.gettempdir()) / "unsloth-studio"
+
+
+def ensure_dir(path: Path) -> Path:
+ path.mkdir(parents = True, exist_ok = True)
+ return path
+
+
+def legacy_hf_cache_dir() -> Path:
+ return cache_root() / "huggingface" / "hub"
+
+
+def hf_default_cache_dir() -> Path:
+ return Path.home() / ".cache" / "huggingface" / "hub"
+
+
+def _is_wsl() -> bool:
+ if sys.platform == "win32":
+ return False
+ try:
+ return "microsoft" in Path("/proc/version").read_text().lower()
+ except Exception:
+ return False
+
+
+_IS_WSL = _is_wsl()
+
+
+def _wsl_automount_root() -> str:
+ """DrvFs root under which WSL maps Windows drives, with a trailing slash.
+
+ Defaults to ``/mnt/`` but is user-configurable via ``/etc/wsl.conf``
+ (``[automount] root``), so hard-coding ``/mnt/`` mistranslates Windows paths
+ on a host with a custom root (e.g. ``root = /`` → ``C:`` at ``/c/``)."""
+ default = "/mnt/"
+ if not _IS_WSL:
+ return default
+ try:
+ import configparser
+
+ parser = configparser.ConfigParser(inline_comment_prefixes = ("#", ";"))
+ parser.read("/etc/wsl.conf")
+ root = parser.get("automount", "root", fallback = "").strip().strip("\"'")
+ except Exception:
+ return default
+ if not root:
+ return default
+ return root if root.endswith("/") else f"{root}/"
+
+
+_WSL_AUTOMOUNT_ROOT = _wsl_automount_root()
+
+
+def normalize_path(path: str) -> str:
+ if not path:
+ return path
+ if len(path) >= 3 and path[1] == ":" and path[2] in ("\\", "/"):
+ if _IS_WSL:
+ drive = path[0].lower()
+ rest = path[3:].replace("\\", "/")
+ return f"{_WSL_AUTOMOUNT_ROOT}{drive}/{rest}"
+ return path.replace("\\", "/")
+ return path.replace("\\", "/")
+
+
+def _host_path(path: str | Path) -> Path:
+ return Path(normalize_path(str(path))).expanduser()
+
+
+def is_local_path(path: str) -> bool:
+ if not path:
+ return False
+ normalized = normalize_path(path)
+ has_local_syntax = (
+ path.startswith(("/", ".", "~"))
+ or ":" in path
+ or "\\" in path
+ or os.path.isabs(path)
+ or os.path.isabs(normalized)
+ )
+ if path.count("/") == 1 and not has_local_syntax:
+ return False
+ try:
+ if has_local_syntax and Path(normalized).expanduser().exists():
+ return True
+ except Exception:
+ pass
+ return has_local_syntax
+
+
+_VALID_REPO_ID_SEGMENT = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$")
+_MAX_REPO_ID_LENGTH = 96
+
+
+def is_valid_repo_id(repo_id: str) -> bool:
+ """Validate Hugging Face ``repo_name`` or ``namespace/repo_name`` IDs."""
+ if not repo_id or repo_id != repo_id.strip():
+ return False
+ if len(repo_id) > _MAX_REPO_ID_LENGTH or repo_id.endswith(".git"):
+ return False
+ if "--" in repo_id or ".." in repo_id:
+ return False
+ segments = repo_id.split("/")
+ if len(segments) not in (1, 2):
+ return False
+ return all(
+ segment not in ("", ".", "..") and _VALID_REPO_ID_SEGMENT.fullmatch(segment) is not None
+ for segment in segments
+ )
+
+
+_GGUF_VARIANT_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]")
+_MAX_GGUF_VARIANT_LENGTH = 512
+
+
+def is_valid_gguf_variant(variant: str) -> bool:
+ """Validate Hub GGUF variant keys.
+
+ Known quant labels are short tokens (``Q4_K_M``), but unknown GGUF layouts
+ use a snapshot-relative key derived from the filename and may contain
+ slashes or spaces.
+ """
+ if not variant or variant != variant.strip():
+ return False
+ if len(variant) > _MAX_GGUF_VARIANT_LENGTH:
+ return False
+ if _GGUF_VARIANT_CONTROL_CHARS.search(variant) or not variant.isprintable():
+ return False
+ normalized = variant.replace("\\", "/")
+ return all(segment not in ("", ".", "..") for segment in normalized.split("/"))
+
+
+def ollama_model_dirs() -> list[Path]:
+ """Return Ollama model directories that exist on disk."""
+ dirs: list[Path] = []
+ seen: set[str] = set()
+
+ def _add(p: Path | str) -> None:
+ try:
+ expanded = _host_path(p)
+ resolved = expanded.resolve()
+ is_dir = expanded.is_dir()
+ except (OSError, RuntimeError, ValueError):
+ return
+ key = str(resolved)
+ if key in seen or not is_dir:
+ return
+ seen.add(key)
+ dirs.append(expanded)
+
+ ollama_env = os.environ.get("OLLAMA_MODELS")
+ if ollama_env:
+ _add(ollama_env)
+ _add(Path.home() / ".ollama" / "models")
+ _add(Path("/usr/share/ollama/.ollama/models"))
+ _add(Path("/var/lib/ollama/.ollama/models"))
+ return dirs
+
+
+# Per-process memo for resolve_cached_repo_id_case. Bounded LRU so a long-lived
+# process touching many repo ids can't grow it without limit; evicted cold
+# entries simply recompute on next use.
+_CACHE_CASE_RESOLUTION_MEMO_MAX = 512
+_CACHE_CASE_RESOLUTION_MEMO: "OrderedDict[tuple[str, str], str]" = OrderedDict()
+_CACHE_CASE_RESOLUTION_LOCK = threading.Lock()
+
+
+def _memo_get(memo_key: tuple[str, str]) -> Optional[str]:
+ with _CACHE_CASE_RESOLUTION_LOCK:
+ value = _CACHE_CASE_RESOLUTION_MEMO.get(memo_key)
+ if value is not None:
+ _CACHE_CASE_RESOLUTION_MEMO.move_to_end(memo_key)
+ return value
+
+
+def _memo_set(memo_key: tuple[str, str], value: str) -> None:
+ with _CACHE_CASE_RESOLUTION_LOCK:
+ _CACHE_CASE_RESOLUTION_MEMO[memo_key] = value
+ _CACHE_CASE_RESOLUTION_MEMO.move_to_end(memo_key)
+ while len(_CACHE_CASE_RESOLUTION_MEMO) > _CACHE_CASE_RESOLUTION_MEMO_MAX:
+ _CACHE_CASE_RESOLUTION_MEMO.popitem(last = False)
+
+
+def _memo_drop(memo_key: tuple[str, str]) -> None:
+ with _CACHE_CASE_RESOLUTION_LOCK:
+ _CACHE_CASE_RESOLUTION_MEMO.pop(memo_key, None)
+
+
+def _hf_hub_cache_dir() -> Path:
+ try:
+ from huggingface_hub.constants import HF_HUB_CACHE
+ return Path(HF_HUB_CACHE)
+ except Exception as exc:
+ logger.debug("Could not read huggingface_hub HF_HUB_CACHE, using default: %s", exc)
+ return Path.home() / ".cache" / "huggingface" / "hub"
+
+
+def _hf_hub_cache_dirs() -> list[Path]:
+ roots: list[Path] = []
+ seen: set[str] = set()
+
+ def _add(path: Path) -> None:
+ try:
+ resolved = path.resolve()
+ except OSError:
+ return
+ key = str(resolved)
+ if key in seen or not resolved.is_dir():
+ return
+ seen.add(key)
+ roots.append(resolved)
+
+ _add(_hf_hub_cache_dir())
+ try:
+ _add(legacy_hf_cache_dir())
+ _add(hf_default_cache_dir())
+ except Exception as exc:
+ logger.debug("Could not enumerate secondary HF cache roots: %s", exc)
+ return roots
+
+
+def lmstudio_model_dirs() -> list[Path]:
+ dirs: list[Path] = []
+ seen: set[str] = set()
+
+ def _add(path: Path | str) -> None:
+ try:
+ expanded = _host_path(path)
+ resolved = expanded.resolve()
+ except (OSError, RuntimeError, ValueError):
+ return
+ key = str(resolved)
+ if key in seen or not expanded.is_dir():
+ return
+ seen.add(key)
+ dirs.append(expanded)
+
+ settings_path = Path.home() / ".lmstudio" / "settings.json"
+ if settings_path.is_file():
+ try:
+ settings = json.loads(settings_path.read_text(encoding = "utf-8"))
+ downloads = settings.get("downloadsFolder", "")
+ if downloads:
+ _add(downloads)
+ except Exception:
+ pass
+ _add(Path.home() / ".lmstudio" / "models")
+ _add(Path.home() / ".cache" / "lm-studio" / "models")
+ return dirs
+
+
+def well_known_model_dirs() -> list[Path]:
+ candidates: list[Path] = []
+ candidates.extend(lmstudio_model_dirs())
+ candidates.extend(ollama_model_dirs())
+ candidates.append(Path.home() / ".cache" / "huggingface" / "hub")
+ candidates.append(Path.home() / "models")
+ candidates.append(Path.home() / "Models")
+
+ out: list[Path] = []
+ seen: set[str] = set()
+ for path in candidates:
+ try:
+ resolved = path.resolve()
+ except OSError:
+ continue
+ key = str(resolved)
+ if key in seen or not resolved.is_dir():
+ continue
+ seen.add(key)
+ out.append(resolved)
+ return out
+
+
+def _assert_contained(resolved: Path, root: Path) -> None:
+ try:
+ resolved_real = Path(os.path.realpath(resolved))
+ root_real = Path(os.path.realpath(root))
+ except OSError as exc:
+ raise ValueError(f"path resolution failed: {exc}") from exc
+ try:
+ resolved_real.relative_to(root_real)
+ except ValueError as exc:
+ raise ValueError(f"path escapes root: {resolved!s}") from exc
+
+
+def path_is_same_or_child(path: Path, root: Path) -> bool:
+ """True when *path* is *root* or lives beneath it.
+
+ Compares real (symlink-resolved, case-normalized) paths so the check holds
+ through symlinks and on case-insensitive filesystems, where a plain
+ ``Path.is_relative_to`` would miss a casing-only match. Returns False on any
+ resolution error rather than raising.
+ """
+ try:
+ path_real = os.path.normcase(os.path.realpath(str(path)))
+ root_real = os.path.normcase(os.path.realpath(str(root)))
+ return os.path.commonpath([path_real, root_real]) == root_real
+ except (OSError, ValueError):
+ return False
+
+
+def resolve_dataset_path(path_value: str) -> Path:
+ raw = str(path_value or "").strip()
+ if "\x00" in raw:
+ raise ValueError("dataset path may not contain null bytes")
+ # Normalize first so Windows/UNC and backslash paths resolve like the rest
+ # of the Hub path layer (e.g. C:\data -> /mnt/c/data on WSL) and a
+ # backslashed '..' is caught by the traversal guard below.
+ normalized = normalize_path(raw)
+ path = Path(normalized).expanduser()
+ if ".." in path.parts:
+ raise ValueError(f"dataset path may not contain '..' segments: {raw!r}")
+ if path.is_absolute():
+ for root in (datasets_root(), dataset_uploads_root(), recipe_datasets_root()):
+ try:
+ _assert_contained(path, root)
+ return path
+ except ValueError:
+ continue
+ raise ValueError(f"dataset path must be relative or under a dataset root: {raw!r}")
+
+ parts = [part for part in Path(normalized).parts if part not in ("", ".")]
+ if parts[:2] == ["assets", "datasets"]:
+ parts = parts[2:]
+ if parts and parts[0] == "uploads":
+ cleaned = Path(*parts[1:]) if len(parts) > 1 else Path()
+ return dataset_uploads_root() / cleaned
+ if parts and parts[0] == "recipes":
+ cleaned = Path(*parts[1:]) if len(parts) > 1 else Path()
+ return recipe_datasets_root() / cleaned
+
+ cleaned = Path(*parts) if parts else Path()
+ candidates = [
+ dataset_uploads_root() / cleaned,
+ recipe_datasets_root() / cleaned,
+ datasets_root() / cleaned,
+ dataset_uploads_root() / cleaned.name,
+ recipe_datasets_root() / cleaned.name,
+ ]
+ for candidate in candidates:
+ if candidate.exists():
+ return candidate
+ return candidates[0]
+
+
+def resolve_cached_repo_id_case(
+ model_name: str,
+ use_memo: bool = True,
+ repo_type: str = "model",
+) -> str:
+ """Resolve repo_id to the exact casing already present in local HF cache.
+
+ Prefers the requested casing, but if a case-variant already exists in
+ local HF cache, reuses that exact cached spelling so we don't trigger
+ a duplicate download.
+ """
+ if not model_name or "/" not in model_name:
+ return model_name
+
+ cache_dirs = _hf_hub_cache_dirs()
+ if not cache_dirs:
+ return model_name
+
+ prefix = f"{repo_type}s--"
+ expected_dir = f"{prefix}{model_name.replace('/', '--')}"
+ memo_key = (repo_type, model_name)
+
+ for cache_dir in cache_dirs:
+ exact_path = cache_dir / expected_dir
+ if exact_path.is_dir():
+ if use_memo:
+ _memo_set(memo_key, model_name)
+ return model_name
+
+ if use_memo:
+ cached = _memo_get(memo_key)
+ if cached is not None:
+ if any(
+ (cache_dir / f"{prefix}{cached.replace('/', '--')}").is_dir()
+ for cache_dir in cache_dirs
+ ):
+ return cached
+ _memo_drop(memo_key)
+
+ expected_lower = expected_dir.lower()
+ try:
+ candidates: set[str] = set()
+ for cache_dir in cache_dirs:
+ for entry in cache_dir.iterdir():
+ if not entry.is_dir():
+ continue
+ if entry.name.lower() != expected_lower:
+ continue
+ # The lowercased full-name match already proves the prefix
+ # matches; a case-sensitive startswith would reject a mixed-case
+ # imported dir such as Models--Org--Repo.
+ repo_part = entry.name[len(prefix) :]
+ if not repo_part:
+ continue
+ candidates.add(repo_part.replace("--", "/"))
+
+ if candidates:
+ resolved = sorted(candidates)[0]
+ if use_memo:
+ _memo_set(memo_key, resolved)
+ return resolved
+ except Exception as exc:
+ logger.debug(f"resolve_cached_repo_id_case failed for {model_name!r}: {exc}")
+
+ return model_name
+
+
+__all__ = [
+ "assets_root",
+ "cache_root",
+ "dataset_uploads_root",
+ "datasets_root",
+ "ensure_dir",
+ "exports_root",
+ "hf_default_cache_dir",
+ "is_local_path",
+ "is_valid_gguf_variant",
+ "is_valid_repo_id",
+ "legacy_hf_cache_dir",
+ "lmstudio_model_dirs",
+ "normalize_path",
+ "ollama_model_dirs",
+ "outputs_root",
+ "path_is_same_or_child",
+ "recipe_datasets_root",
+ "resolve_cached_repo_id_case",
+ "resolve_dataset_path",
+ "studio_root",
+ "tmp_root",
+ "well_known_model_dirs",
+]
diff --git a/studio/backend/hub/utils/snapshot_filters.py b/studio/backend/hub/utils/snapshot_filters.py
new file mode 100644
index 00000000000..20674db4f01
--- /dev/null
+++ b/studio/backend/hub/utils/snapshot_filters.py
@@ -0,0 +1,110 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+from fnmatch import fnmatchcase
+from typing import Iterable
+
+
+SNAPSHOT_IGNORE_PATTERNS: tuple[str, ...] = (
+ "*.gguf",
+ "*.onnx",
+ "onnx/*",
+ "openvino/*",
+ "mlx/*",
+ "*.bin.index.json.bak",
+)
+CONSOLIDATED_PATTERN = "consolidated*"
+SNAPSHOT_WEIGHT_EXTENSIONS = (
+ ".safetensors",
+ ".bin",
+ ".pt",
+ ".pth",
+ ".ckpt",
+ ".h5",
+ ".msgpack",
+ ".npz",
+)
+SNAPSHOT_NON_BIN_WEIGHT_EXTENSIONS = tuple(
+ ext for ext in SNAPSHOT_WEIGHT_EXTENSIONS if ext != ".bin"
+)
+SNAPSHOT_BIN_WEIGHT_PREFIXES = ("model", "pytorch_model", "adapter_model")
+
+
+def _filename(sibling) -> str:
+ value = getattr(sibling, "rfilename", "")
+ return value if isinstance(value, str) else ""
+
+
+def _size(sibling) -> int:
+ value = getattr(sibling, "size", None)
+ return int(value) if isinstance(value, int) and value > 0 else 0
+
+
+def repo_ships_transformers_weights(filenames: Iterable[str]) -> bool:
+ for name in filenames:
+ base = name.rsplit("/", 1)[-1].lower()
+ if base.startswith("consolidated"):
+ continue
+ if base.endswith(SNAPSHOT_NON_BIN_WEIGHT_EXTENSIONS):
+ return True
+ if base.endswith(".bin") and base.startswith(SNAPSHOT_BIN_WEIGHT_PREFIXES):
+ return True
+ return False
+
+
+def resolve_snapshot_ignore_patterns_for_files(filenames: Iterable[str]) -> list[str]:
+ names = list(filenames)
+ ignore = list(SNAPSHOT_IGNORE_PATTERNS)
+ if repo_ships_transformers_weights(names):
+ ignore.append(CONSOLIDATED_PATTERN)
+ return ignore
+
+
+def sibling_matches_ignore(filename: str, ignore_patterns: Iterable[str]) -> bool:
+ return any(fnmatchcase(filename, pattern) for pattern in ignore_patterns)
+
+
+def snapshot_download_siblings(siblings: Iterable) -> list:
+ items = list(siblings)
+ ignore_patterns = resolve_snapshot_ignore_patterns_for_files(
+ _filename(sibling) for sibling in items
+ )
+ return [
+ sibling
+ for sibling in items
+ if not sibling_matches_ignore(_filename(sibling), ignore_patterns)
+ ]
+
+
+def snapshot_download_size(siblings: Iterable) -> int:
+ return sum(_size(sibling) for sibling in snapshot_download_siblings(siblings))
+
+
+def total_size_for_siblings(siblings: Iterable) -> int:
+ """Sum of declared sizes across siblings verbatim (no ignore filter).
+
+ Use for repo types that download every file (datasets); models go
+ through ``snapshot_download_size`` so the ignore patterns apply."""
+ return sum(_size(sibling) for sibling in siblings)
+
+
+def blob_hashes_for_siblings(siblings: Iterable) -> frozenset[str]:
+ # Blob filename == file etag (LFS sha256, else git blob id). Collecting both
+ # lets progress count exactly this revision's files without summing stale
+ # blobs from other revisions.
+ hashes: set[str] = set()
+ for sibling in siblings:
+ sha = getattr(getattr(sibling, "lfs", None), "sha256", None)
+ if isinstance(sha, str) and sha:
+ hashes.add(sha)
+ continue
+ blob_id = getattr(sibling, "blob_id", None)
+ if isinstance(blob_id, str) and blob_id:
+ hashes.add(blob_id)
+ return frozenset(hashes)
+
+
+def snapshot_download_blob_hashes(siblings: Iterable) -> frozenset[str]:
+ return blob_hashes_for_siblings(snapshot_download_siblings(siblings))
diff --git a/studio/backend/hub/utils/state_dir.py b/studio/backend/hub/utils/state_dir.py
new file mode 100644
index 00000000000..a304477a3d9
--- /dev/null
+++ b/studio/backend/hub/utils/state_dir.py
@@ -0,0 +1,154 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Filesystem layout for Hub download state.
+
+State directory sits beside HF's cache (under Studio's own cache root)
+so it survives ``huggingface-cli delete-cache`` and any other HF-side
+cache lifecycle. Two subdirectories:
+
+ <studio cache>/hub-state/
+ manifests/ <key>.json per-download expected-files manifest
+ cancelled/ <key>.json per-download cancel marker
+
+The ``<key>`` mirrors HF's cache dir naming so a state file can be
+eyeballed next to the on-disk repo it describes:
+
+ models--<owner>--<name> full snapshot
+ models--<owner>--<name>--variant--<variant> GGUF variant
+ datasets--<owner>--<name> dataset snapshot
+
+All path accessors return ``Optional[Path]`` and yield ``None`` when
+the directory can't be created (read-only FS, permission error).
+Callers must treat ``None`` as "no state available" and fall through
+to existing on-disk-only behavior; this module never raises on a
+configuration failure.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import re
+from pathlib import Path
+from typing import Literal, Optional, get_args
+
+from loggers import get_logger
+
+from hub.utils.paths import cache_root
+
+logger = get_logger(__name__)
+
+
+RepoType = Literal["model", "dataset"]
+
+_VALID_REPO_TYPES: tuple[RepoType, ...] = get_args(RepoType)
+
+
+_HUB_STATE_DIRNAME = "hub-state"
+_MANIFESTS_SUBDIR = "manifests"
+_CANCELLED_SUBDIR = "cancelled"
+_WORKERS_SUBDIR = "workers"
+_SAFE_VARIANT_FRAGMENT = re.compile(r"^[a-z0-9._-]{1,64}$")
+
+
+def state_root() -> Optional[Path]:
+ """Return the Hub state root, creating it if needed. ``None`` on failure."""
+ root = cache_root() / _HUB_STATE_DIRNAME
+ try:
+ root.mkdir(parents = True, exist_ok = True)
+ except OSError as exc:
+ logger.debug("Could not create hub state root %s: %s", root, exc)
+ return None
+ return root
+
+
+def _subdir(name: str) -> Optional[Path]:
+ root = state_root()
+ if root is None:
+ return None
+ path = root / name
+ try:
+ path.mkdir(parents = True, exist_ok = True)
+ except OSError as exc:
+ logger.debug("Could not create hub state subdir %s: %s", path, exc)
+ return None
+ return path
+
+
+def repo_cache_basename(repo_type: RepoType, repo_id: str) -> str:
+ # Reject a bad repo_type at runtime: a wrong value would silently produce a
+ # wrong filename and a misclassified scanner row (the Literal only guards
+ # statically; dynamic/JSON-sourced values slip past it).
+ if repo_type not in _VALID_REPO_TYPES:
+ raise ValueError(f"repo_type must be one of {_VALID_REPO_TYPES}, got {repo_type!r}")
+ return f"{repo_type}s--{repo_id.replace('/', '--')}".lower()
+
+
+def variant_filename_prefix(repo_type: RepoType, repo_id: str) -> str:
+ """Lowercased prefix every variant-keyed state file for this repo shares.
+
+ The single source the download_manifest enumerators match against, so the
+ scheme in :func:`_entry_key` cannot drift from them silently."""
+ return f"{repo_cache_basename(repo_type, repo_id)}--variant--"
+
+
+def _entry_key(repo_type: RepoType, repo_id: str, variant: Optional[str]) -> str:
+ base = repo_cache_basename(repo_type, repo_id)
+ if not variant:
+ return base
+ normalized_variant = variant.strip().lower()
+ if _SAFE_VARIANT_FRAGMENT.fullmatch(normalized_variant):
+ variant_fragment = normalized_variant
+ else:
+ digest = hashlib.sha256(normalized_variant.encode("utf-8")).hexdigest()[:32]
+ variant_fragment = f"sha256-{digest}"
+ return f"{variant_filename_prefix(repo_type, repo_id)}{variant_fragment}"
+
+
+def manifest_path(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> Optional[Path]:
+ """Path to the manifest file for this triple. May or may not exist."""
+ parent = _subdir(_MANIFESTS_SUBDIR)
+ if parent is None:
+ return None
+ return parent / f"{_entry_key(repo_type, repo_id, variant)}.json"
+
+
+def marker_path(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> Optional[Path]:
+ """Path to the cancel-marker file for this triple. May or may not exist."""
+ parent = _subdir(_CANCELLED_SUBDIR)
+ if parent is None:
+ return None
+ return parent / f"{_entry_key(repo_type, repo_id, variant)}.json"
+
+
+def manifests_dir() -> Optional[Path]:
+ """Manifests subdirectory, created on demand. ``None`` on failure.
+
+ Exposed for iter_variant_manifests, which enumerates the directory to find
+ every variant-keyed manifest for a repo (the path helpers above answer
+ "where would key X go" but not "what keys exist")."""
+ return _subdir(_MANIFESTS_SUBDIR)
+
+
+def cancelled_dir() -> Optional[Path]:
+ """Cancel-marker subdirectory, created on demand. ``None`` on failure.
+
+ See manifests_dir for why this iteration entry point is needed."""
+ return _subdir(_CANCELLED_SUBDIR)
+
+
+def workers_dir() -> Optional[Path]:
+ """Worker PID-breadcrumb subdirectory, created on demand. ``None`` on failure.
+
+ Each live download worker drops one breadcrumb here so a backend that
+ restarts after a hard crash can reap workers it can no longer reach through
+ its in-memory registry."""
+ return _subdir(_WORKERS_SUBDIR)
diff --git a/studio/backend/hub/workers/__init__.py b/studio/backend/hub/workers/__init__.py
new file mode 100644
index 00000000000..32014236c6a
--- /dev/null
+++ b/studio/backend/hub/workers/__init__.py
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
diff --git a/studio/backend/hub/workers/hf_download.py b/studio/backend/hub/workers/hf_download.py
new file mode 100644
index 00000000000..42a8ca52b30
--- /dev/null
+++ b/studio/backend/hub/workers/hf_download.py
@@ -0,0 +1,753 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""HuggingFace Hub download worker, spawned as a subprocess so SIGKILL stops all chunk threads.
+
+Resume safety
+-------------
+Downloads here MUST be single-stream sequential writers so the parent's
+SIGKILL → restart loop can rely on ``os.path.getsize(.incomplete)`` to
+compute the correct resume offset.
+
+Enforced by:
+- Setting ``HF_HUB_DISABLE_XET=1`` and ``HF_HUB_ENABLE_HF_TRANSFER=0`` on
+ the spawning side (see :mod:`hub.utils.download_registry`) for transport=http.
+- Passing ``max_workers=1`` to ``snapshot_download`` so files download
+ serially, making the at-most-one-active-`.incomplete` invariant hold
+ globally and simplifying reasoning about partial state during a SIGKILL.
+- Letting ``prepare_cache_for_transport`` purge any pre-existing
+ ``.incomplete`` blobs not provably from the same sequential writer.
+
+If the final byte count doesn't match what HF declared, huggingface_hub
+raises ``EnvironmentError`` ("Consistency check failed: …"); we surface
+that on stderr so the watcher can show the exact message to the user.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import signal
+import sys
+import threading
+import time
+from pathlib import Path
+
+_HERE = Path(__file__).resolve().parent
+_BACKEND = _HERE.parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+from hub.utils.snapshot_filters import (
+ SNAPSHOT_IGNORE_PATTERNS,
+)
+from hub.utils.gguf_plan import (
+ GgufVariantPlan,
+ build_gguf_variant_plans,
+ plan_from_expected_files,
+ sibling_sha256,
+)
+from hub.utils.state_dir import RepoType
+
+HfTokenArg = str | bool | None
+
+
+# Bound the metadata fetch so a stalled connection fails the worker (exit 1)
+# instead of hanging at 0%. The file download itself is governed separately by
+# huggingface_hub's own timeout.
+_METADATA_REQUEST_TIMEOUT = 10.0
+_METADATA_RETRY_TIMEOUT = 30.0
+_METADATA_RETRY_DELAY = 1.0
+
+
+def _on_signal(signum, frame):
+ # 130 is what `classify_exit` maps to the "cancelled" job state.
+ sys.exit(130)
+
+
+def _install_signal_handlers() -> None:
+ signal.signal(signal.SIGTERM, _on_signal)
+ signal.signal(signal.SIGINT, _on_signal)
+ sigpipe = getattr(signal, "SIGPIPE", None)
+ if sigpipe is not None:
+ signal.signal(sigpipe, _on_signal)
+
+
+def _parent_poll_seconds() -> float:
+ raw = os.environ.get("UNSLOTH_HF_WORKER_PARENT_POLL_SECONDS")
+ if raw:
+ try:
+ value = float(raw)
+ if value > 0:
+ return value
+ except ValueError:
+ pass
+ return 2.0
+
+
+def _protected_blob_hashes() -> frozenset[str]:
+ """Blob hashes a concurrent same-repo peer is writing (passed by the backend
+ as a plain env list). Excluded from this worker's purge so a shared
+ ``.incomplete`` (e.g. a bundled mmproj) is never deleted under the peer."""
+ raw = os.environ.get("UNSLOTH_PROTECTED_BLOB_HASHES", "")
+ return frozenset(h for h in raw.split(",") if h)
+
+
+def _parent_is_alive(parent_pid: int) -> bool:
+ """Whether the recorded parent (the backend) is still running.
+
+ Liveness ONLY: ``os.kill(pid, 0)`` on POSIX, an ``OpenProcess`` handle on
+ Windows, against the *recorded* PID (never os.getppid(), so POSIX
+ reparenting to init after the backend dies still resolves as dead). Probe
+ ambiguity is treated as alive so a transient error never kills a healthy
+ download.
+
+ We deliberately do NOT compare psutil ``create_time()`` for PID-reuse
+ detection: it isn't stable across reads on some platforms, so an exact match
+ can spuriously kill a live download. PID-reuse after parent death is covered
+ by the boot-time orphan reaper.
+ """
+ if sys.platform == "win32":
+ import ctypes
+ from ctypes import wintypes
+
+ SYNCHRONIZE = 0x00100000
+ WAIT_OBJECT_0 = 0x0
+ ERROR_INVALID_PARAMETER = 87
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ kernel32.OpenProcess.restype = wintypes.HANDLE
+ kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
+ kernel32.WaitForSingleObject.restype = wintypes.DWORD
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+ ctypes.set_last_error(0)
+ handle = kernel32.OpenProcess(SYNCHRONIZE, False, parent_pid)
+ if not handle:
+ return ctypes.get_last_error() != ERROR_INVALID_PARAMETER
+ try:
+ return kernel32.WaitForSingleObject(handle, 0) != WAIT_OBJECT_0
+ finally:
+ kernel32.CloseHandle(handle)
+ try:
+ os.kill(parent_pid, 0)
+ except ProcessLookupError:
+ return False
+ except OSError:
+ return True
+ return True
+
+
+def _terminate_orphaned_self() -> None:
+ # Hard exit from the watchdog thread: a self-SIGTERM would be deferred while
+ # the main thread is GIL-blocked in a C socket read. The partial .incomplete
+ # resumes byte-exact and marker/manifest writes are atomic, so cancelled code
+ # 130 is safe. The diagnostic is best-effort: a dead parent's closed stderr
+ # pipe can raise BrokenPipeError, which must never preempt the exit.
+ try:
+ print(
+ "Parent process exited; stopping orphaned download worker.",
+ file = sys.stderr,
+ )
+ sys.stderr.flush()
+ except Exception:
+ pass
+ os._exit(130)
+
+
+def _install_parent_death_watchdog(parent_pid: int | None) -> None:
+ if not parent_pid or parent_pid <= 0:
+ return
+ interval = _parent_poll_seconds()
+
+ def _watch() -> None:
+ while True:
+ try:
+ alive = _parent_is_alive(parent_pid)
+ except Exception:
+ alive = True
+ if not alive:
+ _terminate_orphaned_self()
+ return
+ time.sleep(interval)
+
+ threading.Thread(
+ target = _watch,
+ name = "parent-death-watchdog",
+ daemon = True,
+ ).start()
+
+
+def _hf_token_arg(hf_token: str | None) -> HfTokenArg:
+ return hf_token if hf_token else False
+
+
+def _retry_metadata_fetch(repo_id: str, fetch, *, label: str):
+ for attempt, timeout in enumerate((_METADATA_REQUEST_TIMEOUT, _METADATA_RETRY_TIMEOUT)):
+ try:
+ return fetch(timeout)
+ except Exception as e:
+ if attempt == 1:
+ raise
+ print(
+ f"{label} request failed for {repo_id} " f"({type(e).__name__}: {e}); retrying.",
+ file = sys.stderr,
+ )
+ time.sleep(_METADATA_RETRY_DELAY)
+ raise RuntimeError(f"{label} unavailable for {repo_id}")
+
+
+def _model_info_with_retry(repo_id: str, hf_token: str | None):
+ from huggingface_hub import model_info as hf_model_info
+ return _retry_metadata_fetch(
+ repo_id,
+ lambda timeout: hf_model_info(
+ repo_id,
+ token = _hf_token_arg(hf_token),
+ timeout = timeout,
+ files_metadata = True,
+ ),
+ label = "Metadata",
+ )
+
+
+def _dataset_info_with_retry(repo_id: str, hf_token: str | None):
+ from huggingface_hub import HfApi
+ api = HfApi(token = _hf_token_arg(hf_token))
+ return _retry_metadata_fetch(
+ repo_id,
+ lambda timeout: api.dataset_info(
+ repo_id,
+ timeout = timeout,
+ files_metadata = True,
+ ),
+ label = "Dataset metadata",
+ )
+
+
+# Tied to drain_stderr_excerpt's 500-byte head/tail window in the parent (see
+# hub/utils/download_registry.py): listing every expected file would blow past
+# it and lose the diagnostic. Cap the preview so the summary line survives.
+_VERIFY_PATH_LIST_CAP = 10
+
+
+def _format_path_list(paths: tuple[str, ...], cap: int = _VERIFY_PATH_LIST_CAP) -> str:
+ if len(paths) <= cap:
+ return ", ".join(paths)
+ head = ", ".join(paths[:cap])
+ return f"{head}, ... and {len(paths) - cap} more"
+
+
+def _verify_completed_download(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: str | None,
+ snapshot_path: str,
+ *,
+ metadata_unavailable: bool = False,
+) -> None:
+ """Verify every manifest file is on disk at its declared size; exit nonzero
+ with a diagnostic if not.
+
+ No-op when no manifest exists: the manifest write is best-effort, so absence
+ means "verification unavailable, trust snapshot_download's exit code".
+ """
+ from hub.utils import download_manifest
+
+ manifest = download_manifest.read_manifest(repo_type, repo_id, variant)
+ if manifest is None:
+ return
+ result = download_manifest.verify_against_disk(
+ manifest,
+ Path(snapshot_path),
+ )
+ if result.ok:
+ return
+ label = f"{repo_id}{f' [{variant}]' if variant else ''}"
+ if metadata_unavailable:
+ print(
+ f"Could not reach Hugging Face for {label} and the copy on disk is "
+ f"incomplete ({len(result.missing)} file(s) missing, "
+ f"{len(result.size_mismatched)} the wrong size). Access to a private "
+ "or restricted repo may have been lost (HF token removed or "
+ "changed), the connection dropped, or Hugging Face is temporarily "
+ "unavailable. Set a valid HF token or reconnect, then resume the "
+ "download.",
+ file = sys.stderr,
+ )
+ else:
+ print(
+ f"Verification failed for {label}: snapshot_download completed but "
+ f"{len(result.missing)} expected file(s) are missing and "
+ f"{len(result.size_mismatched)} have incorrect size on disk.",
+ file = sys.stderr,
+ )
+ if result.missing:
+ print(
+ f"Missing: {_format_path_list(result.missing)}",
+ file = sys.stderr,
+ )
+ if result.size_mismatched:
+ print(
+ f"Size mismatched: {_format_path_list(result.size_mismatched)}",
+ file = sys.stderr,
+ )
+ sys.exit(1)
+
+
+def _preflight_disk_space(repo_type: str, repo_id: str, expected_files: list) -> None:
+ """Fail fast when the active HF cache filesystem can't hold what's left to
+ download. Fail-open: any inability to size the work or read free space skips
+ the check, so a real download is never blocked by an estimation gap."""
+ import shutil
+
+ from hub.utils.download_registry import existing_blob_bytes
+ from hub.utils.hf_cache_state import hf_cache_root
+
+ try:
+ size_by_hash: dict[str, int] = {}
+ unhashed_bytes = 0
+ for expected in expected_files:
+ size = int(getattr(expected, "size", 0) or 0)
+ if size <= 0:
+ continue
+ blob_hash = getattr(expected, "sha256", None)
+ if blob_hash:
+ # Dedup by content hash: a blob listed under two filenames is
+ # written once, so it must be counted once.
+ size_by_hash[blob_hash] = size
+ else:
+ unhashed_bytes += size
+ total_expected = sum(size_by_hash.values()) + unhashed_bytes
+ if total_expected <= 0:
+ return
+ already_have = existing_blob_bytes(
+ repo_type,
+ repo_id,
+ frozenset(size_by_hash),
+ )
+ remaining = max(0, total_expected - already_have)
+ if remaining <= 0:
+ return
+ root = hf_cache_root(create = True)
+ if root is None:
+ return
+ free = shutil.disk_usage(root).free
+ except Exception:
+ return
+
+ if free < remaining:
+ print(
+ f"Not enough disk space to download {repo_id}: need about "
+ f"{remaining / (1024 ** 3):.1f} GB free in {root}, but only "
+ f"{free / (1024 ** 3):.1f} GB is available. Free up space and "
+ "try again.",
+ file = sys.stderr,
+ )
+ sys.exit(1)
+
+
+def _snapshot_download_plan(info) -> tuple[list[str], list]:
+ from hub.utils.download_manifest import ExpectedFile
+ from hub.utils.snapshot_filters import (
+ resolve_snapshot_ignore_patterns_for_files,
+ snapshot_download_siblings,
+ )
+
+ filenames = [s.rfilename for s in info.siblings if isinstance(s.rfilename, str)]
+ filtered = snapshot_download_siblings(info.siblings)
+ expected_files = [
+ ExpectedFile(
+ path = s.rfilename,
+ size = int(getattr(s, "size", 0) or 0),
+ sha256 = sibling_sha256(s),
+ )
+ for s in filtered
+ if isinstance(s.rfilename, str)
+ ]
+ return resolve_snapshot_ignore_patterns_for_files(filenames), expected_files
+
+
+def _dataset_expected_files(info) -> list:
+ from hub.utils.download_manifest import ExpectedFile
+ return [
+ ExpectedFile(
+ path = s.rfilename,
+ size = int(getattr(s, "size", 0) or 0),
+ sha256 = sibling_sha256(s),
+ )
+ for s in info.siblings
+ if isinstance(s.rfilename, str)
+ ]
+
+
+def _recover_manifest_after_download(
+ repo_type: RepoType,
+ repo_id: str,
+ snapshot_path: str,
+ mode: str,
+ *,
+ fetch_info,
+ expected_files_from_info,
+ label: str = "",
+) -> None:
+ """Best-effort manifest write for a download whose metadata was unavailable
+ at start: re-fetch and record the expected files, else fall back to the
+ on-disk file list. Shared by the model and dataset workers.
+
+ A pre-existing manifest is authoritative and is preserved untouched. This is
+ load-bearing: when access is lost on resume (token revoked/changed on a
+ gated/private repo), snapshot_download returns the cached partial snapshot
+ WITHOUT downloading, so rebuilding the manifest from on-disk files would record
+ the partial set as expected and let _verify_completed_download certify a
+ half-finished download as complete.
+
+ The same hazard exists with NO prior manifest. When metadata is still
+ unavailable here, leftover ``.incomplete`` blobs prove a cached partial was
+ returned without downloading, so we fail (exit 1) instead of deriving a
+ self-certifying manifest, leaving the partial intact for a later resume. That
+ signal misses a file that never started (no ``.incomplete``), so a kill
+ between files is accepted optimistically from the on-disk subset; a later
+ metadata-bearing attempt writes the true manifest and catches any shortfall."""
+ from hub.utils import download_manifest
+ from hub.utils.hf_cache_state import has_active_incomplete_blobs
+
+ if download_manifest.read_manifest(repo_type, repo_id, None) is not None:
+ return
+
+ try:
+ if download_manifest.write_manifest(
+ repo_type,
+ repo_id,
+ None,
+ expected_files_from_info(fetch_info()),
+ mode,
+ ):
+ return
+ reason = "manifest write failed"
+ except Exception as e:
+ reason = f"{type(e).__name__}: {e}"
+
+ if has_active_incomplete_blobs(repo_type, repo_id):
+ print(
+ f"{label}could not reach Hugging Face for {repo_id} and the copy on "
+ "disk is still incomplete. Access to a private or restricted repo may "
+ "have been lost (HF token removed or changed), the connection dropped, "
+ "or Hugging Face is temporarily unavailable. Set a valid HF token or "
+ "reconnect, then resume the download.",
+ file = sys.stderr,
+ )
+ sys.exit(1)
+
+ fallback_files = download_manifest.expected_files_from_snapshot_dir(Path(snapshot_path))
+ if fallback_files and download_manifest.write_manifest(
+ repo_type,
+ repo_id,
+ None,
+ fallback_files,
+ mode,
+ ):
+ print(
+ f"{label}could not record the metadata manifest for {repo_id}, "
+ "recorded one from the downloaded files so completion "
+ f"is tracked ({reason})",
+ file = sys.stderr,
+ )
+ else:
+ print(
+ f"{label}could not record the metadata manifest for {repo_id}, "
+ f"{download_manifest.MANIFEST_DEGRADED_MARKER} ({reason})",
+ file = sys.stderr,
+ )
+
+
+def _download_snapshot(repo_id: str, hf_token: str | None, mode: str) -> None:
+ from huggingface_hub import snapshot_download
+ from hub.utils.download_registry import prepare_cache_for_transport
+ from hub.utils import download_manifest
+
+ # One metadata fetch powers both the ignore-pattern decision (drop
+ # consolidated.* when transformers weights exist) and the manifest's
+ # expected_files. A failure is non-fatal: fall back to the legacy
+ # ignore-pattern set (keeping consolidated) and skip the manifest, so
+ # download proceeds without the verification + partial detection it enables.
+ try:
+ info = _model_info_with_retry(repo_id, hf_token)
+ except Exception as e:
+ print(
+ f"metadata unavailable, downloading full snapshot for {repo_id} "
+ f"({type(e).__name__}: {e})",
+ file = sys.stderr,
+ )
+ info = None
+
+ download_manifest.clear_cancel_marker("model", repo_id, None)
+ if info is not None:
+ ignore_patterns, expected_files = _snapshot_download_plan(info)
+ # Written for every transport. The manifest verifies the finalized
+ # files under snapshots/, which both transports produce identically
+ # (XET also renames a full, correctly-sized blob into place). XET's
+ # block-level dedup lives only in the chunk-cache the manifest never
+ # inspects, so per-file size verification is valid regardless of transport.
+ download_manifest.write_manifest("model", repo_id, None, expected_files, mode)
+ else:
+ ignore_patterns = list(SNAPSHOT_IGNORE_PATTERNS)
+ expected_files = []
+
+ purged = prepare_cache_for_transport("model", repo_id, mode)
+ if purged:
+ print(
+ f"Purged {purged} untrusted partial blob(s) for {repo_id} "
+ f"before starting {mode} download.",
+ file = sys.stderr,
+ )
+ _preflight_disk_space("model", repo_id, expected_files)
+ snapshot_path = snapshot_download(
+ repo_id = repo_id,
+ token = _hf_token_arg(hf_token),
+ ignore_patterns = ignore_patterns,
+ max_workers = 1,
+ )
+ if info is None:
+ _recover_manifest_after_download(
+ "model",
+ repo_id,
+ snapshot_path,
+ mode,
+ fetch_info = lambda: _model_info_with_retry(repo_id, hf_token),
+ expected_files_from_info = lambda recovered: _snapshot_download_plan(recovered)[1],
+ )
+ _verify_completed_download(
+ "model",
+ repo_id,
+ None,
+ snapshot_path,
+ metadata_unavailable = info is None,
+ )
+
+
+def _gguf_variant_target_plan(
+ repo_id: str, variant: str, hf_token: str | None
+) -> GgufVariantPlan | None:
+ try:
+ info = _model_info_with_retry(repo_id, hf_token)
+ except Exception as e:
+ print(
+ f"metadata unavailable, cannot resolve GGUF variant '{variant}' "
+ f"for {repo_id} ({type(e).__name__}: {e})",
+ file = sys.stderr,
+ )
+ raise RuntimeError(
+ f"Metadata unavailable while resolving GGUF variant '{variant}' " f"for {repo_id}"
+ ) from e
+ return build_gguf_variant_plans(list(info.siblings)).get(variant.lower())
+
+
+def _download_gguf_variant(repo_id: str, variant: str, hf_token: str | None, mode: str) -> None:
+ from huggingface_hub import snapshot_download
+ from hub.utils.download_registry import prepare_cache_for_transport
+ from hub.utils.hf_cache_state import has_active_incomplete_blobs
+ from hub.utils import download_manifest
+
+ metadata_unavailable = False
+ try:
+ plan = _gguf_variant_target_plan(repo_id, variant, hf_token)
+ except RuntimeError:
+ plan = None
+ metadata_unavailable = True
+
+ if not metadata_unavailable:
+ if plan is None:
+ print(
+ f"No GGUF shards matching variant '{variant}' in {repo_id}",
+ file = sys.stderr,
+ )
+ sys.exit(1)
+ targets = list(plan.target_filenames)
+ expected_files = list(plan.expected_files)
+ main_blob_hashes = plan.main_hashes
+ companion_blob_hashes = plan.companion_hashes
+ download_manifest.write_manifest(
+ "model",
+ repo_id,
+ variant,
+ expected_files,
+ mode,
+ )
+ else:
+ # Metadata unreachable (offline / gated / private). Resume the exact
+ # shards the original attempt recorded so snapshot_download can range
+ # over the surviving .incomplete blobs without a model_info call.
+ manifest = download_manifest.read_manifest("model", repo_id, variant)
+ if manifest is None or not manifest.expected_files:
+ print(
+ f"Metadata unavailable and no manifest to resume GGUF "
+ f"variant '{variant}' for {repo_id}",
+ file = sys.stderr,
+ )
+ sys.exit(1)
+ plan = plan_from_expected_files(variant, manifest.expected_files)
+ targets = list(plan.target_filenames)
+ expected_files = list(plan.expected_files)
+ download_manifest.write_manifest(
+ "model",
+ repo_id,
+ variant,
+ expected_files,
+ mode,
+ )
+ main_blob_hashes = plan.main_hashes
+ companion_blob_hashes = plan.companion_hashes
+ print(
+ f"Metadata unavailable; resuming GGUF variant '{variant}' for "
+ f"{repo_id} from the existing manifest.",
+ file = sys.stderr,
+ )
+
+ download_manifest.clear_cancel_marker("model", repo_id, variant)
+ purge_blob_hashes = main_blob_hashes
+ if not main_blob_hashes:
+ if has_active_incomplete_blobs("model", repo_id):
+ print(
+ f"GGUF variant '{variant}' for {repo_id} has partial cache state "
+ "but no resolvable blob hashes; delete the partial download or "
+ "retry when metadata is available.",
+ file = sys.stderr,
+ )
+ sys.exit(1)
+ purge_blob_hashes = frozenset()
+ print(
+ f"GGUF variant '{variant}' for {repo_id} has no resolvable blob "
+ "hashes; starting without partial cache reuse.",
+ file = sys.stderr,
+ )
+ # Main quant blobs are owned by this variant (variant-scoped marker). The
+ # shared vision companion (mmproj) is judged by a separate companion marker
+ # and never purged while a concurrent peer is writing it.
+ purged = prepare_cache_for_transport(
+ "model",
+ repo_id,
+ mode,
+ variant,
+ only_blob_hashes = purge_blob_hashes,
+ companion_blob_hashes = companion_blob_hashes,
+ protected_blob_hashes = _protected_blob_hashes(),
+ )
+ if purged:
+ print(
+ f"Purged {purged} untrusted partial blob(s) for {repo_id} "
+ f"before starting {mode} download.",
+ file = sys.stderr,
+ )
+ _preflight_disk_space("model", repo_id, expected_files)
+ snapshot_path = snapshot_download(
+ repo_id = repo_id,
+ token = _hf_token_arg(hf_token),
+ allow_patterns = targets,
+ max_workers = 1,
+ )
+ _verify_completed_download(
+ "model",
+ repo_id,
+ variant,
+ snapshot_path,
+ metadata_unavailable = metadata_unavailable,
+ )
+
+
+def _download_dataset(repo_id: str, hf_token: str | None, mode: str) -> None:
+ from huggingface_hub import snapshot_download
+ from hub.utils.download_registry import prepare_cache_for_transport
+ from hub.utils import download_manifest
+
+ try:
+ info = _dataset_info_with_retry(repo_id, hf_token)
+ except Exception as e:
+ print(
+ f"dataset metadata unavailable, downloading full dataset for {repo_id} "
+ f"({type(e).__name__}: {e})",
+ file = sys.stderr,
+ )
+ info = None
+ # Cancel-marker clear and manifest write run on every transport. See
+ # _download_snapshot for why per-file size verification is valid under XET.
+ download_manifest.clear_cancel_marker("dataset", repo_id, None)
+ if info is not None:
+ expected_files = _dataset_expected_files(info)
+ download_manifest.write_manifest(
+ "dataset",
+ repo_id,
+ None,
+ expected_files,
+ mode,
+ )
+ else:
+ expected_files = []
+ purged = prepare_cache_for_transport("dataset", repo_id, mode)
+ if purged:
+ print(
+ f"Purged {purged} untrusted partial blob(s) for {repo_id} "
+ f"before starting {mode} download.",
+ file = sys.stderr,
+ )
+ _preflight_disk_space("dataset", repo_id, expected_files)
+ snapshot_path = snapshot_download(
+ repo_id = repo_id,
+ token = _hf_token_arg(hf_token),
+ repo_type = "dataset",
+ max_workers = 1,
+ )
+ if info is None:
+ _recover_manifest_after_download(
+ "dataset",
+ repo_id,
+ snapshot_path,
+ mode,
+ fetch_info = lambda: _dataset_info_with_retry(repo_id, hf_token),
+ expected_files_from_info = _dataset_expected_files,
+ label = "dataset ",
+ )
+ _verify_completed_download(
+ "dataset",
+ repo_id,
+ None,
+ snapshot_path,
+ metadata_unavailable = info is None,
+ )
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description = "HuggingFace Hub download worker")
+ parser.add_argument("--repo-id", required = True)
+ parser.add_argument("--variant", default = None)
+ parser.add_argument("--dataset", action = "store_true")
+ parser.add_argument("--transport", choices = ("http", "xet"), default = "http")
+ parser.add_argument("--parent-pid", type = int, default = None)
+ args = parser.parse_args()
+
+ _install_signal_handlers()
+ _install_parent_death_watchdog(args.parent_pid)
+
+ hf_token = os.environ.get("HF_TOKEN") or None
+
+ try:
+ if args.dataset:
+ _download_dataset(args.repo_id, hf_token, args.transport)
+ elif args.variant:
+ _download_gguf_variant(args.repo_id, args.variant, hf_token, args.transport)
+ else:
+ _download_snapshot(args.repo_id, hf_token, args.transport)
+ sys.exit(0)
+ except SystemExit:
+ raise
+ except Exception as e:
+ # Surface a precise message so the UI doesn't show a generic "worker
+ # exited with code 1". huggingface_hub's consistency check recommends
+ # force_download=True to recover, which our "Restart" UI maps to a fresh
+ # start by purging the partial via prepare_cache_for_transport.
+ print(f"{type(e).__name__}: {e}", file = sys.stderr)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 104d557eea4..a9f7004df76 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -8,6 +8,8 @@ Main FastAPI application for Unsloth UI Backend
import os
import sys
from pathlib import Path as _Path
+import asyncio
+from dataclasses import asdict
# Suppress C-level dependency warnings globally
os.environ["PYTHONWARNINGS"] = "ignore"
@@ -217,6 +219,16 @@ from routes import (
training_history_router,
training_router,
)
+from hub.routes import (
+ inventory_router as hub_inventory_router,
+ datasets_router as hub_datasets_router,
+)
+from hub.schemas.downloads import TransportCapabilities
+from hub.utils.download_registry import (
+ get_download_transport_capabilities,
+ reap_orphan_workers as reap_hub_orphan_workers,
+ terminate_active_downloads as terminate_hub_downloads,
+)
from routes.settings import router as settings_router
from auth import storage
from auth.authentication import get_current_subject
@@ -293,6 +305,9 @@ async def lifespan(app: FastAPI):
# Detect hardware first — sets the DEVICE global used everywhere.
detect_hardware()
+ # Reap download workers orphaned by a previous crash before new downloads start.
+ reap_hub_orphan_workers()
+
# llama.cpp probes: capability (MTP support) + freshness (release age).
# Both cached; freshness has a 24h disk TTL.
try:
@@ -367,6 +382,7 @@ async def lifespan(app: FastAPI):
else:
app.state.bootstrap_password = storage.get_bootstrap_password()
yield
+ await asyncio.to_thread(terminate_hub_downloads)
_hw_module.DEVICE = None
clear_unsloth_compiled_cache()
@@ -389,8 +405,8 @@ logger = LogConfig.setup_logging(
app.add_middleware(LoggingMiddleware)
-# Citation favicons load from www.google.com/s2/favicons; *.gstatic.com is
-# kept for legacy web-search faviconV2 paths. All else is same-origin.
+# img/media-src allow any https origin so HF model-card assets render (mirrors
+# tauri.conf.json); scripts/frames/connect-src stay same-origin + HF.
from starlette.middleware.base import BaseHTTPMiddleware # noqa: E402
from starlette.requests import Request as _StarletteRequest # noqa: E402
@@ -435,9 +451,8 @@ def _build_csp(script_nonce: "str | None" = None) -> str:
return (
"default-src 'self'; "
- "img-src 'self' data: blob: https://t0.gstatic.com "
- "https://t1.gstatic.com https://t2.gstatic.com "
- "https://t3.gstatic.com https://www.google.com; "
+ "img-src 'self' data: blob: https:; "
+ "media-src 'self' data: blob: https:; "
f"connect-src {connect_src}; "
"style-src 'self' 'unsafe-inline'; "
f"{script_src}; "
@@ -491,6 +506,7 @@ _BODY_PROTECTED_PREFIXES = (
"/api/inference",
"/api/data-recipe",
"/api/datasets",
+ "/api/hub",
"/api/chat",
"/api/settings",
"/api/train",
@@ -714,6 +730,8 @@ app.include_router(datasets_router, prefix = "/api/datasets", tags = ["datasets"
app.include_router(data_recipe_router, prefix = "/api/data-recipe", tags = ["data-recipe"])
app.include_router(export_router, prefix = "/api/export", tags = ["export"])
app.include_router(training_history_router, prefix = "/api/train", tags = ["training-history"])
+app.include_router(hub_inventory_router, prefix = "/api/hub", tags = ["hub"])
+app.include_router(hub_datasets_router, prefix = "/api/hub/datasets", tags = ["hub"])
# ============ Health and System Endpoints ============
@@ -781,6 +799,14 @@ def studio_update_status(_current_subject: str = Depends(get_current_subject)):
return get_studio_update_status(UNSLOTH_VERSION)
+ "/api/studio/download-transport-capabilities",
+ response_model = TransportCapabilities,
+)
+def studio_download_transport_capabilities(_current_subject: str = Depends(get_current_subject)):
+ return asdict(get_download_transport_capabilities())
+
+
@app.post("/api/shutdown")
async def shutdown_server(request: Request, current_subject: str = Depends(get_current_subject)):
"""Gracefully shut down the Unsloth Studio server.
@@ -788,7 +814,6 @@ async def shutdown_server(request: Request, current_subject: str = Depends(get_c
Called by the frontend quit dialog so users can stop the server from the UI
without the CLI or killing the process manually.
"""
- import asyncio
async def _delayed_shutdown():
await asyncio.sleep(0.2) # Let the HTTP response return first
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index 16a7bbc46de..1005431926a 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -276,25 +276,22 @@ class TestSecurityHeadersMiddleware:
nonced = main_module._build_csp("XYZ")
assert "script-src 'self' 'nonce-XYZ';" in nonced
- def test_img_src_allows_google_favicons(self, main_module):
- # sources.tsx fetches https://www.google.com/s2/favicons?... ; without
- # this allowlist entry, citation favicons fall back to gray initials.
+ def test_img_and_media_allow_https_sources(self, main_module):
+ # Model-card READMEs and citation favicons pull images/media from many
+ # https origins (HF LFS/XET CDNs, shields/badge hosts, GitHub-hosted
+ # assets, audio/video samples). img-src/media-src allow any https source
+ # so they render; this mirrors the desktop CSP in tauri.conf.json.
csp = main_module._build_csp()
- img_directive = next(
- chunk.strip() for chunk in csp.split(";") if chunk.strip().startswith("img-src ")
- )
- # Tokenise and compare with `==` so CodeQL's URL-substring rule
- # doesn't read directive-string `in` membership as URL sanitisation.
- img_sources = img_directive.split()
- assert any(src == "https://www.google.com" for src in img_sources)
- # Pre-existing favicon CDNs stay allowed.
- for host in (
- "https://t0.gstatic.com",
- "https://t1.gstatic.com",
- "https://t2.gstatic.com",
- "https://t3.gstatic.com",
- ):
- assert any(src == host for src in img_sources)
+ directives = {
+ chunk.strip().split()[0]: chunk.strip().split()
+ for chunk in csp.split(";")
+ if chunk.strip()
+ }
+ for name in ("img-src", "media-src"):
+ assert name in directives, f"missing {name} directive"
+ # Tokenise and compare with `==` so CodeQL's URL-substring rule does
+ # not read directive-string `in` membership as URL sanitisation.
+ assert any(src == "https:" for src in directives[name])
# /api/health auth gate
diff --git a/studio/frontend/package-lock.json b/studio/frontend/package-lock.json
index f36f2d8e790..7d1283e94de 100644
--- a/studio/frontend/package-lock.json
+++ b/studio/frontend/package-lock.json
@@ -31,6 +31,7 @@
"@tailwindcss/vite": "^4.2.2",
"@tanstack/react-router": "1.169.2",
"@tanstack/react-table": "^8.21.3",
+ "@tanstack/react-virtual": "3.13.25",
"@tauri-apps/api": "^2.10.1",
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
"@tauri-apps/plugin-notification": "^2.3.3",
@@ -6112,6 +6113,23 @@
"react-dom": ">=16.8"
}
},
+ "node_modules/@tanstack/react-virtual": {
+ "version": "3.13.25",
+ "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.25.tgz",
+ "integrity": "sha512-bmNoqMu6gcAW9JGrKVB0Q1tN1i5RONZF8r1fW0bbE4Oyf3DwEGnzzQJ2OW+Ozg1P4s8PyugkHg2ULZoFQN+cqw==",
+ "license": "MIT",
+ "dependencies": {
+ "@tanstack/virtual-core": "3.15.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/@tanstack/router-core": {
"version": "1.169.2",
"resolved": "https://registry.npmjs.org/@tanstack/router-core/-/router-core-1.169.2.tgz",
@@ -6154,6 +6172,16 @@
"url": "https://github.com/sponsors/tannerlinsley"
}
},
+ "node_modules/@tanstack/virtual-core": {
+ "version": "3.15.0",
+ "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.15.0.tgz",
+ "integrity": "sha512-0AwPGx0I8QxPYjAxShT/+z+ZOe9u8mW5rsXvivCTjRfRmz9a43+3mRyi4wwlyoUqOC56q/jatKa0Bh9M99BEHQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ }
+ },
"node_modules/@tauri-apps/api": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.11.0.tgz",
diff --git a/studio/frontend/package.json b/studio/frontend/package.json
index 5ba0db143f3..8537b0c076e 100644
--- a/studio/frontend/package.json
+++ b/studio/frontend/package.json
@@ -40,6 +40,7 @@
"@tailwindcss/vite": "^4.2.2",
"@tanstack/react-router": "1.169.2",
"@tanstack/react-table": "^8.21.3",
+ "@tanstack/react-virtual": "3.13.25",
"@tauri-apps/api": "^2.10.1",
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
"@tauri-apps/plugin-notification": "^2.3.3",
diff --git a/studio/frontend/public/hub/profile/logo/anthropic.svg b/studio/frontend/public/hub/profile/logo/anthropic.svg
new file mode 100644
index 00000000000..7545cc8f3e4
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/anthropic.svg
@@ -0,0 +1,6 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="900" height="900" viewBox="0 0 900 900">
+<g>
+<path d="M 222.16 664.50 L 212.35 691.50 L 206.42 691.53 C163.39,691.75 102.00,690.80 102.00,689.92 C102.00,689.34 103.32,685.63 104.94,681.68 C106.56,677.73 124.74,632.20 145.34,580.50 C165.94,528.80 205.07,430.70 232.29,362.50 C259.51,294.30 284.65,231.20 288.14,222.28 L 294.50 206.05 L 404.68 206.00 L 405.94 208.75 C407.23,211.56 413.90,227.98 437.50,286.50 C444.82,304.65 453.36,325.80 456.49,333.50 C459.61,341.20 475.70,381.02 492.24,422.00 C508.78,462.98 528.13,510.90 535.25,528.50 C542.36,546.10 553.72,574.22 560.48,591.00 C567.25,607.78 575.81,628.92 579.50,638.00 C585.05,651.65 598.92,686.11 600.73,690.76 C601.12,691.76 590.44,691.97 547.95,691.76 L 494.69 691.50 L 489.31 678.00 C486.35,670.58 481.94,659.33 479.52,653.00 C477.10,646.67 471.91,633.17 468.00,623.00 C464.08,612.83 459.67,601.24 458.19,597.25 L 455.51 590.00 L 249.31 590.00 L 245.56 600.25 C237.09,623.44 231.46,638.87 222.16,664.50 ZM 798.00 691.05 C798.00,691.64 777.31,692.00 743.50,692.00 C703.78,692.00 689.00,691.69 689.00,690.87 C689.00,690.26 685.87,681.82 682.04,672.12 C678.21,662.43 670.76,643.47 665.49,630.00 C660.21,616.53 652.36,596.50 648.03,585.50 C638.84,562.16 624.19,524.76 620.02,514.00 C615.63,502.69 600.65,464.57 593.49,446.50 C590.00,437.70 582.57,418.80 576.98,404.50 C562.77,368.16 549.76,334.97 543.27,318.50 C540.24,310.80 536.29,300.67 534.50,296.00 C532.71,291.33 526.45,275.35 520.59,260.50 C514.73,245.65 507.70,227.83 504.97,220.91 C502.23,213.98 500.00,207.85 500.00,207.29 C500.00,204.88 522.83,204.39 576.12,205.66 L 603.75 206.32 L 624.52 257.91 C635.94,286.28 646.96,313.77 649.01,319.00 C651.05,324.23 663.76,355.95 677.26,389.50 C699.90,445.80 737.77,540.07 780.62,646.80 C790.18,670.61 798.00,690.53 798.00,691.05 ZM 285.33 500.42 C285.62,501.18 305.07,501.42 351.82,501.24 L 417.90 500.97 L 415.37 494.24 C413.98,490.53 410.81,482.33 408.32,476.00 C405.83,469.67 403.42,463.38 402.98,462.00 C402.53,460.62 398.95,451.17 395.03,441.00 C391.11,430.83 384.57,413.73 380.50,403.00 C376.42,392.27 369.89,375.17 365.97,365.00 C362.05,354.83 357.46,342.77 355.77,338.20 C354.08,333.64 352.38,330.26 352.00,330.70 C351.61,331.14 347.21,341.85 342.21,354.50 C333.07,377.64 317.55,416.89 296.36,470.42 C290.06,486.32 285.10,499.82 285.33,500.42 Z" fill="rgb(37,37,36)"/>
+<path d="M 0.00 450.00 L 0.00 0.00 L 450.00 0.00 L 900.00 0.00 L 900.00 450.00 L 900.00 900.00 L 450.00 900.00 L 0.00 900.00 L 0.00 450.00 ZM 222.16 664.50 C231.46,638.87 237.09,623.44 245.56,600.25 L 249.31 590.00 L 352.41 590.00 L 455.51 590.00 L 458.19 597.25 C459.67,601.24 464.08,612.83 468.00,623.00 C471.91,633.17 477.10,646.67 479.52,653.00 C481.94,659.33 486.35,670.58 489.31,678.00 L 494.69 691.50 L 547.95 691.76 C590.44,691.97 601.12,691.76 600.73,690.76 C598.92,686.11 585.05,651.65 579.50,638.00 C575.81,628.92 567.25,607.78 560.48,591.00 C553.72,574.22 542.36,546.10 535.25,528.50 C528.13,510.90 508.78,462.98 492.24,422.00 C475.70,381.02 459.61,341.20 456.49,333.50 C453.36,325.80 444.82,304.65 437.50,286.50 C413.90,227.98 407.23,211.56 405.94,208.75 L 404.68 206.00 L 349.59 206.03 L 294.50 206.05 L 288.14 222.28 C284.65,231.20 259.51,294.30 232.29,362.50 C205.07,430.70 165.94,528.80 145.34,580.50 C124.74,632.20 106.56,677.73 104.94,681.68 C103.32,685.63 102.00,689.34 102.00,689.92 C102.00,690.80 163.39,691.75 206.42,691.53 L 212.35 691.50 L 222.16 664.50 ZM 798.00 691.05 C798.00,690.53 790.18,670.61 780.62,646.80 C737.77,540.07 699.90,445.80 677.26,389.50 C663.76,355.95 651.05,324.23 649.01,319.00 C646.96,313.77 635.94,286.28 624.52,257.91 L 603.75 206.32 L 576.12 205.66 C522.83,204.39 500.00,204.88 500.00,207.29 C500.00,207.85 502.23,213.98 504.97,220.91 C507.70,227.83 514.73,245.65 520.59,260.50 C526.45,275.35 532.71,291.33 534.50,296.00 C536.29,300.67 540.24,310.80 543.27,318.50 C549.76,334.97 562.77,368.16 576.98,404.50 C582.57,418.80 590.00,437.70 593.49,446.50 C600.65,464.57 615.63,502.69 620.02,514.00 C624.19,524.76 638.84,562.16 648.03,585.50 C652.36,596.50 660.21,616.53 665.49,630.00 C670.76,643.47 678.21,662.43 682.04,672.12 C685.87,681.82 689.00,690.26 689.00,690.87 C689.00,691.69 703.78,692.00 743.50,692.00 C777.31,692.00 798.00,691.64 798.00,691.05 ZM 285.33 500.42 C285.10,499.82 290.06,486.32 296.36,470.42 C317.55,416.89 333.07,377.64 342.21,354.50 C347.21,341.85 351.61,331.14 352.00,330.70 C352.38,330.26 354.08,333.64 355.77,338.20 C357.46,342.77 362.05,354.83 365.97,365.00 C369.89,375.17 376.42,392.27 380.50,403.00 C384.57,413.73 391.11,430.83 395.03,441.00 C398.95,451.17 402.53,460.62 402.98,462.00 C403.42,463.38 405.83,469.67 408.32,476.00 C410.81,482.33 413.98,490.53 415.37,494.24 L 417.90 500.97 L 351.82 501.24 C305.07,501.42 285.62,501.18 285.33,500.42 Z" fill="rgb(209,155,118)"/>
+</g>
+</svg>
\ No newline at end of file
diff --git a/studio/frontend/public/hub/profile/logo/cohere.png b/studio/frontend/public/hub/profile/logo/cohere.png
new file mode 100644
index 00000000000..99eabbb54f1
Binary files /dev/null and b/studio/frontend/public/hub/profile/logo/cohere.png differ
diff --git a/studio/frontend/public/hub/profile/logo/deepseek.svg b/studio/frontend/public/hub/profile/logo/deepseek.svg
new file mode 100644
index 00000000000..d1ba06b942c
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/deepseek.svg
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg id="Layer_2" data-name="Layer 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 377.1 277.86">
+ <defs>
+ <style>
+ .cls-1 {
+ fill: #4d6bfe;
+ stroke-width: 0px;
+ }
+ </style>
+ </defs>
+ <g id="Layer_1-2" data-name="Layer 1">
+ <path id="path" class="cls-1" d="M373.15,23.32c-4-1.95-5.72,1.77-8.06,3.66-.79.62-1.47,1.43-2.14,2.14-5.85,6.26-12.67,10.36-21.57,9.86-13.04-.71-24.16,3.38-33.99,13.37-2.09-12.31-9.04-19.66-19.6-24.38-5.54-2.45-11.13-4.9-14.99-10.23-2.71-3.78-3.44-8-4.81-12.16-.85-2.51-1.72-5.09-4.6-5.52-3.13-.5-4.36,2.14-5.58,4.34-4.93,8.99-6.82,18.92-6.65,28.97.43,22.58,9.97,40.56,28.89,53.37,2.16,1.46,2.71,2.95,2.03,5.09-1.29,4.4-2.82,8.68-4.19,13.09-.85,2.82-2.14,3.44-5.15,2.2-10.39-4.34-19.37-10.76-27.29-18.55-13.46-13.02-25.63-27.41-40.81-38.67-3.57-2.64-7.12-5.09-10.81-7.41-15.49-15.07,2.03-27.45,6.08-28.9,4.25-1.52,1.47-6.79-12.23-6.73-13.69.06-26.24,4.65-42.21,10.76-2.34.93-4.79,1.61-7.32,2.14-14.5-2.73-29.55-3.35-45.29-1.58-29.62,3.32-53.28,17.34-70.68,41.28C1.29,88.2-3.63,120.88,2.39,155c6.33,35.91,24.64,65.68,52.8,88.94,29.18,24.1,62.8,35.91,101.15,33.65,23.29-1.33,49.23-4.46,78.48-29.24,7.38,3.66,15.12,5.12,27.97,6.23,9.89.93,19.41-.5,26.79-2.02,11.55-2.45,10.75-13.15,6.58-15.13-33.87-15.78-26.44-9.36-33.2-14.54,17.21-20.41,43.15-41.59,53.3-110.19.79-5.46.11-8.87,0-13.3-.06-2.67.54-3.72,3.61-4.03,8.48-.96,16.72-3.29,24.28-7.47,21.94-12,30.78-31.69,32.87-55.33.31-3.6-.06-7.35-3.86-9.24ZM181.96,235.97c-32.83-25.83-48.74-34.33-55.31-33.96-6.14.34-5.04,7.38-3.69,11.97,1.41,4.53,3.26,7.66,5.85,11.63,1.78,2.64,3.01,6.57-1.78,9.49-10.57,6.58-28.95-2.2-29.82-2.64-21.38-12.59-39.26-29.24-51.87-52.01-12.16-21.92-19.23-45.43-20.39-70.52-.31-6.08,1.47-8.22,7.49-9.3,7.92-1.46,16.11-1.77,24.03-.62,33.49,4.9,62.01,19.91,85.9,43.63,13.65,13.55,23.97,29.71,34.61,45.49,11.3,16.78,23.48,32.75,38.97,45.84,5.46,4.59,9.83,8.09,14,10.67-12.59,1.4-33.62,1.71-47.99-9.68ZM197.69,134.65c0-2.7,2.15-4.84,4.87-4.84.6,0,1.16.12,1.66.31.67.25,1.29.62,1.77,1.18.87.84,1.36,2.08,1.36,3.35,0,2.7-2.15,4.84-4.85,4.84s-4.81-2.14-4.81-4.84ZM246.55,159.77c-3.13,1.27-6.26,2.39-9.27,2.51-4.67.22-9.77-1.68-12.55-4-4.3-3.6-7.36-5.61-8.67-11.94-.54-2.7-.23-6.85.25-9.24,1.12-5.15-.12-8.44-3.74-11.44-2.96-2.45-6.7-3.1-10.82-3.1-1.54,0-2.95-.68-4-1.24-1.72-.87-3.13-3.01-1.78-5.64.43-.84,2.53-2.92,3.02-3.29,5.58-3.19,12.03-2.14,18,.25,5.54,2.26,9.71,6.42,15.72,12.28,6.16,7.1,7.26,9.09,10.76,14.39,2.76,4.19,5.29,8.47,7.01,13.37,1.04,3.04-.31,5.55-3.94,7.1Z"/>
+ </g>
+</svg>
\ No newline at end of file
diff --git a/studio/frontend/public/hub/profile/logo/google.png b/studio/frontend/public/hub/profile/logo/google.png
new file mode 100644
index 00000000000..01bb81206ed
Binary files /dev/null and b/studio/frontend/public/hub/profile/logo/google.png differ
diff --git a/studio/frontend/public/hub/profile/logo/hf.svg b/studio/frontend/public/hub/profile/logo/hf.svg
new file mode 100644
index 00000000000..ab959d165fa
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/hf.svg
@@ -0,0 +1,8 @@
+<svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M230.721 172.7C230.183 170.673 229.313 168.75 228.146 167.008C228.396 166.091 228.587 165.159 228.714 164.217C229.543 158.241 227.471 152.77 223.567 148.537C221.452 146.225 219.185 144.698 216.784 143.761C218.36 137.018 219.157 130.117 219.161 123.193C219.161 120.03 218.982 116.932 218.682 113.88C218.526 112.356 218.337 110.836 218.115 109.32C217.428 104.847 216.408 100.431 215.064 96.11C214.183 93.2707 213.164 90.476 212.01 87.736C210.281 83.6782 208.262 79.75 205.969 75.982C204.465 73.475 202.827 71.0508 201.062 68.72C200.197 67.543 199.296 66.3938 198.358 65.274C195.58 61.898 192.561 58.7277 189.325 55.788C188.25 54.7997 187.145 53.8453 186.01 52.926C184.893 51.9943 183.751 51.0927 182.586 50.222C180.241 48.4766 177.818 46.8392 175.324 45.315C161.543 36.945 145.382 32.145 128.109 32.145C77.817 32.145 37.057 72.907 37.057 123.196C37.055 130.208 37.867 137.196 39.477 144.02C37.317 144.958 35.247 146.42 33.327 148.535C29.424 152.766 27.351 158.217 28.18 164.193C28.306 165.142 28.495 166.082 28.747 167.006C27.5811 168.749 26.7117 170.673 26.174 172.7C24.974 177.261 25.369 181.374 26.894 184.978C25.236 189.688 25.65 194.704 27.809 199.065C29.379 202.25 31.626 204.714 34.396 206.916C37.689 209.534 41.811 211.758 46.783 213.892C52.715 216.422 59.956 218.799 63.249 219.671C71.755 221.873 79.911 223.269 88.177 223.337C99.954 223.446 110.096 220.677 117.357 213.59C120.924 214.027 124.515 214.246 128.109 214.244C131.906 214.236 135.699 213.997 139.467 213.529C146.711 220.661 156.892 223.455 168.712 223.343C176.977 223.277 185.133 221.881 193.617 219.676C196.932 218.804 204.17 216.427 210.105 213.897C215.077 211.76 219.199 209.536 222.514 206.922C225.263 204.719 227.508 202.256 229.079 199.071C231.26 194.709 231.652 189.693 230.017 184.983C231.527 181.379 231.92 177.257 230.721 172.7ZM222.281 184.673C223.952 187.844 224.059 191.427 222.585 194.764C220.349 199.821 214.795 203.805 204.008 208.082C197.3 210.742 191.158 212.443 191.104 212.458C182.232 214.759 174.208 215.928 167.262 215.928C155.76 215.928 147.201 212.754 141.773 206.486C132.594 208.05 123.222 208.103 114.026 206.644C108.591 212.808 100.081 215.928 88.676 215.928C81.729 215.928 73.706 214.759 64.833 212.458C64.779 212.443 58.639 210.742 51.929 208.082C41.143 203.805 35.587 199.824 33.352 194.764C31.878 191.427 31.985 187.844 33.656 184.673C33.81 184.378 33.976 184.091 34.153 183.813C33.1516 182.309 32.4799 180.61 32.182 178.827C31.8842 177.045 31.967 175.22 32.425 173.472C33.089 170.949 34.46 168.851 36.322 167.344C35.425 165.87 34.8365 164.23 34.592 162.522C34.056 158.808 35.289 155.1 38.062 152.076C40.222 149.723 43.275 148.428 46.655 148.428H46.745C44.1965 140.259 42.9044 131.75 42.913 123.193C42.913 76.522 80.749 38.683 127.427 38.683C174.104 38.683 211.94 76.518 211.94 123.193C211.947 131.773 210.646 140.304 208.081 148.492C208.489 148.452 208.889 148.432 209.282 148.431C212.662 148.431 215.716 149.726 217.874 152.079C220.647 155.1 221.881 158.811 221.344 162.525C221.1 164.233 220.511 165.873 219.615 167.347C221.477 168.854 222.849 170.952 223.512 173.475C223.97 175.223 224.053 177.048 223.755 178.831C223.458 180.613 222.786 182.312 221.784 183.816C221.961 184.091 222.129 184.378 222.281 184.673Z" fill="white"/>
+<path d="M221.784 183.816C222.786 182.312 223.458 180.613 223.756 178.831C224.053 177.048 223.97 175.223 223.512 173.475C222.848 170.952 221.476 168.854 219.615 167.347C220.512 165.873 221.1 164.233 221.344 162.525C221.881 158.811 220.648 155.103 217.874 152.079C215.716 149.726 212.662 148.431 209.282 148.431C208.889 148.431 208.489 148.452 208.081 148.492C210.643 140.304 211.942 131.774 211.933 123.195C211.933 76.5231 174.097 38.6851 127.424 38.6851C80.75 38.6851 42.9099 76.5191 42.9099 123.195C42.9015 131.752 44.1936 140.261 46.742 148.43H46.6519C43.2719 148.43 40.219 149.724 38.06 152.077C35.287 155.098 34.0529 158.81 34.5899 162.523C34.8346 164.231 35.4231 165.872 36.3199 167.346C34.4579 168.852 33.086 170.95 32.422 173.473C31.9642 175.222 31.8817 177.047 32.1799 178.83C32.4781 180.612 33.1501 182.312 34.1519 183.816C33.9739 184.094 33.8099 184.381 33.6549 184.676C31.9849 187.847 31.877 191.43 33.352 194.767C35.588 199.824 41.1419 203.808 51.9289 208.085C58.6359 210.745 64.779 212.446 64.833 212.461C73.705 214.762 81.729 215.931 88.675 215.931C100.081 215.931 108.591 212.811 114.026 206.647C123.222 208.106 132.594 208.052 141.773 206.489C147.201 212.757 155.76 215.931 167.262 215.931C174.208 215.931 182.232 214.762 191.103 212.461C191.158 212.446 197.298 210.745 204.008 208.085C214.795 203.808 220.35 199.824 222.585 194.767C224.059 191.43 223.952 187.847 222.281 184.676C222.129 184.379 221.961 184.091 221.784 183.816ZM110.137 196.997C109.669 197.815 109.168 198.614 108.635 199.391C107.23 201.448 105.382 203.02 103.237 204.188C99.1369 206.424 93.947 207.205 88.675 207.205C80.346 207.205 71.808 205.256 67.023 204.015C66.787 203.954 37.689 195.735 41.373 188.739C41.993 187.562 43.0129 187.092 44.2979 187.092C49.4849 187.092 58.9299 194.816 62.9889 194.816C63.8959 194.816 64.5359 194.43 64.7969 193.488C66.5269 187.284 38.5039 184.676 40.8639 175.692C41.2799 174.102 42.41 173.456 43.998 173.456C50.856 173.455 66.248 185.516 69.467 185.516C69.714 185.516 69.8909 185.443 69.9869 185.291C70.0009 185.268 70.015 185.246 70.028 185.222C71.539 182.727 70.6719 180.913 60.3209 174.573L59.3269 173.968C47.9359 167.074 39.9409 162.925 44.4879 157.975C45.0109 157.404 45.7529 157.151 46.6539 157.151C47.7219 157.151 49.0149 157.508 50.4389 158.108C56.4549 160.645 64.793 167.564 68.276 170.581C68.8239 171.057 69.3683 171.538 69.9089 172.022C69.9089 172.022 74.319 176.608 76.985 176.608C77.599 176.608 78.1199 176.366 78.4729 175.768C80.364 172.58 60.9099 157.838 59.8129 151.755C59.0689 147.634 60.3349 145.546 62.6749 145.546C63.7879 145.546 65.1459 146.02 66.6449 146.971C71.2949 149.922 80.2729 165.35 83.5599 171.352C84.6619 173.363 86.5429 174.213 88.2379 174.213C91.6009 174.213 94.2299 170.87 88.5459 166.622C80.0029 160.23 83.001 149.782 87.078 149.139C87.252 149.111 87.4279 149.097 87.6029 149.097C91.3109 149.097 92.9459 155.486 92.9459 155.486C92.9459 155.486 97.7399 167.524 105.975 175.753C113.447 183.222 114.491 189.351 110.137 196.997ZM136.766 198.407L136.339 198.458L135.611 198.541C135.228 198.581 134.844 198.619 134.459 198.654L134.084 198.688L133.741 198.717L133.255 198.756L132.718 198.795L132.182 198.83L132.063 198.838C131.923 198.846 131.783 198.855 131.641 198.862L131.462 198.872C131.296 198.881 131.13 198.889 130.962 198.896L130.381 198.921L129.854 198.939L129.502 198.949H129.323C129.213 198.949 129.104 198.955 128.994 198.956H128.82C128.71 198.956 128.601 198.956 128.491 198.961L128.043 198.967H127.418C126.927 198.967 126.437 198.962 125.949 198.952L125.553 198.943C125.44 198.943 125.327 198.938 125.216 198.934L124.796 198.922L124.275 198.902L123.805 198.881L123.684 198.876L123.237 198.853C123.112 198.846 122.989 198.84 122.865 198.831L122.576 198.814C122.213 198.791 121.85 198.766 121.487 198.738L121.107 198.707C120.947 198.695 120.787 198.68 120.628 198.666C120.441 198.65 120.254 198.632 120.067 198.614C119.754 198.585 119.441 198.553 119.128 198.519H119.113C123.683 188.324 121.372 178.802 112.137 169.575C106.08 163.526 102.051 154.594 101.215 152.633C99.5229 146.828 95.045 140.375 87.608 140.375C86.979 140.375 86.351 140.425 85.73 140.523C82.472 141.036 79.624 142.911 77.592 145.733C75.396 143.002 73.262 140.831 71.332 139.605C68.422 137.76 65.5179 136.824 62.6889 136.824C59.1579 136.824 56.0019 138.274 53.8019 140.904L53.7459 140.971C53.7039 140.798 53.6639 140.625 53.6229 140.451L53.6179 140.428C53.1992 138.638 52.8477 136.833 52.5639 135.016C52.5639 135.004 52.5639 134.992 52.5579 134.98C52.5359 134.843 52.5159 134.705 52.4949 134.568C52.4334 134.162 52.3757 133.755 52.3219 133.348C52.2979 133.163 52.2719 132.978 52.2489 132.793L52.1809 132.238C52.1589 132.053 52.1409 131.885 52.1209 131.709L52.115 131.665C52.0351 130.945 51.9651 130.225 51.9049 129.503L51.8829 129.226L51.8479 128.754C51.8379 128.625 51.8279 128.495 51.8209 128.365C51.8209 128.334 51.8159 128.304 51.8149 128.275C51.7895 127.913 51.7678 127.55 51.7499 127.187C51.7399 126.998 51.7299 126.81 51.7219 126.62L51.7019 126.124L51.6969 125.974L51.6809 125.517L51.6709 125.128C51.6709 124.973 51.6629 124.818 51.6609 124.663C51.6579 124.508 51.6539 124.338 51.6529 124.174C51.6509 124.01 51.6529 123.848 51.6479 123.685C51.6439 123.521 51.6479 123.358 51.6479 123.195C51.6479 81.3421 85.5789 47.4111 127.436 47.4111C169.292 47.4111 203.222 81.3411 203.222 123.195V124.174C203.222 124.337 203.217 124.501 203.214 124.663C203.214 124.798 203.208 124.931 203.204 125.068C203.204 125.188 203.199 125.309 203.195 125.425C203.195 125.578 203.186 125.731 203.181 125.884V125.896L203.16 126.427C203.153 126.582 203.147 126.738 203.139 126.893L203.134 127.003L203.107 127.499C203.048 128.562 202.967 129.623 202.866 130.683V130.696C202.849 130.87 202.832 131.044 202.813 131.218L202.768 131.629L202.679 132.433L202.628 132.84L202.565 133.319C202.542 133.493 202.519 133.668 202.493 133.841C202.467 134.036 202.438 134.23 202.409 134.424L202.34 134.883L202.258 135.403C202.23 135.576 202.2 135.748 202.168 135.92C202.135 136.093 202.109 136.265 202.079 136.437C202.019 136.781 201.956 137.125 201.89 137.468C201.789 137.981 201.686 138.493 201.58 139.005L201.47 139.512C201.434 139.681 201.395 139.851 201.357 140.02C199.224 137.947 196.399 136.818 193.284 136.818C190.457 136.818 187.55 137.753 184.641 139.598C182.711 140.824 180.578 142.996 178.381 145.726C176.346 142.904 173.498 141.029 170.242 140.516C169.621 140.418 168.993 140.368 168.364 140.368C160.925 140.368 156.45 146.821 154.757 152.626C153.917 154.587 149.887 163.519 143.825 169.577C134.596 178.775 132.268 188.254 136.766 198.407ZM215.007 177.998L214.977 178.087C214.901 178.288 214.813 178.484 214.714 178.674C214.639 178.814 214.558 178.95 214.47 179.082C214.303 179.331 214.12 179.569 213.921 179.793C213.875 179.845 213.831 179.897 213.779 179.948C213.707 180.025 213.634 180.101 213.559 180.175C212.213 181.509 210.161 182.679 207.841 183.752C207.578 183.871 207.311 183.99 207.042 184.11L206.774 184.229C206.595 184.308 206.416 184.386 206.228 184.463C206.049 184.541 205.863 184.619 205.677 184.695L205.119 184.925C203.814 185.462 202.477 185.974 201.173 186.479L200.615 186.696L200.064 186.912C199.697 187.055 199.335 187.198 198.979 187.341L198.448 187.555L197.926 187.768L197.67 187.876C197.499 187.947 197.332 188.018 197.165 188.089C193.328 189.736 190.567 191.411 191.147 193.489C191.163 193.548 191.181 193.604 191.201 193.659C191.253 193.813 191.324 193.958 191.413 194.095C191.465 194.176 191.525 194.253 191.592 194.323C192.274 195.032 193.515 194.92 195.08 194.357C195.3 194.276 195.519 194.192 195.736 194.104L195.872 194.048C196.23 193.896 196.609 193.726 196.996 193.542C197.093 193.496 197.191 193.452 197.289 193.401C199.203 192.465 201.372 191.205 203.524 190.058C204.385 189.593 205.258 189.152 206.142 188.733C208.18 187.774 210.096 187.094 211.636 187.094C212.359 187.094 212.997 187.242 213.529 187.582L213.618 187.641C213.952 187.876 214.232 188.178 214.441 188.528C214.482 188.595 214.522 188.666 214.561 188.739C215.322 190.184 214.685 191.68 213.194 193.147C211.763 194.556 209.537 195.937 207.007 197.215C206.819 197.31 206.631 197.405 206.44 197.498C198.91 201.196 189.049 203.981 188.912 204.016C186.284 204.697 182.526 205.591 178.292 206.26L177.666 206.358L177.563 206.373C177.089 206.445 176.614 206.512 176.138 206.574C175.655 206.639 175.167 206.698 174.676 206.753L174.586 206.763C172.806 206.968 171.019 207.104 169.228 207.169H169.202C168.554 207.192 167.907 207.204 167.259 207.204H166.512C165.524 207.191 164.538 207.146 163.553 207.07C163.53 207.07 163.505 207.07 163.482 207.064C163.129 207.037 162.777 207.004 162.425 206.965C162.06 206.926 161.696 206.882 161.333 206.833C161.094 206.801 160.856 206.765 160.618 206.726C160.376 206.687 160.134 206.647 159.893 206.605L159.564 206.543L159.539 206.538C159.192 206.472 158.847 206.399 158.503 206.319C158.303 206.274 158.104 206.23 157.907 206.176L157.788 206.146C157.69 206.122 157.595 206.096 157.498 206.07L157.445 206.056L157.137 205.966C157.025 205.935 156.913 205.901 156.801 205.868L156.762 205.857L156.471 205.768C156.361 205.734 156.251 205.698 156.142 205.662L155.874 205.573L155.677 205.504C155.487 205.437 155.298 205.368 155.111 205.296L154.933 205.226L154.786 205.168C154.502 205.054 154.22 204.935 153.941 204.81L153.756 204.72L153.725 204.706C153.659 204.675 153.594 204.644 153.528 204.617C153.399 204.555 153.271 204.491 153.144 204.426L153.105 204.407L152.921 204.31C152.594 204.139 152.274 203.957 151.96 203.764L151.788 203.658C151.702 203.605 151.616 203.55 151.532 203.494L151.308 203.346L151.067 203.18L150.923 203.077C150.771 202.969 150.622 202.857 150.476 202.742L150.243 202.563C150.15 202.488 150.058 202.412 149.967 202.335C149.89 202.272 149.815 202.206 149.74 202.14L149.734 202.135C149.653 202.064 149.574 201.993 149.495 201.92C149.417 201.849 149.339 201.777 149.263 201.704L149.254 201.695C149.174 201.619 149.096 201.542 149.019 201.463C148.942 201.385 148.863 201.307 148.788 201.227C148.713 201.148 148.636 201.067 148.562 200.984C148.488 200.902 148.42 200.827 148.35 200.746L148.327 200.719C148.259 200.641 148.192 200.562 148.126 200.481C147.983 200.31 147.844 200.135 147.71 199.956C147.575 199.776 147.443 199.592 147.314 199.405L147.191 199.221C147.027 198.981 146.867 198.739 146.712 198.493C146.596 198.316 146.483 198.138 146.373 197.957C146.302 197.844 146.234 197.73 146.166 197.618L146.138 197.572C146.073 197.462 146.009 197.354 145.947 197.245C145.911 197.186 145.877 197.127 145.845 197.066C145.812 197.004 145.774 196.941 145.739 196.878L145.682 196.779L145.647 196.715C145.58 196.595 145.514 196.474 145.45 196.352C145.42 196.298 145.391 196.244 145.36 196.192L145.271 196.019L145.181 195.848C144.956 195.398 144.743 194.942 144.543 194.48L144.472 194.311C144.426 194.198 144.383 194.086 144.337 193.975C144.315 193.921 144.293 193.868 144.274 193.814C144.167 193.537 144.067 193.257 143.975 192.975C143.942 192.874 143.91 192.775 143.88 192.675C143.808 192.448 143.743 192.219 143.685 191.988C143.614 191.719 143.551 191.448 143.498 191.175C143.487 191.12 143.476 191.065 143.467 191.012C143.415 190.745 143.373 190.476 143.34 190.206C143.332 190.153 143.326 190.1 143.32 190.047L143.303 189.885C143.281 189.673 143.264 189.46 143.254 189.247C143.254 189.193 143.249 189.139 143.247 189.087C143.242 188.981 143.24 188.875 143.239 188.769C143.183 184.496 145.345 180.388 149.968 175.767C158.203 167.54 162.997 155.501 162.997 155.501C162.997 155.501 163.126 154.996 163.394 154.269C163.431 154.168 163.47 154.064 163.514 153.955C163.67 153.548 163.846 153.148 164.041 152.758L164.08 152.683C164.246 152.351 164.428 152.027 164.624 151.712C164.67 151.639 164.714 151.567 164.765 151.494C164.912 151.277 165.067 151.065 165.23 150.86C165.319 150.749 165.416 150.639 165.513 150.532C165.552 150.49 165.59 150.448 165.631 150.408C166.108 149.915 166.653 149.513 167.27 149.299L167.348 149.273C167.4 149.256 167.452 149.24 167.505 149.225C167.566 149.209 167.627 149.195 167.69 149.182L167.719 149.176C167.849 149.15 167.981 149.133 168.114 149.124H168.125C168.194 149.124 168.264 149.117 168.335 149.117C168.424 149.117 168.507 149.117 168.594 149.126C168.684 149.134 168.773 149.144 168.863 149.158C169.605 149.276 170.311 149.718 170.919 150.4C171.15 150.66 171.358 150.94 171.54 151.236C171.66 151.428 171.773 151.631 171.88 151.845C171.923 151.934 171.964 152.016 172.004 152.104C172.108 152.33 172.202 152.56 172.284 152.795C172.479 153.345 172.626 153.911 172.723 154.487C172.807 154.992 172.857 155.502 172.873 156.013C172.881 156.286 172.881 156.563 172.873 156.842C172.819 158.14 172.553 159.421 172.086 160.634C172.044 160.745 171.997 160.857 171.952 160.969C171.86 161.195 171.759 161.417 171.65 161.634C171.569 161.799 171.484 161.965 171.392 162.13C171.332 162.24 171.269 162.35 171.206 162.46C171.045 162.734 170.871 163.006 170.684 163.277L170.571 163.439C170.129 164.055 169.637 164.633 169.099 165.167C168.569 165.698 168.001 166.189 167.4 166.637C166.798 167.083 166.233 167.577 165.711 168.114C164.208 169.691 163.858 171.083 164.196 172.138C164.25 172.304 164.321 172.465 164.407 172.617C164.508 172.791 164.628 172.951 164.764 173.097L164.817 173.152L164.871 173.206C164.925 173.258 164.982 173.309 165.043 173.359L165.103 173.407C165.248 173.519 165.402 173.619 165.563 173.707C165.61 173.732 165.652 173.757 165.705 173.781C165.879 173.866 166.058 173.939 166.242 173.998C166.293 174.015 166.344 174.03 166.396 174.046L166.461 174.063L166.551 174.087L166.628 174.106L166.712 174.124L166.795 174.141L166.874 174.154C166.932 174.164 166.992 174.174 167.052 174.181L167.109 174.19L167.213 174.2L167.277 174.207L167.382 174.214H167.444L167.554 174.22H167.9L167.999 174.214L168.113 174.207L168.252 174.194L168.382 174.179C168.412 174.179 168.442 174.171 168.472 174.165C168.872 174.107 169.264 174.001 169.639 173.849L169.798 173.782C169.887 173.743 169.977 173.702 170.059 173.658C170.235 173.57 170.406 173.47 170.57 173.361C170.799 173.211 171.015 173.043 171.217 172.858C171.265 172.815 171.312 172.769 171.358 172.725C171.381 172.703 171.403 172.682 171.425 172.658C171.469 172.613 171.514 172.569 171.558 172.52C171.878 172.168 172.155 171.78 172.383 171.363C174.34 167.804 176.391 164.298 178.534 160.849L178.828 160.378L179.125 159.907C179.273 159.668 179.423 159.433 179.572 159.199L179.722 158.965C180.22 158.185 180.726 157.41 181.241 156.641L181.546 156.185C182.158 155.278 182.768 154.396 183.373 153.558L183.674 153.143C184.332 152.236 185.017 151.348 185.728 150.482L186.01 150.144C186.057 150.088 186.1 150.032 186.151 149.978C186.244 149.868 186.337 149.761 186.428 149.657C186.474 149.604 186.517 149.552 186.566 149.5L186.834 149.198L186.968 149.051C187.103 148.906 187.235 148.767 187.365 148.634C187.455 148.544 187.538 148.455 187.624 148.371C188.131 147.853 188.69 147.388 189.293 146.985L189.433 146.895C189.567 146.805 189.706 146.721 189.848 146.645C192.212 145.303 194.169 145.204 195.296 146.331C195.978 147.013 196.356 148.144 196.335 149.718C196.335 149.787 196.335 149.857 196.33 149.929V150.006C196.33 150.078 196.324 150.15 196.318 150.223C196.318 150.313 196.308 150.402 196.299 150.492C196.29 150.581 196.285 150.649 196.276 150.729C196.276 150.751 196.272 150.774 196.268 150.798C196.262 150.867 196.253 150.938 196.243 151.009C196.243 151.03 196.243 151.052 196.235 151.074C196.224 151.169 196.21 151.263 196.194 151.357C196.183 151.447 196.168 151.531 196.152 151.619L196.126 151.768C196.1 151.91 196.067 152.05 196.026 152.188C195.948 152.447 195.854 152.7 195.743 152.946C195.588 153.284 195.417 153.613 195.229 153.933C195.125 154.111 195.018 154.286 194.907 154.459C194.793 154.638 194.673 154.819 194.549 155.002C194.233 155.454 193.905 155.897 193.564 156.33L193.408 156.527C192.852 157.22 192.278 157.899 191.686 158.562L191.499 158.772C191.247 159.053 190.991 159.336 190.729 159.62L190.532 159.834C190.401 159.977 190.264 160.12 190.132 160.264C190.001 160.407 189.864 160.552 189.726 160.697L189.315 161.13L188.898 161.566L188.478 162.002C188.196 162.294 187.913 162.586 187.628 162.878C183.573 167.037 179.301 171.182 177.855 173.766C177.758 173.934 177.671 174.108 177.593 174.285C177.387 174.755 177.301 175.157 177.36 175.482C177.379 175.589 177.416 175.691 177.471 175.785C177.552 175.926 177.651 176.056 177.766 176.172C177.819 176.224 177.875 176.272 177.934 176.316C178.232 176.528 178.591 176.637 178.957 176.627H179.071L179.188 176.618L179.305 176.605L179.402 176.591C179.415 176.589 179.429 176.587 179.442 176.583L179.531 176.566L179.554 176.561L179.653 176.54L179.688 176.531C179.723 176.522 179.757 176.513 179.792 176.503C179.827 176.493 179.875 176.48 179.917 176.466C180.093 176.413 180.265 176.35 180.434 176.278C180.523 176.242 180.61 176.203 180.696 176.161C180.741 176.141 180.786 176.12 180.828 176.098L180.962 176.032C181.282 175.866 181.594 175.685 181.898 175.491L182.031 175.401C182.076 175.373 182.121 175.344 182.164 175.312L182.297 175.223L182.368 175.174L182.56 175.039C182.739 174.916 182.906 174.789 183.075 174.66L183.09 174.648L183.359 174.44C183.726 174.15 184.074 173.858 184.39 173.583L184.6 173.399L184.619 173.381L184.729 173.284C184.987 173.052 185.217 172.836 185.408 172.658L185.487 172.581C185.556 172.516 185.619 172.455 185.676 172.403L185.788 172.292L185.828 172.253L185.839 172.242L185.956 172.125L186.03 172.048L186.039 172.041L186.074 172.009L186.118 171.969L186.132 171.956L186.169 171.922L186.373 171.743L186.487 171.641C186.548 171.588 186.607 171.534 186.666 171.479L186.802 171.358C186.827 171.338 186.851 171.316 186.876 171.294L187.019 171.169L187.229 170.984L187.341 170.887C187.776 170.509 188.305 170.052 188.913 169.537L189.162 169.326L189.573 168.981L189.994 168.63C190.544 168.173 191.136 167.688 191.762 167.185L192.173 166.855C192.523 166.576 192.882 166.292 193.246 166.006C193.393 165.891 193.542 165.776 193.694 165.662C194.066 165.373 194.44 165.086 194.817 164.803C195.675 164.155 196.56 163.506 197.456 162.874L197.84 162.606C198.109 162.421 198.377 162.235 198.645 162.054L198.888 161.89C199.367 161.565 199.853 161.248 200.343 160.939L200.586 160.786L200.827 160.636C201.069 160.486 201.309 160.339 201.548 160.196L201.787 160.053L202.265 159.775L202.734 159.506L202.829 159.454L203.2 159.25C203.355 159.166 203.509 159.085 203.663 159.006L203.892 158.888L204.115 158.776C204.193 158.739 204.27 158.7 204.346 158.663C204.848 158.415 205.36 158.187 205.88 157.979C206.021 157.919 206.161 157.865 206.3 157.818L206.71 157.674C206.833 157.633 206.953 157.594 207.068 157.559L207.108 157.547C207.17 157.527 207.232 157.509 207.293 157.493L207.311 157.488C207.439 157.451 207.566 157.419 207.691 157.389H207.7C208.054 157.304 208.414 157.243 208.777 157.206C208.944 157.189 209.111 157.18 209.279 157.181H209.363C209.475 157.181 209.583 157.188 209.69 157.199C209.739 157.199 209.788 157.209 209.836 157.215H209.856C209.904 157.221 209.952 157.228 210 157.239C210.047 157.248 210.095 157.256 210.141 157.267H210.156C210.203 157.277 210.245 157.289 210.294 157.303C210.548 157.374 210.79 157.484 211.012 157.628C211.121 157.699 211.223 157.779 211.317 157.868L211.344 157.894C211.362 157.91 211.379 157.927 211.395 157.944L211.444 157.997C211.846 158.418 212.178 158.901 212.428 159.427L212.466 159.517C212.551 159.717 212.618 159.924 212.666 160.135C212.808 160.781 212.753 161.455 212.508 162.07C212.415 162.318 212.302 162.557 212.169 162.785C211.858 163.309 211.489 163.796 211.07 164.237L210.981 164.332C210.848 164.472 210.71 164.612 210.565 164.752C210.501 164.815 210.434 164.877 210.367 164.94L210.162 165.129L210.055 165.224C209.797 165.454 209.532 165.677 209.263 165.893C209.1 166.025 208.936 166.154 208.77 166.281C208.184 166.729 207.587 167.161 206.979 167.578C206.612 167.83 206.242 168.077 205.869 168.321C204.95 168.924 204.021 169.512 203.083 170.084C201.115 171.294 198.934 172.588 196.609 173.995L196.007 174.36C195.348 174.762 194.726 175.146 194.14 175.512L193.845 175.697L193.287 176.055C192.917 176.292 192.548 176.531 192.179 176.77L191.882 176.966C191.737 177.06 191.593 177.156 191.449 177.252L191.308 177.342L190.876 177.633L190.647 177.79L190.379 177.976L190.13 178.149C189.713 178.444 189.325 178.725 188.968 178.992L188.834 179.094C188.624 179.253 188.416 179.415 188.211 179.58C187.902 179.829 187.62 180.067 187.367 180.296L187.243 180.409C187.172 180.474 187.102 180.539 187.035 180.603C186.989 180.648 186.946 180.693 186.898 180.736L186.834 180.8C186.691 180.944 186.551 181.091 186.416 181.242L186.35 181.318C186.203 181.488 186.075 181.651 185.963 181.81L185.913 181.881C185.825 182.009 185.744 182.141 185.671 182.277C185.652 182.311 185.635 182.345 185.618 182.379L185.569 182.481L185.536 182.555L185.515 182.605L185.498 182.65L185.475 182.711C185.413 182.88 185.37 183.056 185.345 183.234L185.337 183.296L185.331 183.354V183.669C185.331 183.695 185.331 183.721 185.338 183.749L185.343 183.797C185.343 183.823 185.349 183.848 185.353 183.876C185.357 183.902 185.364 183.949 185.372 183.986V183.991C185.379 184.026 185.386 184.06 185.395 184.095C185.404 184.13 185.413 184.17 185.424 184.206C185.443 184.277 185.467 184.347 185.492 184.417C185.508 184.459 185.523 184.5 185.54 184.541C185.54 184.549 185.546 184.558 185.55 184.566L185.586 184.647L185.636 184.758C185.69 184.873 185.749 184.985 185.813 185.094L185.879 185.208L185.947 185.322C185.959 185.341 185.973 185.359 185.988 185.376L186.01 185.399L186.035 185.422L186.061 185.442C186.099 185.469 186.14 185.49 186.183 185.505C186.206 185.513 186.23 185.519 186.254 185.525C186.831 185.655 188.017 185.178 189.593 184.346C189.682 184.298 189.78 184.248 189.875 184.196L190.355 183.934L190.589 183.804C190.756 183.715 190.926 183.614 191.1 183.515L191.417 183.336C193.5 182.137 195.988 180.597 198.56 179.093C198.801 178.952 199.043 178.811 199.285 178.672L199.771 178.361C200.335 178.038 200.902 177.719 201.471 177.404C202.188 177.01 202.91 176.626 203.639 176.254L204.115 176.013C204.431 175.857 204.744 175.705 205.053 175.557C205.651 175.273 206.256 175.003 206.868 174.748L207.203 174.612L207.243 174.596C209.018 173.893 210.627 173.459 211.929 173.459C212.21 173.456 212.492 173.48 212.769 173.528H212.778C212.867 173.544 212.948 173.562 213.031 173.582H213.046C213.259 173.636 213.466 173.713 213.662 173.812C213.937 173.954 214.184 174.143 214.393 174.371C214.489 174.477 214.574 174.592 214.649 174.714C214.789 174.929 214.899 175.162 214.978 175.406C215.01 175.501 215.038 175.594 215.067 175.693C215.278 176.45 215.257 177.253 215.007 177.998Z" fill="#FF9D00"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M203.21 123.685V123.194C203.21 81.34 169.292 47.411 127.435 47.411C85.5791 47.411 51.648 81.342 51.648 123.194V123.358C51.646 123.467 51.645 123.576 51.648 123.685C51.6529 123.848 51.6546 124.011 51.653 124.174L51.6581 124.534L51.661 124.663C51.661 124.723 51.6631 124.782 51.6651 124.842C51.6681 124.937 51.67 125.033 51.67 125.128L51.681 125.517L51.697 125.974L51.702 126.124L51.722 126.597V126.62C51.73 126.805 51.7401 126.989 51.7491 127.173L51.75 127.187C51.76 127.375 51.7701 127.564 51.7821 127.753C51.7921 127.927 51.802 128.101 51.815 128.275L51.8171 128.306C51.8258 128.455 51.8358 128.605 51.847 128.754L51.85 128.794L51.883 129.226L51.8861 129.254C51.8921 129.338 51.898 129.422 51.906 129.503C51.9658 130.224 52.0355 130.945 52.1151 131.664L52.12 131.709L52.181 132.238L52.2491 132.793L52.299 133.17L52.322 133.347C52.3753 133.755 52.433 134.162 52.495 134.568L52.4991 134.595L52.558 134.979C52.8435 136.808 53.1971 138.626 53.618 140.429L53.6231 140.451L53.655 140.586L53.746 140.971L53.802 140.904C56.002 138.274 59.158 136.824 62.689 136.824C65.519 136.824 68.4221 137.76 71.3321 139.605C73.2621 140.831 75.3961 143.002 77.5921 145.733C79.6241 142.911 82.4721 141.035 85.7301 140.523C86.3513 140.425 86.9792 140.376 87.6081 140.375C95.0441 140.375 99.523 146.828 101.215 152.633C102.051 154.594 106.08 163.526 112.156 169.568C121.392 178.795 123.703 188.316 119.132 198.511H119.148C119.459 198.546 119.772 198.578 120.087 198.607C120.274 198.625 120.46 198.643 120.648 198.659L120.714 198.665L121.127 198.7L121.507 198.73C121.869 198.758 122.232 198.784 122.596 198.807L122.885 198.824L123.114 198.838L123.256 198.846L123.703 198.869L123.825 198.874L124.294 198.895L124.816 198.915L125.235 198.927L125.305 198.929C125.394 198.933 125.483 198.936 125.572 198.936L125.668 198.939C126.258 198.953 126.847 198.96 127.437 198.959H128.063L128.51 198.954C128.62 198.949 128.729 198.949 128.84 198.949H129.014L129.165 198.945C129.224 198.943 129.283 198.941 129.343 198.941H129.522L129.873 198.932L130.401 198.914L130.982 198.888C131.15 198.882 131.316 198.873 131.482 198.865L131.661 198.854L131.927 198.84L132.083 198.831L132.201 198.823L132.738 198.788L133.274 198.749L133.761 198.71L134.103 198.681L134.479 198.647C135.107 198.591 135.733 198.525 136.359 198.45L136.786 198.399C132.287 188.247 134.616 178.767 143.813 169.577C149.876 163.519 153.905 154.587 154.745 152.625C156.438 146.821 160.914 140.368 168.352 140.368C168.981 140.368 169.61 140.418 170.231 140.516C173.486 141.028 176.334 142.904 178.369 145.726C180.566 142.996 182.699 140.823 184.63 139.597C187.539 137.753 190.445 136.817 193.272 136.817C196.388 136.817 199.212 137.947 201.345 140.02C201.384 139.851 201.422 139.682 201.459 139.512L201.568 139.006C201.607 138.821 201.646 138.636 201.683 138.451C201.749 138.124 201.815 137.797 201.878 137.467C201.944 137.125 202.007 136.781 202.067 136.437L202.098 136.251C202.117 136.141 202.135 136.031 202.156 135.92C202.19 135.748 202.218 135.576 202.246 135.402L202.257 135.336L202.328 134.883L202.398 134.424V134.42C202.449 134.081 202.497 133.742 202.542 133.403L202.553 133.319L202.616 132.841L202.667 132.433L202.757 131.629L202.792 131.306L202.801 131.218C202.82 131.044 202.838 130.87 202.854 130.696V130.682C202.867 130.544 202.881 130.405 202.893 130.266C202.964 129.478 203.024 128.686 203.072 127.891C203.081 127.761 203.088 127.63 203.096 127.499V127.493L203.122 127.002L203.128 126.892C203.144 126.56 203.158 126.228 203.169 125.896V125.884L203.174 125.754C203.179 125.645 203.183 125.535 203.183 125.425L203.185 125.381C203.189 125.278 203.193 125.172 203.193 125.067L203.196 124.977C203.199 124.872 203.202 124.768 203.202 124.663L203.204 124.574C203.207 124.441 203.21 124.307 203.21 124.174V123.685ZM108.638 199.391C114.64 190.59 114.214 183.984 105.98 175.754C97.7441 167.523 92.951 155.487 92.951 155.487C92.951 155.487 91.1621 148.496 87.0821 149.138C83.0021 149.78 80.0091 160.227 88.5521 166.622C97.0941 173.017 86.8521 177.353 83.5641 171.352C80.2761 165.35 71.299 149.923 66.645 146.972C61.991 144.021 58.718 145.675 59.815 151.757C60.36 154.776 65.4281 159.929 70.1631 164.743C74.9671 169.627 79.428 174.163 78.474 175.768C76.581 178.955 69.9141 172.023 69.9141 172.023C69.9141 172.023 49.038 153.025 44.494 157.976C40.304 162.539 46.765 166.418 56.7211 172.397C57.5671 172.905 58.4391 173.429 59.3321 173.969C70.7231 180.865 71.609 182.684 69.992 185.293C69.395 186.257 65.582 183.968 60.892 181.153C52.897 176.352 42.3551 170.023 40.8661 175.688C39.5781 180.591 47.334 183.595 54.368 186.32C60.228 188.59 65.5881 190.666 64.7991 193.484C63.9821 196.406 59.5531 193.969 54.7121 191.305C49.2771 188.314 43.3221 185.038 41.3731 188.735C37.6901 195.725 66.7831 203.954 67.0231 204.015C76.4231 206.453 100.295 211.619 108.638 199.391ZM147.303 199.391C141.301 190.59 141.727 183.984 149.962 175.754C158.197 167.523 162.99 155.487 162.99 155.487C162.99 155.487 164.779 148.496 168.859 149.138C172.939 149.78 175.932 160.227 167.39 166.622C158.847 173.017 169.089 177.353 172.377 171.352C175.666 165.35 184.637 149.923 189.291 146.972C193.945 144.021 197.22 145.675 196.122 151.757C195.578 154.776 190.509 159.929 185.774 164.744C180.97 169.628 176.509 174.163 177.462 175.768C179.355 178.955 186.027 172.019 186.027 172.019C186.027 172.019 206.902 153.022 211.448 157.973C215.637 162.535 209.176 166.415 199.219 172.394C198.348 172.917 197.478 173.441 196.609 173.966C185.218 180.862 184.332 182.681 185.948 185.289C186.546 186.254 190.359 183.964 195.048 181.149C203.044 176.349 213.586 170.019 215.075 175.685C216.364 180.588 208.607 183.592 201.573 186.317C195.713 188.587 190.353 190.663 191.141 193.481C191.957 196.402 196.385 193.965 201.225 191.301C206.66 188.31 212.616 185.032 214.564 188.732C218.248 195.726 189.15 203.947 188.915 204.007C179.515 206.453 155.643 211.619 147.303 199.391Z" fill="#FFD21E"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M152.047 102.567C153.229 102.985 154.108 104.257 154.944 105.468C156.074 107.104 157.126 108.627 158.74 107.769C160.644 106.756 162.205 105.202 163.225 103.302C164.246 101.402 164.681 99.2427 164.475 97.096C164.321 95.4908 163.813 93.9398 162.987 92.5548C162.161 91.1697 161.038 89.985 159.7 89.0862C158.361 88.1874 156.839 87.5968 155.245 87.3569C153.65 87.117 152.022 87.2339 150.478 87.699C148.934 88.1639 147.513 88.9653 146.316 90.0455C145.119 91.1257 144.176 92.4578 143.556 93.946C142.936 95.4342 142.653 97.0415 142.728 98.652C142.804 100.263 143.235 101.836 143.992 103.26C144.74 104.667 146.4 104.003 148.152 103.302C149.525 102.753 150.956 102.181 152.047 102.567ZM100.672 102.567C99.49 102.985 98.611 104.258 97.775 105.468C96.645 107.105 95.592 108.627 93.979 107.769C91.5845 106.501 89.7482 104.386 88.8278 101.838C87.9075 99.2895 87.9692 96.4896 89.0008 93.9841C90.0324 91.4786 91.9601 89.4471 94.408 88.2855C96.856 87.1239 99.6488 86.9156 102.242 87.701C104.307 88.3228 106.141 89.5427 107.513 91.2065C108.885 92.8704 109.732 94.9035 109.949 97.049C110.165 99.1945 109.74 101.356 108.728 103.26C107.979 104.667 106.319 104.003 104.567 103.303C103.193 102.753 101.764 102.181 100.672 102.567ZM144.099 149.318C152.242 142.903 155.233 132.429 155.233 125.977C155.233 120.877 151.802 122.482 146.309 125.202L145.999 125.355C140.957 127.852 134.245 131.177 126.877 131.177C119.508 131.177 112.796 127.852 107.755 125.354C102.084 122.545 98.527 120.783 98.527 125.978C98.527 132.634 101.709 143.563 110.443 149.912C111.596 147.573 113.219 145.497 115.211 143.813C117.202 142.129 119.52 140.874 122.018 140.126C122.89 139.866 123.788 141.367 124.707 142.904C125.594 144.386 126.501 145.902 127.423 145.902C128.406 145.902 129.371 144.408 130.314 142.95C131.299 141.425 132.26 139.94 133.189 140.237C137.864 141.738 141.775 144.993 144.099 149.318Z" fill="#32343D"/>
+<path d="M144.097 149.317C139.856 152.659 134.219 154.9 126.878 154.9C119.981 154.9 114.587 152.922 110.443 149.911C111.596 147.572 113.219 145.495 115.211 143.812C117.202 142.128 119.52 140.873 122.018 140.125C123.73 139.614 125.545 145.901 127.423 145.901C129.433 145.901 131.37 139.655 133.189 140.236C137.863 141.738 141.773 144.993 144.097 149.317Z" fill="#FF323D"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M81.2 111.64C80.2312 112.288 79.1173 112.687 77.9572 112.801C76.7971 112.916 75.6267 112.742 74.55 112.295C73.6893 111.94 72.9072 111.418 72.2488 110.759C71.5903 110.101 71.0684 109.319 70.713 108.458C70.267 107.381 70.0935 106.211 70.2082 105.051C70.3228 103.891 70.7219 102.777 71.37 101.808C72.1488 100.642 73.2558 99.7333 74.5512 99.1967C75.8466 98.6601 77.272 98.5197 78.6471 98.7935C80.0223 99.0672 81.2853 99.7427 82.2764 100.734C83.2675 101.726 83.9422 102.99 84.215 104.365C84.4883 105.74 84.3477 107.165 83.8113 108.46C83.2748 109.755 82.3654 110.861 81.2 111.64ZM182.613 111.64C181.644 112.288 180.53 112.687 179.37 112.801C178.209 112.916 177.039 112.742 175.962 112.295C175.101 111.939 174.319 111.418 173.661 110.759C173.003 110.101 172.481 109.319 172.125 108.458C171.68 107.381 171.507 106.211 171.621 105.051C171.736 103.891 172.135 102.777 172.782 101.808C173.364 100.936 174.133 100.205 175.032 99.6658C175.931 99.1269 176.938 98.7942 177.981 98.6917C179.025 98.5891 180.078 98.7193 181.064 99.0728C182.051 99.4264 182.947 99.9944 183.688 100.736C184.68 101.727 185.355 102.99 185.628 104.365C185.902 105.74 185.761 107.165 185.224 108.46C184.687 109.755 183.779 110.861 182.613 111.64Z" fill="#FFAD03"/>
+</svg>
diff --git a/studio/frontend/public/hub/profile/logo/ibm.png b/studio/frontend/public/hub/profile/logo/ibm.png
new file mode 100644
index 00000000000..31c965f0b3e
Binary files /dev/null and b/studio/frontend/public/hub/profile/logo/ibm.png differ
diff --git a/studio/frontend/public/hub/profile/logo/meta.svg b/studio/frontend/public/hub/profile/logo/meta.svg
new file mode 100644
index 00000000000..9fa656bd6bb
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/meta.svg
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:cc="http://creativecommons.org/ns#" width="287.56" height="191">
+<desc>Logo of Meta Platforms -- Graphic created by Detmar Owen</desc>
+<defs>
+<linearGradient id="Grad_Logo1" x1="61" y1="117" x2="259" y2="127" gradientUnits="userSpaceOnUse">
+<stop style="stop-color:#0064e1" offset="0"/>
+<stop style="stop-color:#0064e1" offset="0.4"/>
+<stop style="stop-color:#0073ee" offset="0.83"/>
+<stop style="stop-color:#0082fb" offset="1"/>
+</linearGradient>
+<linearGradient id="Grad_Logo2" x1="45" y1="139" x2="45" y2="66" gradientUnits="userSpaceOnUse">
+<stop style="stop-color:#0082fb" offset="0"/>
+<stop style="stop-color:#0064e0" offset="1"/>
+</linearGradient>
+</defs>
+<path id="Logo0" style="fill:#0081fb" d="m31.06,125.96c0,10.98 2.41,19.41 5.56,24.51 4.13,6.68 10.29,9.51 16.57,9.51 8.1,0 15.51-2.01 29.79-21.76 11.44-15.83 24.92-38.05 33.99-51.98l15.36-23.6c10.67-16.39 23.02-34.61 37.18-46.96 11.56-10.08 24.03-15.68 36.58-15.68 21.07,0 41.14,12.21 56.5,35.11 16.81,25.08 24.97,56.67 24.97,89.27 0,19.38-3.82,33.62-10.32,44.87-6.28,10.88-18.52,21.75-39.11,21.75l0-31.02c17.63,0 22.03-16.2 22.03-34.74 0-26.42-6.16-55.74-19.73-76.69-9.63-14.86-22.11-23.94-35.84-23.94-14.85,0-26.8,11.2-40.23,31.17-7.14,10.61-14.47,23.54-22.7,38.13l-9.06,16.05c-18.2,32.27-22.81,39.62-31.91,51.75-15.95,21.24-29.57,29.29-47.5,29.29-21.27,0-34.72-9.21-43.05-23.09-6.8-11.31-10.14-26.15-10.14-43.06z"/>
+<path id="Logo1" style="fill:url(#Grad_Logo1)" d="m24.49,37.3c14.24-21.95 34.79-37.3 58.36-37.3 13.65,0 27.22,4.04 41.39,15.61 15.5,12.65 32.02,33.48 52.63,67.81l7.39,12.32c17.84,29.72 27.99,45.01 33.93,52.22 7.64,9.26 12.99,12.02 19.94,12.02 17.63,0 22.03-16.2 22.03-34.74l27.4-.86c0,19.38-3.82,33.62-10.32,44.87-6.28,10.88-18.52,21.75-39.11,21.75-12.8,0-24.14-2.78-36.68-14.61-9.64-9.08-20.91-25.21-29.58-39.71l-25.79-43.08c-12.94-21.62-24.81-37.74-31.68-45.04-7.39-7.85-16.89-17.33-32.05-17.33-12.27,0-22.69,8.61-31.41,21.78z"/>
+<path id="Logo2" style="fill:url(#Grad_Logo2)" d="m82.35,31.23c-12.27,0-22.69,8.61-31.41,21.78-12.33,18.61-19.88,46.33-19.88,72.95 0,10.98 2.41,19.41 5.56,24.51l-26.48,17.44c-6.8-11.31-10.14-26.15-10.14-43.06 0-30.75 8.44-62.8 24.49-87.55 14.24-21.95 34.79-37.3 58.36-37.3z"/>
+</svg>
\ No newline at end of file
diff --git a/studio/frontend/public/hub/profile/logo/microsoft.svg b/studio/frontend/public/hub/profile/logo/microsoft.svg
new file mode 100644
index 00000000000..5334aa7ca68
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/microsoft.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 23 23"><path fill="#f3f3f3" d="M0 0h23v23H0z"/><path fill="#f35325" d="M1 1h10v10H1z"/><path fill="#81bc06" d="M12 1h10v10H12z"/><path fill="#05a6f0" d="M1 12h10v10H1z"/><path fill="#ffba08" d="M12 12h10v10H12z"/></svg>
\ No newline at end of file
diff --git a/studio/frontend/public/hub/profile/logo/minimax-color.png b/studio/frontend/public/hub/profile/logo/minimax-color.png
new file mode 100644
index 00000000000..e9472c676dc
Binary files /dev/null and b/studio/frontend/public/hub/profile/logo/minimax-color.png differ
diff --git a/studio/frontend/public/hub/profile/logo/mistral.svg b/studio/frontend/public/hub/profile/logo/mistral.svg
new file mode 100644
index 00000000000..40c2591b314
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/mistral.svg
@@ -0,0 +1,19 @@
+<svg width="191" height="135" viewBox="0 0 191 135" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_134_208)">
+<path d="M54.3221 0H27.1531V27.0892H54.3221V0Z" fill="#FFD800"/>
+<path d="M162.984 0H135.815V27.0892H162.984V0Z" fill="#FFD800"/>
+<path d="M81.4823 27.0913H27.1531V54.1805H81.4823V27.0913Z" fill="#FFAF00"/>
+<path d="M162.99 27.0913H108.661V54.1805H162.99V27.0913Z" fill="#FFAF00"/>
+<path d="M162.972 54.168H27.1531V81.2572H162.972V54.168Z" fill="#FF8205"/>
+<path d="M54.3221 81.2593H27.1531V108.349H54.3221V81.2593Z" fill="#FA500F"/>
+<path d="M108.661 81.2593H81.4917V108.349H108.661V81.2593Z" fill="#FA500F"/>
+<path d="M162.984 81.2593H135.815V108.349H162.984V81.2593Z" fill="#FA500F"/>
+<path d="M81.4879 108.339H-0.00146484V135.429H81.4879V108.339Z" fill="#E10500"/>
+<path d="M190.159 108.339H108.661V135.429H190.159V108.339Z" fill="#E10500"/>
+</g>
+<defs>
+<clipPath id="clip0_134_208">
+<rect width="190.141" height="135" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/studio/frontend/public/hub/profile/logo/moonshot.jpg b/studio/frontend/public/hub/profile/logo/moonshot.jpg
new file mode 100644
index 00000000000..956a5b58b10
Binary files /dev/null and b/studio/frontend/public/hub/profile/logo/moonshot.jpg differ
diff --git a/studio/frontend/public/hub/profile/logo/nvidia.svg b/studio/frontend/public/hub/profile/logo/nvidia.svg
new file mode 100644
index 00000000000..ae65b09a2bc
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/nvidia.svg
@@ -0,0 +1 @@
+<svg viewBox="0 0 271.7 179.7" xmlns="http://www.w3.org/2000/svg" width="2500" height="1653"><path d="M101.3 53.6V37.4c1.6-.1 3.2-.2 4.8-.2 44.4-1.4 73.5 38.2 73.5 38.2S148.2 119 114.5 119c-4.5 0-8.9-.7-13.1-2.1V67.7c17.3 2.1 20.8 9.7 31.1 27l23.1-19.4s-16.9-22.1-45.3-22.1c-3-.1-6 .1-9 .4m0-53.6v24.2l4.8-.3c61.7-2.1 102 50.6 102 50.6s-46.2 56.2-94.3 56.2c-4.2 0-8.3-.4-12.4-1.1v15c3.4.4 6.9.7 10.3.7 44.8 0 77.2-22.9 108.6-49.9 5.2 4.2 26.5 14.3 30.9 18.7-29.8 25-99.3 45.1-138.7 45.1-3.8 0-7.4-.2-11-.6v21.1h170.2V0H101.3zm0 116.9v12.8c-41.4-7.4-52.9-50.5-52.9-50.5s19.9-22 52.9-25.6v14h-.1c-17.3-2.1-30.9 14.1-30.9 14.1s7.7 27.3 31 35.2M27.8 77.4s24.5-36.2 73.6-40V24.2C47 28.6 0 74.6 0 74.6s26.6 77 101.3 84v-14c-54.8-6.8-73.5-67.2-73.5-67.2z" fill="#76b900"/></svg>
\ No newline at end of file
diff --git a/studio/frontend/public/hub/profile/logo/openai.svg b/studio/frontend/public/hub/profile/logo/openai.svg
new file mode 100644
index 00000000000..74d9b1b44bc
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/openai.svg
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 158.7128 157.296">
+ <!-- Generator: Adobe Illustrator 29.2.1, SVG Export Plug-In . SVG Version: 2.1.0 Build 116) -->
+ <path d="M60.8734,57.2556v-14.9432c0-1.2586.4722-2.2029,1.5728-2.8314l30.0443-17.3023c4.0899-2.3593,8.9662-3.4599,13.9988-3.4599,18.8759,0,30.8307,14.6289,30.8307,30.2006,0,1.1007,0,2.3593-.158,3.6178l-31.1446-18.2467c-1.8872-1.1006-3.7754-1.1006-5.6629,0l-39.4812,22.9651ZM131.0276,115.4561v-35.7074c0-2.2028-.9446-3.7756-2.8318-4.8763l-39.481-22.9651,12.8982-7.3934c1.1007-.6285,2.0453-.6285,3.1458,0l30.0441,17.3024c8.6523,5.0341,14.4708,15.7296,14.4708,26.1107,0,11.9539-7.0769,22.965-18.2461,27.527v.0021ZM51.593,83.9964l-12.8982-7.5497c-1.1007-.6285-1.5728-1.5728-1.5728-2.8314v-34.6048c0-16.8303,12.8982-29.5722,30.3585-29.5722,6.607,0,12.7403,2.2029,17.9324,6.1349l-30.987,17.9324c-1.8871,1.1007-2.8314,2.6735-2.8314,4.8764v45.6159l-.0014-.0015ZM79.3562,100.0403l-18.4829-10.3811v-22.0209l18.4829-10.3811,18.4812,10.3811v22.0209l-18.4812,10.3811ZM91.2319,147.8591c-6.607,0-12.7403-2.2031-17.9324-6.1344l30.9866-17.9333c1.8872-1.1005,2.8318-2.6728,2.8318-4.8759v-45.616l13.0564,7.5498c1.1005.6285,1.5723,1.5728,1.5723,2.8314v34.6051c0,16.8297-13.0564,29.5723-30.5147,29.5723v.001ZM53.9522,112.7822l-30.0443-17.3024c-8.652-5.0343-14.471-15.7296-14.471-26.1107,0-12.1119,7.2356-22.9652,18.403-27.5272v35.8634c0,2.2028.9443,3.7756,2.8314,4.8763l39.3248,22.8068-12.8982,7.3938c-1.1007.6287-2.045.6287-3.1456,0ZM52.2229,138.5791c-17.7745,0-30.8306-13.3713-30.8306-29.8871,0-1.2585.1578-2.5169.3143-3.7754l30.987,17.9323c1.8871,1.1005,3.7757,1.1005,5.6628,0l39.4811-22.807v14.9435c0,1.2585-.4721,2.2021-1.5728,2.8308l-30.0443,17.3025c-4.0898,2.359-8.9662,3.4605-13.9989,3.4605h.0014ZM91.2319,157.296c19.0327,0,34.9188-13.5272,38.5383-31.4594,17.6164-4.562,28.9425-21.0779,28.9425-37.908,0-11.0112-4.719-21.7066-13.2133-29.4143.7867-3.3035,1.2595-6.607,1.2595-9.909,0-22.4929-18.2471-39.3247-39.3251-39.3247-4.2461,0-8.3363.6285-12.4262,2.045-7.0792-6.9213-16.8318-11.3254-27.5271-11.3254-19.0331,0-34.9191,13.5268-38.5384,31.4591C11.3255,36.0212,0,52.5373,0,69.3675c0,11.0112,4.7184,21.7065,13.2125,29.4142-.7865,3.3035-1.2586,6.6067-1.2586,9.9092,0,22.4923,18.2466,39.3241,39.3248,39.3241,4.2462,0,8.3362-.6277,12.426-2.0441,7.0776,6.921,16.8302,11.3251,27.5271,11.3251Z"/>
+</svg>
\ No newline at end of file
diff --git a/studio/frontend/public/hub/profile/logo/qwen.png b/studio/frontend/public/hub/profile/logo/qwen.png
new file mode 100644
index 00000000000..67d2258f407
Binary files /dev/null and b/studio/frontend/public/hub/profile/logo/qwen.png differ
diff --git a/studio/frontend/public/hub/profile/logo/xai.svg b/studio/frontend/public/hub/profile/logo/xai.svg
new file mode 100644
index 00000000000..0c83eb3d9bc
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/xai.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 466.04 516.93"><polygon points="0.12 182.71 234.14 516.92 338.15 516.92 104.13 182.71 0.12 182.71"/><polygon points="0 516.92 104.08 516.92 156.08 442.67 104.04 368.34 0 516.92"/><polygon points="466.04 0 361.96 0 182.1 256.86 234.15 331.18 466.04 0"/><polygon points="380.78 516.92 466.04 516.92 466.04 37.16 380.78 158.92 380.78 516.92"/></svg>
\ No newline at end of file
diff --git a/studio/frontend/public/hub/profile/logo/zai.svg b/studio/frontend/public/hub/profile/logo/zai.svg
new file mode 100644
index 00000000000..28ca7280a10
--- /dev/null
+++ b/studio/frontend/public/hub/profile/logo/zai.svg
@@ -0,0 +1,215 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0.0 0.0 30.0 30.0" style="enable-background:new 0 0 30 30;" xml:space="preserve" width="316.22776601683796" height="316.22776601683796">
+<style type="text/css">
+ .st0{opacity:0.3;fill:#E2E4E7;}
+ .st1{opacity:0.8;fill:#E2E4E7;stroke:#FFFFFF;stroke-width:5;stroke-miterlimit:10;}
+ .st2{fill:url(#SVGID_1_);}
+ .st3{fill:none;stroke:#E0E4E9;stroke-width:0.25;stroke-miterlimit:10;}
+ .st4{fill:none;}
+ .st5{fill:#9DA1A5;}
+ .st6{fill-rule:evenodd;clip-rule:evenodd;fill:none;}
+ .st7{fill-rule:evenodd;clip-rule:evenodd;fill:#DFE2E7;}
+ .st8{fill-rule:evenodd;clip-rule:evenodd;fill:#CDD4DA;}
+ .st9{fill-rule:evenodd;clip-rule:evenodd;fill:#B3BCC7;}
+ .st10{fill-rule:evenodd;clip-rule:evenodd;fill:#9DAAB7;}
+ .st11{fill-rule:evenodd;clip-rule:evenodd;fill:#8698A8;}
+ .st12{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_2_);}
+ .st13{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_3_);}
+ .st14{fill:#1F63EC;}
+ .st15{fill:#2D2D2D;}
+ .st16{fill:none;stroke:#E0E4E9;stroke-width:0.5;stroke-miterlimit:10;}
+ .st17{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_4_);}
+ .st18{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_5_);}
+ .st19{fill:none;stroke:#677380;stroke-width:0.5;stroke-miterlimit:10;}
+ .st20{fill:none;stroke:url(#SVGID_6_);stroke-width:2;stroke-miterlimit:10;}
+ .st21{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_7_);}
+ .st22{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_8_);}
+ .st23{fill:#FFFFFF;}
+ .st24{fill-rule:evenodd;clip-rule:evenodd;fill:#2D2D2D;}
+ .st25{clip-path:url(#SVGID_10_);}
+ .st26{clip-path:url(#SVGID_12_);}
+ .st27{fill:url(#SVGID_13_);}
+ .st28{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_14_);}
+ .st29{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_15_);}
+ .st30{clip-path:url(#SVGID_17_);}
+ .st31{clip-path:url(#SVGID_19_);}
+ .st32{fill:url(#SVGID_20_);}
+ .st33{fill:none;stroke:url(#SVGID_21_);stroke-width:2;stroke-miterlimit:10;}
+ .st34{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_22_);}
+ .st35{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_23_);}
+ .st36{clip-path:url(#SVGID_25_);}
+ .st37{clip-path:url(#SVGID_27_);}
+ .st38{fill:url(#SVGID_28_);}
+ .st39{clip-path:url(#SVGID_30_);}
+ .st40{clip-path:url(#SVGID_32_);}
+ .st41{fill:url(#SVGID_33_);}
+ .st42{fill-rule:evenodd;clip-rule:evenodd;fill:#126EF6;}
+ .st43{fill-rule:evenodd;clip-rule:evenodd;fill:#FFFFFF;}
+ .st44{clip-path:url(#SVGID_35_);}
+ .st45{clip-path:url(#SVGID_37_);}
+ .st46{fill:url(#SVGID_38_);}
+ .st47{fill-rule:evenodd;clip-rule:evenodd;fill:#9DA1A5;}
+ .st48{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_39_);}
+ .st49{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_40_);}
+ .st50{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_41_);}
+ .st51{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_42_);}
+ .st52{fill:none;stroke:url(#SVGID_43_);stroke-width:2;stroke-miterlimit:10;}
+ .st53{fill-rule:evenodd;clip-rule:evenodd;fill:none;stroke:#E0E4E9;stroke-width:0.5;stroke-miterlimit:10;}
+ .st54{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_44_);}
+ .st55{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_45_);}
+ .st56{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_46_);}
+ .st57{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_47_);}
+ .st58{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_48_);}
+ .st59{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_49_);}
+ .st60{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_50_);}
+ .st61{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_51_);}
+ .st62{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_52_);}
+ .st63{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_53_);}
+ .st64{clip-path:url(#SVGID_55_);}
+ .st65{clip-path:url(#SVGID_57_);}
+ .st66{fill:url(#SVGID_58_);}
+ .st67{clip-path:url(#SVGID_60_);}
+ .st68{clip-path:url(#SVGID_62_);}
+ .st69{fill:url(#SVGID_63_);}
+ .st70{fill:none;stroke:url(#SVGID_64_);stroke-width:2;stroke-miterlimit:10;}
+ .st71{clip-path:url(#SVGID_66_);}
+ .st72{clip-path:url(#SVGID_68_);}
+ .st73{fill:url(#SVGID_69_);}
+ .st74{clip-path:url(#SVGID_71_);}
+ .st75{clip-path:url(#SVGID_73_);}
+ .st76{fill:url(#SVGID_74_);}
+ .st77{clip-path:url(#SVGID_76_);}
+ .st78{clip-path:url(#SVGID_78_);}
+ .st79{fill:url(#SVGID_79_);}
+ .st80{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_80_);}
+ .st81{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_81_);}
+ .st82{clip-path:url(#SVGID_83_);}
+ .st83{clip-path:url(#SVGID_85_);}
+ .st84{fill:url(#SVGID_86_);}
+ .st85{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_87_);}
+ .st86{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_88_);}
+ .st87{clip-path:url(#SVGID_90_);}
+ .st88{clip-path:url(#SVGID_92_);}
+ .st89{fill:url(#SVGID_93_);}
+ .st90{fill:none;stroke:url(#SVGID_94_);stroke-width:2;stroke-miterlimit:10;}
+ .st91{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_95_);}
+ .st92{fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_96_);}
+ .st93{clip-path:url(#SVGID_98_);}
+ .st94{clip-path:url(#SVGID_100_);}
+ .st95{fill:url(#SVGID_101_);}
+ .st96{clip-path:url(#SVGID_103_);}
+ .st97{clip-path:url(#SVGID_105_);}
+ .st98{fill:url(#SVGID_106_);}
+ .st99{clip-path:url(#SVGID_108_);}
+ .st100{clip-path:url(#SVGID_110_);}
+ .st101{fill:url(#SVGID_111_);}
+ .st102{fill:#FFFFFF;stroke:#B3BCC7;stroke-width:0.275;stroke-miterlimit:10;}
+ .st103{clip-path:url(#SVGID_113_);}
+ .st104{fill:#FDD138;}
+ .st105{fill:#FCA62F;}
+ .st106{fill:#FB7927;}
+ .st107{fill:#F44B22;}
+ .st108{fill:#D81915;}
+ .st109{fill:#2D2D2D;stroke:#FFFFFF;stroke-width:0.3354;stroke-miterlimit:10;}
+ .st110{fill:none;stroke:#65727F;stroke-width:2;stroke-miterlimit:10;}
+ .st111{fill:none;stroke:#65727F;stroke-width:0.75;stroke-miterlimit:10;}
+ .st112{fill:url(#SVGID_114_);}
+ .st113{fill:#D06C50;}
+ .st114{fill:#2D2D2D;stroke:#B3BCC7;stroke-width:0.275;stroke-miterlimit:10;}
+ .st115{opacity:0.2;}
+ .st116{fill:none;stroke:#677380;stroke-width:0.3564;stroke-miterlimit:10;}
+ .st117{fill:none;stroke:#677380;stroke-width:0.3564;stroke-miterlimit:10;stroke-dasharray:1.0212,1.0212;}
+ .st118{fill:none;stroke:#677380;stroke-width:0.3564;stroke-miterlimit:10;stroke-dasharray:1.0205,1.0205;}
+ .st119{opacity:0.2;fill:none;}
+ .st120{fill:none;stroke:#677380;stroke-width:0.3689;stroke-miterlimit:10;}
+ .st121{fill:none;stroke:#677380;stroke-width:0.3689;stroke-miterlimit:10;stroke-dasharray:1.0509,1.0509;}
+ .st122{opacity:0.3;fill:#1F63EC;}
+ .st123{fill:#2D2D2D;stroke:#FFFFFF;stroke-width:0.3162;stroke-miterlimit:10;}
+ .st124{fill:#FFFFFF;stroke:#B3BCC7;stroke-width:0.3162;stroke-miterlimit:10;}
+ .st125{clip-path:url(#SVGID_118_);}
+ .st126{fill:url(#SVGID_119_);}
+ .st127{fill:none;stroke:#DFE2E7;stroke-width:0.75;stroke-miterlimit:10;}
+ .st128{fill:#9DA1A5;stroke:#FFFFFF;stroke-miterlimit:10;}
+ .st129{fill:url(#SVGID_120_);}
+ .st130{fill:none;stroke:#677380;stroke-width:0.75;stroke-miterlimit:10;}
+ .st131{opacity:0.4;}
+ .st132{clip-path:url(#SVGID_122_);}
+ .st133{clip-path:url(#SVGID_124_);}
+ .st134{fill:url(#SVGID_125_);}
+ .st135{fill:none;stroke:#8392A3;stroke-width:0.35;stroke-miterlimit:10;}
+ .st136{fill:none;stroke:#8392A3;stroke-width:0.35;stroke-miterlimit:10;stroke-dasharray:0.9951,0.9951;}
+ .st137{fill:none;stroke:#8392A3;stroke-width:0.35;stroke-miterlimit:10;stroke-dasharray:1.004,1.004;}
+ .st138{fill:none;stroke:url(#SVGID_126_);stroke-width:1.5;stroke-miterlimit:10;}
+ .st139{fill:url(#SVGID_127_);}
+ .st140{fill:none;stroke:#DDE0E4;stroke-width:0.35;stroke-miterlimit:10;}
+ .st141{fill:#2D2D2D;stroke:#A9B3BE;stroke-width:0.275;stroke-miterlimit:10;}
+ .st142{fill-rule:evenodd;clip-rule:evenodd;fill:#126EF4;}
+ .st143{fill:#FFFFFF;stroke:#B1BAC4;stroke-width:0.275;stroke-miterlimit:10;}
+ .st144{fill:#CE6C50;}
+ .st145{fill:#5B5B5B;}
+ .st146{fill:#8392A3;}
+ .st147{fill:none;stroke:url(#SVGID_128_);stroke-width:1.5;stroke-miterlimit:10;}
+ .st148{fill:url(#SVGID_129_);}
+ .st149{fill:none;stroke:#B5BDC4;stroke-width:0.7;stroke-miterlimit:10;}
+ .st150{opacity:0.6;fill:none;stroke:#78838E;stroke-width:0.35;stroke-miterlimit:10;}
+ .st151{opacity:0.2;fill:none;stroke:#8392A3;stroke-width:0.35;stroke-miterlimit:10;stroke-dasharray:1,1;}
+ .st152{fill:none;stroke:#DDE0E4;stroke-width:0.75;stroke-miterlimit:10;}
+ .st153{fill:none;stroke:#8392A3;stroke-width:0.5;stroke-miterlimit:10;}
+ .st154{opacity:0.2;fill:none;stroke:#677380;stroke-width:0.3564;stroke-miterlimit:10;stroke-dasharray:1.0182,1.0182;}
+ .st155{fill:none;stroke:#DDE0E4;stroke-width:0.765;stroke-miterlimit:10;}
+ .st156{fill:url(#SVGID_130_);}
+ .st157{fill:url(#SVGID_131_);}
+ .st158{fill:#B1BAC4;}
+ .st159{fill:#CBD1D8;}
+ .st160{fill:#0B1B2B;}
+ .st161{fill:#91D119;}
+ .st162{opacity:0.7;}
+ .st163{fill:#FFFFFF;stroke:#000000;stroke-width:0.4418;stroke-miterlimit:10;}
+ .st164{fill:none;stroke:#939CAA;stroke-width:0.2209;stroke-miterlimit:10;}
+ .st165{fill:none;stroke:#FFFFFF;stroke-width:3.0924;stroke-miterlimit:10;}
+ .st166{fill:url(#SVGID_132_);}
+ .st167{fill:none;stroke:url(#SVGID_133_);stroke-width:1.714;stroke-miterlimit:10;}
+ .st168{fill:url(#SVGID_134_);}
+ .st169{fill:url(#SVGID_135_);}
+ .st170{fill:url(#SVGID_136_);}
+ .st171{fill:url(#SVGID_137_);}
+ .st172{fill:url(#SVGID_138_);}
+ .st173{fill:url(#SVGID_139_);}
+ .st174{fill:url(#SVGID_140_);}
+ .st175{fill:url(#SVGID_141_);}
+ .st176{fill:url(#SVGID_142_);}
+ .st177{fill:url(#SVGID_143_);}
+ .st178{fill:url(#SVGID_144_);}
+ .st179{fill:none;stroke:#1F63EC;stroke-width:4;stroke-miterlimit:10;}
+ .st180{fill:none;stroke:#0B1B2B;stroke-width:4;stroke-miterlimit:10;}
+ .st181{fill:none;stroke:#677380;stroke-width:0.3989;stroke-miterlimit:10;}
+ .st182{fill:none;stroke:#677380;stroke-width:0.3989;stroke-miterlimit:10;stroke-dasharray:1.14,1.14;}
+ .st183{fill:#257AF1;}
+ .st184{opacity:0.3;fill:#FFFFFF;}
+ .st185{fill:none;stroke:#98A5B2;stroke-width:4;stroke-miterlimit:10;}
+ .st186{fill:none;stroke:#65727F;stroke-width:0.3989;stroke-miterlimit:10;}
+ .st187{fill:none;stroke:#65727F;stroke-width:0.3989;stroke-miterlimit:10;stroke-dasharray:1.14,1.14;}
+ .st188{fill:none;stroke:#DDDFE4;stroke-width:0.75;stroke-miterlimit:10;}
+ .st189{fill:#9A9EA2;}
+ .st190{fill-rule:evenodd;clip-rule:evenodd;fill:#3267AC;}
+ .st191{fill:#FFFFFF;stroke:#AFB8C3;stroke-width:0.275;stroke-miterlimit:10;}
+ .st192{fill:#C5694E;}
+ .st193{fill:#8192A2;}
+ .st194{fill:#2D2D2D;stroke:#FFFFFF;stroke-width:0.6317;stroke-miterlimit:10;}
+</style>
+<g id="图层_2">
+</g>
+<g id="图层_1">
+ <path class="st194" d="M24.51,28.51H5.49c-2.21,0-4-1.79-4-4V5.49c0-2.21,1.79-4,4-4h19.03c2.21,0,4,1.79,4,4v19.03 C28.51,26.72,26.72,28.51,24.51,28.51z"/>
+ <g>
+ <g>
+ <g>
+ <g>
+ <path class="st23" d="M15.47,7.1l-1.3,1.85c-0.2,0.29-0.54,0.47-0.9,0.47h-7.1V7.09C6.16,7.1,15.47,7.1,15.47,7.1z"/>
+ <polygon class="st23" points="24.3,7.1 13.14,22.91 5.7,22.91 16.86,7.1 "/>
+ <path class="st23" d="M14.53,22.91l1.31-1.86c0.2-0.29,0.54-0.47,0.9-0.47h7.09v2.33H14.53z"/>
+ </g>
+ </g>
+ </g>
+ </g>
+</g>
+</svg>
\ No newline at end of file
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index 4bd348effce..25dbfdc780d 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -9,7 +9,9 @@ import {
shouldUseCustomWindowTitlebar,
} from "@/components/tauri/window-titlebar";
import { Toaster } from "@/components/ui/sonner";
+import { TooltipProvider } from "@/components/ui/tooltip";
import { WebUpdateBanner } from "@/components/web/update-banner";
+import { DownloadManagerPanel } from "@/features/hub/download-manager";
import { getTauriAuthFailure, tauriAutoAuth } from "@/features/auth";
import { NativeIntentDrain } from "@/features/native-intents/native-intent-drain";
import { useTauriBackend, type BackendStatus } from "@/hooks/use-tauri-backend";
@@ -255,6 +257,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
return (
<>
{children}
+ <DownloadManagerPanel />
<WebUpdateBanner enabled={!WEB_UPDATE_HIDDEN_ROUTES.has(pathname)} />
</>
);
@@ -272,6 +275,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
<TauriUpdateLayer isExternalServer={isExternalServer} />
<NativeIntentDrain />
{children}
+ <DownloadManagerPanel />
</>
) : (
<StartupScreen
@@ -308,17 +312,19 @@ function TauriWrapper({ children }: { children: ReactNode }) {
export function AppProvider({ children }: AppProviderProps) {
return (
<ThemeProvider attribute="class" defaultTheme="light">
- <TauriWrapper>
- {children}
- </TauriWrapper>
- <Toaster
- position="top-right"
- visibleToasts={2}
- expand={true}
- closeButton={true}
- // Clear the chat header buttons on the right.
- offset={{ top: 12, right: 64 }}
- />
+ <TooltipProvider>
+ <TauriWrapper>
+ {children}
+ </TauriWrapper>
+ <Toaster
+ position="top-right"
+ visibleToasts={2}
+ expand={true}
+ closeButton={true}
+ // Clear the chat header buttons on the right.
+ offset={{ top: 12, right: 64 }}
+ />
+ </TooltipProvider>
</ThemeProvider>
);
}
diff --git a/studio/frontend/src/app/router.tsx b/studio/frontend/src/app/router.tsx
index a0ca1e8cdb6..dbb74ee1a13 100644
--- a/studio/frontend/src/app/router.tsx
+++ b/studio/frontend/src/app/router.tsx
@@ -12,6 +12,7 @@ import { Route as exportRoute } from "./routes/export";
import { Route as gridTestRoute } from "./routes/grid-test";
import { Route as indexRoute } from "./routes/index";
import { Route as loginRoute } from "./routes/login";
+import { Route as hubRoute } from "./routes/hub";
import { Route as onboardingRoute } from "./routes/onboarding";
import { Route as projectsRoute } from "./routes/projects";
import { Route as changePasswordRoute } from "./routes/change-password";
@@ -24,6 +25,7 @@ const routeTree = rootRoute.addChildren([
loginRoute,
changePasswordRoute,
gridTestRoute,
+ hubRoute,
settingsRoute,
studioRoute,
chatRoute,
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 200200d190a..c8e47902b9c 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -42,6 +42,7 @@ const CHAT_ONLY_ALLOWED = new Set([
"/",
"/chat",
"/projects",
+ "/hub",
"/login",
"/signup",
"/change-password",
diff --git a/studio/frontend/src/app/routes/hub.tsx b/studio/frontend/src/app/routes/hub.tsx
new file mode 100644
index 00000000000..dcd6617ec85
--- /dev/null
+++ b/studio/frontend/src/app/routes/hub.tsx
@@ -0,0 +1,29 @@
+// 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 { createRoute } from "@tanstack/react-router";
+import { lazy } from "react";
+import { requireAuth } from "../auth-guards";
+import { Route as rootRoute } from "./__root";
+
+const ModelsPage = lazy(() =>
+ import("@/features/hub/hub-page").then((m) => ({
+ default: m.ModelsPage,
+ })),
+);
+
+export interface ModelsSearch {
+ tab?: "discover" | "downloaded";
+}
+
+export const Route = createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/hub",
+ beforeLoad: () => requireAuth(),
+ component: ModelsPage,
+ validateSearch: (search: Record<string, unknown>): ModelsSearch => {
+ const raw = search.tab;
+ if (raw === "discover" || raw === "downloaded") return { tab: raw };
+ return {};
+ },
+});
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 8d56d90f980..2abc4d190ba 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -47,6 +47,7 @@ import { cn } from "@/lib/utils";
import {
ChefHatIcon,
CursorInfo02Icon,
+ DashboardCircleIcon,
Delete02Icon,
DownloadSquare01Icon,
Edit03Icon,
@@ -791,6 +792,15 @@ export function AppSidebar() {
closeMobileIfOpen();
}}
/>
+ <NavItem
+ icon={DashboardCircleIcon}
+ label={t("shell.navigation.hub")}
+ active={pathname === "/hub" || pathname.startsWith("/hub/")}
+ onClick={() => {
+ navigate({ to: "/hub" });
+ closeMobileIfOpen();
+ }}
+ />
{/* Train has a labelled section when expanded; plain icon here only when collapsed. */}
<NavItem
icon={TestTubeOutlineIcon}
diff --git a/studio/frontend/src/components/ui/tooltip.tsx b/studio/frontend/src/components/ui/tooltip.tsx
index b01dbccde15..954b1871f3f 100644
--- a/studio/frontend/src/components/ui/tooltip.tsx
+++ b/studio/frontend/src/components/ui/tooltip.tsx
@@ -48,16 +48,14 @@ function Tooltip({
}, []);
return (
- <TooltipProvider>
- <TooltipToggleCtx.Provider value={toggle}>
- <TooltipPrimitive.Root
- data-slot="tooltip"
- open={isControlled ? controlledOpen : clickOpen || undefined}
- onOpenChange={onOpenChange}
- {...props}
- />
- </TooltipToggleCtx.Provider>
- </TooltipProvider>
+ <TooltipToggleCtx.Provider value={toggle}>
+ <TooltipPrimitive.Root
+ data-slot="tooltip"
+ open={isControlled ? controlledOpen : clickOpen || undefined}
+ onOpenChange={onOpenChange}
+ {...props}
+ />
+ </TooltipToggleCtx.Provider>
);
}
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 320cf4c9622..ebaa756501e 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -23,6 +23,7 @@ import {
} from "../utils/chat-settings-storage";
const HF_TOKEN_KEY = "unsloth_hf_token";
+const HF_TOKEN_CHANGED_EVENT = "unsloth:hf-token-changed";
export const CHAT_REASONING_ENABLED_KEY = "unsloth_chat_reasoning_enabled";
export const CHAT_TOOLS_ENABLED_KEY = "unsloth_chat_tools_enabled";
export const CHAT_CODE_TOOLS_ENABLED_KEY = "unsloth_chat_code_tools_enabled";
@@ -231,6 +232,15 @@ function saveString(key: string, value: string): void {
}
}
+function notifyHfTokenChanged(value: string): void {
+ if (!canUseStorage()) return;
+ try {
+ window.dispatchEvent(new CustomEvent(HF_TOKEN_CHANGED_EVENT, { detail: value }));
+ } catch {
+ // ignore
+ }
+}
+
type ChatRuntimeStore = {
settingsHydrated: boolean;
params: InferenceParams;
@@ -766,11 +776,11 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
setScalarSettingVersion("autoTitle", autoTitle, state.autoTitle);
return { autoTitle };
}),
- setHfToken: (hfToken) =>
- set(() => {
- saveString(HF_TOKEN_KEY, hfToken);
- return { hfToken };
- }),
+ setHfToken: (hfToken) => {
+ saveString(HF_TOKEN_KEY, hfToken);
+ set({ hfToken });
+ notifyHfTokenChanged(hfToken);
+ },
setModelsError: (modelsError) => set({ modelsError }),
setCheckpoint: (modelId, ggufVariant) =>
set((state) => {
diff --git a/studio/frontend/src/features/hub/catalog/catalog-states.tsx b/studio/frontend/src/features/hub/catalog/catalog-states.tsx
new file mode 100644
index 00000000000..e4c85547739
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/catalog-states.tsx
@@ -0,0 +1,300 @@
+// 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 {
+ CloudOffIcon,
+ CubeIcon,
+ FilterIcon,
+ RefreshIcon,
+ WifiDisconnected02Icon,
+} from "@hugeicons/core-free-icons";
+import type { IconSvgElement } from "@hugeicons/react";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useLayoutEffect, useRef, useState } from "react";
+
+export function NetworkErrorState({
+ online,
+ message,
+ onRetry,
+ onSwitchDevice,
+ resourceLabel = "models",
+}: {
+ online: boolean;
+ message: string;
+ onRetry: () => void;
+ onSwitchDevice?: () => void;
+ resourceLabel?: "models" | "datasets";
+}) {
+ const title = online ? "Couldn't reach Hugging Face" : "You're offline";
+ const body = online
+ ? "The discovery feed couldn't load. Check your connection or try again."
+ : `Reconnect to the internet to browse ${resourceLabel} from Hugging Face.`;
+ const icon = online ? CloudOffIcon : WifiDisconnected02Icon;
+
+ return (
+ <div className="flex min-h-[260px] flex-col items-center justify-center gap-3 px-6 text-center">
+ <div className="inline-flex size-11 items-center justify-center rounded-[12px] bg-amber-500/10 text-amber-700 dark:text-amber-300">
+ <HugeiconsIcon icon={icon} strokeWidth={1.6} className="size-5" />
+ </div>
+ <div className="space-y-1">
+ <p className="text-[14px] font-semibold tracking-tight text-foreground">
+ {title}
+ </p>
+ <p className="max-w-md text-[12.5px] leading-5 text-muted-foreground">
+ {body}
+ </p>
+ <p className="text-[11px] text-muted-foreground/70">{message}</p>
+ </div>
+ <div className="flex flex-wrap items-center justify-center gap-2">
+ {onSwitchDevice ? (
+ <button
+ type="button"
+ onClick={onSwitchDevice}
+ className="inline-flex h-8 items-center gap-1.5 rounded-[10px] bg-foreground/[0.06] px-3 text-[12px] font-medium text-foreground transition-colors hover:bg-foreground/[0.1] dark:bg-white/[0.06] dark:hover:bg-white/[0.1]"
+ >
+ On Device
+ </button>
+ ) : null}
+ <button
+ type="button"
+ onClick={onRetry}
+ className="inline-flex h-8 items-center gap-1.5 rounded-[10px] bg-transparent px-3 text-[12px] font-medium text-foreground transition-colors hover:bg-foreground/[0.04] dark:hover:bg-white/[0.05]"
+ >
+ <HugeiconsIcon
+ icon={RefreshIcon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ Try again
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export function DiscoverFetchMoreState({
+ scannedCount,
+ hasActiveFilters,
+ isLoadingMore,
+ onFetchMore,
+ onClearFilters,
+}: {
+ scannedCount: number;
+ hasActiveFilters: boolean;
+ isLoadingMore: boolean;
+ onFetchMore: () => void;
+ onClearFilters: () => void;
+}) {
+ return (
+ <div className="flex min-h-[260px] flex-col items-center justify-center gap-3 px-6 text-center">
+ <div className="inline-flex size-11 items-center justify-center rounded-[12px] bg-muted text-muted-foreground">
+ <HugeiconsIcon icon={FilterIcon} strokeWidth={1.5} className="size-5" />
+ </div>
+ <div className="space-y-1">
+ <p className="text-[14px] font-semibold tracking-tight text-foreground">
+ No matches yet
+ </p>
+ <p className="max-w-md text-[12.5px] leading-5 text-muted-foreground">
+ Scanned {scannedCount.toLocaleString()} results. Load another page to
+ keep searching Hugging Face.
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center justify-center gap-2 pt-1">
+ {hasActiveFilters && (
+ <button
+ type="button"
+ onClick={onClearFilters}
+ className="inline-flex h-8 items-center gap-1.5 rounded-[10px] bg-foreground/[0.06] px-3 text-[12px] font-medium text-foreground transition-colors hover:bg-foreground/[0.1] dark:bg-white/[0.06] dark:hover:bg-white/[0.1]"
+ >
+ Clear filters
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={onFetchMore}
+ disabled={isLoadingMore}
+ className="inline-flex h-8 items-center gap-1.5 rounded-[10px] bg-transparent px-3 text-[12px] font-medium text-foreground transition-colors hover:bg-foreground/[0.04] disabled:cursor-not-allowed disabled:opacity-50 dark:hover:bg-white/[0.05]"
+ >
+ <HugeiconsIcon
+ icon={RefreshIcon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ {isLoadingMore ? "Loading..." : "Load more"}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export function DiscoverFetchMoreFooter({
+ scannedCount,
+ manualFetchAvailable,
+ hasActiveFilters,
+ isLoadingMore,
+ onFetchMore,
+}: {
+ scannedCount: number;
+ manualFetchAvailable: boolean;
+ hasActiveFilters: boolean;
+ isLoadingMore: boolean;
+ onFetchMore: () => void;
+}) {
+ return (
+ <div className="relative z-10 flex flex-col items-center gap-2 bg-card px-4 py-4 text-center">
+ <p className="text-[11.5px] leading-4 text-muted-foreground">
+ {hasActiveFilters
+ ? "Some results may be hidden by your filters."
+ : manualFetchAvailable
+ ? `Scanned ${scannedCount.toLocaleString()} results. Load more to continue.`
+ : "More results are available."}
+ </p>
+ <button
+ type="button"
+ onClick={onFetchMore}
+ disabled={isLoadingMore}
+ className="inline-flex h-8 items-center gap-1.5 rounded-[10px] bg-foreground/[0.06] px-3 text-[12px] font-medium text-foreground transition-colors hover:bg-foreground/[0.1] disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white/[0.06] dark:hover:bg-white/[0.1]"
+ >
+ <HugeiconsIcon
+ icon={RefreshIcon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ {isLoadingMore ? "Loading..." : "Load more"}
+ </button>
+ </div>
+ );
+}
+
+export function InventoryErrorState({
+ isDataset,
+ onRetry,
+}: {
+ isDataset: boolean;
+ onRetry: () => void;
+}) {
+ return (
+ <div className="flex min-h-[260px] flex-col items-center justify-center gap-3 px-6 text-center">
+ <div className="inline-flex size-11 items-center justify-center rounded-[12px] bg-amber-500/10 text-amber-700 dark:text-amber-300">
+ <HugeiconsIcon icon={CloudOffIcon} strokeWidth={1.6} className="size-5" />
+ </div>
+ <div className="space-y-1">
+ <p className="text-[14px] font-semibold tracking-tight text-foreground">
+ Couldn't load your library
+ </p>
+ <p className="max-w-md text-[12.5px] leading-5 text-muted-foreground">
+ Something went wrong reading your downloaded{" "}
+ {isDataset ? "datasets" : "models"}. Check that the backend is running
+ and try again.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={onRetry}
+ className="inline-flex h-8 items-center gap-1.5 rounded-[10px] bg-transparent px-3 text-[12px] font-medium text-foreground transition-colors hover:bg-foreground/[0.04] dark:hover:bg-white/[0.05]"
+ >
+ <HugeiconsIcon icon={RefreshIcon} strokeWidth={1.75} className="size-3.5" />
+ Try again
+ </button>
+ </div>
+ );
+}
+
+export function EmptyState({
+ title,
+ body,
+ icon = CubeIcon,
+}: {
+ title: string;
+ body: string;
+ icon?: IconSvgElement;
+}) {
+ return (
+ <div className="flex min-h-[220px] flex-col items-center justify-center gap-3 px-6 text-center">
+ <div className="inline-flex size-11 items-center justify-center rounded-[12px] bg-muted text-muted-foreground">
+ <HugeiconsIcon icon={icon} strokeWidth={1.5} className="size-5" />
+ </div>
+ <div className="space-y-1">
+ <p className="text-[14px] font-semibold tracking-tight text-foreground">
+ {title}
+ </p>
+ <p className="max-w-md text-[12.5px] leading-5 text-muted-foreground">
+ {body}
+ </p>
+ </div>
+ </div>
+ );
+}
+
+function SkeletonRow() {
+ return (
+ <div className="flex items-center gap-3 px-3 py-2.5">
+ <div className="size-8 shrink-0 animate-pulse rounded-[9px] bg-muted" />
+ <div className="min-w-0 flex-1 space-y-1.5">
+ <div className="h-[13px] w-1/2 animate-pulse rounded-full bg-muted" />
+ <div className="h-[11px] w-3/4 animate-pulse rounded-full bg-muted/70" />
+ </div>
+ </div>
+ );
+}
+
+const SKELETON_ROW_ESTIMATE_PX = 56;
+const MIN_SKELETON_ROWS = 4;
+const MAX_SKELETON_ROWS = 24;
+const DEFAULT_SKELETON_ROWS = 6;
+
+function clampSkeletonCount(height: number): number {
+ if (!Number.isFinite(height) || height <= 0) return DEFAULT_SKELETON_ROWS;
+ return Math.max(
+ MIN_SKELETON_ROWS,
+ Math.min(MAX_SKELETON_ROWS, Math.ceil(height / SKELETON_ROW_ESTIMATE_PX)),
+ );
+}
+
+export function SkeletonList({ count }: { count?: number }) {
+ const ref = useRef<HTMLUListElement>(null);
+ const [autoCount, setAutoCount] = useState(count ?? DEFAULT_SKELETON_ROWS);
+ const rowCount = count ?? autoCount;
+
+ useLayoutEffect(() => {
+ if (count != null) return;
+ const container = ref.current?.parentElement;
+ if (!container || typeof window === "undefined") return;
+
+ let frame: number | null = null;
+ const update = () => {
+ frame = null;
+ setAutoCount(clampSkeletonCount(container.clientHeight));
+ };
+ const schedule = () => {
+ if (frame !== null) return;
+ frame = window.requestAnimationFrame(update);
+ };
+ schedule();
+
+ if (typeof ResizeObserver === "undefined") {
+ window.addEventListener("resize", schedule);
+ return () => {
+ if (frame !== null) window.cancelAnimationFrame(frame);
+ window.removeEventListener("resize", schedule);
+ };
+ }
+
+ const observer = new ResizeObserver(schedule);
+ observer.observe(container);
+ return () => {
+ if (frame !== null) window.cancelAnimationFrame(frame);
+ observer.disconnect();
+ };
+ }, [count]);
+
+ return (
+ <ul ref={ref} className="divide-y divide-border" aria-hidden="true">
+ {Array.from({ length: rowCount }).map((_, i) => (
+ <li key={i}>
+ <SkeletonRow />
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/dataset-download-section.tsx b/studio/frontend/src/features/hub/catalog/dataset-download-section.tsx
new file mode 100644
index 00000000000..253d8181161
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/dataset-download-section.tsx
@@ -0,0 +1,193 @@
+// 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 {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { useRepoDownload } from "../download-manager";
+import { deleteCachedDataset } from "../inventory";
+import { cn } from "@/lib/utils";
+import { TrainIcon } from "../components/train-icon";
+import { HUB_POST_DOWNLOAD_ACTIONS_VISIBLE } from "../lib/hub-feature-flags";
+import { DotTag } from "./dot-tag";
+import { PathInfoButton } from "./path-info-button";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useState } from "react";
+import { useHfTokenStore } from "../stores/hf-token-store";
+import { formatBytes } from "../lib/format";
+import { useDatasetSize } from "../hooks/use-dataset-size";
+import {
+ CardDivider,
+ CardDeleteButton,
+ DeleteConfirmDialog,
+ DownloadActionButton,
+ DownloadCard,
+} from "./download-card";
+import { useCardDelete } from "./use-card-delete";
+import { useDownloadCardState } from "./use-download-card-state";
+
+export function DatasetDownloadSection({
+ repoId,
+ isDownloaded,
+ isPartial = false,
+ partialTransport = null,
+ cachePath,
+ knownBytes,
+ onTrain,
+ onChange,
+}: {
+ repoId: string;
+ isDownloaded: boolean;
+ isPartial?: boolean;
+ partialTransport?: string | null;
+ cachePath?: string | null;
+ knownBytes?: number | null;
+ onTrain?: () => void;
+ onChange?: () => void;
+}) {
+ const hfToken = useHfTokenStore((s) => s.token);
+ const [deleteOpen, setDeleteOpen] = useState(false);
+ const { deleting, runDelete } = useCardDelete({
+ action: () => deleteCachedDataset(repoId),
+ resourceName: "dataset",
+ successMessage: () => `Deleted ${repoId}`,
+ onSuccess: () => {
+ setDeleteOpen(false);
+ onChange?.();
+ },
+ });
+
+ const job = useRepoDownload({
+ kind: "dataset",
+ repoId,
+ autoAdopt: true,
+ });
+
+ const progress = job.progress;
+ const cancelling = job.cancelling;
+ const upstreamSize = useDatasetSize(repoId, {
+ enabled:
+ progress === null && !isDownloaded && !(knownBytes && knownBytes > 0),
+ token: hfToken || undefined,
+ });
+ const upstreamBytes =
+ upstreamSize?.numBytesParquet ?? upstreamSize?.numBytesOriginal ?? null;
+ const progressBytes =
+ progress && progress.expectedBytes > 0 ? progress.expectedBytes : null;
+ const totalBytes =
+ progressBytes && progressBytes > 0
+ ? progressBytes
+ : knownBytes && knownBytes > 0
+ ? knownBytes
+ : upstreamBytes;
+
+ const downloading = progress !== null;
+ const canDelete =
+ (isDownloaded || isPartial) && !downloading && !cancelling && !deleting;
+ const downloadAction = useDownloadCardState({
+ job,
+ variant: null,
+ // The datasets-server size above is a parquet/original estimate, not the raw
+ // repo bytes snapshot_download fetches; 0 lets the backend resolve the true total.
+ expectedBytes: 0,
+ downloading,
+ disabled: cancelling || deleting,
+ isPartial,
+ partialTransport,
+ });
+
+ return (
+ <DownloadCard
+ job={job}
+ progress={downloading ? progress : null}
+ dialogs={
+ <DeleteConfirmDialog
+ open={deleteOpen}
+ onOpenChange={(o) => {
+ if (!o && !deleting) setDeleteOpen(false);
+ }}
+ title="Delete cached dataset?"
+ deleting={deleting}
+ onConfirm={() => void runDelete()}
+ description={
+ <>
+ This will remove{" "}
+ <span className="font-medium text-foreground">{repoId}</span> and
+ its downloaded files
+ {totalBytes && totalBytes > 0
+ ? ` (${formatBytes(totalBytes)})`
+ : ""}{" "}
+ from disk. You can re-download it later.
+ </>
+ }
+ />
+ }
+ >
+ <div className="relative flex h-9 min-w-0 flex-1 items-center pl-3 pr-2">
+ <span className="flex items-center gap-1.5 text-[12px] text-muted-foreground">
+ {isDownloaded && <DotTag tone="success" label="On device" />}
+ {!isDownloaded && isPartial && !downloading && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex">
+ <DotTag tone="warning" label="Partial" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={4}>
+ Partial download. Click to continue.
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {totalBytes && totalBytes > 0 && (
+ <span className="tabular-nums">{formatBytes(totalBytes)}</span>
+ )}
+ </span>
+ <div className="ml-auto flex items-center gap-0.5">
+ {canDelete && (
+ <CardDeleteButton
+ label={`Delete ${repoId}`}
+ onClick={() => setDeleteOpen(true)}
+ />
+ )}
+ {isDownloaded && cachePath && (
+ <PathInfoButton
+ path={cachePath}
+ title="On-device location"
+ description={`Where ${repoId} lives on disk.`}
+ />
+ )}
+ </div>
+ </div>
+ {/* Train CTA hidden until Hub->train picker ships; divider pairs with it. */}
+ {(!isDownloaded || downloading || HUB_POST_DOWNLOAD_ACTIONS_VISIBLE) && (
+ <CardDivider />
+ )}
+ {isDownloaded && !downloading ? (
+ <button
+ type="button"
+ onClick={() => onTrain?.()}
+ className={cn(
+ "hub-action-btn w-28",
+ !HUB_POST_DOWNLOAD_ACTIONS_VISIBLE && "hidden",
+ )}
+ >
+ <HugeiconsIcon icon={TrainIcon} strokeWidth={1.75} />
+ Train
+ </button>
+ ) : (
+ <DownloadActionButton
+ downloading={downloadAction.downloading}
+ cancelling={downloadAction.cancelling}
+ loading={downloadAction.starting}
+ isPartial={downloadAction.isPartial}
+ partialTransport={downloadAction.partialTransport}
+ progressPercent={downloadAction.progressPercent}
+ disabled={downloadAction.disabled}
+ onClick={downloadAction.onClick}
+ />
+ )}
+ </DownloadCard>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/dot-tag.tsx b/studio/frontend/src/features/hub/catalog/dot-tag.tsx
new file mode 100644
index 00000000000..77b0a73d7bc
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/dot-tag.tsx
@@ -0,0 +1,46 @@
+// 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 { cn } from "@/lib/utils";
+
+type DotTagTone =
+ | "success"
+ | "warning"
+ | "danger"
+ | "gguf"
+ | "checkpoint"
+ | "adapter";
+
+const TONE_CLASS: Record<DotTagTone, string> = {
+ success: "bg-status-success",
+ warning: "bg-status-warning",
+ danger: "bg-status-danger",
+ gguf: "bg-format-gguf",
+ checkpoint: "bg-format-checkpoint",
+ adapter: "bg-format-adapter",
+};
+
+export function DotTag({
+ tone,
+ label,
+ className,
+}: {
+ tone: DotTagTone;
+ label: string;
+ className?: string;
+}) {
+ return (
+ <span
+ className={cn(
+ "inline-flex h-5 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-[7px] border border-border/60 bg-transparent px-1.5 text-[11px] font-medium leading-none text-muted-foreground",
+ className,
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className={cn("inline-block size-1.5 shrink-0 rounded-full", TONE_CLASS[tone])}
+ />
+ {label}
+ </span>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/download-cancel-indicator.tsx b/studio/frontend/src/features/hub/catalog/download-cancel-indicator.tsx
new file mode 100644
index 00000000000..d1b8671bfed
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/download-cancel-indicator.tsx
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Spinner } from "@/components/ui/spinner";
+import { Cancel01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+
+/**
+ * Inspector action-button affordance during a download: spinner that cross-fades
+ * to a cancel glyph on `.hub-action-btn` hover, in the same 16x16 slot so the
+ * percentage label never shifts. The swap is pure CSS; the component only carries
+ * the marker classes.
+ */
+export function DownloadCancelIndicator() {
+ return (
+ <span className="hub-cta-indicator">
+ <Spinner className="hub-cta-indicator-spinner" />
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ strokeWidth={1.75}
+ className="hub-cta-indicator-cancel"
+ />
+ </span>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/download-card.tsx b/studio/frontend/src/features/hub/catalog/download-card.tsx
new file mode 100644
index 00000000000..e5253526ab4
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/download-card.tsx
@@ -0,0 +1,217 @@
+// 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 { ReactNode } from "react";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Spinner } from "@/components/ui/spinner";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { Delete02Icon, Download01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ DownloadProgressBar,
+ type DownloadJob,
+ type DownloadJobProgress,
+} from "../download-manager";
+import { DownloadCancelIndicator } from "./download-cancel-indicator";
+import { TransportConflictDialog } from "./transport-conflict-dialog";
+import {
+ downloadActionAriaLabel,
+ downloadActionLabel,
+} from "./use-download-card-state";
+
+/**
+ * Shared shell for every download surface (safetensors, GGUF, dataset): card frame,
+ * progress bar, transport-conflict dialog, plus card-specific `dialogs` and children.
+ */
+export function DownloadCard({
+ job,
+ progress,
+ children,
+ dialogs,
+}: {
+ job: DownloadJob;
+ progress: DownloadJobProgress | null;
+ children: ReactNode;
+ dialogs?: ReactNode;
+}) {
+ return (
+ <>
+ <div className="hub-download-card">
+ <div className="group/dl flex items-center">{children}</div>
+ {progress && (
+ <DownloadProgressBar progress={progress} bytesPerSec={job.bytesPerSec} />
+ )}
+ </div>
+ <TransportConflictDialog
+ conflict={job.transportConflict}
+ onCancel={job.cancelConflict}
+ onKeepTransport={job.resumeConflict}
+ onSwitchTransport={job.restartConflict}
+ />
+ {dialogs}
+ </>
+ );
+}
+
+/** Vertical hairline that fades out on row hover, separating info from actions. */
+export function CardDivider() {
+ return (
+ <div
+ aria-hidden="true"
+ className="ml-1 mr-0 h-5 w-px shrink-0 bg-foreground/[0.06] opacity-100 transition-opacity duration-150 group-hover/dl:opacity-0 dark:bg-white/[0.04]"
+ />
+ );
+}
+
+export function CardDeleteButton({
+ label,
+ onClick,
+}: {
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ aria-label={label}
+ onClick={(e) => {
+ e.stopPropagation();
+ onClick();
+ }}
+ className="inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-[8px] text-muted-foreground opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-rose-500/10 hover:text-rose-600 focus-visible:opacity-100 group-hover/dl:opacity-100 dark:hover:bg-rose-500/15 dark:hover:text-rose-400"
+ >
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={4}>
+ Delete from device
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+/**
+ * Download / Cancel / Resume button for the safetensors and dataset cards
+ * (the GGUF card folds Run/Chat into its own bespoke CTA).
+ */
+export function DownloadActionButton({
+ downloading,
+ cancelling,
+ loading = false,
+ isPartial = false,
+ partialTransport = null,
+ progressPercent = null,
+ disabled,
+ onClick,
+ className,
+}: {
+ downloading: boolean;
+ cancelling: boolean;
+ loading?: boolean;
+ isPartial?: boolean;
+ partialTransport?: string | null;
+ progressPercent?: number | null;
+ disabled: boolean;
+ onClick: () => void;
+ className?: string;
+}) {
+ return (
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={onClick}
+ aria-label={downloadActionAriaLabel(downloading, cancelling)}
+ className={cn(
+ "hub-action-btn w-28",
+ (loading || cancelling) && "opacity-70",
+ downloading &&
+ !cancelling &&
+ "hover:bg-rose-500/10 hover:text-rose-600 dark:hover:text-rose-400",
+ className,
+ )}
+ >
+ {cancelling ? (
+ <span className="inline-flex items-center gap-2 text-muted-foreground">
+ <Spinner />
+ Cancelling…
+ </span>
+ ) : downloading ? (
+ <>
+ <DownloadCancelIndicator />
+ {progressPercent != null ? `${progressPercent}%` : null}
+ </>
+ ) : loading ? (
+ <>
+ <Spinner />
+ Loading…
+ </>
+ ) : (
+ <>
+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} />
+ {downloadActionLabel(isPartial, partialTransport)}
+ </>
+ )}
+ </button>
+ );
+}
+
+/** Confirmation dialog shared by the model, quantization, and dataset delete flows. */
+export function DeleteConfirmDialog({
+ open,
+ onOpenChange,
+ title,
+ description,
+ deleting,
+ onConfirm,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: string;
+ description: ReactNode;
+ deleting: boolean;
+ onConfirm: () => void;
+}) {
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent size="sm">
+ <AlertDialogHeader>
+ <AlertDialogTitle>{title}</AlertDialogTitle>
+ <AlertDialogDescription>{description}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ disabled={deleting}
+ onClick={(e) => {
+ e.preventDefault();
+ onConfirm();
+ }}
+ >
+ {deleting ? "Deleting…" : "Delete"}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/download-section.tsx b/studio/frontend/src/features/hub/catalog/download-section.tsx
new file mode 100644
index 00000000000..fb2921649bc
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/download-section.tsx
@@ -0,0 +1,82 @@
+// 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 { GgufDownloadCard } from "./gguf-download-card";
+import { SafetensorsDownloadCard } from "./safetensors-download-card";
+import type { ModelInventoryFormat } from "../inventory";
+
+export function DownloadSection({
+ repoId,
+ isGguf,
+ isDownloaded,
+ isPartial = false,
+ partialTransport = null,
+ modelFormat,
+ canRun = true,
+ isActive,
+ activeQuant,
+ isLoadingThisModel,
+ gpuGb,
+ systemRamGb,
+ cachePath,
+ knownBytes,
+ onLoad,
+ onUseInChat,
+ onTrain,
+ onChange,
+}: {
+ repoId: string;
+ isGguf: boolean;
+ isDownloaded: boolean;
+ isPartial?: boolean;
+ partialTransport?: string | null;
+ modelFormat?: ModelInventoryFormat | null;
+ canRun?: boolean;
+ isActive: boolean;
+ activeQuant: string | null;
+ isLoadingThisModel: boolean;
+ gpuGb?: number;
+ systemRamGb?: number;
+ cachePath?: string | null;
+ knownBytes?: number | null;
+ onLoad: (opts: { ggufVariant?: string; expectedBytes?: number }) => void;
+ onUseInChat?: () => void;
+ onTrain?: () => void;
+ onChange?: () => void;
+}) {
+ if (isGguf) {
+ return (
+ <GgufDownloadCard
+ repoId={repoId}
+ isActive={isActive}
+ activeQuant={activeQuant}
+ isLoadingThisModel={isLoadingThisModel}
+ gpuGb={gpuGb}
+ systemRamGb={systemRamGb}
+ cachePath={cachePath}
+ isPartial={isPartial}
+ onLoad={onLoad}
+ onUseInChat={onUseInChat}
+ onChange={onChange}
+ />
+ );
+ }
+ return (
+ <SafetensorsDownloadCard
+ repoId={repoId}
+ isDownloaded={isDownloaded}
+ isPartial={isPartial}
+ partialTransport={partialTransport}
+ modelFormat={modelFormat}
+ canRun={canRun}
+ isActive={isActive}
+ isLoadingThisModel={isLoadingThisModel}
+ cachePath={cachePath}
+ knownBytes={knownBytes}
+ onLoad={onLoad}
+ onUseInChat={onUseInChat}
+ onTrain={onTrain}
+ onChange={onChange}
+ />
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/external-link-confirm-dialog.tsx b/studio/frontend/src/features/hub/catalog/external-link-confirm-dialog.tsx
new file mode 100644
index 00000000000..5a661467fc4
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/external-link-confirm-dialog.tsx
@@ -0,0 +1,79 @@
+// 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 {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { openLink } from "@/lib/open-link";
+import { LinkSquare02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useExternalLinkConfirm } from "../stores/external-link-confirm";
+
+function hostOf(url: string): string {
+ try {
+ return new URL(url, "https://_").host;
+ } catch {
+ return url;
+ }
+}
+
+export function ExternalLinkConfirmDialog() {
+ const pendingUrl = useExternalLinkConfirm((s) => s.pendingUrl);
+ const dismiss = useExternalLinkConfirm((s) => s.dismiss);
+ const open = pendingUrl !== null;
+
+ return (
+ <AlertDialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) dismiss();
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <HugeiconsIcon
+ icon={LinkSquare02Icon}
+ strokeWidth={1.75}
+ className="text-muted-foreground"
+ />
+ </AlertDialogMedia>
+ <AlertDialogTitle>Open external link</AlertDialogTitle>
+ <AlertDialogDescription>
+ You are about to leave Unsloth and open this page in your browser.
+ Only continue if you trust the destination.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {pendingUrl && (
+ <div className="min-w-0 rounded-[12px] bg-muted/50 px-3 py-2.5 text-left">
+ <p className="truncate text-[13px] font-medium text-foreground">
+ {hostOf(pendingUrl)}
+ </p>
+ <p className="mt-0.5 break-all text-[11.5px] leading-[16px] text-muted-foreground">
+ {pendingUrl}
+ </p>
+ </div>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ if (pendingUrl) openLink(pendingUrl);
+ dismiss();
+ }}
+ >
+ Open link
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
new file mode 100644
index 00000000000..c9be7b549b3
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
@@ -0,0 +1,857 @@
+// 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 {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Spinner } from "@/components/ui/spinner";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ downloadManager,
+ useDownloadManagerStore,
+ useRepoDownload,
+} from "../download-manager";
+import { type GgufVariantDetail, deleteCachedModel } from "../inventory";
+import { formatBytes } from "../lib/format";
+import { type GgufFitClass, classifyGgufFit } from "../lib/gguf-fit";
+import { HUB_POST_DOWNLOAD_ACTIONS_VISIBLE } from "../lib/hub-feature-flags";
+import {
+ ggufVariantsMatch,
+ normalizeGgufVariantIdentity,
+} from "../lib/model-identity";
+import { cn } from "@/lib/utils";
+import { useHfTokenStore } from "../stores/hf-token-store";
+import {
+ ArrowDown01Icon,
+ Delete02Icon,
+ Download01Icon,
+ InformationCircleIcon,
+ PencilEdit02Icon,
+ PlayIcon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+ type KeyboardEventHandler,
+ type MouseEventHandler,
+} from "react";
+import {
+ ggufVariantDisplayLabel,
+ ggufVariantDownloadSizeBytes,
+ sortDownloadableGgufVariants,
+} from "../lib/gguf-variant-sort";
+import { DotTag } from "./dot-tag";
+import { DownloadCancelIndicator } from "./download-cancel-indicator";
+import {
+ CardDivider,
+ DeleteConfirmDialog,
+ DownloadCard,
+} from "./download-card";
+import {
+ activeDownloadState,
+ applyLiveGgufVariantStates,
+ createLiveGgufVariantStatesSelector,
+} from "./gguf-live-variant-states";
+import {
+ GgufDownloadStatusCard,
+ GgufDownloadingFallbackCard,
+} from "./gguf-status-cards";
+import { PathInfoButton } from "./path-info-button";
+import { useDeleteConfirmAction } from "./use-delete-confirm-action";
+import { useDownloadCardState } from "./use-download-card-state";
+import { useGgufVariantFetchState } from "./use-gguf-variant-fetch-state";
+
+interface FitBadgeMeta {
+ label: string;
+ tooltip: string;
+ iconClassName: string;
+}
+
+const FIT_BADGE: Record<GgufFitClass, FitBadgeMeta> = {
+ fits: {
+ label: "Full GPU offload",
+ tooltip: "Full offload likely possible on your system.",
+ iconClassName: "text-emerald-600 dark:text-emerald-400",
+ },
+ marginal: {
+ label: "Might fit",
+ tooltip:
+ "Might fit. Within the last GB of VRAM headroom, so loading can fail if other apps are using GPU memory.",
+ iconClassName: "text-amber-600 dark:text-amber-400",
+ },
+ partial: {
+ label: "Partial offload",
+ tooltip:
+ "Partial offload possible. Exceeds VRAM but fits with system RAM offload. Inference will be slower.",
+ iconClassName: "text-sky-600 dark:text-sky-400",
+ },
+ ram: {
+ label: "RAM fallback",
+ tooltip:
+ "No GPU VRAM detected. This GGUF may run with system RAM and CPU offload. Inference will be slower.",
+ iconClassName: "text-sky-600 dark:text-sky-400",
+ },
+ oom: {
+ label: "Won't fit",
+ tooltip: "Exceeds combined VRAM and system RAM budget.",
+ iconClassName: "text-rose-600 dark:text-rose-400",
+ },
+};
+
+/** Chip styling matching the on-device list's StatChip, no icon. */
+const CHIP_BASE =
+ "inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded-[7px] border px-1.5 text-[11.5px] font-medium tabular-nums leading-3 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]";
+const CHIP_DEFAULT =
+ "border-foreground/15 bg-muted text-foreground/85 dark:border-border/60 dark:bg-white/[0.04] dark:text-foreground/85";
+const CHIP_ACTIVE =
+ "border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300";
+
+function QuantBadge({
+ quant,
+ fit,
+ showFit = true,
+ active = false,
+ variant = "trigger",
+ tooltipMode = "eager",
+}: {
+ quant: string;
+ fit: GgufFitClass;
+ showFit?: boolean;
+ active?: boolean;
+ variant?: "trigger" | "menu";
+ tooltipMode?: "eager" | "lazy" | "none";
+}) {
+ const meta = FIT_BADGE[fit];
+ const [tooltipArmed, setTooltipArmed] = useState(false);
+ const [tooltipOpen, setTooltipOpen] = useState(false);
+ const armTooltip = useCallback(() => {
+ setTooltipArmed((armed) => (armed ? armed : true));
+ if (tooltipMode === "lazy") setTooltipOpen(true);
+ }, [tooltipMode]);
+ const tooltipActive = tooltipMode === "eager" || tooltipArmed;
+ const inner =
+ variant === "menu" ? (
+ <span
+ className={cn(
+ CHIP_BASE,
+ "gap-1.5 cursor-help",
+ active ? CHIP_ACTIVE : CHIP_DEFAULT,
+ )}
+ >
+ {showFit && (
+ <HugeiconsIcon
+ icon={InformationCircleIcon}
+ strokeWidth={2.25}
+ className={cn("size-3.5 shrink-0", meta.iconClassName)}
+ />
+ )}
+ <span>{quant}</span>
+ </span>
+ ) : (
+ <span
+ className={cn(
+ "inline-flex cursor-help items-center gap-1.5 text-[12.5px] font-medium tracking-tight tabular-nums",
+ active ? "text-emerald-600 dark:text-emerald-400" : "text-foreground",
+ )}
+ >
+ {showFit && (
+ <HugeiconsIcon
+ icon={InformationCircleIcon}
+ strokeWidth={2.25}
+ className={cn("size-3.5 shrink-0", meta.iconClassName)}
+ />
+ )}
+ <span>{quant}</span>
+ </span>
+ );
+ if (!showFit || tooltipMode === "none") return inner;
+ if (!tooltipActive) {
+ return (
+ <span
+ className="inline-flex min-w-0"
+ onPointerEnter={armTooltip}
+ onFocusCapture={armTooltip}
+ >
+ {inner}
+ </span>
+ );
+ }
+ return (
+ <Tooltip
+ open={tooltipMode === "lazy" ? tooltipOpen : undefined}
+ onOpenChange={tooltipMode === "lazy" ? setTooltipOpen : undefined}
+ >
+ <TooltipTrigger
+ asChild
+ onFocusCapture={tooltipMode === "lazy" ? armTooltip : undefined}
+ onPointerEnter={tooltipMode === "lazy" ? armTooltip : undefined}
+ >
+ {inner}
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={4}>
+ {meta.tooltip}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+interface GgufVariantMenuItem {
+ filename: string;
+ key: string;
+ quant: string;
+ label: string;
+ fit: GgufFitClass;
+ downloaded: boolean;
+ partial: boolean;
+ downloadSizeLabel: string;
+}
+
+function createGgufVariantMenuItems(
+ variants: readonly GgufVariantDetail[] | null,
+ resources: { gpuGb?: number; systemRamGb?: number },
+): GgufVariantMenuItem[] {
+ if (!variants) return [];
+ return variants.map((variant) => ({
+ filename: variant.filename,
+ key: normalizeGgufVariantIdentity(variant.quant),
+ quant: variant.quant,
+ label: ggufVariantDisplayLabel(variant),
+ fit: classifyGgufFit(variant.size_bytes, resources),
+ downloaded: Boolean(variant.downloaded),
+ partial: Boolean(variant.partial),
+ downloadSizeLabel: formatBytes(ggufVariantDownloadSizeBytes(variant)),
+ }));
+}
+
+const GgufVariantMenuRow = memo(function GgufVariantMenuRow({
+ item,
+ selected,
+ loaded,
+ liveActive,
+ showFitInfo,
+ onSelect,
+ onDelete,
+}: {
+ item: GgufVariantMenuItem;
+ selected: boolean;
+ loaded: boolean;
+ liveActive: boolean;
+ showFitInfo: boolean;
+ onSelect: (quant: string) => void;
+ onDelete: (quant: string) => void;
+}) {
+ const selectVariant = useCallback(() => {
+ onSelect(item.quant);
+ }, [item.quant, onSelect]);
+ const handleKeyDown = useCallback<KeyboardEventHandler<HTMLDivElement>>(
+ (e) => {
+ if (e.target !== e.currentTarget) return;
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ selectVariant();
+ }
+ },
+ [selectVariant],
+ );
+ const handleDelete = useCallback<MouseEventHandler<HTMLButtonElement>>(
+ (e) => {
+ e.stopPropagation();
+ onDelete(item.quant);
+ },
+ [item.quant, onDelete],
+ );
+ const canDelete = (item.downloaded || item.partial) && !loaded && !liveActive;
+
+ return (
+ <div
+ role="button"
+ tabIndex={0}
+ aria-pressed={selected}
+ onClick={selectVariant}
+ onKeyDown={handleKeyDown}
+ className={cn(
+ "group relative mx-2 flex cursor-pointer items-center gap-2 rounded-[12px] px-2.5 py-2 text-left transition-colors",
+ selected
+ ? "bg-foreground/[0.07] dark:bg-foreground/[0.12]"
+ : "hover:bg-foreground/[0.05] dark:hover:bg-foreground/[0.06]",
+ )}
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-2">
+ <QuantBadge
+ quant={item.label}
+ fit={item.fit}
+ showFit={showFitInfo}
+ active={loaded}
+ variant="menu"
+ tooltipMode="lazy"
+ />
+ </span>
+ <span className="ml-auto flex shrink-0 items-center gap-1.5">
+ {item.downloaded && (
+ <DotTag tone="success" label={loaded ? "Loaded" : "On device"} />
+ )}
+ {!item.downloaded && item.partial && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex">
+ <DotTag
+ tone="warning"
+ label={liveActive ? "Downloading" : "Partial"}
+ />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={4}>
+ {liveActive
+ ? "Download is running. Select it to view progress."
+ : "Partial download. Select it to continue."}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ <DotTag tone="gguf" label="GGUF" />
+ <span className="relative">
+ <span className={cn(CHIP_BASE, CHIP_DEFAULT)}>
+ {item.downloadSizeLabel}
+ </span>
+ {canDelete && (
+ <button
+ type="button"
+ onClick={handleDelete}
+ aria-label={`Delete ${item.label}${item.partial && !item.downloaded ? " (partial)" : ""}`}
+ className={cn(
+ "absolute inset-0 inline-flex cursor-pointer items-center justify-center rounded-[7px]",
+ "bg-popover text-foreground/70 ring-1 ring-border transition-colors",
+ "opacity-0 group-hover:opacity-100 focus-visible:opacity-100",
+ "hover:text-destructive hover:ring-destructive/40",
+ )}
+ >
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ strokeWidth={1.75}
+ className="size-3"
+ />
+ </button>
+ )}
+ </span>
+ </span>
+ </div>
+ );
+});
+
+export function GgufDownloadCard({
+ repoId,
+ isActive,
+ activeQuant,
+ isLoadingThisModel,
+ gpuGb,
+ systemRamGb,
+ cachePath,
+ preferLocalCache = false,
+ isPartial = false,
+ onLoad,
+ onUseInChat,
+ onChange,
+}: {
+ repoId: string;
+ isActive: boolean;
+ activeQuant: string | null;
+ isLoadingThisModel: boolean;
+ gpuGb?: number;
+ systemRamGb?: number;
+ cachePath?: string | null;
+ preferLocalCache?: boolean;
+ isPartial?: boolean;
+ onLoad: (opts: { ggufVariant?: string; expectedBytes?: number }) => void;
+ onUseInChat?: () => void;
+ onChange?: () => void;
+}) {
+ const hfToken = useHfTokenStore((s) => s.token);
+ const localVariantPath = cachePath?.trim() || null;
+ const { variants, loading, error, refreshError, refresh } =
+ useGgufVariantFetchState({
+ repoId,
+ hfToken,
+ preferLocalCache,
+ localPath: localVariantPath,
+ });
+ const [selectedQuantState, setSelectedQuantState] = useState<{
+ repoId: string;
+ quant: string | null;
+ userPicked?: boolean;
+ }>(() => ({ repoId, quant: null }));
+ const selectedQuantOverride =
+ selectedQuantState.repoId === repoId ? selectedQuantState.quant : null;
+ const [open, setOpen] = useState(false);
+ const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
+ const [completedVariantKeys, setCompletedVariantKeys] = useState<
+ ReadonlySet<string>
+ >(() => new Set<string>());
+
+ const rawSortedVariants = useMemo(() => {
+ if (!variants) return null;
+ return sortDownloadableGgufVariants(variants, { gpuGb, systemRamGb });
+ }, [variants, gpuGb, systemRamGb]);
+ const selectLiveGgufVariantStates = useMemo(
+ () => createLiveGgufVariantStatesSelector(repoId),
+ [repoId],
+ );
+ const liveVariantStates = useDownloadManagerStore(selectLiveGgufVariantStates);
+ const sortedVariants = useMemo(() => {
+ if (!rawSortedVariants) return null;
+ const withLive = applyLiveGgufVariantStates(
+ rawSortedVariants,
+ liveVariantStates,
+ );
+ if (completedVariantKeys.size === 0) return withLive;
+ return withLive.map((v) =>
+ completedVariantKeys.has(normalizeGgufVariantIdentity(v.quant))
+ ? { ...v, downloaded: true, partial: false }
+ : v,
+ );
+ }, [completedVariantKeys, liveVariantStates, rawSortedVariants]);
+ const variantMenuItems = useMemo(
+ () => createGgufVariantMenuItems(sortedVariants, { gpuGb, systemRamGb }),
+ [gpuGb, sortedVariants, systemRamGb],
+ );
+
+ const selectedQuant =
+ (selectedQuantOverride
+ ? sortedVariants?.find((v) =>
+ ggufVariantsMatch(v.quant, selectedQuantOverride),
+ )?.quant
+ : null) ??
+ sortedVariants?.[0]?.quant ??
+ null;
+
+ const job = useRepoDownload({
+ kind: "model",
+ repoId,
+ activeVariant: selectedQuant ?? undefined,
+ onComplete: (variant) => {
+ if (!variant) return;
+ const key = normalizeGgufVariantIdentity(variant);
+ setCompletedVariantKeys((prev) =>
+ prev.has(key) ? prev : new Set(prev).add(key),
+ );
+ },
+ });
+ const progress = job.progress;
+ const cancelling = job.cancelling;
+
+ const setExpectedBytes = job.setExpectedBytes;
+ useEffect(() => {
+ const controller = new AbortController();
+ void downloadManager.probeAndAdopt("model", repoId, controller.signal, {
+ includeVariants: true,
+ fresh: true,
+ onModelAdopt: (active) => {
+ if (controller.signal.aborted) return;
+ if (active.variant) {
+ setSelectedQuantState((prev) =>
+ prev.repoId === repoId && prev.userPicked
+ ? prev
+ : { repoId, quant: active.variant },
+ );
+ }
+ },
+ });
+ return () => {
+ controller.abort();
+ };
+ }, [repoId]);
+
+ useEffect(() => {
+ if (!variants || !progress?.variant) return;
+ const knownVariant = variants.find((variant) =>
+ ggufVariantsMatch(variant.quant, progress.variant),
+ );
+ if (!knownVariant) return;
+ const expectedBytes =
+ knownVariant.download_size_bytes ?? knownVariant.size_bytes ?? 0;
+ if (expectedBytes > progress.expectedBytes) {
+ setExpectedBytes(expectedBytes, progress.variant);
+ }
+ }, [
+ variants,
+ progress?.variant,
+ progress?.expectedBytes,
+ setExpectedBytes,
+ ]);
+
+ useEffect(() => {
+ setCompletedVariantKeys(new Set<string>());
+ }, [repoId]);
+
+ useEffect(() => {
+ if (loading || error || refreshError || !variants) return;
+ setCompletedVariantKeys((prev) =>
+ prev.size === 0 ? prev : new Set<string>(),
+ );
+ }, [loading, error, refreshError, variants]);
+
+ const selected =
+ sortedVariants?.find((v) => ggufVariantsMatch(v.quant, selectedQuant)) ??
+ null;
+ const selectedLiveState = selectedQuant
+ ? liveVariantStates.get(normalizeGgufVariantIdentity(selectedQuant))
+ : undefined;
+ const selectedLiveActive = activeDownloadState(selectedLiveState?.state);
+ const downloadingThisVariant =
+ progress !== null && ggufVariantsMatch(progress.variant, selectedQuant);
+ const ctaDisabled = isLoadingThisModel || !selected;
+ const selectedIsActive =
+ isActive && activeQuant && ggufVariantsMatch(selected?.quant, activeQuant);
+ const isGgufRunCta =
+ !!selected?.downloaded &&
+ !cancelling &&
+ !downloadingThisVariant &&
+ !isLoadingThisModel &&
+ !selectedIsActive;
+ const showFitInfo = Boolean(gpuGb) || Boolean(systemRamGb);
+ const selectedFit = useMemo(
+ () =>
+ selected
+ ? classifyGgufFit(selected.size_bytes, { gpuGb, systemRamGb })
+ : null,
+ [gpuGb, selected?.size_bytes, systemRamGb],
+ );
+ const selectedDownloadSizeLabel = selected
+ ? formatBytes(ggufVariantDownloadSizeBytes(selected))
+ : null;
+ const selectedVariantKey = selectedQuant
+ ? normalizeGgufVariantIdentity(selectedQuant)
+ : null;
+ const activeVariantKey = activeQuant
+ ? normalizeGgufVariantIdentity(activeQuant)
+ : null;
+ const handleSelectVariant = useCallback(
+ (quant: string) => {
+ setSelectedQuantState({
+ repoId,
+ quant,
+ userPicked: true,
+ });
+ setOpen(false);
+ },
+ [repoId],
+ );
+ const handleDeleteVariant = useCallback((quant: string) => {
+ setDeleteTarget(quant);
+ }, []);
+ const downloadAction = useDownloadCardState({
+ job,
+ variant: selectedQuant,
+ expectedBytes: selected?.download_size_bytes ?? selected?.size_bytes ?? 0,
+ downloading: downloadingThisVariant,
+ cancelling,
+ disabled: cancelling
+ ? true
+ : downloadingThisVariant
+ ? false
+ : ctaDisabled && !selectedIsActive,
+ isPartial: Boolean(selected?.partial),
+ partialTransport: selected?.partial_transport ?? null,
+ });
+ const selectedLabel = selected ? ggufVariantDisplayLabel(selected) : null;
+ const deleteTargetVariant =
+ deleteTarget && sortedVariants
+ ? sortedVariants.find((v) => ggufVariantsMatch(v.quant, deleteTarget))
+ : null;
+ const deleteTargetLabel = deleteTargetVariant
+ ? ggufVariantDisplayLabel(deleteTargetVariant)
+ : deleteTarget;
+ const { deleting, runDelete } = useDeleteConfirmAction({
+ action: async () => {
+ if (!deleteTarget) return;
+ await deleteCachedModel(repoId, deleteTarget, hfToken || undefined);
+ },
+ successMessage: () => `Deleted ${repoId} ${deleteTargetLabel ?? deleteTarget}`,
+ errorToast: (err) => ({
+ title: err instanceof Error ? err.message : "Failed to delete",
+ }),
+ onSuccess: () => {
+ onChange?.();
+ },
+ onSettled: () => {
+ setDeleteTarget(null);
+ },
+ });
+ const variantListUnavailable = !sortedVariants || sortedVariants.length === 0;
+ const showVariantLoadingState = loading && variantListUnavailable;
+
+ // Keep showing download progress even when the variant list is unavailable, so a
+ // remount never hides an in-flight download behind the variant status card.
+ if (progress && variantListUnavailable) {
+ return (
+ <GgufDownloadingFallbackCard
+ job={job}
+ progress={progress}
+ cancelling={cancelling}
+ />
+ );
+ }
+
+ if (showVariantLoadingState) {
+ return (
+ <GgufDownloadStatusCard
+ job={job}
+ loading
+ message="Loading available quantizations…"
+ />
+ );
+ }
+
+ if (variantListUnavailable) {
+ if (isPartial) {
+ return (
+ <GgufDownloadStatusCard
+ job={job}
+ tone="muted"
+ partial
+ message="Partial download present. Couldn't load quantizations."
+ actionLabel="Reload"
+ onAction={() => void refresh()}
+ />
+ );
+ }
+ return (
+ <GgufDownloadStatusCard
+ job={job}
+ tone="danger"
+ message={error ?? "No GGUF quantizations found in this repository."}
+ />
+ );
+ }
+
+ return (
+ <div className="flex w-full flex-col gap-2">
+ <DownloadCard
+ job={job}
+ progress={downloadingThisVariant ? progress : null}
+ dialogs={
+ <DeleteConfirmDialog
+ open={deleteTarget !== null}
+ onOpenChange={(o) => {
+ if (!o && !deleting) setDeleteTarget(null);
+ }}
+ title="Delete quantization?"
+ deleting={deleting}
+ onConfirm={() => void runDelete()}
+ description={
+ <>
+ This will remove{" "}
+ <span className="font-medium text-foreground">
+ {repoId} ({deleteTargetLabel})
+ </span>{" "}
+ from disk. You can re-download it later.
+ </>
+ }
+ />
+ }
+ >
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.preventDefault();
+ setOpen((o) => !o);
+ }}
+ className="hub-menu-trigger flex h-9 min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-[12px] px-3 text-left transition-colors hover:bg-foreground/[0.04] data-[state=open]:bg-foreground/[0.06] dark:hover:bg-white/[0.04] dark:data-[state=open]:bg-white/[0.06]"
+ >
+ {selected ? (
+ <QuantBadge
+ quant={selectedLabel ?? selected.quant}
+ fit={selectedFit ?? "oom"}
+ showFit={showFitInfo}
+ active={Boolean(selectedIsActive)}
+ />
+ ) : (
+ <span className="text-[12.5px] text-muted-foreground">
+ Select quantization
+ </span>
+ )}
+ <span className="ml-auto flex items-center gap-1.5 text-[12px] text-muted-foreground">
+ {selected?.downloaded && (
+ <DotTag
+ tone="success"
+ label={selectedIsActive ? "Loaded" : "On device"}
+ />
+ )}
+ {selected && !selected.downloaded && selected.partial && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex">
+ <DotTag
+ tone="warning"
+ label={selectedLiveActive ? "Downloading" : "Partial"}
+ />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={4}>
+ {selectedLiveActive
+ ? "Download is running. Click to cancel."
+ : "Partial download. Click to continue."}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ <DotTag tone="gguf" label="GGUF" />
+ {selected &&
+ selectedDownloadSizeLabel &&
+ !selected.downloaded && (
+ <span className="tabular-nums">
+ {selectedDownloadSizeLabel}
+ </span>
+ )}
+ <HugeiconsIcon
+ icon={ArrowDown01Icon}
+ strokeWidth={1.25}
+ className="ml-0.5 size-3.5 shrink-0"
+ />
+ </span>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ side="bottom"
+ sideOffset={8}
+ avoidCollisions={false}
+ className="hub-menu-instant menu-soft-surface w-[var(--radix-popover-trigger-width)] min-w-[200px] gap-0 overflow-hidden p-0 py-2 ring-0"
+ >
+ <div className="max-h-[344px] overflow-y-auto [scrollbar-width:thin]">
+ {variantMenuItems.map((item) => {
+ const liveState = liveVariantStates.get(item.key);
+ const liveActive = activeDownloadState(liveState?.state);
+ return (
+ <GgufVariantMenuRow
+ key={item.filename}
+ item={item}
+ selected={item.key === selectedVariantKey}
+ loaded={isActive && item.key === activeVariantKey}
+ liveActive={liveActive}
+ showFitInfo={showFitInfo}
+ onSelect={handleSelectVariant}
+ onDelete={handleDeleteVariant}
+ />
+ );
+ })}
+ </div>
+ </PopoverContent>
+ </Popover>
+
+ {selected?.downloaded && cachePath && (
+ <PathInfoButton
+ path={cachePath}
+ title="On-device location"
+ description={`Where ${repoId} (${selectedLabel}) lives on disk.`}
+ className="ml-0.5"
+ />
+ )}
+
+ {!isGgufRunCta && <CardDivider />}
+
+ <button
+ type="button"
+ disabled={downloadAction.disabled}
+ onClick={() => {
+ if (downloadingThisVariant) {
+ downloadAction.onClick();
+ return;
+ }
+ if (selectedIsActive) {
+ onUseInChat?.();
+ return;
+ }
+ if (!selected) return;
+ if (selected.downloaded) {
+ onLoad({
+ ggufVariant: selected.quant,
+ expectedBytes: selected.size_bytes,
+ });
+ } else {
+ downloadAction.onClick();
+ }
+ }}
+ aria-label={downloadAction.ariaLabel}
+ className={cn(
+ isGgufRunCta ? "hub-run-action-btn w-28" : "hub-action-btn w-28",
+ isGgufRunCta && "ml-2",
+ ctaDisabled &&
+ !selectedIsActive &&
+ !downloadingThisVariant &&
+ !cancelling &&
+ "opacity-70",
+ (cancelling || downloadAction.starting) && "opacity-70",
+ downloadingThisVariant &&
+ !cancelling &&
+ "hover:bg-rose-500/10 hover:text-rose-600 dark:hover:text-rose-400",
+ // Hide post-download CTAs (Run / New Chat) for this PR.
+ !HUB_POST_DOWNLOAD_ACTIONS_VISIBLE &&
+ !downloadingThisVariant &&
+ !cancelling &&
+ !isLoadingThisModel &&
+ (selectedIsActive || selected?.downloaded) &&
+ "hidden",
+ )}
+ >
+ {cancelling ? (
+ <span className="inline-flex items-center gap-2 text-muted-foreground">
+ <Spinner />
+ Cancelling…
+ </span>
+ ) : downloadingThisVariant ? (
+ <span className="inline-flex items-center gap-2">
+ <DownloadCancelIndicator />
+ {downloadAction.progressPercent != null
+ ? `${downloadAction.progressPercent}%`
+ : null}
+ </span>
+ ) : downloadAction.starting ? (
+ <span className="inline-flex items-center gap-2">
+ <Spinner />
+ Starting…
+ </span>
+ ) : isLoadingThisModel ? (
+ <span className="inline-flex items-center gap-2">
+ <Spinner />
+ Loading…
+ </span>
+ ) : selectedIsActive ? (
+ <>
+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} />
+ New Chat
+ </>
+ ) : selected?.downloaded ? (
+ <>
+ <HugeiconsIcon icon={PlayIcon} strokeWidth={1.75} />
+ Run
+ </>
+ ) : (
+ <>
+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} />
+ {downloadAction.downloadLabel}
+ </>
+ )}
+ </button>
+ </DownloadCard>
+ {refreshError && (
+ <button
+ type="button"
+ onClick={() => void refresh()}
+ className="self-start px-1 text-[11px] text-status-warning underline-offset-2 transition-colors hover:underline"
+ >
+ Couldn't refresh quantizations. Retry
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts b/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts
new file mode 100644
index 00000000000..ca18a00bcee
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts
@@ -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 type { ManagedDownload } from "../download-manager";
+import type { GgufVariantDetail } from "../inventory";
+import { normalizeGgufVariantIdentity } from "../lib/model-identity";
+
+export type LiveGgufVariantState = {
+ state: ManagedDownload["state"];
+ expectedBytes: number;
+ startedAt: number;
+};
+
+export function activeDownloadState(state: ManagedDownload["state"] | undefined): boolean {
+ return state === "running" || state === "cancelling";
+}
+
+function terminalPartialState(state: ManagedDownload["state"] | undefined): boolean {
+ return state === "cancelled" || state === "error";
+}
+
+function completedDownloadState(
+ state: ManagedDownload["state"] | undefined,
+): boolean {
+ return state === "complete";
+}
+
+export function createLiveGgufVariantStatesSelector(repoId: string): (state: {
+ jobs: Record<string, ManagedDownload>;
+}) => Map<string, LiveGgufVariantState> {
+ const repoKey = repoId.trim().toLowerCase();
+ let cache: { signature: string; states: Map<string, LiveGgufVariantState> } = {
+ signature: "",
+ states: new Map(),
+ };
+ return (state) => {
+ const entries: Array<[string, LiveGgufVariantState]> = [];
+ for (const job of Object.values(state.jobs)) {
+ if (job.kind !== "model" || !job.variant) continue;
+ if (job.repoId.trim().toLowerCase() !== repoKey) continue;
+ const live =
+ activeDownloadState(job.state) ||
+ completedDownloadState(job.state) ||
+ (terminalPartialState(job.state) &&
+ Math.max(job.downloadedBytes, job.completedBytes) > 0);
+ if (!live) continue;
+ entries.push([
+ normalizeGgufVariantIdentity(job.variant),
+ {
+ state: job.state,
+ expectedBytes: job.expectedBytes,
+ startedAt: job.startedAt,
+ },
+ ]);
+ }
+ entries.sort(([left], [right]) => left.localeCompare(right));
+ const signature = JSON.stringify(entries);
+ if (signature === cache.signature) return cache.states;
+ cache = { signature, states: new Map(entries) };
+ return cache.states;
+ };
+}
+
+export function applyLiveGgufVariantStates(
+ variants: readonly GgufVariantDetail[],
+ liveStates: ReadonlyMap<string, LiveGgufVariantState>,
+): GgufVariantDetail[] {
+ return variants.map((variant) => {
+ const live = liveStates.get(normalizeGgufVariantIdentity(variant.quant));
+ if (!live) return variant;
+ const liveComplete = completedDownloadState(live.state);
+ const livePartial =
+ activeDownloadState(live.state) || terminalPartialState(live.state);
+ const expectedBytes = Math.max(
+ live.expectedBytes,
+ variant.download_size_bytes ?? 0,
+ variant.size_bytes,
+ );
+ return {
+ ...variant,
+ downloaded: liveComplete ? true : livePartial ? false : variant.downloaded,
+ partial: liveComplete ? false : livePartial || variant.partial,
+ download_size_bytes:
+ expectedBytes > 0 ? expectedBytes : variant.download_size_bytes,
+ };
+ });
+}
diff --git a/studio/frontend/src/features/hub/catalog/gguf-status-cards.tsx b/studio/frontend/src/features/hub/catalog/gguf-status-cards.tsx
new file mode 100644
index 00000000000..6cc764b876e
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/gguf-status-cards.tsx
@@ -0,0 +1,110 @@
+// 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 { Spinner } from "@/components/ui/spinner";
+import { cn } from "@/lib/utils";
+import type { DownloadJob, DownloadJobProgress } from "../download-manager";
+import { DotTag } from "./dot-tag";
+import {
+ CardDivider,
+ DownloadActionButton,
+ DownloadCard,
+} from "./download-card";
+
+export function GgufDownloadStatusCard({
+ job,
+ message,
+ tone = "muted",
+ loading = false,
+ partial = false,
+ actionLabel,
+ onAction,
+}: {
+ job: DownloadJob;
+ message: string;
+ tone?: "muted" | "danger";
+ loading?: boolean;
+ partial?: boolean;
+ actionLabel?: string;
+ onAction?: () => void;
+}) {
+ return (
+ <div className="flex w-full flex-col gap-2">
+ <DownloadCard job={job} progress={null}>
+ <div className="relative flex h-9 min-w-0 flex-1 items-center pl-3 pr-2">
+ <span
+ className={cn(
+ "flex min-w-0 items-center gap-2 text-[12.5px]",
+ tone === "danger" ? "text-destructive" : "text-muted-foreground",
+ )}
+ >
+ {loading && <Spinner className="size-3.5 shrink-0" />}
+ {partial && <DotTag tone="warning" label="Partial" />}
+ <span className="truncate">{message}</span>
+ </span>
+ </div>
+ <CardDivider />
+ {actionLabel && onAction ? (
+ <button
+ type="button"
+ onClick={onAction}
+ className="hub-action-btn w-28"
+ >
+ {actionLabel}
+ </button>
+ ) : (
+ <button
+ type="button"
+ disabled
+ className="hub-action-btn w-28 opacity-70"
+ >
+ {loading ? (
+ <>
+ <Spinner />
+ Loading
+ </>
+ ) : (
+ "Unavailable"
+ )}
+ </button>
+ )}
+ </DownloadCard>
+ </div>
+ );
+}
+
+/**
+ * Shown when a download is in flight but the variant list isn't loaded. Keeps the
+ * live job as source of truth so progress + cancel survive a remount instead of
+ * being replaced by the variant-status card.
+ */
+export function GgufDownloadingFallbackCard({
+ job,
+ progress,
+ cancelling,
+}: {
+ job: DownloadJob;
+ progress: DownloadJobProgress;
+ cancelling: boolean;
+}) {
+ return (
+ <div className="flex w-full flex-col gap-2">
+ <DownloadCard job={job} progress={progress}>
+ <div className="relative flex h-9 min-w-0 flex-1 items-center pl-3 pr-2">
+ <span className="flex min-w-0 items-center gap-2 text-[12.5px] text-muted-foreground">
+ {progress.variant && <DotTag tone="gguf" label={progress.variant} />}
+ <span className="truncate">Downloading…</span>
+ </span>
+ </div>
+ <CardDivider />
+ <DownloadActionButton
+ downloading
+ cancelling={cancelling}
+ progressPercent={Math.round(Math.min(progress.fraction, 1) * 100)}
+ disabled={cancelling}
+ onClick={() => void job.cancelDownload(progress.variant)}
+ />
+ </DownloadCard>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/hub-option-menu.tsx b/studio/frontend/src/features/hub/catalog/hub-option-menu.tsx
new file mode 100644
index 00000000000..76539d43ded
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/hub-option-menu.tsx
@@ -0,0 +1,239 @@
+// 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 {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { cn } from "@/lib/utils";
+import { ArrowDown01Icon, Tick02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ type KeyboardEvent,
+ type ReactNode,
+ useCallback,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+
+export interface HubOption<T extends string> {
+ value: T;
+ label: ReactNode;
+ triggerLabel?: ReactNode;
+ checkClassName?: string;
+}
+
+export function HubOptionMenu<T extends string>({
+ value,
+ options,
+ onValueChange,
+ className,
+ contentClassName,
+ ariaLabel,
+ align = "start",
+ showChevron = true,
+ title,
+ triggerContent,
+}: {
+ value: T;
+ options: readonly HubOption<T>[];
+ onValueChange: (value: T) => void;
+ className?: string;
+ contentClassName?: string;
+ ariaLabel: string;
+ align?: "start" | "center" | "end";
+ showChevron?: boolean;
+ title?: string;
+ triggerContent?: ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ const [activeIndex, setActiveIndex] = useState(0);
+ const triggerRef = useRef<HTMLButtonElement | null>(null);
+ const listboxRef = useRef<HTMLDivElement | null>(null);
+ const idBase = useId();
+ const listboxId = `${idBase}-listbox`;
+
+ const selectedIndex = useMemo(() => {
+ const index = options.findIndex((option) => option.value === value);
+ return index >= 0 ? index : 0;
+ }, [options, value]);
+ const selected = options[selectedIndex];
+ const resolvedActiveIndex =
+ options.length === 0
+ ? -1
+ : Math.min(Math.max(activeIndex, 0), options.length - 1);
+ const activeOptionId =
+ resolvedActiveIndex >= 0 ? `${idBase}-option-${resolvedActiveIndex}` : undefined;
+
+ const activateIndex = useCallback((index: number) => {
+ setActiveIndex((current) => (current === index ? current : index));
+ }, []);
+
+ const closeAndRestoreFocus = useCallback(() => {
+ setOpen(false);
+ requestAnimationFrame(() => triggerRef.current?.focus());
+ }, []);
+
+ const selectIndex = useCallback(
+ (index: number) => {
+ const option = options[index];
+ if (!option) return;
+ onValueChange(option.value);
+ closeAndRestoreFocus();
+ },
+ [closeAndRestoreFocus, onValueChange, options],
+ );
+
+ const handleOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ setOpen(nextOpen);
+ if (nextOpen) {
+ activateIndex(selectedIndex);
+ requestAnimationFrame(() => listboxRef.current?.focus());
+ }
+ },
+ [activateIndex, selectedIndex],
+ );
+
+ const handleContentKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ if (options.length === 0) return;
+ const currentIndex =
+ resolvedActiveIndex >= 0 ? resolvedActiveIndex : selectedIndex;
+
+ if (event.key === "Escape") {
+ event.preventDefault();
+ closeAndRestoreFocus();
+ return;
+ }
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ setActiveIndex((currentIndex + 1) % options.length);
+ return;
+ }
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ setActiveIndex((currentIndex - 1 + options.length) % options.length);
+ return;
+ }
+ if (event.key === "Home") {
+ event.preventDefault();
+ setActiveIndex(0);
+ return;
+ }
+ if (event.key === "End") {
+ event.preventDefault();
+ setActiveIndex(options.length - 1);
+ return;
+ }
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ selectIndex(currentIndex);
+ }
+ },
+ [
+ closeAndRestoreFocus,
+ options,
+ resolvedActiveIndex,
+ selectIndex,
+ selectedIndex,
+ ],
+ );
+
+ return (
+ <Popover open={open} onOpenChange={handleOpenChange}>
+ <PopoverTrigger asChild>
+ <button
+ ref={triggerRef}
+ type="button"
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ aria-controls={open ? listboxId : undefined}
+ aria-label={ariaLabel}
+ title={title}
+ className={cn(
+ "field-trigger hub-menu-trigger field-soft field-filter inline-flex h-9 shrink-0 cursor-pointer items-center justify-between gap-2 rounded-full px-3 text-[12.5px] transition-colors",
+ "focus-visible:border-border focus-visible:ring-0 focus-visible:ring-offset-0",
+ className,
+ )}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ event.preventDefault();
+ handleOpenChange(true);
+ }
+ }}
+ >
+ <span className="flex min-w-0 items-center gap-2 truncate">
+ {triggerContent ?? selected?.triggerLabel ?? selected?.label ?? value}
+ </span>
+ {showChevron && (
+ <HugeiconsIcon
+ icon={ArrowDown01Icon}
+ strokeWidth={1.5}
+ className="size-3.5 shrink-0 text-muted-foreground"
+ />
+ )}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align={align}
+ side="bottom"
+ sideOffset={8}
+ collisionPadding={12}
+ onCloseAutoFocus={(event) => event.preventDefault()}
+ className={cn(
+ "hub-menu-instant menu-soft-surface w-max min-w-[var(--radix-popover-trigger-width)] max-w-[min(var(--radix-popover-content-available-width),calc(100vw-1rem))] rounded-[14px] p-1 ring-0",
+ contentClassName,
+ )}
+ >
+ <div
+ ref={listboxRef}
+ id={listboxId}
+ role="listbox"
+ aria-label={ariaLabel}
+ aria-activedescendant={activeOptionId}
+ tabIndex={0}
+ onKeyDown={handleContentKeyDown}
+ className="outline-none"
+ >
+ {options.map((option, index) => {
+ const selectedOption = option.value === value;
+ const activeOption = index === resolvedActiveIndex;
+ return (
+ <div
+ key={option.value}
+ id={`${idBase}-option-${index}`}
+ role="option"
+ aria-selected={selectedOption}
+ data-highlighted={activeOption || undefined}
+ onClick={() => {
+ selectIndex(index);
+ }}
+ onPointerEnter={() => activateIndex(index)}
+ className={cn(
+ "relative flex w-full min-w-0 cursor-pointer select-none items-center rounded-xl corner-squircle py-2 pr-8 pl-3 text-left text-sm leading-snug outline-none transition-colors",
+ )}
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-2.5 overflow-hidden whitespace-normal break-words">
+ {option.label}
+ </span>
+ {selectedOption && (
+ <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
+ <HugeiconsIcon
+ icon={Tick02Icon}
+ strokeWidth={2}
+ className={cn("size-4", option.checkClassName)}
+ />
+ </span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/local-dataset-card.tsx b/studio/frontend/src/features/hub/catalog/local-dataset-card.tsx
new file mode 100644
index 00000000000..5b9ca6b1dec
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/local-dataset-card.tsx
@@ -0,0 +1,64 @@
+// 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 { TrainIcon } from "@/features/hub/components/train-icon";
+import { HUB_POST_DOWNLOAD_ACTIONS_VISIBLE } from "@/features/hub/lib/hub-feature-flags";
+import { HugeiconsIcon } from "@hugeicons/react";
+import type { LocalSource } from "../types";
+import { DotTag } from "./dot-tag";
+import { PathInfoButton } from "./path-info-button";
+
+interface LocalDatasetCardProps {
+ sourceLabel: string;
+ source: LocalSource;
+ path: string;
+ onTrain?: () => void;
+}
+
+export function LocalDatasetCard({
+ sourceLabel,
+ source,
+ path,
+ onTrain,
+}: LocalDatasetCardProps) {
+ return (
+ <div className="hub-download-card">
+ <div className="group/dl flex items-center">
+ <div className="relative flex h-9 min-w-0 flex-1 items-center pl-3 pr-2">
+ <span className="flex min-w-0 items-center gap-1.5 text-[12px] text-muted-foreground">
+ <DotTag tone="success" label="On device" />
+ {source !== "hf_cache" && (
+ <span className="truncate text-muted-foreground/85">
+ {sourceLabel}
+ </span>
+ )}
+ </span>
+ <div className="ml-auto flex items-center gap-0.5">
+ <PathInfoButton
+ path={path}
+ title={sourceLabel}
+ description="Where this dataset lives on disk."
+ />
+ </div>
+ </div>
+ {HUB_POST_DOWNLOAD_ACTIONS_VISIBLE && (
+ <div
+ aria-hidden="true"
+ className="ml-1 mr-0 h-5 w-px shrink-0 bg-foreground/[0.06] opacity-100 transition-opacity duration-150 group-hover/dl:opacity-0 dark:bg-white/[0.04]"
+ />
+ )}
+ {/* Train CTA hidden until Hub->train picker ships. */}
+ {onTrain && HUB_POST_DOWNLOAD_ACTIONS_VISIBLE && (
+ <button
+ type="button"
+ onClick={() => onTrain()}
+ className="hub-action-btn w-28"
+ >
+ <HugeiconsIcon icon={TrainIcon} strokeWidth={1.75} />
+ Train
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
new file mode 100644
index 00000000000..c5e754d9822
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
@@ -0,0 +1,545 @@
+// 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 { TrainIcon } from "../components/train-icon";
+import { HUB_POST_DOWNLOAD_ACTIONS_VISIBLE } from "../lib/hub-feature-flags";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Spinner } from "@/components/ui/spinner";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ type BaseModelSource,
+ type LocalModelInfo,
+ type ModelInventoryFormat,
+ deleteCachedModel,
+} from "../inventory";
+import { formatBytes } from "../lib/format";
+import { ggufVariantsMatch } from "../lib/model-identity";
+import { cn } from "@/lib/utils";
+import { confirmExternalLink } from "../stores/external-link-confirm";
+import { useHfTokenStore } from "../stores/hf-token-store";
+import {
+ Alert02Icon,
+ ArrowDown01Icon,
+ CubeIcon,
+ PencilEdit02Icon,
+ PlayIcon,
+ Share05Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useMemo, useState } from "react";
+import {
+ ggufVariantDisplayLabel,
+ sortLocalGgufVariants,
+} from "../lib/gguf-variant-sort";
+import { DotTag } from "./dot-tag";
+import { CardDeleteButton, DeleteConfirmDialog } from "./download-card";
+import { PathInfoButton } from "./path-info-button";
+import { useCardDelete } from "./use-card-delete";
+import { useGgufVariantFetchState } from "./use-gguf-variant-fetch-state";
+
+type LocalLoadOptions = {
+ ggufVariant?: string;
+ expectedBytes?: number;
+};
+
+interface LocalOnDeviceCardProps {
+ modelId: string;
+ repoId: string | null;
+ sourceLabel: string;
+ source: LocalModelInfo["source"];
+ path: string;
+ isGguf: boolean;
+ requiresVariant?: boolean;
+ modelFormat: ModelInventoryFormat | null;
+ baseModel?: string | null;
+ baseModelSource?: BaseModelSource | null;
+ baseModelHubId?: string | null;
+ baseModelSummary?: string | null;
+ adapterType?: string | null;
+ trainingMethod?: string | null;
+ canRun?: boolean;
+ isActive: boolean;
+ activeGgufVariant?: string | null;
+ isLoading: boolean;
+ loadingPhase?: "downloading" | "starting";
+ gpuGb?: number;
+ systemRamGb?: number;
+ unsupportedReason?: string | null;
+ onLoad: (opts?: LocalLoadOptions) => void;
+ onUseInChat: () => void;
+ onTrain?: () => void;
+ onChange?: () => void;
+}
+
+function formatAdapterLabel(
+ adapterType?: string | null,
+ trainingMethod?: string | null,
+): string {
+ const method = trainingMethod?.trim().toLowerCase();
+ if (method === "qlora") return "QLoRA adapter";
+ if (method === "lora") return "LoRA adapter";
+ const type = adapterType?.trim();
+ return type ? `${type.toUpperCase()} adapter` : "Adapter";
+}
+
+function baseModelSourceLabel(source?: BaseModelSource | null): string {
+ if (source === "huggingface") return "Hugging Face base model";
+ if (source === "local") return "Local base model";
+ return "Base model";
+}
+
+function BaseModelReference({
+ baseModel,
+ baseModelSource,
+ baseModelHubId,
+ baseModelSummary,
+}: {
+ baseModel: string;
+ baseModelSource?: BaseModelSource | null;
+ baseModelHubId?: string | null;
+ baseModelSummary?: string | null;
+}) {
+ const canOpenHub = baseModelSource === "huggingface" && !!baseModelHubId;
+ return (
+ <div className="flex min-w-0 items-center gap-2 rounded-[10px] border border-border/55 bg-muted/35 px-3 py-2">
+ <div className="flex size-7 shrink-0 items-center justify-center rounded-[8px] bg-background/70 text-muted-foreground">
+ <HugeiconsIcon
+ icon={CubeIcon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="shrink-0 text-[11px] font-medium text-muted-foreground">
+ {baseModelSourceLabel(baseModelSource)}
+ </span>
+ <span className="truncate text-[12px] font-medium text-foreground">
+ {baseModel}
+ </span>
+ </div>
+ {baseModelSummary && (
+ <p className="mt-0.5 truncate text-[11px] text-muted-foreground">
+ {baseModelSummary}
+ </p>
+ )}
+ </div>
+ {canOpenHub && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <a
+ href={`https://huggingface.co/${baseModelHubId}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={`Open ${baseModelHubId} on Hugging Face`}
+ className="inline-flex size-7 shrink-0 items-center justify-center rounded-[8px] text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
+ onClick={(event) => {
+ event.stopPropagation();
+ if (confirmExternalLink(`https://huggingface.co/${baseModelHubId}`)) {
+ event.preventDefault();
+ }
+ }}
+ >
+ <HugeiconsIcon
+ icon={Share05Icon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </a>
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={4}>
+ Open base model
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ );
+}
+
+export function LocalOnDeviceCard({
+ modelId,
+ repoId,
+ sourceLabel,
+ source,
+ path,
+ isGguf,
+ requiresVariant = false,
+ modelFormat,
+ baseModel,
+ baseModelSource,
+ baseModelHubId,
+ baseModelSummary,
+ adapterType,
+ trainingMethod,
+ canRun = true,
+ isActive,
+ activeGgufVariant = null,
+ isLoading,
+ loadingPhase,
+ gpuGb,
+ systemRamGb,
+ unsupportedReason,
+ onLoad,
+ onUseInChat,
+ onTrain,
+ onChange,
+}: LocalOnDeviceCardProps) {
+ const [deleteOpen, setDeleteOpen] = useState(false);
+ const [variantOpen, setVariantOpen] = useState(false);
+ const hfToken = useHfTokenStore((s) => s.token);
+ const { deleting, runDelete } = useCardDelete({
+ action: async () => {
+ if (!repoId) return;
+ await deleteCachedModel(repoId, undefined, hfToken || undefined);
+ },
+ resourceName: "model",
+ successMessage: () => `Deleted ${repoId}`,
+ onSuccess: () => {
+ setDeleteOpen(false);
+ onChange?.();
+ },
+ });
+ const localGgufPath = path.trim();
+ const needsVariantSelection =
+ isGguf && requiresVariant && !localGgufPath.toLowerCase().endsWith(".gguf");
+ const currentVariantState = useGgufVariantFetchState({
+ repoId: modelId,
+ hfToken,
+ preferLocalCache: true,
+ localPath: localGgufPath,
+ enabled: needsVariantSelection,
+ errorFallback: "Failed to load quantizations",
+ });
+ const variantKey = currentVariantState.key;
+ const [selectedVariantState, setSelectedVariantState] = useState<{
+ key: string;
+ quant: string | null;
+ }>(() => ({
+ key: variantKey,
+ quant: null,
+ }));
+
+ const canDelete =
+ source === "hf_cache" && !!repoId && !isActive && !isLoading;
+ const variants = currentVariantState.variants;
+ const sortedVariants = useMemo(
+ () =>
+ variants
+ ? sortLocalGgufVariants(variants, {
+ defaultVariant: currentVariantState.defaultVariant,
+ activeGgufVariant: isActive ? activeGgufVariant : null,
+ gpuGb,
+ systemRamGb,
+ })
+ : null,
+ [
+ variants,
+ currentVariantState.defaultVariant,
+ isActive,
+ activeGgufVariant,
+ gpuGb,
+ systemRamGb,
+ ],
+ );
+ const selectedVariantOverride =
+ selectedVariantState.key === variantKey ? selectedVariantState.quant : null;
+ const selectedQuant =
+ selectedVariantOverride &&
+ sortedVariants?.some((variant) =>
+ ggufVariantsMatch(variant.quant, selectedVariantOverride),
+ )
+ ? selectedVariantOverride
+ : (sortedVariants?.find(
+ (variant) =>
+ isActive && ggufVariantsMatch(variant.quant, activeGgufVariant),
+ )?.quant ??
+ sortedVariants?.find((variant) =>
+ ggufVariantsMatch(variant.quant, currentVariantState.defaultVariant),
+ )?.quant ??
+ sortedVariants?.[0]?.quant ??
+ null);
+ const selectedVariant =
+ sortedVariants?.find((variant) =>
+ ggufVariantsMatch(variant.quant, selectedQuant),
+ ) ?? null;
+ const selectedVariantIsActive =
+ needsVariantSelection && selectedQuant
+ ? isActive && ggufVariantsMatch(activeGgufVariant, selectedQuant)
+ : isActive;
+ const variantUnavailable =
+ needsVariantSelection &&
+ (currentVariantState.loading ||
+ currentVariantState.error !== null ||
+ selectedVariant === null);
+ const variantActionPending =
+ needsVariantSelection && currentVariantState.loading;
+
+ const formatLabel =
+ modelFormat === "gguf"
+ ? "GGUF"
+ : modelFormat === "adapter"
+ ? formatAdapterLabel(adapterType, trainingMethod)
+ : modelFormat === "checkpoint"
+ ? "Checkpoint"
+ : modelFormat === "safetensors"
+ ? "Safetensors"
+ : "Model";
+ const formatTone =
+ modelFormat === "adapter" ? "adapter" : isGguf ? "gguf" : "checkpoint";
+ const showOldCacheHint = source === "hf_cache" && !!unsupportedReason;
+
+ return (
+ <div className="flex w-full flex-col gap-2">
+ {showOldCacheHint && (
+ <div className="flex items-start gap-2 rounded-[12px] border border-amber-500/20 bg-amber-500/8 px-3 py-2 text-[12px] leading-5 text-amber-700 dark:text-amber-300">
+ <HugeiconsIcon
+ icon={Alert02Icon}
+ strokeWidth={1.75}
+ className="mt-[1px] size-3.5 shrink-0"
+ />
+ <span>
+ This looks like an older Hub cache. It may use a format that Unsloth
+ no longer loads (missing config or unsupported quantization). You
+ can still keep it on disk, or delete it to free space.
+ </span>
+ </div>
+ )}<div className="hub-download-card">
+ <div className="group/dl flex items-center">
+ <div className="relative flex h-9 min-w-0 flex-1 items-center pl-3 pr-2">
+ <span className="flex min-w-0 items-center gap-1.5 text-[12px] text-muted-foreground">
+ <DotTag
+ tone="success"
+ label={selectedVariantIsActive ? "Loaded" : "On device"}
+ />
+ <DotTag tone={formatTone} label={formatLabel} />
+ {needsVariantSelection && (
+ <Popover open={variantOpen} onOpenChange={setVariantOpen}>
+ <PopoverTrigger asChild={true}>
+ <button
+ type="button"
+ disabled={currentVariantState.loading}
+ className="inline-flex h-6 max-w-[170px] shrink-0 cursor-pointer items-center gap-1.5 rounded-[8px] border border-format-gguf/35 px-2 font-mono text-[10.5px] leading-none text-format-gguf transition-colors hover:bg-format-gguf/8 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <span className="truncate">
+ {currentVariantState.loading
+ ? "Loading"
+ : currentVariantState.error
+ ? "Unavailable"
+ : selectedVariant
+ ? ggufVariantDisplayLabel(selectedVariant)
+ : "Select"}
+ </span>
+ {selectedVariant && (
+ <span className="shrink-0 font-sans text-[10px] text-muted-foreground tabular-nums">
+ {formatBytes(selectedVariant.size_bytes)}
+ </span>
+ )}
+ <HugeiconsIcon
+ icon={ArrowDown01Icon}
+ strokeWidth={1.5}
+ className="size-3 shrink-0"
+ />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ side="bottom"
+ sideOffset={8}
+ avoidCollisions={false}
+ className="hub-menu-instant menu-soft-surface w-[var(--radix-popover-trigger-width)] min-w-[220px] gap-0 overflow-hidden p-0 py-2 ring-0"
+ >
+ <div className="max-h-[280px] overflow-y-auto [scrollbar-width:thin]">
+ {sortedVariants?.map((variant) => {
+ const label = ggufVariantDisplayLabel(variant);
+ const isSelected = ggufVariantsMatch(
+ variant.quant,
+ selectedQuant,
+ );
+ const isLoaded =
+ ggufVariantsMatch(variant.quant, activeGgufVariant) &&
+ isActive;
+ return (
+ <button
+ key={variant.filename}
+ type="button"
+ onClick={() => {
+ setSelectedVariantState({
+ key: variantKey,
+ quant: variant.quant,
+ });
+ setVariantOpen(false);
+ }}
+ className={cn(
+ "mx-2 flex w-[calc(100%-1rem)] min-w-0 cursor-pointer items-center gap-2 rounded-[10px] px-2.5 py-2 text-left transition-colors",
+ isSelected
+ ? "bg-foreground/[0.07] dark:bg-foreground/[0.12]"
+ : "hover:bg-foreground/[0.05] dark:hover:bg-foreground/[0.06]",
+ )}
+ >
+ <span className="min-w-0 flex-1 truncate font-mono text-[12px] text-format-gguf">
+ {label}
+ </span>
+ <span className="flex shrink-0 items-center gap-1.5">
+ {isLoaded && (
+ <DotTag tone="success" label="Loaded" />
+ )}
+ <span className="text-[10px] text-muted-foreground tabular-nums">
+ {formatBytes(variant.size_bytes)}
+ </span>
+ </span>
+ </button>
+ );
+ })}
+ {!currentVariantState.loading &&
+ !currentVariantState.error &&
+ sortedVariants?.length === 0 && (
+ <div className="px-4 py-2 text-xs text-muted-foreground">
+ No quantizations found.
+ </div>
+ )}
+ {currentVariantState.error && (
+ <div className="px-4 py-2 text-xs text-destructive">
+ {currentVariantState.error}
+ </div>
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ )}
+ {source !== "hf_cache" && (
+ <span className="truncate text-muted-foreground/85">
+ {sourceLabel}
+ </span>
+ )}
+ </span>
+ <div className="ml-auto flex items-center gap-0.5">
+ {canDelete && (
+ <CardDeleteButton
+ label={`Delete ${repoId}`}
+ onClick={() => setDeleteOpen(true)}
+ />
+ )}
+ <PathInfoButton
+ path={path}
+ title={sourceLabel}
+ description="Where this model lives on disk."
+ />
+ </div>
+ </div>
+ {onTrain && HUB_POST_DOWNLOAD_ACTIONS_VISIBLE && (
+ <div
+ aria-hidden="true"
+ className="ml-1 mr-0 h-5 w-px shrink-0 bg-foreground/[0.06] opacity-100 transition-opacity duration-150 group-hover/dl:opacity-0 dark:bg-white/[0.04]"
+ />
+ )}
+ {/* Run + Train pair hidden until Hub->chat/train pickers ship. */}
+ <div
+ className={cn(
+ "group/pair flex h-9 shrink-0 items-stretch gap-1.5",
+ !HUB_POST_DOWNLOAD_ACTIONS_VISIBLE && "hidden",
+ )}
+ >
+ {onTrain && (
+ <button
+ type="button"
+ onClick={() => onTrain()}
+ className="hub-action-btn w-24"
+ >
+ <HugeiconsIcon icon={TrainIcon} strokeWidth={1.75} />
+ Train
+ </button>
+ )}
+ <button
+ type="button"
+ disabled={isLoading || variantUnavailable || !canRun}
+ onClick={() => {
+ if (!canRun) return;
+ if (selectedVariantIsActive) {
+ onUseInChat();
+ return;
+ }
+ if (needsVariantSelection) {
+ if (!selectedVariant) return;
+ onLoad({
+ ggufVariant: selectedVariant.quant,
+ expectedBytes: selectedVariant.size_bytes,
+ });
+ return;
+ }
+ onLoad();
+ }}
+ className={cn(
+ isLoading ||
+ selectedVariantIsActive ||
+ variantUnavailable ||
+ !canRun
+ ? "hub-action-btn w-24"
+ : "hub-run-action-btn w-24",
+ (isLoading || variantUnavailable || !canRun) && "opacity-70",
+ )}
+ >
+ {isLoading ? (
+ <>
+ <Spinner />
+ {loadingPhase === "downloading" ? "Preparing…" : "Loading…"}
+ </>
+ ) : selectedVariantIsActive ? (
+ <>
+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} />
+ Chat
+ </>
+ ) : variantActionPending ? (
+ <>
+ <Spinner />
+ Loading…
+ </>
+ ) : !canRun ? (
+ <>
+ <HugeiconsIcon icon={Alert02Icon} strokeWidth={1.75} />
+ No run
+ </>
+ ) : (
+ <>
+ <HugeiconsIcon icon={PlayIcon} strokeWidth={1.75} />
+ Run
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ {baseModel && (
+ <BaseModelReference
+ baseModel={baseModel}
+ baseModelSource={baseModelSource}
+ baseModelHubId={baseModelHubId}
+ baseModelSummary={baseModelSummary}
+ />
+ )}
+ <DeleteConfirmDialog
+ open={deleteOpen}
+ onOpenChange={(o) => {
+ if (!o && !deleting) setDeleteOpen(false);
+ }}
+ title="Delete cached model?"
+ deleting={deleting}
+ onConfirm={() => void runDelete()}
+ description={
+ <>
+ This will remove{" "}
+ <span className="font-medium text-foreground">{repoId}</span> and
+ its downloaded files from disk. You can re-download it later.
+ </>
+ }
+ />
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/model-inspector.tsx b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
new file mode 100644
index 00000000000..54165aa5e6b
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
@@ -0,0 +1,732 @@
+// 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 {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { usePlatformStore } from "@/config/env";
+import {
+ type UnslothSupport,
+ classifyUnslothSupport,
+} from "@/features/hub/hooks/use-hub-model-search";
+import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
+import { formatBytes, formatRelativeShort } from "@/features/hub/lib/format";
+import { cn, formatCompact } from "@/lib/utils";
+import { confirmExternalLink } from "../stores/external-link-confirm";
+import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";
+import {
+ Calendar03Icon,
+ Copy01Icon,
+ CpuIcon,
+ CubeIcon,
+ Database02Icon,
+ Download01Icon,
+ FavouriteIcon,
+ Globe02Icon,
+ LayersLogoIcon,
+ LicenseIcon,
+ PackageIcon,
+ RamMemoryIcon,
+ Share05Icon,
+ Tick02Icon,
+} from "@hugeicons/core-free-icons";
+import type { IconSvgElement } from "@hugeicons/react";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ memo,
+ useDeferredValue,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { useCopyFeedback } from "../hooks/use-copy-feedback";
+import { useDatasetSize } from "../hooks/use-dataset-size";
+import {
+ formatLocalUpdated,
+ formatPipelineTag,
+ parseLanguageTags,
+} from "../lib/view-models";
+import type { SelectedModelView } from "../types";
+import {
+ selectActiveJob,
+ useDownloadManagerStore,
+} from "../download-manager";
+import { DatasetDownloadSection } from "./dataset-download-section";
+import { DownloadSection } from "./download-section";
+import { LocalDatasetCard } from "./local-dataset-card";
+import { LocalOnDeviceCard } from "./local-on-device-card";
+import { ModelReadme } from "./model-readme";
+import { OwnerAvatar } from "./owner-avatar";
+import { CapabilityPill } from "./shared";
+
+function ViewRepositoryButton({
+ repoId,
+ isDataset,
+}: {
+ repoId: string;
+ isDataset: boolean;
+}) {
+ const online = useOnlineStatus();
+ const url = `https://huggingface.co/${isDataset ? "datasets/" : ""}${repoId}`;
+ const baseClass =
+ "inline-flex size-7 shrink-0 items-center justify-center rounded-[8px] text-muted-foreground transition-colors";
+ const icon = (
+ <HugeiconsIcon icon={Share05Icon} strokeWidth={1.75} className="size-4" />
+ );
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ {online ? (
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label="View repository"
+ className={cn(baseClass, "hover:bg-muted hover:text-foreground")}
+ onClick={(event) => {
+ event.stopPropagation();
+ if (confirmExternalLink(url)) {
+ event.preventDefault();
+ }
+ }}
+ >
+ {icon}
+ </a>
+ ) : (
+ <span
+ aria-label="View repository unavailable offline"
+ aria-disabled="true"
+ className={cn(baseClass, "cursor-not-allowed opacity-45")}
+ >
+ {icon}
+ </span>
+ )}
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="tooltip-compact">
+ {online ? "Open on Hugging Face" : "Unavailable offline"}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+function CopyRepoButton({ repoId }: { repoId: string }) {
+ const { copied, copy } = useCopyFeedback();
+
+ const handleCopy = async (event: React.MouseEvent<HTMLButtonElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ await copy(repoId);
+ };
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label="Copy repository ID"
+ onClick={handleCopy}
+ className="inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-[8px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={copied ? Tick02Icon : Copy01Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="tooltip-compact">
+ {repoId}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+function StatRow({
+ label,
+ value,
+ icon,
+}: {
+ label: string;
+ value: string;
+ icon: IconSvgElement;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <span className="hub-tag-meta inline-flex cursor-default items-center gap-1.5 px-2.5 py-1 text-[11.5px] text-muted-foreground transition-colors hover:text-foreground/80">
+ <HugeiconsIcon
+ icon={icon}
+ strokeWidth={1.75}
+ className="size-3.5 shrink-0"
+ />
+ <span className="font-medium tabular-nums">{value}</span>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent className="tooltip-compact">{label}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+function StatGrid({ children }: { children: React.ReactNode }) {
+ return <div className="flex flex-wrap items-center gap-1.5">{children}</div>;
+}
+
+function InspectorDownloadSlot({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="shrink-0 pl-6 pr-10 pt-3 sm:pr-14 lg:pr-[4.5rem] xl:pr-[5.5rem]">
+ {children}
+ </div>
+ );
+}
+
+function StatusChip({
+ tone,
+ label,
+ className,
+}: {
+ tone: "success" | "warning" | "danger";
+ label: string;
+ className?: string;
+}) {
+ const toneClass =
+ tone === "danger"
+ ? "border-red-500/35 text-red-700 dark:border-red-400/40 dark:text-red-300"
+ : tone === "warning"
+ ? "border-amber-500/40 text-amber-700 dark:border-amber-400/45 dark:text-amber-300"
+ : "border-emerald-500/40 text-emerald-700 dark:border-emerald-400/45 dark:text-emerald-300";
+ return (
+ <span
+ className={cn(
+ "inline-flex h-5 shrink-0 items-center whitespace-nowrap rounded-[7px] border bg-transparent px-1.5 text-[11px] font-medium leading-none",
+ toneClass,
+ className,
+ )}
+ >
+ {label}
+ </span>
+ );
+}
+
+type VramInfo = { est: number; status: "fits" | "tight" | "exceeds" } | null;
+
+function ModelStatusChips({
+ isDataset,
+ isGguf,
+ unslothSupport,
+ vramInfo,
+}: {
+ isDataset: boolean;
+ isGguf: boolean;
+ unslothSupport: UnslothSupport;
+ vramInfo: VramInfo;
+}) {
+ const showUnsupported = !isDataset && unslothSupport.status === "unsupported";
+ const showVram = !isDataset && vramInfo && !isGguf;
+ if (!showUnsupported && !showVram) return null;
+
+ const vramTone = vramInfo
+ ? vramInfo.status === "exceeds"
+ ? "danger"
+ : vramInfo.status === "tight"
+ ? "warning"
+ : "success"
+ : "success";
+ const vramLabel = vramInfo
+ ? vramInfo.status === "exceeds"
+ ? `Over VRAM budget · ~${vramInfo.est} GB`
+ : vramInfo.status === "tight"
+ ? `Tight fit · ~${vramInfo.est} GB`
+ : `Likely fits · ~${vramInfo.est} GB`
+ : "";
+ const vramDetail = vramInfo
+ ? vramInfo.status === "exceeds"
+ ? "A 4-bit load is likely to exceed the current GPU budget. Higher-precision loads need even more."
+ : vramInfo.status === "tight"
+ ? "A 4-bit load should fit, with limited headroom for context and activations."
+ : "A 4-bit load should fit comfortably on the current GPU."
+ : "";
+
+ return (
+ <div className="mt-3 flex flex-wrap items-center gap-1.5">
+ {showUnsupported && (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <span tabIndex={0} className="inline-flex outline-none">
+ <StatusChip tone="danger" label="May not be supported" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ sideOffset={6}
+ className="tooltip-compact max-w-xs"
+ >
+ This model may not be supported yet.
+ {unslothSupport.reason && (
+ <span className="mt-1 block text-[10.5px] font-normal text-white/75">
+ {unslothSupport.reason}
+ </span>
+ )}
+ <span className="mt-1 block text-[10.5px] font-normal text-white/75">
+ Still downloadable to your Hugging Face cache, shared with every
+ framework that reads it.
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {showVram && vramInfo && (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <span tabIndex={0} className="inline-flex outline-none">
+ <StatusChip tone={vramTone} label={vramLabel} />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ sideOffset={6}
+ className="tooltip-compact max-w-xs"
+ >
+ Estimated 4-bit memory load is around {vramInfo.est} GB.
+ <span className="mt-1 block text-[10.5px] font-normal text-white/75">
+ {vramDetail}
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ );
+}
+
+export type ModelInspectorRuntime = {
+ isActive: boolean;
+ activeGgufVariant: string | null;
+ isLoadingThisModel: boolean;
+ loadingPhase?: "downloading" | "starting";
+ minMemory: string | null;
+ vramInfo: {
+ est: number;
+ status: "fits" | "tight" | "exceeds";
+ } | null;
+ gpuGb?: number;
+ systemRamGb?: number;
+};
+
+export type ModelInspectorActions = {
+ onLoad: (opts: { ggufVariant?: string; expectedBytes?: number }) => void;
+ onLoadLocal: (opts?: {
+ ggufVariant?: string;
+ expectedBytes?: number;
+ }) => void;
+ onUseInChat: () => void;
+ onTrain?: () => void;
+ onInventoryChange?: () => void;
+};
+
+export const ModelInspector = memo(function ModelInspector({
+ model,
+ runtime,
+ actions,
+ isDataset = false,
+ metadataUnavailable = false,
+ selectionHiddenByFilters = false,
+}: {
+ model: SelectedModelView | null;
+ isDataset?: boolean;
+ metadataUnavailable?: boolean;
+ selectionHiddenByFilters?: boolean;
+ runtime: ModelInspectorRuntime;
+ actions: ModelInspectorActions;
+}) {
+ const {
+ isActive,
+ activeGgufVariant,
+ isLoadingThisModel,
+ loadingPhase,
+ minMemory,
+ vramInfo,
+ gpuGb,
+ systemRamGb,
+ } = runtime;
+ const { onLoad, onLoadLocal, onUseInChat, onTrain, onInventoryChange } =
+ actions;
+ const deviceType = usePlatformStore((s) => s.deviceType);
+ const hfToken = useHfTokenStore((s) => s.token);
+ const datasetRepoId = isDataset && model?.hubRepoId ? model.hubRepoId : null;
+ const datasetSize = useDatasetSize(datasetRepoId, {
+ token: hfToken || undefined,
+ });
+ // Inventory rows are snapshots; the download manager is the live source of truth.
+ // When a download is in flight, route through the download-aware section so
+ // progress/cancel stays visible across refreshes.
+ const activeDownloadRepoId = model?.hubRepoId ?? null;
+ const hasActiveHubDownload = useDownloadManagerStore((state) =>
+ activeDownloadRepoId
+ ? selectActiveJob(
+ state,
+ isDataset ? "dataset" : "model",
+ activeDownloadRepoId,
+ ) !== null
+ : false,
+ );
+ const readmeRepoId =
+ model?.hubRepoId ?? (isDataset ? null : (model?.baseModelHubId ?? null));
+ const readmeSubject = isDataset
+ ? "dataset"
+ : model?.hubRepoId
+ ? "model"
+ : "baseModel";
+ const supportModelId =
+ model?.hubRepoId ??
+ model?.baseModelHubId ??
+ (model?.baseModelSource === "huggingface" ? model.baseModel : null);
+ const supportPipelineTag = model?.pipelineTag;
+ const supportTagsKey = model?.tags?.join("\0") ?? "";
+ const supportLibraryName = model?.libraryName;
+ const supportQuantMethod = model?.quantMethod;
+ const unslothSupport = useMemo<UnslothSupport>(() => {
+ return classifyUnslothSupport({
+ modelId: supportModelId,
+ pipelineTag: supportPipelineTag,
+ tags: supportTagsKey ? supportTagsKey.split("\0") : undefined,
+ libraryName: supportLibraryName,
+ deviceType,
+ quantMethod: supportQuantMethod,
+ });
+ }, [
+ deviceType,
+ supportLibraryName,
+ supportModelId,
+ supportPipelineTag,
+ supportQuantMethod,
+ supportTagsKey,
+ ]);
+
+ const descScrollRef = useRef<HTMLDivElement | null>(null);
+ const descScrollKey = `${model?.id ?? ""}\0${readmeRepoId ?? ""}`;
+ const deferredReadmeRepoId = useDeferredValue(readmeRepoId);
+ const readmeReady = deferredReadmeRepoId === readmeRepoId;
+ const [descScrollState, setDescScrollState] = useState({
+ key: descScrollKey,
+ scrolled: false,
+ });
+ const descScrolled =
+ descScrollState.key === descScrollKey && descScrollState.scrolled;
+ useEffect(() => {
+ const el = descScrollRef.current;
+ if (!el) return;
+ el.scrollTop = 0;
+ const onScroll = () => {
+ const scrolled = el.scrollTop > 0;
+ setDescScrollState((current) =>
+ current.key === descScrollKey && current.scrolled === scrolled
+ ? current
+ : { key: descScrollKey, scrolled },
+ );
+ };
+ el.addEventListener("scroll", onScroll, { passive: true });
+ return () => el.removeEventListener("scroll", onScroll);
+ }, [descScrollKey]);
+
+ if (!model) {
+ return (
+ <div className="flex h-full min-h-0 flex-1 flex-col items-center justify-center gap-3 px-6 py-10 text-center">
+ <div className="inline-flex size-12 items-center justify-center rounded-[14px] bg-muted text-muted-foreground">
+ <HugeiconsIcon icon={CubeIcon} strokeWidth={1.5} className="size-5" />
+ </div>
+ <div className="space-y-1">
+ <p className="text-[15px] font-semibold tracking-tight text-foreground">
+ Select a {isDataset ? "dataset" : "model"}
+ </p>
+ <p className="max-w-sm text-[12.5px] leading-5 text-muted-foreground">
+ {isDataset
+ ? "Choose a dataset from the catalog to inspect its download state and details."
+ : "Choose an item from the catalog to inspect its runtime fit, download state, and model card."}
+ </p>
+ </div>
+ </div>
+ );
+ }
+
+ const updatedRaw = model.updatedAt
+ ? formatRelativeShort(model.updatedAt)
+ : formatLocalUpdated(model.localUpdatedAt);
+ const updatedLabel = updatedRaw === "Unknown update" ? "N/A" : updatedRaw;
+ const taskLabel = formatPipelineTag(model.pipelineTag) ?? "General";
+ const licenseLabel = model.license ?? "N/A";
+ const paramsLabel = model.totalParams
+ ? formatCompact(model.totalParams)
+ : "N/A";
+ const trainingSupported = unslothSupport.status !== "unsupported";
+ const canRunModel =
+ !isDataset && (model.runtimeCapabilities?.canChat ?? true);
+ const canTrainModel =
+ !isDataset &&
+ (model.runtimeCapabilities?.canTrain ?? false) &&
+ model.modelFormat !== "gguf" &&
+ model.modelFormat !== "adapter" &&
+ trainingSupported;
+
+ const languages = parseLanguageTags(model.tags);
+ const datasetSizeBytes =
+ datasetSize?.numBytesParquet ?? datasetSize?.numBytesOriginal ?? null;
+
+ return (
+ <div className="flex h-full min-h-0 flex-1 flex-col">
+ <div className="shrink-0 px-6 pb-2 pt-0">
+ <div className="flex items-center gap-3.5">
+ <OwnerAvatar
+ owner={model.owner}
+ repoName={model.title}
+ className="size-[52px] rounded-[14px] text-[16px]"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <h2 className="truncate text-[22px] font-semibold leading-[28px] tracking-[-0.025em] text-foreground">
+ {model.title}
+ </h2>
+ {model.hubRepoId && (
+ <div className="flex shrink-0 items-center gap-0.5">
+ <CopyRepoButton repoId={model.hubRepoId} />
+ <ViewRepositoryButton
+ repoId={model.hubRepoId}
+ isDataset={isDataset}
+ />
+ </div>
+ )}
+ </div>
+ <div className="mt-0.5 flex min-w-0 items-center gap-1 text-[14px] leading-[22px] text-muted-foreground">
+ <span className="truncate">{model.owner}</span>
+ {model.owner.toLowerCase() === "unsloth" && (
+ <span
+ aria-label="Verified Unsloth"
+ className="hub-verified-badge size-4 shrink-0 text-primary"
+ />
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="mt-4 flex flex-wrap items-center gap-1.5">
+ {isDataset && (
+ <span className="inline-flex shrink-0 items-center rounded-full border border-violet-500/40 bg-transparent px-2 py-0.5 text-[11.5px] font-medium text-violet-600 dark:text-violet-400">
+ Dataset
+ </span>
+ )}
+ {!isDataset && (
+ <span className="inline-flex h-6 items-center gap-1.5 rounded-full bg-muted px-2.5 text-[11.5px] font-medium text-foreground dark:bg-[rgba(255,255,255,0.04)]">
+ <HugeiconsIcon
+ icon={CubeIcon}
+ strokeWidth={1.75}
+ className="size-3 text-muted-foreground"
+ />
+ {taskLabel}
+ </span>
+ )}
+ {model.capabilities.map((capability) => (
+ <CapabilityPill key={capability.key} capability={capability} />
+ ))}
+ </div>
+ </div>
+
+ {isDataset &&
+ model.hubRepoId &&
+ (!model.isLocal || hasActiveHubDownload) && (
+ <InspectorDownloadSlot>
+ <DatasetDownloadSection
+ repoId={model.hubRepoId}
+ isDownloaded={model.isDownloaded}
+ isPartial={model.isPartial ?? false}
+ partialTransport={model.partialTransport ?? null}
+ cachePath={model.path}
+ knownBytes={model.cachedBytes}
+ onTrain={onTrain}
+ onChange={onInventoryChange}
+ />
+ </InspectorDownloadSlot>
+ )}
+ {isDataset && model.isLocal && !hasActiveHubDownload && model.path && (
+ <InspectorDownloadSlot>
+ <LocalDatasetCard
+ sourceLabel={model.sourceLabel}
+ source={model.localSource ?? "custom"}
+ path={model.path}
+ onTrain={onTrain}
+ />
+ </InspectorDownloadSlot>
+ )}
+ {!isDataset && (
+ <InspectorDownloadSlot>
+ {model.isLocal && !hasActiveHubDownload ? (
+ <LocalOnDeviceCard
+ modelId={model.id}
+ repoId={model.hubRepoId}
+ sourceLabel={model.sourceLabel}
+ source={model.localSource ?? "custom"}
+ path={model.path ?? model.displayId}
+ isGguf={model.isGguf}
+ requiresVariant={model.requiresVariant}
+ modelFormat={model.modelFormat}
+ baseModel={model.baseModel}
+ baseModelSource={model.baseModelSource}
+ baseModelHubId={model.baseModelHubId}
+ baseModelSummary={model.baseModelSummary}
+ adapterType={model.adapterType}
+ trainingMethod={model.trainingMethod}
+ canRun={canRunModel}
+ isActive={isActive}
+ activeGgufVariant={activeGgufVariant}
+ isLoading={isLoadingThisModel}
+ loadingPhase={loadingPhase}
+ gpuGb={gpuGb}
+ systemRamGb={systemRamGb}
+ unsupportedReason={
+ unslothSupport.status === "unsupported"
+ ? (unslothSupport.reason ?? "Unsupported format")
+ : null
+ }
+ onLoad={onLoadLocal}
+ onUseInChat={onUseInChat}
+ onTrain={
+ model.isDownloaded && canTrainModel ? onTrain : undefined
+ }
+ onChange={onInventoryChange}
+ />
+ ) : (
+ <DownloadSection
+ repoId={model.isLocal ? (model.hubRepoId ?? model.id) : model.id}
+ isGguf={model.isGguf}
+ isDownloaded={model.isDownloaded}
+ isPartial={model.isPartial ?? false}
+ partialTransport={model.partialTransport ?? null}
+ modelFormat={model.modelFormat}
+ canRun={canRunModel}
+ isActive={isActive}
+ activeQuant={isActive ? (activeGgufVariant ?? null) : null}
+ isLoadingThisModel={isLoadingThisModel}
+ gpuGb={gpuGb}
+ systemRamGb={systemRamGb}
+ cachePath={model.path}
+ knownBytes={model.cachedBytes}
+ onLoad={model.isLocal ? onLoadLocal : onLoad}
+ onUseInChat={onUseInChat}
+ onTrain={
+ model.isDownloaded && canTrainModel ? onTrain : undefined
+ }
+ onChange={onInventoryChange}
+ />
+ )}
+ </InspectorDownloadSlot>
+ )}
+
+ <div className="shrink-0 px-6 pb-5 pt-5">
+ {selectionHiddenByFilters && (
+ <p className="mb-3 rounded-[8px] border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11.5px] leading-snug text-muted-foreground">
+ Current selection is hidden by the active filters or search.
+ </p>
+ )}
+ {metadataUnavailable && (
+ <p className="mb-3 text-[11.5px] leading-snug text-muted-foreground">
+ Couldn't load full details from Hugging Face. Some fields may be
+ incomplete.
+ </p>
+ )}
+ <StatGrid>
+ <StatRow label="Updated" value={updatedLabel} icon={Calendar03Icon} />
+ <StatRow
+ label="Downloads"
+ value={
+ model.downloads !== undefined
+ ? formatCompact(model.downloads)
+ : "N/A"
+ }
+ icon={Download01Icon}
+ />
+ <StatRow
+ label="Likes"
+ value={
+ model.likes !== undefined ? formatCompact(model.likes) : "N/A"
+ }
+ icon={FavouriteIcon}
+ />
+ {!isDataset && (
+ <StatRow label="Parameters" value={paramsLabel} icon={CpuIcon} />
+ )}
+ {!isDataset && (
+ <StatRow
+ label="Memory"
+ value={minMemory ?? "N/A"}
+ icon={RamMemoryIcon}
+ />
+ )}
+ {isDataset && datasetSize?.numRows != null && (
+ <StatRow
+ label="Rows"
+ value={formatCompact(datasetSize.numRows)}
+ icon={Database02Icon}
+ />
+ )}
+ {isDataset && datasetSizeBytes != null && (
+ <StatRow
+ label="Size"
+ value={formatBytes(datasetSizeBytes)}
+ icon={PackageIcon}
+ />
+ )}
+ {isDataset &&
+ datasetSize?.numSplits != null &&
+ datasetSize.numSplits > 0 && (
+ <StatRow
+ label="Splits"
+ value={String(datasetSize.numSplits)}
+ icon={LayersLogoIcon}
+ />
+ )}
+ {isDataset && languages.length > 0 && (
+ <StatRow
+ label="Languages"
+ value={
+ languages.length > 3
+ ? `${languages.slice(0, 3).join(", ")} +${languages.length - 3}`
+ : languages.join(", ")
+ }
+ icon={Globe02Icon}
+ />
+ )}
+ <StatRow label="License" value={licenseLabel} icon={LicenseIcon} />
+ </StatGrid>
+ <ModelStatusChips
+ isDataset={isDataset}
+ isGguf={model.isGguf}
+ unslothSupport={unslothSupport}
+ vramInfo={vramInfo}
+ />
+ </div>
+
+ <div
+ aria-hidden="true"
+ className={cn(
+ "mx-6 shrink-0 border-t transition-colors",
+ descScrolled ? "border-border" : "border-transparent",
+ )}
+ />
+
+ <div
+ ref={descScrollRef}
+ data-hub-scroll="true"
+ className="min-h-0 flex-1 space-y-4 overflow-y-auto pl-6 pr-4 pt-5 pb-0 [scrollbar-gutter:stable] [scrollbar-width:thin]"
+ >
+ {readmeReady && readmeRepoId && (
+ <ModelReadme
+ repoId={readmeRepoId}
+ kind={isDataset ? "dataset" : "model"}
+ subject={readmeSubject}
+ />
+ )}
+ </div>
+
+ <div aria-hidden="true" className="h-3 shrink-0" />
+ </div>
+ );
+});
diff --git a/studio/frontend/src/features/hub/catalog/model-readme.tsx b/studio/frontend/src/features/hub/catalog/model-readme.tsx
new file mode 100644
index 00000000000..3d215473e24
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/model-readme.tsx
@@ -0,0 +1,582 @@
+// 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 { Spinner } from "@/components/ui/spinner";
+import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
+import { LruMap } from "@/features/hub/lib/lru-map";
+import { isHuggingFaceOffline } from "@/features/hub/lib/network";
+import { fingerprintToken } from "@/features/hub/lib/token-fingerprint";
+import { cn } from "@/lib/utils";
+import { confirmExternalLink } from "../stores/external-link-confirm";
+import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";
+import { code as streamdownCode } from "@streamdown/code";
+import { math as streamdownMath } from "@streamdown/math";
+import { mermaid as streamdownMermaid } from "@streamdown/mermaid";
+import {
+ createContext,
+ startTransition,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import type { ComponentProps } from "react";
+import { Streamdown, type Components } from "streamdown";
+import {
+ createReadmeUrlTransform,
+ fetchReadme,
+ readmeBaseUrl,
+ stripChromeHeadings,
+ stripFrontmatter,
+} from "../lib/hf-readme";
+
+type ReadmePlugins = NonNullable<ComponentProps<typeof Streamdown>["plugins"]>;
+
+interface ReadmeState {
+ key: string;
+ body: string | null;
+ baseUrl: string | null;
+ loading: boolean;
+ error: string | null;
+ plugins: ReadmePlugins | null;
+}
+
+type ReadmeCacheEntry = Pick<ReadmeState, "body" | "baseUrl" | "error">;
+type ReadmeSubject = "model" | "dataset" | "baseModel";
+
+const README_ALLOWED_TAGS: NonNullable<
+ ComponentProps<typeof Streamdown>["allowedTags"]
+> = {
+ audio: ["src", "controls", "preload", "loop", "muted"],
+ video: [
+ "src",
+ "controls",
+ "preload",
+ "loop",
+ "muted",
+ "poster",
+ "width",
+ "height",
+ "playsinline",
+ ],
+ source: ["src", "type", "media"],
+ track: ["src", "kind", "srclang", "label", "default"],
+};
+
+const READMEX_NEEDS_MATH = /\$\$|\\\(|\\\[/;
+const READMEX_NEEDS_MERMAID = /```mermaid\b/;
+const README_RENDER_CHAR_LIMIT = 120_000;
+const README_CACHE_TTL_MS = 60_000;
+const README_TRUNCATED_NOTICE =
+ "\n\n---\n\nCard truncated for performance. Open the repository on Hugging Face to read the full README.";
+const ReadmeOnlineContext = createContext(true);
+
+interface ResolvedReadmeCacheEntry {
+ entry: ReadmeCacheEntry;
+ expiresAt: number;
+}
+
+type ReadmeCacheValue =
+ | ResolvedReadmeCacheEntry
+ | Promise<ReadmeCacheEntry>;
+
+const readmeCache = new LruMap<string, ReadmeCacheValue>(64);
+
+function isReadmeCachePromise(
+ entry: ReadmeCacheValue,
+): entry is Promise<ReadmeCacheEntry> {
+ return typeof (entry as Promise<ReadmeCacheEntry>).then === "function";
+}
+
+function readResolvedReadmeCache(cacheKey: string): ReadmeCacheEntry | null {
+ const cached = readmeCache.get(cacheKey);
+ if (!cached || isReadmeCachePromise(cached)) {
+ return null;
+ }
+ if (cached.expiresAt <= Date.now()) {
+ readmeCache.delete(cacheKey);
+ return null;
+ }
+ return cached.entry;
+}
+
+function readmeStateFromEntry(
+ key: string,
+ entry: ReadmeCacheEntry,
+): ReadmeState {
+ return {
+ key,
+ body: entry.body,
+ baseUrl: entry.baseUrl,
+ loading: false,
+ error: entry.error,
+ plugins: null,
+ };
+}
+
+function hasReadmeContent(state: Pick<ReadmeState, "body" | "error">): boolean {
+ return state.error == null && state.body != null;
+}
+
+function prepareReadmeBody(markdown: string): string {
+ const { body } = stripFrontmatter(markdown);
+ const cleaned = stripChromeHeadings(body).trim();
+ if (cleaned.length <= README_RENDER_CHAR_LIMIT) return cleaned;
+ return `${cleaned.slice(0, README_RENDER_CHAR_LIMIT).trimEnd()}${README_TRUNCATED_NOTICE}`;
+}
+
+const PROSE = cn(
+ "max-w-none text-[13.5px] leading-[1.7] text-foreground/85",
+ "[&_h1]:text-[18px] [&_h1]:font-semibold [&_h1]:tracking-tight [&_h1]:mt-2 [&_h1]:mb-3",
+ "[&_h2]:text-[15.5px] [&_h2]:font-semibold [&_h2]:tracking-tight [&_h2]:mt-5 [&_h2]:mb-2",
+ "[&_h3]:text-[14px] [&_h3]:font-semibold [&_h3]:mt-4 [&_h3]:mb-1.5",
+ "[&_p]:my-2.5 [&_ul]:my-2 [&_ol]:my-2 [&_li]:my-0.5",
+ "[&_a]:text-primary [&_a:hover]:underline",
+ "[&_code]:rounded-md [&_code]:bg-muted/60 [&_code]:px-1 [&_code]:py-0.5 [&_code]:text-[12px] [&_code]:font-mono",
+ "[&_pre]:rounded-[12px] [&_pre]:border [&_pre]:border-border/60 [&_pre]:bg-muted/40 [&_pre]:p-3 [&_pre]:text-[12px] [&_pre]:overflow-x-auto",
+ "[&_pre_code]:bg-transparent [&_pre_code]:p-0",
+ "[&_blockquote]:border-l-2 [&_blockquote]:border-border/60 [&_blockquote]:pl-3 [&_blockquote]:text-muted-foreground",
+ "[&_table]:my-3 [&_table]:text-[12.5px]",
+ "[&_th]:px-2 [&_th]:py-1.5 [&_th]:text-left [&_th]:font-semibold [&_th]:border-b [&_th]:border-border/60",
+ "[&_td]:px-2 [&_td]:py-1.5 [&_td]:border-b [&_td]:border-border/40",
+ "[&_img]:rounded-[10px] [&_img]:my-2 [&_img]:max-w-full",
+ "[&_audio]:my-1 [&_audio]:max-w-full [&_audio]:h-9 [&_audio]:align-middle",
+ "[&_video]:my-2 [&_video]:max-w-full [&_video]:rounded-[10px]",
+ "[&_hr]:my-4 [&_hr]:border-border/40",
+);
+
+function ReadmeLink({
+ node,
+ href,
+ target,
+ rel,
+ className,
+ title,
+ children,
+ ...props
+}: ComponentProps<"a"> & { node?: unknown }) {
+ void node;
+ const online = useContext(ReadmeOnlineContext);
+ const rawHref = typeof href === "string" ? href.trim() : "";
+ const disabledExternal =
+ !online &&
+ rawHref.length > 0 &&
+ !rawHref.startsWith("#") &&
+ (/^(https?:)?\/\//i.test(rawHref) || rawHref.startsWith("/"));
+ if (disabledExternal) {
+ return (
+ <span
+ aria-disabled="true"
+ title={title ?? "Unavailable offline"}
+ className={cn(className, "cursor-not-allowed opacity-60")}
+ >
+ {children}
+ </span>
+ );
+ }
+ return (
+ <a
+ {...props}
+ href={href}
+ rel={rel ?? "noreferrer noopener"}
+ target={target ?? "_blank"}
+ className={className}
+ title={title}
+ onClick={(event) => {
+ if (confirmExternalLink(rawHref)) {
+ event.preventDefault();
+ }
+ }}
+ >
+ {children}
+ </a>
+ );
+}
+
+function ReadmeImage({
+ node,
+ alt,
+ loading,
+ decoding,
+ ...props
+}: ComponentProps<"img"> & { node?: unknown }) {
+ void node;
+ return (
+ <img
+ {...props}
+ alt={alt ?? ""}
+ decoding={decoding ?? "async"}
+ loading={loading ?? "lazy"}
+ />
+ );
+}
+
+const README_COMPONENTS: Components = {
+ a: ReadmeLink,
+ img: ReadmeImage,
+};
+
+function readmeLoadingMessage(subject: ReadmeSubject): string {
+ if (subject === "dataset") return "Loading dataset card...";
+ if (subject === "baseModel") return "Loading base model card...";
+ return "Loading model card...";
+}
+
+function readmePreparingMessage(subject: ReadmeSubject): string {
+ if (subject === "dataset") return "Preparing dataset card...";
+ if (subject === "baseModel") return "Preparing base model card...";
+ return "Preparing model card...";
+}
+
+function readmeOfflineMessage(subject: ReadmeSubject): string {
+ if (subject === "dataset") return "Dataset card unavailable offline.";
+ if (subject === "baseModel") return "Base model card unavailable offline.";
+ return "Model card unavailable offline.";
+}
+
+function readmeMissingMessage(subject: ReadmeSubject): string {
+ if (subject === "dataset") return "This dataset has no README.";
+ if (subject === "baseModel") return "This base model has no README.";
+ return "This repository has no README.";
+}
+
+function readmeUnavailableMessage(subject: ReadmeSubject): string {
+ if (subject === "dataset") {
+ return "Dataset card unavailable. It may be private, gated, or temporarily unreachable.";
+ }
+ if (subject === "baseModel") {
+ return "Base model card unavailable. It may be private, gated, or temporarily unreachable.";
+ }
+ return "Model card unavailable. It may be private, gated, or temporarily unreachable.";
+}
+
+function isMissingReadmeError(error: string): boolean {
+ return /^No (dataset|model) card available\.$/.test(error);
+}
+
+function scheduleIdleTask(callback: () => void, timeout = 250): () => void {
+ let canceled = false;
+ const run = () => {
+ if (!canceled) callback();
+ };
+
+ if (typeof window === "undefined") {
+ run();
+ return () => {
+ canceled = true;
+ };
+ }
+
+ const idleWindow = window as Window & {
+ requestIdleCallback?: Window["requestIdleCallback"];
+ cancelIdleCallback?: Window["cancelIdleCallback"];
+ };
+
+ if (idleWindow.requestIdleCallback && idleWindow.cancelIdleCallback) {
+ const handle = idleWindow.requestIdleCallback(run, { timeout });
+ return () => {
+ canceled = true;
+ idleWindow.cancelIdleCallback?.(handle);
+ };
+ }
+
+ const handle = globalThis.setTimeout(run, Math.min(timeout, 120));
+ return () => {
+ canceled = true;
+ globalThis.clearTimeout(handle);
+ };
+}
+
+function ReadmePlaceholder({
+ kind,
+ message,
+}: {
+ kind: "model" | "dataset";
+ message?: string;
+}) {
+ return (
+ <div
+ className="min-h-[108px] space-y-3 py-0.5"
+ aria-busy="true"
+ aria-live="polite"
+ >
+ <div className="flex items-center gap-2 text-[12.5px] text-muted-foreground">
+ <Spinner className="size-3.5" />
+ {message ?? `Loading ${kind === "dataset" ? "dataset" : "model"} card…`}
+ </div>
+ <div className="space-y-2" aria-hidden="true">
+ <div className="h-2.5 w-11/12 rounded-full bg-muted/60" />
+ <div className="h-2.5 w-4/5 rounded-full bg-muted/50" />
+ <div className="h-2.5 w-2/3 rounded-full bg-muted/40" />
+ </div>
+ </div>
+ );
+}
+
+async function loadReadmeFromCache({
+ cacheKey,
+ repoId,
+ kind,
+ hfToken,
+}: {
+ cacheKey: string;
+ repoId: string;
+ kind: "model" | "dataset";
+ hfToken: string | undefined;
+}): Promise<ReadmeCacheEntry> {
+ const cached = readmeCache.get(cacheKey);
+ if (cached) {
+ if (isReadmeCachePromise(cached)) return cached;
+ if (cached.expiresAt > Date.now()) return cached.entry;
+ readmeCache.delete(cacheKey);
+ }
+
+ const promise = fetchReadme(repoId, kind, hfToken || null).then((fetched) => {
+ if (fetched == null) {
+ return {
+ body: null,
+ baseUrl: null,
+ error: `No ${kind === "dataset" ? "dataset" : "model"} card available.`,
+ };
+ }
+ return {
+ body: prepareReadmeBody(fetched.markdown),
+ baseUrl: readmeBaseUrl(repoId, kind, fetched.branch),
+ error: null,
+ };
+ });
+
+ readmeCache.set(cacheKey, promise);
+ try {
+ const entry = await promise;
+ if (entry.error == null) {
+ readmeCache.set(cacheKey, {
+ entry,
+ expiresAt: Date.now() + README_CACHE_TTL_MS,
+ });
+ } else if (readmeCache.get(cacheKey) === promise) {
+ readmeCache.delete(cacheKey);
+ }
+ return entry;
+ } catch (err) {
+ if (readmeCache.get(cacheKey) === promise) {
+ readmeCache.delete(cacheKey);
+ }
+ throw err;
+ }
+}
+
+function loadPlugins(needs: {
+ math: boolean;
+ mermaid: boolean;
+}): ReadmePlugins {
+ const plugins: ReadmePlugins = { code: streamdownCode };
+ if (needs.math) plugins.math = streamdownMath;
+ if (needs.mermaid) plugins.mermaid = streamdownMermaid;
+ return plugins;
+}
+
+export function ModelReadme({
+ repoId,
+ kind = "model",
+ subject = kind,
+}: {
+ repoId: string;
+ kind?: "model" | "dataset";
+ subject?: ReadmeSubject;
+}) {
+ const hfToken = useHfTokenStore((s) => s.token);
+ const online = useOnlineStatus();
+ const tokenFingerprint = useMemo(() => fingerprintToken(hfToken), [hfToken]);
+ const stateKey = useMemo(
+ () => `${kind}::${repoId}::${tokenFingerprint}`,
+ [kind, repoId, tokenFingerprint],
+ );
+ const [state, setState] = useState<ReadmeState>(() => {
+ const cached = readResolvedReadmeCache(stateKey);
+ if (cached) return readmeStateFromEntry(stateKey, cached);
+ return {
+ key: stateKey,
+ body: null,
+ baseUrl: null,
+ loading: !isHuggingFaceOffline(),
+ error: null,
+ plugins: null,
+ };
+ });
+ const matchingState = state.key === stateKey ? state : null;
+ const cachedEntry = readResolvedReadmeCache(stateKey);
+ const cachedState = cachedEntry
+ ? readmeStateFromEntry(stateKey, cachedEntry)
+ : null;
+ const current = matchingState && hasReadmeContent(matchingState)
+ ? matchingState
+ : cachedState && hasReadmeContent(cachedState)
+ ? cachedState
+ : !online
+ ? {
+ key: stateKey,
+ body: null,
+ baseUrl: null,
+ loading: false,
+ error: readmeOfflineMessage(subject),
+ plugins: null,
+ }
+ : matchingState ?? {
+ key: stateKey,
+ body: null,
+ baseUrl: null,
+ loading: true,
+ error: null,
+ plugins: null,
+ };
+
+ const urlTransform = useMemo(
+ () =>
+ current.baseUrl ? createReadmeUrlTransform(current.baseUrl) : undefined,
+ [current.baseUrl],
+ );
+
+ useEffect(() => {
+ let canceled = false;
+ if (!online) return;
+ void loadReadmeFromCache({
+ cacheKey: stateKey,
+ repoId,
+ kind,
+ hfToken,
+ })
+ .then((entry) => {
+ if (canceled) return;
+ startTransition(() => {
+ setState({
+ key: stateKey,
+ body: entry.body,
+ baseUrl: entry.baseUrl,
+ loading: false,
+ error: entry.error,
+ plugins: null,
+ });
+ });
+ })
+ .catch((err) => {
+ if (canceled) return;
+ startTransition(() => {
+ setState({
+ key: stateKey,
+ body: null,
+ baseUrl: null,
+ loading: false,
+ error:
+ err instanceof Error ? err.message : "Failed to load model card",
+ plugins: null,
+ });
+ });
+ });
+ return () => {
+ canceled = true;
+ };
+ }, [repoId, kind, hfToken, stateKey, online]);
+
+ useEffect(() => {
+ // Plugin assembly is synchronous, so it runs regardless of connectivity: a
+ // body served from the README cache while offline still clears the preparing gate.
+ if (!current.body || current.loading || current.error || current.plugins) {
+ return;
+ }
+ let canceled = false;
+ const key = current.key;
+ const body = current.body;
+ const baseUrl = current.baseUrl;
+ const applyPlugins = (next: ReadmePlugins) => {
+ if (canceled) return;
+ startTransition(() => {
+ setState((prev) => {
+ if (prev.key === key) {
+ return prev.plugins ? prev : { ...prev, plugins: next };
+ }
+ return {
+ key,
+ body,
+ baseUrl,
+ loading: false,
+ error: null,
+ plugins: next,
+ };
+ });
+ });
+ };
+ const cancelIdle = scheduleIdleTask(() => {
+ applyPlugins(
+ loadPlugins({
+ math: READMEX_NEEDS_MATH.test(body),
+ mermaid: READMEX_NEEDS_MERMAID.test(body),
+ }),
+ );
+ }, 400);
+ return () => {
+ canceled = true;
+ cancelIdle();
+ };
+ }, [
+ current.body,
+ current.loading,
+ current.error,
+ current.plugins,
+ current.key,
+ current.baseUrl,
+ ]);
+
+ if (current.loading) {
+ return (
+ <ReadmePlaceholder kind={kind} message={readmeLoadingMessage(subject)} />
+ );
+ }
+
+ if (current.error) {
+ const errorMessage = isMissingReadmeError(current.error)
+ ? readmeMissingMessage(subject)
+ : current.error.toLowerCase().includes("offline")
+ ? current.error
+ : readmeUnavailableMessage(subject);
+ return (
+ <p className="min-h-[44px] text-[12.5px] text-muted-foreground">
+ {errorMessage}
+ </p>
+ );
+ }
+
+ if (!current.body) {
+ return (
+ <p className="min-h-[44px] text-[12.5px] text-muted-foreground">
+ {readmeMissingMessage(subject)}
+ </p>
+ );
+ }
+
+ if (!current.plugins) {
+ return (
+ <ReadmePlaceholder
+ kind={kind}
+ message={readmePreparingMessage(subject)}
+ />
+ );
+ }
+
+ return (
+ <div className={cn("hub-readme-prose", PROSE)}>
+ <ReadmeOnlineContext.Provider value={online}>
+ <Streamdown
+ mode="static"
+ plugins={current.plugins}
+ controls={false}
+ components={README_COMPONENTS}
+ allowedTags={README_ALLOWED_TAGS}
+ urlTransform={urlTransform}
+ >
+ {current.body}
+ </Streamdown>
+ </ReadmeOnlineContext.Provider>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
new file mode 100644
index 00000000000..b506f6a02d8
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
@@ -0,0 +1,287 @@
+// 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 { Spinner } from "@/components/ui/spinner";
+import { modelIdsMatch } from "@/features/hub/lib/model-identity";
+import {
+ CubeIcon,
+ DownloadCircle02Icon,
+ FolderSearchIcon,
+} from "@hugeicons/core-free-icons";
+import type { RefObject } from "react";
+import { useMemo } from "react";
+import { inventoryRowMatches, scoreInventoryRow } from "../lib/inventory-search";
+import type {
+ CachedInventoryRow,
+ DiscoverRow,
+ LocalInventoryRow,
+} from "../types";
+import {
+ DiscoverFetchMoreFooter,
+ DiscoverFetchMoreState,
+ EmptyState,
+ InventoryErrorState,
+ NetworkErrorState,
+ SkeletonList,
+} from "./catalog-states";
+import {
+ DiscoverModelRow,
+ InventoryRow,
+ VirtualRows,
+} from "./models-catalog-rows";
+
+type InventoryItem =
+ | { variant: "cached"; row: CachedInventoryRow }
+ | { variant: "local"; row: LocalInventoryRow };
+
+export function InventoryWarningRow({
+ isDataset,
+ onRetry,
+}: {
+ isDataset: boolean;
+ onRetry: () => void;
+}) {
+ return (
+ <div className="mx-5 mt-2 rounded-[8px] border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[12.5px] text-muted-foreground">
+ <div className="flex items-center justify-between gap-3">
+ <span>
+ Some on-device sources couldn't be scanned. Showing available{" "}
+ {isDataset ? "datasets" : "models"}.
+ </span>
+ <button
+ type="button"
+ className="shrink-0 text-[12px] font-medium text-foreground transition-colors hover:text-primary"
+ onClick={onRetry}
+ >
+ Retry
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export function DiscoverList({
+ discoverRows,
+ selectedId,
+ onSelect,
+ isLoading,
+ query,
+ scrollElement,
+ sentinelRef,
+ activeCheckpoint,
+ searchError,
+ online,
+ isDataset,
+ deviceType,
+ scannedCount,
+ isLoadingMore,
+ hasMore,
+ manualFetchAvailable,
+ hasActiveFilters,
+ onFetchMore,
+ onClearFilters,
+ onRetry,
+ onSwitchDevice,
+}: {
+ discoverRows: DiscoverRow[];
+ selectedId: string | null;
+ onSelect: (id: string) => void;
+ isLoading: boolean;
+ query: string;
+ scrollElement: HTMLDivElement | null;
+ sentinelRef: RefObject<HTMLDivElement | null>;
+ activeCheckpoint: string | null;
+ searchError: string | null;
+ online: boolean;
+ isDataset: boolean;
+ deviceType: string | null;
+ scannedCount: number;
+ isLoadingMore: boolean;
+ hasMore: boolean;
+ manualFetchAvailable: boolean;
+ hasActiveFilters: boolean;
+ onFetchMore: () => void;
+ onClearFilters: () => void;
+ onRetry: () => void;
+ onSwitchDevice?: () => void;
+}) {
+ return (
+ <>
+ {online ? (
+ searchError && discoverRows.length === 0 ? (
+ <NetworkErrorState
+ online={online}
+ message={searchError}
+ onRetry={onRetry}
+ resourceLabel={isDataset ? "datasets" : "models"}
+ />
+ ) : hasMore && discoverRows.length === 0 ? (
+ <DiscoverFetchMoreState
+ scannedCount={scannedCount}
+ hasActiveFilters={hasActiveFilters}
+ isLoadingMore={isLoadingMore}
+ onFetchMore={onFetchMore}
+ onClearFilters={onClearFilters}
+ />
+ ) : discoverRows.length === 0 && isLoading ? (
+ <SkeletonList />
+ ) : discoverRows.length === 0 ? (
+ <EmptyState
+ icon={query.trim() ? FolderSearchIcon : CubeIcon}
+ title={
+ query.trim()
+ ? `No matching ${isDataset ? "datasets" : "models"}`
+ : `No ${isDataset ? "datasets" : "models"} available`
+ }
+ body={
+ query.trim()
+ ? "Try a broader search or remove some filters."
+ : "The current filters are excluding every result."
+ }
+ />
+ ) : (
+ <>
+ <VirtualRows
+ items={discoverRows}
+ scrollElement={scrollElement}
+ getKey={(row) => row.id}
+ renderRow={(row) => (
+ <DiscoverModelRow
+ row={row}
+ selected={selectedId === row.id}
+ active={modelIdsMatch(activeCheckpoint, row.id)}
+ deviceType={deviceType}
+ isDataset={isDataset}
+ onSelect={onSelect}
+ />
+ )}
+ />
+ {hasMore && (
+ <DiscoverFetchMoreFooter
+ scannedCount={scannedCount}
+ manualFetchAvailable={manualFetchAvailable}
+ hasActiveFilters={hasActiveFilters}
+ isLoadingMore={isLoadingMore}
+ onFetchMore={onFetchMore}
+ />
+ )}
+ </>
+ )
+ ) : (
+ <NetworkErrorState
+ online={online}
+ message="Discovery is unavailable while offline."
+ onRetry={onRetry}
+ onSwitchDevice={onSwitchDevice}
+ resourceLabel={isDataset ? "datasets" : "models"}
+ />
+ )}
+
+ <div ref={sentinelRef} className="h-px" />
+ </>
+ );
+}
+
+export function DownloadedList({
+ cachedRows,
+ localRows,
+ selectedId,
+ onSelect,
+ downloadedReady,
+ inventoryError,
+ query,
+ scrollElement,
+ activeCheckpoint,
+ activeGgufVariant,
+ isDataset,
+ inventoryTokens,
+ deviceType,
+ onInventoryChange,
+}: {
+ cachedRows: CachedInventoryRow[];
+ localRows: LocalInventoryRow[];
+ selectedId: string | null;
+ onSelect: (id: string) => void;
+ downloadedReady: boolean;
+ inventoryError: boolean;
+ query: string;
+ scrollElement: HTMLDivElement | null;
+ activeCheckpoint: string | null;
+ activeGgufVariant: string | null;
+ isDataset: boolean;
+ inventoryTokens: readonly string[];
+ deviceType: string | null;
+ onInventoryChange?: () => void;
+}) {
+ const inventoryItems = useMemo<InventoryItem[]>(() => {
+ const merged: InventoryItem[] = [
+ ...cachedRows.map((row) => ({ variant: "cached" as const, row })),
+ ...localRows.map((row) => ({ variant: "local" as const, row })),
+ ];
+ if (inventoryTokens.length === 0) return merged;
+ return merged
+ .map((item, index) => ({
+ item,
+ index,
+ score: scoreInventoryRow(item.row, inventoryTokens),
+ }))
+ .sort((a, b) => b.score - a.score || a.index - b.index)
+ .map((entry) => entry.item);
+ }, [cachedRows, localRows, inventoryTokens]);
+ const hasInventoryRows = cachedRows.length > 0 || localRows.length > 0;
+
+ if (!downloadedReady && !hasInventoryRows) {
+ return (
+ <div className="flex min-h-[240px] items-center justify-center gap-3 text-[13px] text-muted-foreground">
+ <Spinner className="size-4" />
+ Loading local inventory...
+ </div>
+ );
+ }
+
+ if (inventoryError && cachedRows.length === 0 && localRows.length === 0) {
+ return (
+ <InventoryErrorState
+ isDataset={isDataset}
+ onRetry={() => onInventoryChange?.()}
+ />
+ );
+ }
+
+ if (cachedRows.length === 0 && localRows.length === 0) {
+ return (
+ <EmptyState
+ icon={query.trim() ? FolderSearchIcon : DownloadCircle02Icon}
+ title={query.trim() ? "No matches on device" : "Nothing on device yet"}
+ body={
+ query.trim()
+ ? `Clear the search or try a different query. No cached or local ${isDataset ? "dataset" : "model"} matches it.`
+ : isDataset
+ ? "Downloaded datasets, recipe outputs, and uploaded files will appear here."
+ : "Downloaded repositories and indexed local folders will appear here."
+ }
+ />
+ );
+ }
+
+ return (
+ <VirtualRows
+ items={inventoryItems}
+ scrollElement={scrollElement}
+ getKey={(item) => `${item.variant}-${item.row.id}`}
+ renderRow={(item) => (
+ <InventoryRow
+ row={item.row}
+ selected={selectedId === item.row.id}
+ activeCheckpoint={activeCheckpoint}
+ activeGgufVariant={activeGgufVariant}
+ isDataset={isDataset}
+ dimmed={!inventoryRowMatches(item.row, inventoryTokens)}
+ deviceType={deviceType}
+ onSelect={onSelect}
+ onChange={onInventoryChange}
+ />
+ )}
+ />
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
new file mode 100644
index 00000000000..cc87fc23ced
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
@@ -0,0 +1,768 @@
+// 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 { ModelDeleteAction } from "@/components/assistant-ui/model-selector/model-delete-action";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ type GgufVariantDetail,
+ deleteCachedModel,
+ deleteCachedDataset,
+ formatLocalUpdated,
+ listGgufVariants,
+ useGgufVariantsCacheVersion,
+} from "@/features/hub/inventory";
+import { classifyUnslothSupport } from "@/features/hub/hooks/use-hub-model-search";
+import { formatBytes, formatRelativeShort } from "@/features/hub/lib/format";
+import { ggufVariantDisplayLabel } from "@/features/hub/lib/gguf-variant-sort";
+import { modelIdsMatch } from "@/features/hub/lib/model-identity";
+import { cn, formatCompact } from "@/lib/utils";
+import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";
+import {
+ Download01Icon,
+ FavouriteIcon,
+ PackageIcon,
+} from "@hugeicons/core-free-icons";
+import type { IconSvgElement } from "@hugeicons/react";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import {
+ type ReactNode,
+ createContext,
+ memo,
+ useCallback,
+ useContext,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import type {
+ CachedInventoryRow,
+ DiscoverRow,
+ LocalInventoryRow,
+} from "../types";
+import { OwnerAvatar } from "./owner-avatar";
+
+const COARSE_POINTER =
+ typeof window !== "undefined" &&
+ typeof window.matchMedia === "function" &&
+ window.matchMedia("(pointer: coarse)").matches;
+
+// Defer the cached-size chip (a Radix Tooltip + two store subscriptions) until the
+// row is hovered/focused so flicking the list doesn't pay that cost per row. The
+// placeholder renders an identical StatChip, so the swap shifts nothing. Coarse
+// pointers have no hover, so arm immediately; default true so out-of-row usage works.
+const CatalogRowInteractiveContext = createContext(true);
+
+function CachedSizeChip(props: {
+ repoId: string;
+ totalBytes: number;
+ isGguf: boolean;
+ isDataset?: boolean;
+ cachePath?: string | null;
+}) {
+ const interactive = useContext(CatalogRowInteractiveContext);
+ if (!interactive) {
+ return <StatChip icon={PackageIcon} value={formatBytes(props.totalBytes)} />;
+ }
+ return <CachedSizeChipLive {...props} />;
+}
+
+function CachedSizeChipLive({
+ repoId,
+ totalBytes,
+ isGguf,
+ isDataset = false,
+ cachePath,
+}: {
+ repoId: string;
+ totalBytes: number;
+ isGguf: boolean;
+ isDataset?: boolean;
+ cachePath?: string | null;
+}) {
+ const hfToken = useHfTokenStore((s) => s.token) || undefined;
+ const variantsVersion = useGgufVariantsCacheVersion(repoId);
+ const fetchKey = `${repoId}::${cachePath ?? ""}::${variantsVersion}`;
+ const [variantState, setVariantState] = useState<{
+ key: string;
+ status: "idle" | "loading" | "loaded" | "error";
+ variants: GgufVariantDetail[];
+ }>(() => ({
+ key: fetchKey,
+ status: "idle",
+ variants: [],
+ }));
+ const fetchedForRef = useRef<string | null>(null);
+ const needsVariantFetch = isGguf && !isDataset;
+ const currentVariantState =
+ variantState.key === fetchKey
+ ? variantState
+ : { key: fetchKey, status: "idle" as const, variants: [] };
+
+ const ensureVariantsLoaded = useCallback(() => {
+ if (!needsVariantFetch) return;
+ if (fetchedForRef.current === fetchKey) return;
+ fetchedForRef.current = fetchKey;
+ setVariantState({ key: fetchKey, status: "loading", variants: [] });
+ listGgufVariants(repoId, hfToken, {
+ preferLocalCache: true,
+ localPath: cachePath ?? null,
+ })
+ .then((res) => {
+ if (fetchedForRef.current !== fetchKey) return;
+ setVariantState({
+ key: fetchKey,
+ status: "loaded",
+ variants: res.variants.filter((v) => v.downloaded),
+ });
+ })
+ .catch(() => {
+ if (fetchedForRef.current !== fetchKey) return;
+ fetchedForRef.current = null;
+ setVariantState({ key: fetchKey, status: "error", variants: [] });
+ });
+ }, [needsVariantFetch, fetchKey, repoId, hfToken, cachePath]);
+
+ const trigger = (
+ <span
+ className="pointer-events-auto hub-modal-pe-guard"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <StatChip icon={PackageIcon} value={formatBytes(totalBytes)} />
+ </span>
+ );
+
+ const rows: Array<{ label: string; size_bytes: number }> | null =
+ !needsVariantFetch
+ ? [{ label: repoId, size_bytes: totalBytes }]
+ : currentVariantState.status === "loaded" &&
+ currentVariantState.variants.length > 0
+ ? currentVariantState.variants.map((variant) => ({
+ label: ggufVariantDisplayLabel(variant),
+ size_bytes: variant.size_bytes,
+ }))
+ : null;
+ const variantMessage =
+ currentVariantState.status === "loading"
+ ? "Loading downloaded variants..."
+ : currentVariantState.status === "error"
+ ? "Couldn't load downloaded variants. Open again to retry."
+ : currentVariantState.status === "loaded"
+ ? "No downloaded GGUF variants found."
+ : "Open to load downloaded variants.";
+
+ return (
+ <Tooltip
+ onOpenChange={(open) => {
+ if (open) ensureVariantsLoaded();
+ }}
+ >
+ <TooltipTrigger asChild={true}>{trigger}</TooltipTrigger>
+ <TooltipContent variant="default" side="top" sideOffset={4}>
+ {rows ? (
+ <ul className="flex flex-col gap-1">
+ {rows.map((row) => (
+ <li
+ key={row.label}
+ className="flex items-center gap-3 tabular-nums"
+ >
+ <span className="min-w-0 truncate">{row.label}</span>
+ <span className="ml-auto">
+ <StatChip
+ icon={PackageIcon}
+ value={formatBytes(row.size_bytes)}
+ />
+ </span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <span className="block max-w-52 text-[11px] leading-4 text-muted-foreground">
+ {variantMessage}
+ </span>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+export function StatChip({
+ icon,
+ value,
+}: {
+ icon: IconSvgElement;
+ value: string;
+}) {
+ return (
+ <span className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap text-[10px] font-medium leading-none tabular-nums text-muted-foreground/75">
+ <HugeiconsIcon
+ icon={icon}
+ strokeWidth={1.75}
+ className="size-2.5 shrink-0"
+ />
+ {value}
+ </span>
+ );
+}
+
+function CatalogRow({
+ selected,
+ active,
+ onClick,
+ tooltip,
+ label,
+ children,
+}: {
+ selected: boolean;
+ active?: boolean;
+ tooltip?: ReactNode;
+ onClick: () => void;
+ label: string;
+ children: ReactNode;
+}) {
+ const [interactive, setInteractive] = useState(COARSE_POINTER);
+ const arm = useCallback(() => setInteractive(true), []);
+ const button = (
+ <div
+ data-selected={selected || undefined}
+ data-active={active || undefined}
+ onPointerEnter={arm}
+ onFocusCapture={arm}
+ className="catalog-row group/row relative block w-full select-none overflow-hidden rounded-[14px] pl-3 pr-2.5 py-2.5 text-left"
+ >
+ <button
+ type="button"
+ aria-label={label}
+ onClick={onClick}
+ className="absolute inset-0 cursor-pointer rounded-[14px] outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
+ />
+ <CatalogRowInteractiveContext.Provider value={interactive}>
+ <div className="pointer-events-none relative">{children}</div>
+ </CatalogRowInteractiveContext.Provider>
+ </div>
+ );
+ if (!tooltip || !interactive) return button;
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>{button}</TooltipTrigger>
+ <TooltipContent
+ side="right"
+ align="center"
+ sideOffset={8}
+ className="tooltip-compact max-w-xs"
+ >
+ {tooltip}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+function StatusDot({
+ tone,
+ label,
+}: {
+ tone: "warning" | "danger" | "success";
+ label: string;
+}) {
+ const toneClass =
+ tone === "warning"
+ ? "bg-status-warning"
+ : tone === "danger"
+ ? "bg-status-danger"
+ : "bg-status-success";
+ return (
+ <span
+ role="img"
+ aria-label={label}
+ className={cn("inline-block size-[5px] shrink-0 rounded-full", toneClass)}
+ />
+ );
+}
+
+function TooltipLegendRow({
+ toneClass,
+ children,
+}: {
+ toneClass: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className="flex items-start gap-1.5 leading-snug">
+ <span
+ aria-hidden="true"
+ className={cn(
+ "mt-1 inline-block size-1.5 shrink-0 rounded-full",
+ toneClass,
+ )}
+ />
+ <span className="min-w-0">{children}</span>
+ </div>
+ );
+}
+
+function buildRowStatusTooltip({
+ isGguf,
+ isAdapter,
+ isAvailableOnDevice,
+ partialRepoId,
+ unsupported,
+ unsupportedReason,
+ resourceLabel = "model",
+}: {
+ isGguf?: boolean;
+ isAdapter?: boolean;
+ isAvailableOnDevice?: boolean;
+ partialRepoId?: string;
+ unsupported?: boolean;
+ unsupportedReason?: string | null;
+ resourceLabel?: "model" | "dataset";
+}): ReactNode {
+ const lines: ReactNode[] = [];
+
+ if (isGguf) {
+ lines.push(
+ <TooltipLegendRow key="gguf" toneClass="bg-format-gguf">
+ GGUF format.
+ </TooltipLegendRow>,
+ );
+ }
+ if (isAdapter) {
+ lines.push(
+ <TooltipLegendRow key="adapter" toneClass="bg-format-adapter">
+ Adapter format.
+ </TooltipLegendRow>,
+ );
+ }
+
+ if (partialRepoId) {
+ lines.push(
+ <TooltipLegendRow key="partial" toneClass="bg-status-warning">
+ Partial download of <span className="font-medium">{partialRepoId}</span>
+ . Click Resume to continue.
+ </TooltipLegendRow>,
+ );
+ } else if (isAvailableOnDevice) {
+ lines.push(
+ <TooltipLegendRow key="success" toneClass="bg-status-success">
+ On device. Ready to use locally.
+ </TooltipLegendRow>,
+ );
+ }
+
+ if (unsupported) {
+ lines.push(
+ <TooltipLegendRow key="danger" toneClass="bg-status-danger">
+ <span className="block">
+ This {resourceLabel} may not be supported yet.
+ </span>
+ {unsupportedReason && (
+ <span className="mt-0.5 block text-white/75">
+ {unsupportedReason}
+ </span>
+ )}
+ <span className="mt-0.5 block text-white/75">
+ Still downloadable to your Hugging Face cache, shared with every
+ framework that reads it.
+ </span>
+ </TooltipLegendRow>,
+ );
+ }
+
+ if (lines.length === 0) return null;
+ return <div className="space-y-1.5">{lines}</div>;
+}
+
+export const DiscoverModelRow = memo(function DiscoverModelRow({
+ row,
+ selected,
+ active,
+ deviceType,
+ isDataset,
+ onSelect,
+}: {
+ row: DiscoverRow;
+ selected: boolean;
+ active: boolean;
+ deviceType: string | null;
+ isDataset: boolean;
+ onSelect: (id: string) => void;
+}) {
+ const support = useMemo(
+ () =>
+ isDataset
+ ? null
+ : classifyUnslothSupport({
+ modelId: row.id,
+ pipelineTag: row.result.pipelineTag,
+ tags: row.result.tags,
+ libraryName: row.result.libraryName,
+ deviceType,
+ quantMethod: row.result.quantMethod,
+ }),
+ [isDataset, row.id, row.result, deviceType],
+ );
+ const unsupported = support?.status === "unsupported";
+ const handleClick = useCallback(() => onSelect(row.id), [onSelect, row.id]);
+ const partialRepoId =
+ row.isAvailableOnDevice && row.isPartialOnDevice
+ ? row.result.id
+ : undefined;
+ const tooltip = buildRowStatusTooltip({
+ isGguf: row.result.isGguf,
+ isAdapter: false,
+ isAvailableOnDevice: row.isAvailableOnDevice,
+ partialRepoId,
+ unsupported,
+ unsupportedReason: support?.reason ?? null,
+ resourceLabel: isDataset ? "dataset" : "model",
+ });
+ return (
+ <CatalogRow
+ selected={selected}
+ active={active}
+ tooltip={tooltip}
+ label={row.repo}
+ onClick={handleClick}
+ >
+ <div className="flex items-center gap-3">
+ <OwnerAvatar
+ owner={row.owner}
+ repoName={row.repo}
+ className="size-8 rounded-[9px]"
+ />
+ <div className="flex min-w-0 flex-1 flex-col gap-[3px]">
+ <div className="flex h-[18px] min-w-0 items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-1.5 pr-2">
+ <p className="truncate text-[12px] font-medium leading-[18px] tracking-[-0.005em] text-foreground">
+ {row.repo}
+ </p>
+ {row.result.isGguf && (
+ <span
+ role="img"
+ aria-label="GGUF"
+ className="inline-block size-[5px] shrink-0 rounded-full bg-format-gguf"
+ />
+ )}
+ {unsupported && (
+ <StatusDot tone="danger" label="May not be supported yet" />
+ )}
+ {row.isAvailableOnDevice && row.isPartialOnDevice && (
+ <StatusDot tone="warning" label="Partial download" />
+ )}
+ {row.isAvailableOnDevice && !row.isPartialOnDevice && (
+ <StatusDot tone="success" label="On device" />
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-2.5">
+ <StatChip
+ icon={FavouriteIcon}
+ value={formatCompact(row.result.likes)}
+ />
+ <StatChip
+ icon={Download01Icon}
+ value={formatCompact(row.result.downloads)}
+ />
+ </div>
+ </div>
+ <div className="flex h-[16px] min-w-0 items-center justify-between gap-2 text-[11.5px] leading-[16px] text-muted-foreground/85">
+ <span className="flex min-w-0 items-center gap-1">
+ <span className="truncate">{row.owner}</span>
+ {row.owner.toLowerCase() === "unsloth" && (
+ <span
+ aria-label="Verified Unsloth"
+ className="hub-verified-badge size-3.5 shrink-0 text-primary"
+ />
+ )}
+ </span>
+ <span className="shrink-0 text-[10.5px] tabular-nums">
+ {formatRelativeShort(row.result.updatedAt)}
+ </span>
+ </div>
+ </div>
+ </div>
+ </CatalogRow>
+ );
+});
+
+function cachedRowActive(
+ row: CachedInventoryRow,
+ activeCheckpoint: string | null,
+ activeGgufVariant: string | null,
+): boolean {
+ if (!modelIdsMatch(activeCheckpoint, row.loadId)) return false;
+ if (row.modelFormat === "gguf") {
+ return row.capabilities.requiresVariant ? activeGgufVariant !== null : true;
+ }
+ return activeGgufVariant === null;
+}
+
+function localRowActive(
+ row: LocalInventoryRow,
+ activeCheckpoint: string | null,
+ activeGgufVariant: string | null,
+): boolean {
+ if (!modelIdsMatch(activeCheckpoint, row.loadId)) return false;
+ if (row.modelFormat === "gguf") {
+ return row.capabilities.requiresVariant ? activeGgufVariant !== null : true;
+ }
+ return activeGgufVariant === null;
+}
+
+export const InventoryRow = memo(function InventoryRow({
+ row,
+ selected,
+ activeCheckpoint,
+ activeGgufVariant,
+ isDataset,
+ dimmed,
+ deviceType,
+ onSelect,
+ onChange,
+}: {
+ row: CachedInventoryRow | LocalInventoryRow;
+ selected: boolean;
+ activeCheckpoint: string | null;
+ activeGgufVariant: string | null;
+ isDataset: boolean;
+ dimmed: boolean;
+ deviceType: string | null;
+ onSelect: (id: string) => void;
+ onChange?: () => void;
+}) {
+ const rowModelId =
+ row.kind === "cache"
+ ? row.repoId
+ : (row.repoId ?? row.baseModelHubId ?? row.baseModel ?? row.loadId);
+ const rowTagsSignature = row.tags?.join("\u0001") ?? "";
+ const unsupported = useMemo(() => {
+ if (isDataset) return false;
+ return (
+ classifyUnslothSupport({
+ modelId: rowModelId,
+ pipelineTag: row.pipelineTag,
+ tags: rowTagsSignature ? rowTagsSignature.split("\u0001") : undefined,
+ libraryName: row.libraryName,
+ quantMethod: row.quantMethod,
+ deviceType,
+ }).status === "unsupported"
+ );
+ }, [
+ isDataset,
+ rowModelId,
+ row.pipelineTag,
+ rowTagsSignature,
+ row.libraryName,
+ row.quantMethod,
+ deviceType,
+ ]);
+ const handleClick = useCallback(() => onSelect(row.id), [onSelect, row.id]);
+ const active =
+ row.kind === "cache"
+ ? cachedRowActive(row, activeCheckpoint, activeGgufVariant)
+ : localRowActive(row, activeCheckpoint, activeGgufVariant);
+ const title = row.kind === "cache" ? row.repo : row.title;
+
+ const subLabel = row.owner;
+ const trailing =
+ row.kind === "local" && row.updatedAt
+ ? formatLocalUpdated(row.updatedAt)
+ : null;
+ const cacheDeletableRepoId =
+ row.kind === "cache"
+ ? row.repoId
+ : row.source === "hf_cache" && row.repoId
+ ? row.repoId
+ : null;
+ const canDelete = cacheDeletableRepoId !== null;
+ const partialRepoId = row.partial
+ ? row.kind === "cache"
+ ? row.repoId
+ : (row.repoId ?? row.loadId)
+ : undefined;
+ const tooltip = buildRowStatusTooltip({
+ isGguf: row.isGguf,
+ isAdapter: row.modelFormat === "adapter",
+ isAvailableOnDevice: !partialRepoId,
+ partialRepoId,
+ unsupported,
+ resourceLabel: isDataset ? "dataset" : "model",
+ });
+
+ return (
+ <CatalogRow
+ selected={selected}
+ active={active}
+ tooltip={tooltip}
+ label={title}
+ onClick={handleClick}
+ >
+ <div
+ className={cn(
+ "flex items-center gap-3 transition-opacity",
+ dimmed && "opacity-25 group-hover/row:opacity-60",
+ )}
+ >
+ <OwnerAvatar
+ owner={row.owner}
+ repoName={title}
+ className="size-8 rounded-[9px]"
+ />
+ <div className="flex min-w-0 flex-1 flex-col gap-[3px]">
+ <div className="flex h-[18px] min-w-0 items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-1.5 pr-2">
+ <p className="truncate text-[12px] font-medium leading-[18px] tracking-[-0.005em] text-foreground">
+ {title}
+ </p>
+ {row.isGguf && (
+ <span
+ role="img"
+ aria-label="GGUF"
+ className="inline-block size-[5px] shrink-0 rounded-full bg-format-gguf"
+ />
+ )}
+ {row.modelFormat === "adapter" && (
+ <span
+ role="img"
+ aria-label="Adapter"
+ className="inline-block size-[5px] shrink-0 rounded-full bg-format-adapter"
+ />
+ )}
+ {partialRepoId ? (
+ <StatusDot tone="warning" label="Partial download" />
+ ) : (
+ <StatusDot tone="success" label="On device" />
+ )}
+ {unsupported && (
+ <StatusDot tone="danger" label="May not be supported yet" />
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {canDelete && cacheDeletableRepoId && (
+ <ModelDeleteAction
+ ariaLabel={`Delete ${cacheDeletableRepoId}`}
+ title={
+ isDataset
+ ? "Delete cached dataset?"
+ : "Delete cached model?"
+ }
+ description={
+ <>
+ This will remove{" "}
+ <span className="font-medium text-foreground">
+ {cacheDeletableRepoId}
+ </span>{" "}
+ {isDataset
+ ? "and its downloaded files"
+ : row.isGguf
+ ? "and all of its downloaded quantizations"
+ : "and all of its downloaded files"}
+ {row.kind === "cache"
+ ? ` (${formatBytes(row.bytes)})`
+ : ""}{" "}
+ from disk. You can re-download it later.
+ </>
+ }
+ successMessage={`Deleted ${cacheDeletableRepoId}`}
+ buttonClassName="pointer-events-auto hub-modal-pe-guard opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 [@media(pointer:coarse)]:opacity-100"
+ iconClassName="size-3.5"
+ onConfirm={async () => {
+ if (isDataset) {
+ await deleteCachedDataset(cacheDeletableRepoId);
+ } else {
+ await deleteCachedModel(cacheDeletableRepoId);
+ }
+ }}
+ onDeleted={onChange}
+ />
+ )}
+ {row.kind === "cache" && (
+ <CachedSizeChip
+ repoId={row.repoId}
+ totalBytes={row.bytes}
+ isGguf={row.isGguf}
+ isDataset={isDataset}
+ cachePath={row.cachePath}
+ />
+ )}
+ </div>
+ </div>
+ <div className="flex h-[16px] min-w-0 items-center justify-between gap-2 text-[11.5px] leading-[16px] text-muted-foreground/85">
+ <span className="flex min-w-0 items-center gap-1">
+ <span className="truncate">{subLabel}</span>
+ {subLabel.toLowerCase() === "unsloth" && (
+ <span
+ aria-label="Verified Unsloth"
+ className="hub-verified-badge size-3.5 shrink-0 text-primary"
+ />
+ )}
+ </span>
+ {trailing && (
+ <span className="shrink-0 text-[10.5px] tabular-nums">
+ {trailing}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ </CatalogRow>
+ );
+});
+
+export const CATALOG_ROW_HEIGHT_PX = 57;
+
+export function VirtualRows<T>({
+ items,
+ scrollElement,
+ getKey,
+ renderRow,
+}: {
+ items: readonly T[];
+ scrollElement: HTMLDivElement | null;
+ getKey: (item: T, index: number) => string;
+ renderRow: (item: T) => ReactNode;
+}) {
+ // eslint-disable-next-line react-hooks/incompatible-library
+ const virtualizer = useVirtualizer({
+ count: items.length,
+ getScrollElement: () => scrollElement,
+ estimateSize: () => CATALOG_ROW_HEIGHT_PX,
+ overscan: 10,
+ getItemKey: (index) => getKey(items[index], index),
+ });
+
+ return (
+ <ul
+ style={{
+ height: virtualizer.getTotalSize(),
+ position: "relative",
+ width: "100%",
+ overflowAnchor: "none",
+ }}
+ >
+ {virtualizer.getVirtualItems().map((virtualRow) => (
+ <li
+ key={virtualRow.key}
+ data-index={virtualRow.index}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ transform: `translateY(${virtualRow.start}px)`,
+ // Lock rows to estimateSize with no measureElement ref: per-mount
+ // measurement churns the virtualizer (re-renders + offset recompute)
+ // that reads as a jump. A fixed matching height keeps appends stable.
+ height: `${CATALOG_ROW_HEIGHT_PX}px`,
+ contain: "layout paint",
+ }}
+ >
+ {renderRow(items[virtualRow.index])}
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog.tsx b/studio/frontend/src/features/hub/catalog/models-catalog.tsx
new file mode 100644
index 00000000000..872baf61d00
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/models-catalog.tsx
@@ -0,0 +1,396 @@
+// 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 { usePlatformStore } from "@/config/env";
+import { cn } from "@/lib/utils";
+import {
+ type RefObject,
+ memo,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
+import type {
+ CachedInventoryRow,
+ DiscoverRow,
+ LocalInventoryRow,
+ ModelsTab,
+} from "../types";
+import {
+ DiscoverList,
+ DownloadedList,
+ InventoryWarningRow,
+} from "./models-catalog-lists";
+import { CATALOG_ROW_HEIGHT_PX } from "./models-catalog-rows";
+
+export interface ModelsCatalogState {
+ tab: ModelsTab;
+ discoverRows: DiscoverRow[];
+ cachedRows: CachedInventoryRow[];
+ localRows: LocalInventoryRow[];
+ selectedId: string | null;
+ isLoading: boolean;
+ downloadedReady: boolean;
+ inventoryError: boolean;
+ inventoryWarning: boolean;
+ query: string;
+ activeCheckpoint: string | null;
+ activeGgufVariant: string | null;
+ searchError: string | null;
+ online: boolean;
+ isDataset: boolean;
+ inventoryTokens: readonly string[];
+ scannedCount: number;
+ loadingIntentCount: number;
+ hasMore: boolean;
+ manualFetchAvailable: boolean;
+ hasActiveFilters: boolean;
+}
+
+export interface ModelsCatalogPagination {
+ scrollRef: RefObject<HTMLDivElement | null>;
+ sentinelRef: RefObject<HTMLDivElement | null>;
+ isLoadingMore: boolean;
+}
+
+export interface ModelsCatalogHandlers {
+ onSelect: (id: string) => void;
+ onFetchMore: () => void;
+ onClearFilters: () => void;
+ onRetry: () => void;
+ onInventoryChange?: () => void;
+ onSwitchDevice?: () => void;
+}
+
+function assignRef<T>(ref: RefObject<T | null>, value: T | null) {
+ (ref as { current: T | null }).current = value;
+}
+
+export const ModelsCatalog = memo(function ModelsCatalog({
+ state,
+ pagination,
+ handlers,
+}: {
+ state: ModelsCatalogState;
+ pagination: ModelsCatalogPagination;
+ handlers: ModelsCatalogHandlers;
+}) {
+ const {
+ tab,
+ discoverRows,
+ cachedRows,
+ localRows,
+ selectedId,
+ isLoading,
+ downloadedReady,
+ inventoryError,
+ inventoryWarning,
+ query,
+ activeCheckpoint,
+ activeGgufVariant,
+ searchError,
+ online,
+ isDataset,
+ inventoryTokens,
+ scannedCount,
+ loadingIntentCount,
+ hasMore,
+ manualFetchAvailable,
+ hasActiveFilters,
+ } = state;
+ const { scrollRef, sentinelRef, isLoadingMore } = pagination;
+ const {
+ onSelect,
+ onFetchMore,
+ onClearFilters,
+ onRetry,
+ onInventoryChange,
+ onSwitchDevice,
+ } = handlers;
+ const [scrolled, setScrolled] = useState(false);
+ const [streamingActive, setStreamingActive] = useState(false);
+ const previousScannedCountRef = useRef(scannedCount);
+ const previousLoadingIntentRef = useRef(loadingIntentCount);
+ const discoverScrollRef = useRef<HTMLDivElement>(null);
+ const downloadedScrollRef = useRef<HTMLDivElement>(null);
+ const [discoverScrollEl, setDiscoverScrollEl] = useState<HTMLDivElement | null>(
+ null,
+ );
+ const [downloadedScrollEl, setDownloadedScrollEl] =
+ useState<HTMLDivElement | null>(null);
+ const activeTabRef = useRef(tab);
+ // Per-tab scroll positions. Some browsers drop the hidden pane's scrollTop, so
+ // mirror it live via the scroll listener and restore on tab entry.
+ const savedScrollTopsRef = useRef<Record<ModelsTab, number>>({
+ discover: 0,
+ downloaded: 0,
+ });
+ const savedScrollHeightsRef = useRef<Record<ModelsTab, number>>({
+ discover: 0,
+ downloaded: 0,
+ });
+ const deviceType = usePlatformStore((s) => s.deviceType);
+
+ const setDiscoverScrollNode = useCallback((node: HTMLDivElement | null) => {
+ discoverScrollRef.current = node;
+ setDiscoverScrollEl(node);
+ }, []);
+
+ const setDownloadedScrollNode = useCallback((node: HTMLDivElement | null) => {
+ downloadedScrollRef.current = node;
+ setDownloadedScrollEl(node);
+ }, []);
+
+ // Restore the incoming pane's scrollTop and rebind scrollRef. Don't read scrollTop
+ // off the outgoing pane: overflow toggling can clamp it to 0 before this runs, so
+ // trust the live listener mirror instead and avoid that race.
+ useLayoutEffect(() => {
+ let restoreFrame: number | null = null;
+ const previousTab = activeTabRef.current;
+ if (previousTab !== tab) {
+ const previousEl =
+ previousTab === "discover"
+ ? discoverScrollRef.current
+ : downloadedScrollRef.current;
+ if (previousEl) {
+ savedScrollTopsRef.current[previousTab] = previousEl.scrollTop;
+ savedScrollHeightsRef.current[previousTab] = previousEl.scrollHeight;
+ }
+ }
+ const nextEl =
+ tab === "discover"
+ ? discoverScrollRef.current
+ : downloadedScrollRef.current;
+ if (nextEl) {
+ const saved = savedScrollTopsRef.current[tab];
+ if (nextEl.scrollTop !== saved) {
+ nextEl.scrollTop = saved;
+ }
+ savedScrollHeightsRef.current[tab] = nextEl.scrollHeight;
+ restoreFrame = window.requestAnimationFrame(() => {
+ if (activeTabRef.current === tab && nextEl.scrollTop !== saved) {
+ nextEl.scrollTop = saved;
+ }
+ });
+ }
+ activeTabRef.current = tab;
+ assignRef(scrollRef, nextEl);
+ const nextScrolled = (nextEl?.scrollTop ?? 0) > 0;
+ setScrolled((current) => (current === nextScrolled ? current : nextScrolled));
+ return () => {
+ if (restoreFrame !== null) {
+ window.cancelAnimationFrame(restoreFrame);
+ }
+ };
+ }, [scrollRef, tab]);
+
+ useEffect(() => {
+ const discoverEl = discoverScrollRef.current;
+ const downloadedEl = downloadedScrollRef.current;
+ // Mirror scrollTop ONLY from the active pane; the inactive pane can fire
+ // spurious scroll events that would overwrite the saved position with 0.
+ const onDiscoverScroll = () => {
+ if (!discoverEl || activeTabRef.current !== "discover") {
+ return;
+ }
+ savedScrollTopsRef.current.discover = discoverEl.scrollTop;
+ savedScrollHeightsRef.current.discover = discoverEl.scrollHeight;
+ const nextScrolled = discoverEl.scrollTop > 0;
+ setScrolled((current) =>
+ current === nextScrolled ? current : nextScrolled,
+ );
+ };
+ const onDownloadedScroll = () => {
+ if (!downloadedEl || activeTabRef.current !== "downloaded") {
+ return;
+ }
+ savedScrollTopsRef.current.downloaded = downloadedEl.scrollTop;
+ savedScrollHeightsRef.current.downloaded = downloadedEl.scrollHeight;
+ const nextScrolled = downloadedEl.scrollTop > 0;
+ setScrolled((current) =>
+ current === nextScrolled ? current : nextScrolled,
+ );
+ };
+ discoverEl?.addEventListener("scroll", onDiscoverScroll, { passive: true });
+ downloadedEl?.addEventListener("scroll", onDownloadedScroll, {
+ passive: true,
+ });
+ return () => {
+ discoverEl?.removeEventListener("scroll", onDiscoverScroll);
+ downloadedEl?.removeEventListener("scroll", onDownloadedScroll);
+ };
+ }, []);
+
+ useEffect(
+ () => () => {
+ if (
+ scrollRef.current === discoverScrollRef.current ||
+ scrollRef.current === downloadedScrollRef.current
+ ) {
+ assignRef(scrollRef, null);
+ }
+ },
+ [scrollRef],
+ );
+
+ useEffect(() => {
+ // Only the Discover tab drives the streaming loading bar.
+ if (tab !== "discover") {
+ previousScannedCountRef.current = scannedCount;
+ previousLoadingIntentRef.current = loadingIntentCount;
+ setStreamingActive((current) => (current ? false : current));
+ return;
+ }
+ const previousCount = previousScannedCountRef.current;
+ const previousLoadingIntent = previousLoadingIntentRef.current;
+ previousScannedCountRef.current = scannedCount;
+ previousLoadingIntentRef.current = loadingIntentCount;
+ const rowsScanned = scannedCount > previousCount;
+ const fetchRequested = loadingIntentCount > previousLoadingIntent;
+ let nextActive = false;
+ let linger = false;
+ if (isLoading || isLoadingMore) {
+ nextActive = true;
+ } else if (rowsScanned || fetchRequested) {
+ nextActive = true;
+ linger = true;
+ }
+ setStreamingActive((current) => (current === nextActive ? current : nextActive));
+ const timer = linger
+ ? window.setTimeout(() => setStreamingActive(false), 1400)
+ : null;
+ return () => {
+ if (timer !== null) {
+ window.clearTimeout(timer);
+ }
+ };
+ }, [tab, isLoading, isLoadingMore, scannedCount, loadingIntentCount]);
+
+ const showDiscoverLoading = tab === "discover" && streamingActive;
+ // overflow-y stays `auto` on BOTH panes: toggling to `hidden` would clamp the
+ // inactive pane's scrollTop to 0 and corrupt our mirror. Visibility +
+ // pointer-events-none hides it while preserving native scroll state.
+ const scrollPaneClassName =
+ "absolute inset-0 min-h-0 overflow-y-auto pb-6 pl-5 pr-3 pt-0 [overflow-anchor:none] [scrollbar-gutter:stable] [scrollbar-width:thin]";
+ const discoverActive = tab === "discover";
+ const downloadedActive = tab === "downloaded";
+ const discoverInactiveHeight = Math.max(
+ savedScrollHeightsRef.current.discover,
+ discoverRows.length * CATALOG_ROW_HEIGHT_PX,
+ );
+ const downloadedInactiveHeight = Math.max(
+ savedScrollHeightsRef.current.downloaded,
+ (cachedRows.length + localRows.length) * CATALOG_ROW_HEIGHT_PX,
+ );
+
+ return (
+ <div className="relative flex h-full min-h-0 flex-1 flex-col overflow-hidden">
+ <div
+ aria-hidden="true"
+ className={cn(
+ "mx-5 shrink-0 border-t transition-colors",
+ scrolled ? "border-border" : "border-transparent",
+ )}
+ />
+ {/* Banner sits outside the scroll container so toggling it never shifts virtualized rows. */}
+ {downloadedActive && inventoryWarning && (
+ <InventoryWarningRow
+ isDataset={isDataset}
+ onRetry={() => onInventoryChange?.()}
+ />
+ )}
+ <div className="relative min-h-0 flex-1">
+ <div
+ ref={setDiscoverScrollNode}
+ data-hub-scroll="true"
+ aria-hidden={!discoverActive}
+ tabIndex={discoverActive ? undefined : -1}
+ className={cn(
+ scrollPaneClassName,
+ discoverActive ? "visible" : "pointer-events-none invisible",
+ )}
+ >
+ {discoverActive ? (
+ <DiscoverList
+ discoverRows={discoverRows}
+ selectedId={selectedId}
+ onSelect={onSelect}
+ isLoading={isLoading}
+ query={query}
+ scrollElement={discoverScrollEl}
+ sentinelRef={sentinelRef}
+ activeCheckpoint={activeCheckpoint}
+ searchError={searchError}
+ online={online}
+ isDataset={isDataset}
+ deviceType={deviceType}
+ scannedCount={scannedCount}
+ isLoadingMore={isLoadingMore}
+ hasMore={hasMore}
+ manualFetchAvailable={manualFetchAvailable}
+ hasActiveFilters={hasActiveFilters}
+ onFetchMore={onFetchMore}
+ onClearFilters={onClearFilters}
+ onRetry={onRetry}
+ onSwitchDevice={onSwitchDevice}
+ />
+ ) : (
+ <div
+ aria-hidden="true"
+ style={{ height: discoverInactiveHeight }}
+ />
+ )}
+ </div>
+ <div
+ ref={setDownloadedScrollNode}
+ data-hub-scroll="true"
+ aria-hidden={!downloadedActive}
+ tabIndex={downloadedActive ? undefined : -1}
+ className={cn(
+ scrollPaneClassName,
+ downloadedActive ? "visible" : "pointer-events-none invisible",
+ )}
+ >
+ {downloadedActive ? (
+ <DownloadedList
+ cachedRows={cachedRows}
+ localRows={localRows}
+ selectedId={selectedId}
+ onSelect={onSelect}
+ downloadedReady={downloadedReady}
+ inventoryError={inventoryError}
+ query={query}
+ scrollElement={downloadedScrollEl}
+ activeCheckpoint={activeCheckpoint}
+ activeGgufVariant={activeGgufVariant}
+ isDataset={isDataset}
+ inventoryTokens={inventoryTokens}
+ deviceType={deviceType}
+ onInventoryChange={onInventoryChange}
+ />
+ ) : (
+ <div
+ aria-hidden="true"
+ style={{ height: downloadedInactiveHeight }}
+ />
+ )}
+ </div>
+ </div>
+ <output
+ aria-live="polite"
+ aria-label={showDiscoverLoading ? "Loading models" : undefined}
+ className={cn(
+ "pointer-events-none absolute inset-x-0 bottom-0 z-10 h-[3px] transition-opacity duration-150",
+ showDiscoverLoading ? "opacity-100" : "opacity-0",
+ )}
+ >
+ <div
+ className="hub-loading-bar"
+ data-active={showDiscoverLoading || undefined}
+ />
+ </output>
+ </div>
+ );
+});
diff --git a/studio/frontend/src/features/hub/catalog/models-header.tsx b/studio/frontend/src/features/hub/catalog/models-header.tsx
new file mode 100644
index 00000000000..d1b3acced9e
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/models-header.tsx
@@ -0,0 +1,139 @@
+// 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 { HfTokenIndicator } from "@/features/hub/components/hf-token-indicator";
+import { PageHeading } from "@/features/hub/components/page-heading";
+import { TransportToggle } from "./transport-toggle";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import {
+ ChipIcon,
+ Database02Icon,
+ Logout01Icon,
+ PackageIcon,
+ RamMemoryIcon,
+} from "@hugeicons/core-free-icons";
+import type { IconSvgElement } from "@hugeicons/react";
+import { HugeiconsIcon } from "@hugeicons/react";
+
+function StatPill({
+ icon,
+ label,
+ value,
+ tone = "default",
+}: {
+ icon: IconSvgElement;
+ label: string;
+ value: string;
+ tone?: "default" | "active";
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div
+ className={cn(
+ "inline-flex cursor-default items-center gap-1.5 px-2.5 py-1 text-[11.5px] transition-colors duration-150",
+ tone === "active"
+ ? "rounded-[11px] bg-emerald-500/10 text-emerald-700 ring-1 ring-inset ring-emerald-500/20 dark:text-emerald-300"
+ : "hub-tag-soft text-muted-foreground hover:text-foreground/80",
+ )}
+ >
+ <HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-3.5" />
+ <span className="font-medium tabular-nums">{value}</span>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent className="tooltip-compact">{label}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+export function ModelsHeader({
+ cachedCount,
+ localCount,
+ isDataset,
+ gpuLabel,
+ ramLabel,
+ activeCheckpoint,
+ activeGgufVariant,
+ onEject,
+}: {
+ cachedCount: number;
+ localCount: number;
+ isDataset: boolean;
+ gpuLabel: string;
+ ramLabel: string;
+ activeCheckpoint: string | null;
+ activeGgufVariant: string | null;
+ onEject: () => void;
+}) {
+ return (
+ <header className="font-heading flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between">
+ <PageHeading
+ title="Hub"
+ subtitle={
+ isDataset
+ ? "Discover, download, and train on datasets locally."
+ : "Discover, download, and run inference models locally."
+ }
+ />
+
+ <div className="flex flex-wrap items-center gap-1.5">
+ <HfTokenIndicator />
+ <TransportToggle />
+ <StatPill
+ icon={PackageIcon}
+ label="Cache"
+ value={String(cachedCount)}
+ />
+ <StatPill
+ icon={Database02Icon}
+ label="Local"
+ value={String(localCount)}
+ />
+ <StatPill icon={ChipIcon} label="VRAM" value={gpuLabel} />
+ <StatPill icon={RamMemoryIcon} label="CPU RAM" value={ramLabel} />
+
+ {activeCheckpoint && (
+ <div className="hub-tag-soft ml-1 inline-flex items-center gap-1.5 px-2 py-1 text-[11.5px]">
+ <span
+ className="size-1.5 rounded-full bg-emerald-500"
+ aria-hidden="true"
+ />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="max-w-[120px] cursor-default truncate font-medium text-primary">
+ {activeCheckpoint}
+ {activeGgufVariant ? ` · ${activeGgufVariant}` : ""}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ sideOffset={6}
+ className="tooltip-compact"
+ >
+ {activeCheckpoint}
+ {activeGgufVariant ? ` · ${activeGgufVariant}` : ""}
+ </TooltipContent>
+ </Tooltip>
+ <button
+ type="button"
+ onClick={onEject}
+ className="-mr-0.5 ml-0.5 inline-flex cursor-pointer items-center gap-1 rounded-md px-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={Logout01Icon}
+ strokeWidth={1.75}
+ className="size-3"
+ />
+ Eject
+ </button>
+ </div>
+ )}
+ </div>
+ </header>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/models-toolbar.tsx b/studio/frontend/src/features/hub/catalog/models-toolbar.tsx
new file mode 100644
index 00000000000..82033642bd4
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/models-toolbar.tsx
@@ -0,0 +1,405 @@
+// 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 { Input } from "@/components/ui/input";
+import { Spinner } from "@/components/ui/spinner";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import {
+ AiChipIcon,
+ Database02Icon,
+ FolderSearchIcon,
+ Refresh01Icon,
+ Search01Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import type { HfSortKey } from "@/features/hub/hooks/use-hub-model-search";
+import type {
+ CapabilityFilter,
+ ModelFormatFilter,
+ ModelsTab,
+ ResourceTypeFilter,
+} from "../types";
+import {
+ CHANNEL_PRESETS,
+ type ChannelId,
+ findChannel,
+} from "../lib/channels";
+import {
+ CAPABILITY_FILTER_OPTIONS,
+ FORMAT_FILTER_OPTIONS,
+} from "../lib/view-models";
+import { HubOptionMenu, type HubOption } from "./hub-option-menu";
+import { memo, useMemo } from "react";
+
+const SORT_OPTIONS: ReadonlyArray<{
+ value: HfSortKey;
+ label: string;
+}> = [
+ { value: "trendingScore", label: "Trending" },
+ { value: "likes", label: "Most likes" },
+ { value: "downloads", label: "Most downloads" },
+ { value: "lastModified", label: "Recently updated" },
+ { value: "createdAt", label: "Newest" },
+];
+
+type ChannelOptionValue = "all" | ChannelId;
+
+export const ModelsToolbar = memo(function ModelsToolbar({
+ tab,
+ onTabChange,
+ query,
+ onQueryChange,
+ isLoading,
+ sortBy,
+ onSortChange,
+ resourceType,
+ onResourceTypeChange,
+ formatFilter,
+ onFormatFilterChange,
+ capabilityFilter,
+ onCapabilityFilterChange,
+ activeChannelId,
+ onChannelSelect,
+ onRefresh,
+ onManageLocalFolders,
+}: {
+ tab: ModelsTab;
+ onTabChange: (tab: ModelsTab) => void;
+ query: string;
+ onQueryChange: (value: string) => void;
+ isLoading: boolean;
+ onRefresh: () => void;
+ sortBy: HfSortKey;
+ onSortChange: (value: HfSortKey) => void;
+ resourceType: ResourceTypeFilter;
+ onResourceTypeChange: (value: ResourceTypeFilter) => void;
+ formatFilter: ModelFormatFilter;
+ onFormatFilterChange: (value: ModelFormatFilter) => void;
+ capabilityFilter: CapabilityFilter;
+ onCapabilityFilterChange: (value: CapabilityFilter) => void;
+ activeChannelId: ChannelId | null;
+ onChannelSelect: (id: ChannelId | null) => void;
+ onManageLocalFolders: () => void;
+}) {
+ const activeChannel = findChannel(activeChannelId);
+ const isDataset = resourceType === "datasets";
+ const channelValue: ChannelOptionValue = activeChannelId ?? "all";
+ const formatOptions = useMemo<HubOption<ModelFormatFilter>[]>(
+ () =>
+ FORMAT_FILTER_OPTIONS.map((option) => ({
+ value: option.value,
+ triggerLabel: option.label,
+ label: (
+ <>
+ {option.value === "gguf" && (
+ <span className="inline-block size-1.5 shrink-0 rounded-full bg-format-gguf" />
+ )}
+ {option.value === "checkpoint" && (
+ <span className="inline-block size-1.5 shrink-0 rounded-full bg-format-checkpoint" />
+ )}
+ {option.label}
+ </>
+ ),
+ })),
+ [],
+ );
+ const capabilityOptions = useMemo<HubOption<CapabilityFilter>[]>(
+ () =>
+ CAPABILITY_FILTER_OPTIONS.map((option) => ({
+ value: option.value,
+ label: option.label,
+ })),
+ [],
+ );
+ const sortOptions = useMemo<HubOption<HfSortKey>[]>(
+ () =>
+ SORT_OPTIONS.map((option) => ({
+ value: option.value,
+ label: option.label,
+ })),
+ [],
+ );
+ const channelOptions = useMemo<HubOption<ChannelOptionValue>[]>(
+ () => [
+ { value: "all", label: "All models" },
+ ...CHANNEL_PRESETS.map((preset) => ({
+ value: preset.id,
+ checkClassName: "text-primary",
+ label: (
+ <span className="flex w-full min-w-0 items-start gap-2">
+ <HugeiconsIcon
+ icon={preset.icon}
+ strokeWidth={1.75}
+ className="mt-0.5 size-4 shrink-0 text-muted-foreground"
+ />
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="min-w-0 truncate">{preset.label}</span>
+ <span className="min-w-0 whitespace-normal break-words text-[11px] leading-snug text-muted-foreground">
+ {preset.hint}
+ </span>
+ </span>
+ </span>
+ ),
+ })),
+ ],
+ [],
+ );
+ const triggerBase = cn(
+ "field-trigger hub-menu-trigger field-soft transition-colors",
+ "focus-visible:ring-0 focus-visible:ring-offset-0 focus-visible:border-border",
+ );
+ return (
+ <div className="flex min-w-0 flex-col gap-2 lg:flex-row lg:flex-wrap lg:items-center">
+ <div
+ className={cn(
+ "hub-menu-trigger hub-tab-toggle relative inline-flex h-9 w-full shrink-0 items-center rounded-full lg:w-[240px]",
+ )}
+ role="radiogroup"
+ aria-label="View"
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ "hub-tab-toggle-pill",
+ "pointer-events-none absolute inset-y-0 left-0 w-1/2 rounded-full transition-transform duration-200 ease-out",
+ tab === "downloaded" ? "translate-x-full" : "translate-x-0",
+ )}
+ />
+ <button
+ type="button"
+ role="radio"
+ aria-checked={tab === "discover"}
+ onClick={() => onTabChange("discover")}
+ className={cn(
+ "relative z-10 inline-flex h-9 flex-1 items-center justify-center rounded-full px-3 text-[12.5px] transition-colors",
+ tab === "discover"
+ ? "text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ Discover
+ </button>
+ <button
+ type="button"
+ role="radio"
+ aria-checked={tab === "downloaded"}
+ onClick={() => onTabChange("downloaded")}
+ className={cn(
+ "relative z-10 inline-flex h-9 flex-1 items-center justify-center rounded-full px-3 text-[12.5px] transition-colors",
+ tab === "downloaded"
+ ? "text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ On Device
+ </button>
+ </div>
+
+ <div className="flex min-w-0 items-center gap-2 lg:flex-[1_1_280px]">
+ <div
+ className="hub-menu-trigger hub-tab-toggle relative inline-flex h-9 shrink-0 items-center rounded-full"
+ role="radiogroup"
+ aria-label="Resource type"
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ "hub-tab-toggle-pill",
+ "pointer-events-none absolute inset-y-0 left-0 w-1/2 rounded-full transition-transform duration-200 ease-out",
+ resourceType === "datasets" ? "translate-x-full" : "translate-x-0",
+ )}
+ />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ role="radio"
+ aria-checked={resourceType === "models"}
+ aria-label="Models"
+ onClick={() => onResourceTypeChange("models")}
+ className={cn(
+ "relative z-10 inline-flex h-9 w-9 items-center justify-center rounded-full transition-colors",
+ resourceType === "models"
+ ? "text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ <HugeiconsIcon
+ icon={AiChipIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={6}>
+ Models
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ role="radio"
+ aria-checked={resourceType === "datasets"}
+ aria-label="Datasets"
+ onClick={() => onResourceTypeChange("datasets")}
+ className={cn(
+ "relative z-10 inline-flex h-9 w-9 items-center justify-center rounded-full transition-colors",
+ resourceType === "datasets"
+ ? "text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ <HugeiconsIcon
+ icon={Database02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={6}>
+ Datasets
+ </TooltipContent>
+ </Tooltip>
+ </div>
+
+ <div className="relative min-w-0 flex-1">
+ <HugeiconsIcon
+ icon={Search01Icon}
+ strokeWidth={1.8}
+ className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
+ />
+ <Input
+ value={query}
+ onChange={(event) => onQueryChange(event.target.value)}
+ placeholder={
+ tab === "downloaded"
+ ? `Search on-device ${isDataset ? "datasets" : "models"}`
+ : "Search Hugging Face"
+ }
+ className="field-soft h-9 rounded-full pl-10 pr-10 text-[12.5px] placeholder:text-muted-foreground/80"
+ />
+ {tab === "discover" && isLoading && (
+ <Spinner className="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
+ )}
+ </div>
+ </div>
+
+ <div className="flex min-w-0 flex-wrap items-center gap-2 lg:flex-[0_1_auto] lg:justify-end">
+ {tab === "downloaded" && !isDataset && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={onManageLocalFolders}
+ className={cn(
+ triggerBase,
+ "field-filter inline-flex h-9 shrink-0 items-center gap-1.5 rounded-full px-3 text-[12.5px]",
+ )}
+ >
+ <HugeiconsIcon
+ icon={FolderSearchIcon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ Add folder
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={6}>
+ Manage local model folders
+ </TooltipContent>
+ </Tooltip>
+ )}
+
+ {!isDataset && (
+ <HubOptionMenu
+ value={formatFilter}
+ options={formatOptions}
+ onValueChange={onFormatFilterChange}
+ ariaLabel="Format filter"
+ className={cn(triggerBase, "min-w-[124px]")}
+ />
+ )}
+
+ {tab === "discover" && !isDataset && (
+ <HubOptionMenu
+ value={capabilityFilter}
+ options={capabilityOptions}
+ onValueChange={onCapabilityFilterChange}
+ ariaLabel="Capability filter"
+ className={cn(triggerBase, "min-w-[136px]")}
+ />
+ )}
+
+ {tab === "discover" && (
+ <HubOptionMenu
+ value={sortBy}
+ options={sortOptions}
+ onValueChange={onSortChange}
+ ariaLabel="Sort models"
+ className={cn(triggerBase, "min-w-[140px]")}
+ />
+ )}
+
+ {tab === "discover" && !isDataset && (
+ <HubOptionMenu
+ value={channelValue}
+ options={channelOptions}
+ onValueChange={(next) =>
+ onChannelSelect(next === "all" ? null : next)
+ }
+ ariaLabel="Curated channels"
+ title={activeChannel ? activeChannel.label : "Curated channels"}
+ align="end"
+ showChevron={false}
+ triggerContent={
+ <span
+ aria-hidden="true"
+ className={cn(
+ "hub-verified-badge size-4",
+ activeChannel ? "text-primary" : "text-muted-foreground",
+ )}
+ />
+ }
+ className={cn(
+ triggerBase,
+ "field-filter inline-flex size-9 shrink-0 items-center justify-center rounded-full p-0",
+ )}
+ contentClassName="w-[calc(100vw-1.5rem)] sm:w-[320px]"
+ />
+ )}
+
+ {tab === "discover" && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ aria-label="Refresh from Hugging Face"
+ onClick={onRefresh}
+ className={cn(
+ triggerBase,
+ "field-filter inline-flex size-9 shrink-0 items-center justify-center rounded-full p-0",
+ )}
+ >
+ <HugeiconsIcon
+ icon={Refresh01Icon}
+ strokeWidth={1.75}
+ className={cn("size-4", isLoading && "animate-spin")}
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={6}>
+ Refresh from Hugging Face
+ </TooltipContent>
+ </Tooltip>
+ )}
+
+ </div>
+ </div>
+ );
+});
diff --git a/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsx b/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsx
new file mode 100644
index 00000000000..94726b92952
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsx
@@ -0,0 +1,370 @@
+// 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 { FolderBrowser } from "@/components/assistant-ui/model-selector/folder-browser";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Spinner } from "@/components/ui/spinner";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ type ScanFolderInfo,
+ addScanFolder,
+ listScanFolders,
+ removeScanFolder,
+} from "@/features/hub/inventory";
+import { cn } from "@/lib/utils";
+import {
+ Delete02Icon,
+ FileSearchIcon,
+ FolderAddIcon,
+ FolderOpenIcon,
+ FolderSearchIcon,
+ PlusSignIcon,
+ RefreshIcon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "@/lib/toast";
+
+function pathTail(path: string): string {
+ const parts = path.split(/[\\/]/).filter(Boolean);
+ return parts.at(-1) ?? path;
+}
+
+function formatError(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+export function OnDeviceFoldersDialog({
+ open,
+ onOpenChange,
+ onInventoryChange,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onInventoryChange?: () => void;
+}) {
+ const [folders, setFolders] = useState<ScanFolderInfo[]>([]);
+ const [path, setPath] = useState("");
+ const [browserOpen, setBrowserOpen] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [pending, setPending] = useState<"add" | `remove:${number}` | null>(
+ null,
+ );
+ const refreshIdRef = useRef(0);
+ const mutationVersionRef = useRef(0);
+
+ const sortedFolders = useMemo(
+ () => [...folders].sort((a, b) => a.path.localeCompare(b.path)),
+ [folders],
+ );
+
+ const refreshFolders = useCallback(() => {
+ const refreshId = refreshIdRef.current + 1;
+ const mutationVersion = mutationVersionRef.current;
+ refreshIdRef.current = refreshId;
+ setLoading(true);
+ setError(null);
+ listScanFolders()
+ .then((nextFolders) => {
+ if (refreshIdRef.current !== refreshId) {
+ return;
+ }
+ if (mutationVersionRef.current !== mutationVersion) {
+ return;
+ }
+ setFolders(nextFolders);
+ })
+ .catch((err) => {
+ if (refreshIdRef.current === refreshId) {
+ setError(formatError(err));
+ }
+ })
+ .finally(() => {
+ if (refreshIdRef.current === refreshId) {
+ setLoading(false);
+ }
+ });
+ }, []);
+
+ useEffect(() => {
+ if (!open) return;
+ const timer = window.setTimeout(refreshFolders, 0);
+ return () => window.clearTimeout(timer);
+ }, [open, refreshFolders]);
+
+ const handleInventoryChanged = useCallback(() => {
+ onInventoryChange?.();
+ }, [onInventoryChange]);
+
+ const handleAdd = useCallback(
+ async (rawPath: string) => {
+ const nextPath = rawPath.trim();
+ if (!nextPath || pending) return;
+ setPending("add");
+ setError(null);
+ try {
+ const folder = await addScanFolder(nextPath);
+ setPath("");
+ mutationVersionRef.current += 1;
+ setFolders((current) => {
+ const withoutDuplicate = current.filter((row) => row.id !== folder.id);
+ return [...withoutDuplicate, folder];
+ });
+ toast.success("Location added", {
+ description: pathTail(folder.path),
+ });
+ handleInventoryChanged();
+ } catch (err) {
+ const message = formatError(err);
+ setError(message);
+ toast.error("Couldn't add location", { description: message });
+ } finally {
+ setPending(null);
+ }
+ },
+ [handleInventoryChanged, pending],
+ );
+
+ const handleRemove = useCallback(
+ async (folder: ScanFolderInfo) => {
+ const key = `remove:${folder.id}` as const;
+ if (pending) return;
+ setPending(key);
+ setError(null);
+ try {
+ await removeScanFolder(folder.id);
+ mutationVersionRef.current += 1;
+ setFolders((current) => current.filter((row) => row.id !== folder.id));
+ toast.success("Location removed", {
+ description: pathTail(folder.path),
+ });
+ handleInventoryChanged();
+ } catch (err) {
+ const message = formatError(err);
+ setError(message);
+ toast.error("Couldn't remove location", { description: message });
+ } finally {
+ setPending(null);
+ }
+ },
+ [handleInventoryChanged, pending],
+ );
+
+ return (
+ <>
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ className="max-w-[600px] gap-0 overflow-hidden p-0"
+ overlayClassName="bg-black/20 backdrop-blur-none"
+ >
+ <DialogHeader className="border-b border-border/60 px-5 py-4">
+ <DialogTitle className="text-[15px]">On-device locations</DialogTitle>
+ <DialogDescription className="sr-only">
+ Hugging Face model folders, GGUF files, and adapters are indexed here.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 px-5 py-4">
+ <div className="rounded-[14px] border border-border/70 bg-muted/20 p-3">
+ <div className="mb-2 flex items-center gap-2 text-[12px] font-medium text-foreground">
+ <HugeiconsIcon
+ icon={FolderAddIcon}
+ strokeWidth={1.75}
+ className="size-3.5 text-muted-foreground"
+ />
+ Add location
+ </div>
+
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
+ <div className="relative min-w-0 flex-1">
+ <HugeiconsIcon
+ icon={FileSearchIcon}
+ strokeWidth={1.75}
+ className="pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"
+ />
+ <Input
+ value={path}
+ onChange={(event) => setPath(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== "Enter") return;
+ event.preventDefault();
+ void handleAdd(path);
+ }}
+ placeholder="Paste model folder or file path"
+ className="field-soft h-9 rounded-full pl-9 pr-3 font-mono text-[12px] placeholder:font-sans"
+ />
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon-sm"
+ onClick={() => setBrowserOpen(true)}
+ aria-label="Browse locations"
+ className="size-9 rounded-full"
+ >
+ <HugeiconsIcon
+ icon={FolderSearchIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="tooltip-compact">
+ Browse
+ </TooltipContent>
+ </Tooltip>
+ <Button
+ type="button"
+ size="sm"
+ onClick={() => void handleAdd(path)}
+ disabled={!path.trim() || pending !== null}
+ className="h-9 rounded-full px-3 text-[12.5px]"
+ >
+ {pending === "add" ? (
+ <Spinner className="size-3.5" />
+ ) : (
+ <HugeiconsIcon
+ icon={PlusSignIcon}
+ strokeWidth={1.75}
+ data-icon="inline-start"
+ className="size-3.5"
+ />
+ )}
+ Add
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ {error ? (
+ <div className="rounded-[10px] border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] text-destructive">
+ {error}
+ </div>
+ ) : null}
+
+ <div className="overflow-hidden rounded-[14px] border border-border/70">
+ <div className="flex h-10 items-center justify-between border-b border-border/60 px-3">
+ <span className="text-[12px] font-medium text-foreground">
+ Indexed locations
+ </span>
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label="Refresh locations"
+ onClick={refreshFolders}
+ disabled={loading}
+ className="inline-flex size-7 items-center justify-center rounded-[8px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50"
+ >
+ <HugeiconsIcon
+ icon={RefreshIcon}
+ strokeWidth={1.75}
+ className={cn("size-3.5", loading && "animate-spin")}
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="tooltip-compact">
+ Refresh
+ </TooltipContent>
+ </Tooltip>
+ </div>
+
+ <div className="max-h-64 overflow-y-auto">
+ {loading ? (
+ <div className="flex h-24 items-center justify-center gap-2 text-[12px] text-muted-foreground">
+ <Spinner className="size-3.5" />
+ Loading locations...
+ </div>
+ ) : sortedFolders.length === 0 ? (
+ <div className="flex h-28 flex-col items-center justify-center gap-2 px-4 text-center text-[12px] text-muted-foreground">
+ <HugeiconsIcon
+ icon={FolderOpenIcon}
+ strokeWidth={1.75}
+ className="size-5 text-muted-foreground/60"
+ />
+ No custom locations
+ </div>
+ ) : (
+ sortedFolders.map((folder) => {
+ const removing = pending === `remove:${folder.id}`;
+ return (
+ <div
+ key={folder.id}
+ className="flex min-h-12 items-center gap-3 border-b border-border/50 px-3 py-2 last:border-b-0"
+ >
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-[9px] bg-muted text-muted-foreground">
+ <HugeiconsIcon
+ icon={FolderOpenIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[12.5px] font-medium text-foreground">
+ {pathTail(folder.path)}
+ </p>
+ <p
+ title={folder.path}
+ className="truncate font-mono text-[10.5px] text-muted-foreground"
+ >
+ {folder.path}
+ </p>
+ </div>
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={`Remove ${folder.path}`}
+ onClick={() => void handleRemove(folder)}
+ disabled={pending !== null}
+ className="inline-flex size-8 shrink-0 items-center justify-center rounded-[9px] text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:opacity-50"
+ >
+ {removing ? (
+ <Spinner className="size-3.5" />
+ ) : (
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ )}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="left" className="tooltip-compact">
+ Remove from list
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ <FolderBrowser
+ open={browserOpen}
+ onOpenChange={setBrowserOpen}
+ onSelect={(selectedPath) => void handleAdd(selectedPath)}
+ />
+ </>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/owner-avatar.tsx b/studio/frontend/src/features/hub/catalog/owner-avatar.tsx
new file mode 100644
index 00000000000..cb2adc0b051
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/owner-avatar.tsx
@@ -0,0 +1,221 @@
+// 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 { cn } from "@/lib/utils";
+import { useEffect, useState } from "react";
+import { useHfOwnerAvatar } from "../lib/hf-owner-avatar";
+import {
+ type ProviderLogo,
+ resolveOwnerProviderLogo,
+} from "../lib/provider-logos";
+
+const PALETTE = [
+ "hsl(214 42% 42%)",
+ "hsl(172 32% 36%)",
+ "hsl(30 42% 42%)",
+ "hsl(348 36% 44%)",
+ "hsl(198 38% 40%)",
+ "hsl(140 26% 38%)",
+ "hsl(222 24% 46%)",
+ "hsl(16 34% 44%)",
+ "hsl(260 22% 48%)",
+ "hsl(44 44% 40%)",
+];
+
+function hashOwner(owner: string): number {
+ let h = 0;
+ for (let i = 0; i < owner.length; i++) {
+ h = (h * 31 + owner.charCodeAt(i)) | 0;
+ }
+ return Math.abs(h);
+}
+
+type AvatarSize = "xs" | "sm" | "md" | "lg";
+
+const SIZES: Record<AvatarSize, string> = {
+ xs: "size-5 rounded-[6px] text-[9px]",
+ sm: "size-7 rounded-[8px] text-[11px]",
+ md: "size-9 rounded-[10px] text-[13px]",
+ lg: "size-12 rounded-[13px] text-[16px]",
+};
+
+const AVATAR_IMAGE_RETRY_BASE_MS = 60_000;
+const AVATAR_IMAGE_RETRY_MAX_MS = 30 * 60_000;
+
+interface FailedAvatarImage {
+ url: string;
+ failures: number;
+ retryReady: boolean;
+}
+
+function avatarImageRetryDelay(failures: number): number {
+ return Math.min(
+ AVATAR_IMAGE_RETRY_BASE_MS * 2 ** Math.max(failures - 1, 0),
+ AVATAR_IMAGE_RETRY_MAX_MS,
+ );
+}
+
+export function OwnerAvatar({
+ owner,
+ repoName,
+ size = "md",
+ className,
+}: {
+ owner: string;
+ // For an eligible owner (currently "unsloth"), match a known upstream provider
+ // and render its logo (e.g. an Unsloth Qwen2.5 re-upload shows the Qwen logo).
+ repoName?: string;
+ size?: AvatarSize;
+ className?: string;
+}) {
+ const providerLogo = resolveOwnerProviderLogo(owner, repoName);
+ if (providerLogo) {
+ return (
+ <ProviderLogoTile
+ provider={providerLogo}
+ size={size}
+ className={className}
+ />
+ );
+ }
+ return <DefaultAvatar owner={owner} size={size} className={className} />;
+}
+
+function ProviderLogoTile({
+ provider,
+ size,
+ className,
+}: {
+ provider: ProviderLogo;
+ size: AvatarSize;
+ className?: string;
+}) {
+ const altLabel = `${provider.name} logo`;
+ const bgClass =
+ provider.background === "white" ? "bg-white" : "bg-transparent";
+
+ if (provider.treatment === "original") {
+ const fit = provider.fit ?? "contain";
+ return (
+ <span
+ role="img"
+ aria-label={altLabel}
+ className={cn(
+ "hub-avatar-tile inline-flex shrink-0 items-center justify-center overflow-hidden",
+ bgClass,
+ SIZES[size],
+ className,
+ )}
+ >
+ <img
+ src={provider.logoPath}
+ alt=""
+ loading="lazy"
+ className={cn(
+ fit === "cover" ? "size-full object-cover" : "size-3/4 object-contain",
+ )}
+ />
+ </span>
+ );
+ }
+
+ // mono treatments paint a silhouette via CSS mask; host text color drives its color.
+ const colorClass =
+ provider.treatment === "mono-black" ? "text-black" : "text-foreground";
+ return (
+ <span
+ role="img"
+ aria-label={altLabel}
+ className={cn(
+ "hub-avatar-tile inline-flex shrink-0 items-center justify-center overflow-hidden",
+ bgClass,
+ colorClass,
+ SIZES[size],
+ className,
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className="size-3/4 bg-current"
+ style={{
+ mask: `url(${provider.logoPath}) center / contain no-repeat`,
+ WebkitMask: `url(${provider.logoPath}) center / contain no-repeat`,
+ }}
+ />
+ </span>
+ );
+}
+
+function DefaultAvatar({
+ owner,
+ size,
+ className,
+}: {
+ owner: string;
+ size: AvatarSize;
+ className?: string;
+}) {
+ const owned = owner.trim() || "?";
+ const initial = owned[0]?.toUpperCase() ?? "?";
+ const color = PALETTE[hashOwner(owned) % PALETTE.length];
+ const remoteUrl = useHfOwnerAvatar(owned);
+ const [failedImage, setFailedImage] = useState<FailedAvatarImage | null>(
+ null,
+ );
+ const imageBlocked =
+ Boolean(remoteUrl) &&
+ failedImage?.url === remoteUrl &&
+ !failedImage.retryReady;
+ const showImage = Boolean(remoteUrl) && !imageBlocked;
+
+ useEffect(() => {
+ const activeFailure =
+ remoteUrl && failedImage?.url === remoteUrl ? failedImage : null;
+ if (!activeFailure || activeFailure.retryReady) {
+ return;
+ }
+
+ const timer = globalThis.setTimeout(() => {
+ setFailedImage((current) =>
+ current?.url === remoteUrl && !current.retryReady
+ ? { ...current, retryReady: true }
+ : current,
+ );
+ }, avatarImageRetryDelay(activeFailure.failures));
+ return () => globalThis.clearTimeout(timer);
+ }, [remoteUrl, failedImage]);
+
+ return (
+ <span
+ style={showImage ? undefined : { backgroundColor: color }}
+ className={cn(
+ "hub-avatar-tile inline-flex shrink-0 items-center justify-center overflow-hidden font-semibold text-white",
+ SIZES[size],
+ className,
+ )}
+ aria-hidden="true"
+ >
+ {showImage ? (
+ <img
+ src={remoteUrl ?? ""}
+ alt=""
+ loading="lazy"
+ className="size-full object-cover"
+ onLoad={() => setFailedImage(null)}
+ onError={() => {
+ if (!remoteUrl) {
+ return;
+ }
+ setFailedImage((current) => ({
+ url: remoteUrl,
+ failures: current?.url === remoteUrl ? current.failures + 1 : 1,
+ retryReady: false,
+ }));
+ }}
+ />
+ ) : (
+ initial
+ )}
+ </span>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/path-info-button.tsx b/studio/frontend/src/features/hub/catalog/path-info-button.tsx
new file mode 100644
index 00000000000..c2c897412c2
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/path-info-button.tsx
@@ -0,0 +1,111 @@
+// 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 {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import {
+ Copy01Icon,
+ FolderSearchIcon,
+ Tick02Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import type { MouseEvent } from "react";
+import { useState } from "react";
+import { useCopyFeedback } from "../hooks/use-copy-feedback";
+
+export function PathInfoButton({
+ path,
+ title = "On-device location",
+ description = "Where this model lives on disk.",
+ className,
+}: {
+ path: string;
+ title?: string;
+ description?: string;
+ className?: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const { copied, copy } = useCopyFeedback();
+
+ const handleCopy = async (event: MouseEvent<HTMLButtonElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ await copy(path);
+ };
+
+ return (
+ <>
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label="Show on-device path"
+ onClick={(e) => {
+ e.stopPropagation();
+ setOpen(true);
+ }}
+ className={cn(
+ "inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-[8px] text-muted-foreground opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-muted hover:text-foreground focus-visible:opacity-100 group-hover/dl:opacity-100",
+ className,
+ )}
+ >
+ <HugeiconsIcon
+ icon={FolderSearchIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="tooltip-compact">
+ Show path
+ </TooltipContent>
+ </Tooltip>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent
+ className="sm:max-w-[520px]"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>{description}</DialogDescription>
+ </DialogHeader>
+ <div className="flex items-stretch gap-2">
+ <div className="flex-1 select-text rounded-[10px] border border-border bg-muted/30 px-3 py-2.5 text-[12px] leading-5 text-foreground/85 break-all">
+ {path}
+ </div>
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label="Copy path"
+ onClick={handleCopy}
+ className="inline-flex shrink-0 cursor-pointer items-center justify-center rounded-[10px] border border-border bg-muted/30 px-3 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={copied ? Tick02Icon : Copy01Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="tooltip-compact">
+ {copied ? "Copied" : "Copy path"}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx
new file mode 100644
index 00000000000..5c5d3901168
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx
@@ -0,0 +1,327 @@
+// 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 { Spinner } from "@/components/ui/spinner";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { useRepoDownload } from "../download-manager";
+import { deleteCachedModel } from "../inventory";
+import { cn } from "@/lib/utils";
+import {
+ Alert02Icon,
+ PencilEdit02Icon,
+ PlayIcon,
+} from "@hugeicons/core-free-icons";
+import { TrainIcon } from "../components/train-icon";
+import { HUB_POST_DOWNLOAD_ACTIONS_VISIBLE } from "../lib/hub-feature-flags";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useEffect, useState } from "react";
+import { useHfTokenStore } from "../stores/hf-token-store";
+import { fetchModelSize } from "../lib/dataset-size";
+import { formatBytes } from "../lib/format";
+import { fingerprintToken } from "../lib/token-fingerprint";
+import { useOnlineStatus } from "../hooks/use-online-status";
+import {
+ CardDivider,
+ CardDeleteButton,
+ DeleteConfirmDialog,
+ DownloadActionButton,
+ DownloadCard,
+} from "./download-card";
+import { DotTag } from "./dot-tag";
+import { PathInfoButton } from "./path-info-button";
+import { useCardDelete } from "./use-card-delete";
+import type { ModelInventoryFormat } from "../inventory";
+import { useDownloadCardState } from "./use-download-card-state";
+
+function formatModelLabel(modelFormat?: ModelInventoryFormat | null): string {
+ if (modelFormat === "adapter") return "Adapter";
+ if (modelFormat === "checkpoint") return "Checkpoint";
+ if (!modelFormat || modelFormat === "safetensors") return "Safetensors";
+ return "Model";
+}
+
+function formatModelTone(
+ modelFormat?: ModelInventoryFormat | null,
+): "checkpoint" | "adapter" {
+ return modelFormat === "adapter" ? "adapter" : "checkpoint";
+}
+
+export function SafetensorsDownloadCard({
+ repoId,
+ isDownloaded,
+ isPartial = false,
+ partialTransport = null,
+ modelFormat,
+ canRun = true,
+ isActive,
+ isLoadingThisModel,
+ cachePath,
+ knownBytes,
+ onLoad,
+ onUseInChat,
+ onTrain,
+ onChange,
+}: {
+ repoId: string;
+ isDownloaded: boolean;
+ isPartial?: boolean;
+ partialTransport?: string | null;
+ modelFormat?: ModelInventoryFormat | null;
+ canRun?: boolean;
+ isActive: boolean;
+ isLoadingThisModel: boolean;
+ cachePath?: string | null;
+ knownBytes?: number | null;
+ onLoad: (opts: { ggufVariant?: string; expectedBytes?: number }) => void;
+ onUseInChat?: () => void;
+ onTrain?: () => void;
+ onChange?: () => void;
+}) {
+ const hfToken = useHfTokenStore((s) => s.token);
+ const online = useOnlineStatus();
+ const sizeKey = `${repoId}::${fingerprintToken(hfToken)}`;
+ const [modelSize, setModelSize] = useState<{
+ key: string;
+ bytes: number | null;
+ }>(() => ({ key: sizeKey, bytes: null }));
+ const modelTotalBytes =
+ knownBytes && knownBytes > 0
+ ? knownBytes
+ : modelSize.key === sizeKey
+ ? modelSize.bytes
+ : null;
+ const [deleteRepoOpen, setDeleteRepoOpen] = useState(false);
+ const { deleting, runDelete } = useCardDelete({
+ action: () => deleteCachedModel(repoId, undefined, hfToken || undefined),
+ resourceName: "model",
+ successMessage: () => `Deleted ${repoId}`,
+ onSuccess: () => {
+ setDeleteRepoOpen(false);
+ onChange?.();
+ },
+ });
+
+ const job = useRepoDownload({
+ kind: "model",
+ repoId,
+ activeVariant: null,
+ autoAdopt: true,
+ });
+
+ const progress = job.progress;
+ const cancelling = job.cancelling;
+ const repoPeerActive = job.repoPeerActive;
+ const setJobExpectedBytes = job.setExpectedBytes;
+
+ useEffect(() => {
+ if (knownBytes && knownBytes > 0) {
+ setJobExpectedBytes(knownBytes);
+ return;
+ }
+ if (!online) return;
+ if (!repoId) return;
+ const controller = new AbortController();
+ const { signal } = controller;
+ void fetchModelSize(repoId, hfToken || undefined, signal)
+ .then((info) => {
+ if (signal.aborted || !info) return;
+ const upstream = info.weightsBytes ?? info.totalBytes;
+ if (upstream && upstream > 0) {
+ setModelSize({ key: sizeKey, bytes: upstream });
+ setJobExpectedBytes(upstream);
+ }
+ })
+ .catch((err) => {
+ if (!signal.aborted && import.meta.env.DEV) {
+ console.debug("Model size lookup failed", err);
+ }
+ });
+ return () => {
+ controller.abort();
+ };
+ }, [repoId, hfToken, sizeKey, setJobExpectedBytes, knownBytes, online]);
+
+ const downloading = progress !== null && progress.variant === null;
+ const downloadAction = useDownloadCardState({
+ job,
+ variant: null,
+ expectedBytes: modelTotalBytes ?? 0,
+ downloading,
+ disabled: isLoadingThisModel || cancelling || repoPeerActive,
+ isPartial,
+ partialTransport,
+ });
+ const showActionPair = isDownloaded && !downloading && (canRun || !!onTrain);
+ const showUnavailableAction =
+ isDownloaded && !downloading && !canRun && !onTrain;
+ const canDelete =
+ (isDownloaded || isPartial) &&
+ !downloading &&
+ !repoPeerActive &&
+ !isActive &&
+ !isLoadingThisModel;
+
+ return (
+ <div className="flex w-full flex-col gap-2"><DownloadCard
+ job={job}
+ progress={downloading ? progress : null}
+ dialogs={
+ <DeleteConfirmDialog
+ open={deleteRepoOpen}
+ onOpenChange={(o) => {
+ if (!o && !deleting) setDeleteRepoOpen(false);
+ }}
+ title="Delete cached model?"
+ deleting={deleting}
+ onConfirm={() => void runDelete()}
+ description={
+ <>
+ This will remove{" "}
+ <span className="font-medium text-foreground">{repoId}</span>{" "}
+ and its downloaded files
+ {modelTotalBytes && modelTotalBytes > 0
+ ? ` (${formatBytes(modelTotalBytes)})`
+ : ""}{" "}
+ from disk. You can re-download it later.
+ </>
+ }
+ />
+ }
+ >
+ <div className="relative flex h-9 min-w-0 flex-1 items-center pl-3 pr-2">
+ <span className="flex items-center gap-1.5 text-[12px] text-muted-foreground">
+ {(isActive || isDownloaded) && (
+ <DotTag
+ tone="success"
+ label={isActive ? "Loaded" : "On device"}
+ />
+ )}
+ {!isDownloaded && !isActive && isPartial && !downloading && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex">
+ <DotTag tone="warning" label="Partial" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={4}>
+ Partial download. Click to continue.
+ </TooltipContent>
+ </Tooltip>
+ )}
+ <DotTag
+ tone={formatModelTone(modelFormat)}
+ label={formatModelLabel(modelFormat)}
+ />
+ {modelTotalBytes && modelTotalBytes > 0 && (
+ <span className="tabular-nums">
+ {formatBytes(modelTotalBytes)}
+ </span>
+ )}
+ </span>
+ <div className="ml-auto flex items-center gap-0.5">
+ {canDelete && (
+ <CardDeleteButton
+ label={`Delete ${repoId}`}
+ onClick={() => setDeleteRepoOpen(true)}
+ />
+ )}
+ {isDownloaded && cachePath && (
+ <PathInfoButton
+ path={cachePath}
+ title="On-device location"
+ description={`Where ${repoId} lives on disk.`}
+ />
+ )}
+ </div>
+ </div>
+ {/* Divider sits above the Download CTA; in the action-pair state it hides with the pair. */}
+ {(!showActionPair || HUB_POST_DOWNLOAD_ACTIONS_VISIBLE) && <CardDivider />}
+ {showActionPair ? (
+ <div
+ className={cn(
+ "group/pair flex h-9 shrink-0 items-stretch gap-1.5",
+ // Run + Train pair hidden until Hub->chat/train pickers ship.
+ !HUB_POST_DOWNLOAD_ACTIONS_VISIBLE && "hidden",
+ )}
+ >
+ {onTrain && (
+ <button
+ type="button"
+ onClick={onTrain}
+ className="hub-action-btn w-24"
+ >
+ <HugeiconsIcon icon={TrainIcon} strokeWidth={1.75} />
+ Train
+ </button>
+ )}
+ <button
+ type="button"
+ disabled={isLoadingThisModel || !canRun}
+ onClick={() => {
+ if (!canRun) return;
+ if (isActive) {
+ onUseInChat?.();
+ return;
+ }
+ onLoad({});
+ }}
+ className={cn(
+ isLoadingThisModel || isActive || !canRun
+ ? "hub-action-btn w-24"
+ : "hub-run-action-btn w-24",
+ (isLoadingThisModel || !canRun) && "opacity-70",
+ )}
+ >
+ {isLoadingThisModel ? (
+ <>
+ <Spinner />
+ Loading…
+ </>
+ ) : isActive ? (
+ <>
+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} />
+ Chat
+ </>
+ ) : !canRun ? (
+ <>
+ <HugeiconsIcon icon={Alert02Icon} strokeWidth={1.75} />
+ No run
+ </>
+ ) : (
+ <>
+ <HugeiconsIcon icon={PlayIcon} strokeWidth={1.75} />
+ Run
+ </>
+ )}
+ </button>
+ </div>
+ ) : showUnavailableAction ? (
+ <button
+ type="button"
+ disabled
+ className="hub-action-btn w-28 opacity-70"
+ >
+ <HugeiconsIcon icon={Alert02Icon} strokeWidth={1.75} />
+ Unavailable
+ </button>
+ ) : (
+ <DownloadActionButton
+ downloading={downloadAction.downloading}
+ cancelling={downloadAction.cancelling}
+ loading={isLoadingThisModel || downloadAction.starting}
+ isPartial={downloadAction.isPartial}
+ partialTransport={downloadAction.partialTransport}
+ progressPercent={downloadAction.progressPercent}
+ disabled={downloadAction.disabled}
+ onClick={downloadAction.onClick}
+ className={repoPeerActive ? "opacity-70" : undefined}
+ />
+ )}
+ </DownloadCard>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/shared.tsx b/studio/frontend/src/features/hub/catalog/shared.tsx
new file mode 100644
index 00000000000..d8e53fdb14e
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/shared.tsx
@@ -0,0 +1,56 @@
+// 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 {
+ BrainIcon,
+ CodeIcon,
+ GlobeIcon,
+ HeadphonesIcon,
+ SparklesIcon,
+ ViewIcon,
+ Wrench01Icon,
+} from "@hugeicons/core-free-icons";
+import type { IconSvgElement } from "@hugeicons/react";
+import { HugeiconsIcon } from "@hugeicons/react";
+import type { Capability, CapabilityKey } from "../lib/model-capabilities";
+
+const CAPABILITY_ICON: Record<CapabilityKey, IconSvgElement> = {
+ vision: ViewIcon,
+ audio: HeadphonesIcon,
+ tools: Wrench01Icon,
+ reasoning: BrainIcon,
+ code: CodeIcon,
+ embedding: SparklesIcon,
+ multilingual: GlobeIcon,
+};
+
+const CAPABILITY_TONE: Record<CapabilityKey, string> = {
+ vision:
+ "bg-indigo-500/10 text-indigo-700 dark:bg-indigo-400/20 dark:text-indigo-300",
+ audio:
+ "bg-rose-500/10 text-rose-700 dark:bg-rose-400/20 dark:text-rose-300",
+ tools:
+ "bg-amber-500/10 text-amber-800 dark:bg-amber-400/20 dark:text-amber-300",
+ reasoning:
+ "bg-violet-500/10 text-violet-700 dark:bg-violet-400/20 dark:text-violet-300",
+ code: "bg-cyan-500/10 text-cyan-800 dark:bg-cyan-400/20 dark:text-cyan-300",
+ embedding:
+ "bg-emerald-500/10 text-emerald-700 dark:bg-emerald-400/20 dark:text-emerald-300",
+ multilingual:
+ "bg-sky-500/10 text-sky-700 dark:bg-sky-400/20 dark:text-sky-300",
+};
+
+export function CapabilityPill({ capability }: { capability: Capability }) {
+ return (
+ <span
+ className={`inline-flex h-6 items-center gap-1.5 rounded-full px-2.5 text-[11.5px] font-medium ${CAPABILITY_TONE[capability.key]}`}
+ >
+ <HugeiconsIcon
+ icon={CAPABILITY_ICON[capability.key]}
+ strokeWidth={1.75}
+ className="size-3"
+ />
+ {capability.label}
+ </span>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/transport-conflict-dialog.tsx b/studio/frontend/src/features/hub/catalog/transport-conflict-dialog.tsx
new file mode 100644
index 00000000000..7fe21268881
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/transport-conflict-dialog.tsx
@@ -0,0 +1,95 @@
+// 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 {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import type { TransportConflictInfo } from "@/features/hub/download-manager";
+
+export type { TransportConflictInfo } from "@/features/hub/download-manager";
+
+export function TransportConflictDialog({
+ conflict,
+ onCancel,
+ onKeepTransport,
+ onSwitchTransport,
+}: {
+ conflict: TransportConflictInfo | null;
+ onCancel: () => void;
+ // Continue on the partial download's existing transport (resumes if possible);
+ // distinct from switching transport, which always restarts from scratch.
+ onKeepTransport: () => void;
+ onSwitchTransport: () => void;
+}) {
+ const previousLabel = conflict?.previous.toUpperCase() ?? "";
+ const nextLabel = conflict?.next.toUpperCase() ?? "";
+ const description = conflict?.resumable ? (
+ <>
+ You started this download with{" "}
+ <span className="font-medium text-foreground">{previousLabel}</span>, but
+ your current setting is{" "}
+ <span className="font-medium text-foreground">{nextLabel}</span>. Resume
+ with {previousLabel} to keep the progress you already have, or restart
+ with {nextLabel} to begin from scratch.
+ </>
+ ) : (
+ <>
+ Your previous download used{" "}
+ <span className="font-medium text-foreground">{previousLabel}</span>,
+ which can't resume its partial files, so the existing partial will be
+ discarded and this download will start from the beginning either way.
+ Restart with {previousLabel} to keep it usually faster, or restart with{" "}
+ {nextLabel} so future cancels can resume.
+ </>
+ );
+ const primaryLabel = conflict?.resumable
+ ? `Resume with ${previousLabel}`
+ : `Restart with ${previousLabel}`;
+ const secondaryLabel = `Restart with ${nextLabel}`;
+ return (
+ <AlertDialog
+ open={conflict !== null}
+ onOpenChange={(o) => {
+ if (!o) onCancel();
+ }}
+ >
+ <AlertDialogContent className="sm:!max-w-[22rem]">
+ <AlertDialogHeader>
+ <AlertDialogTitle>Different transport mode</AlertDialogTitle>
+ <AlertDialogDescription>{description}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter className="!flex !flex-col gap-2 sm:!flex-col sm:!justify-stretch">
+ <AlertDialogAction
+ className="w-full"
+ onClick={(e) => {
+ e.preventDefault();
+ onKeepTransport();
+ }}
+ >
+ {primaryLabel}
+ </AlertDialogAction>
+ <AlertDialogAction
+ variant="outline"
+ className="w-full !bg-transparent hover:!bg-transparent"
+ onClick={(e) => {
+ e.preventDefault();
+ onSwitchTransport();
+ }}
+ >
+ {secondaryLabel}
+ </AlertDialogAction>
+ <AlertDialogCancel className="w-full !bg-transparent hover:!bg-transparent">
+ Cancel
+ </AlertDialogCancel>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/transport-toggle.tsx b/studio/frontend/src/features/hub/catalog/transport-toggle.tsx
new file mode 100644
index 00000000000..d3fc68fbf32
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/transport-toggle.tsx
@@ -0,0 +1,84 @@
+// 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 {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ useDownloadTransportCapabilities,
+ useTransportMode,
+} from "@/features/hub/download-manager";
+import { cn } from "@/lib/utils";
+import { useEffect } from "react";
+
+const OPTIONS: { value: "http" | "xet"; label: string; hint: string }[] = [
+ {
+ value: "http",
+ label: "HTTP",
+ hint: "Resumes from where it stopped if you cancel.",
+ },
+ {
+ value: "xet",
+ label: "Xet",
+ hint: "Usually faster on a fresh download, but starts over if you cancel.",
+ },
+];
+
+export function TransportToggle() {
+ const [mode, setMode] = useTransportMode();
+ const { capabilities } = useDownloadTransportCapabilities();
+ const xetUnavailable = capabilities?.xet.available === false;
+
+ useEffect(() => {
+ if (mode === "xet" && xetUnavailable) {
+ setMode("http");
+ }
+ }, [mode, setMode, xetUnavailable]);
+
+ return (
+ <fieldset
+ aria-label="Download transport"
+ className="hub-tag-soft m-0 inline-flex h-[26px] min-w-0 items-center gap-0.5 rounded-[11px] border-0 p-0.5 text-[11px]"
+ >
+ {OPTIONS.map((opt) => {
+ const active = mode === opt.value;
+ const disabled = opt.value === "xet" && xetUnavailable;
+ const hint =
+ disabled && capabilities?.xet.reason
+ ? capabilities.xet.reason
+ : opt.hint;
+ return (
+ <Tooltip key={opt.value}>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => setMode(opt.value)}
+ aria-pressed={active}
+ className={cn(
+ "inline-flex h-[22px] cursor-pointer items-center justify-center rounded-[8px] px-2 font-medium tracking-tight transition-colors",
+ active
+ ? "hub-tab-toggle-pill text-foreground"
+ : disabled
+ ? "cursor-not-allowed text-muted-foreground/45"
+ : "text-muted-foreground hover:text-foreground/80",
+ )}
+ >
+ {opt.label}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ sideOffset={6}
+ className="tooltip-compact"
+ >
+ {hint}
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </fieldset>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/use-card-delete.ts b/studio/frontend/src/features/hub/catalog/use-card-delete.ts
new file mode 100644
index 00000000000..6f853a962d7
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/use-card-delete.ts
@@ -0,0 +1,31 @@
+// 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 { useDeleteConfirmAction } from "./use-delete-confirm-action";
+
+type DeleteSuccessMessage = string | (() => string);
+
+export function useCardDelete({
+ action,
+ resourceName,
+ successMessage,
+ onSuccess,
+ onSettled,
+}: {
+ action: () => Promise<void>;
+ resourceName: string;
+ successMessage: DeleteSuccessMessage;
+ onSuccess?: () => void;
+ onSettled?: () => void;
+}) {
+ return useDeleteConfirmAction({
+ action,
+ successMessage,
+ errorToast: (err) => ({
+ title: `Failed to delete ${resourceName}`,
+ description: err instanceof Error ? err.message : undefined,
+ }),
+ onSuccess,
+ onSettled,
+ });
+}
diff --git a/studio/frontend/src/features/hub/catalog/use-delete-confirm-action.ts b/studio/frontend/src/features/hub/catalog/use-delete-confirm-action.ts
new file mode 100644
index 00000000000..26e1c8c21a5
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/use-delete-confirm-action.ts
@@ -0,0 +1,66 @@
+// 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 { useCallback, useEffect, useRef, useState } from "react";
+import { toast } from "@/lib/toast";
+
+type DeleteSuccessMessage = string | (() => string);
+type DeleteErrorToast =
+ | { title: string; description?: string }
+ | ((error: unknown) => { title: string; description?: string });
+
+function resolveSuccessMessage(message: DeleteSuccessMessage): string {
+ return typeof message === "function" ? message() : message;
+}
+
+function resolveErrorToast(
+ errorToast: DeleteErrorToast,
+ error: unknown,
+): { title: string; description?: string } {
+ return typeof errorToast === "function" ? errorToast(error) : errorToast;
+}
+
+export function useDeleteConfirmAction({
+ action,
+ successMessage,
+ errorToast,
+ onSuccess,
+ onSettled,
+}: {
+ action: () => Promise<void>;
+ successMessage: DeleteSuccessMessage;
+ errorToast: DeleteErrorToast;
+ onSuccess?: () => void;
+ onSettled?: () => void;
+}) {
+ const [deleting, setDeleting] = useState(false);
+ const inFlightRef = useRef(false);
+ const mountedRef = useRef(true);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+
+ const runDelete = useCallback(async () => {
+ if (inFlightRef.current) return;
+ inFlightRef.current = true;
+ setDeleting(true);
+ try {
+ await action();
+ toast.success(resolveSuccessMessage(successMessage));
+ onSuccess?.();
+ } catch (error) {
+ const resolved = resolveErrorToast(errorToast, error);
+ toast.error(resolved.title, { description: resolved.description });
+ } finally {
+ inFlightRef.current = false;
+ if (mountedRef.current) setDeleting(false);
+ onSettled?.();
+ }
+ }, [action, errorToast, onSettled, onSuccess, successMessage]);
+
+ return { deleting, runDelete };
+}
diff --git a/studio/frontend/src/features/hub/catalog/use-download-card-state.ts b/studio/frontend/src/features/hub/catalog/use-download-card-state.ts
new file mode 100644
index 00000000000..67613d9abe4
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/use-download-card-state.ts
@@ -0,0 +1,95 @@
+// 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 { DownloadJob } from "../download-manager";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+export function partialResumeLabel(transport: string | null | undefined): string {
+ if (transport === "xet") return "Redownload";
+ if (transport === "http") return "Continue";
+ return "Retry";
+}
+
+export function downloadActionAriaLabel(
+ downloading: boolean,
+ cancelling: boolean,
+): string | undefined {
+ return cancelling ? "Cancelling…" : downloading ? "Cancel download" : undefined;
+}
+
+export function downloadActionLabel(
+ isPartial: boolean,
+ partialTransport: string | null | undefined,
+): string {
+ return isPartial ? partialResumeLabel(partialTransport) : "Download";
+}
+
+export function useDownloadCardState({
+ job,
+ variant,
+ expectedBytes,
+ downloading,
+ cancelling = job.cancelling,
+ disabled,
+ isPartial = false,
+ partialTransport = null,
+}: {
+ job: DownloadJob;
+ variant: string | null;
+ expectedBytes: number;
+ downloading: boolean;
+ cancelling?: boolean;
+ disabled: boolean;
+ isPartial?: boolean;
+ partialTransport?: string | null;
+}) {
+ const [starting, setStarting] = useState(false);
+ const mountedRef = useRef(true);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+ useEffect(() => {
+ if (downloading || cancelling || disabled) {
+ setStarting(false);
+ }
+ }, [cancelling, disabled, downloading]);
+ const progressPercent =
+ job.progress != null
+ ? Math.round(Math.min(job.progress.fraction, 1) * 100)
+ : null;
+ const effectiveDisabled = disabled || starting;
+ const onClick = useCallback(() => {
+ if (disabled || cancelling || starting) return;
+ if (downloading) {
+ void job.cancelDownload(variant);
+ return;
+ }
+ setStarting(true);
+ void job.requestStartDownload(variant, expectedBytes).finally(() => {
+ if (mountedRef.current) setStarting(false);
+ });
+ }, [
+ cancelling,
+ disabled,
+ downloading,
+ expectedBytes,
+ job,
+ starting,
+ variant,
+ ]);
+ return {
+ downloading,
+ cancelling,
+ starting,
+ isPartial,
+ partialTransport,
+ progressPercent,
+ disabled: effectiveDisabled,
+ ariaLabel: downloadActionAriaLabel(downloading, cancelling),
+ downloadLabel: downloadActionLabel(isPartial, partialTransport),
+ onClick,
+ };
+}
diff --git a/studio/frontend/src/features/hub/catalog/use-gguf-variant-fetch-state.ts b/studio/frontend/src/features/hub/catalog/use-gguf-variant-fetch-state.ts
new file mode 100644
index 00000000000..aeba45383dc
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/use-gguf-variant-fetch-state.ts
@@ -0,0 +1,175 @@
+// 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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ type GgufVariantDetail,
+ listGgufVariants,
+ useGgufVariantsCacheVersion,
+} from "../inventory";
+import { fingerprintToken } from "../lib/token-fingerprint";
+
+interface GgufVariantFetchState {
+ key: string;
+ scopeKey: string;
+ variants: GgufVariantDetail[] | null;
+ defaultVariant: string | null;
+ loading: boolean;
+ error: string | null;
+ refreshError: string | null;
+}
+
+function isAbortError(error: unknown): boolean {
+ return error instanceof DOMException && error.name === "AbortError";
+}
+
+export function useGgufVariantFetchState({
+ repoId,
+ hfToken,
+ preferLocalCache = false,
+ localPath = null,
+ enabled = true,
+ errorFallback = "Failed to load variants",
+}: {
+ repoId: string;
+ hfToken?: string | null;
+ preferLocalCache?: boolean;
+ localPath?: string | null;
+ enabled?: boolean;
+ errorFallback?: string;
+}) {
+ const variantsVersion = useGgufVariantsCacheVersion(repoId);
+ const localVariantPath = localPath?.trim() || null;
+ const variantScopeKey = useMemo(
+ () =>
+ `${repoId}::${fingerprintToken(hfToken)}::${
+ preferLocalCache ? "local" : "remote"
+ }::${localVariantPath ?? ""}`,
+ [hfToken, localVariantPath, preferLocalCache, repoId],
+ );
+ const variantKey = useMemo(
+ () => `${variantScopeKey}::${variantsVersion}`,
+ [variantScopeKey, variantsVersion],
+ );
+ const [state, setState] = useState<GgufVariantFetchState>(() => ({
+ key: variantKey,
+ scopeKey: variantScopeKey,
+ variants: null,
+ defaultVariant: null,
+ loading: enabled,
+ error: null,
+ refreshError: null,
+ }));
+ const abortRef = useRef<AbortController | null>(null);
+
+ const refresh = useCallback(async (): Promise<void> => {
+ abortRef.current?.abort();
+ if (!enabled) {
+ setState({
+ key: variantKey,
+ scopeKey: variantScopeKey,
+ variants: null,
+ defaultVariant: null,
+ loading: false,
+ error: null,
+ refreshError: null,
+ });
+ return;
+ }
+
+ const controller = new AbortController();
+ abortRef.current = controller;
+ setState((prev) => {
+ const sameScope = prev.scopeKey === variantScopeKey;
+ return {
+ key: variantKey,
+ scopeKey: variantScopeKey,
+ variants: sameScope ? prev.variants : null,
+ defaultVariant: sameScope ? prev.defaultVariant : null,
+ loading: true,
+ error: null,
+ refreshError: null,
+ };
+ });
+ try {
+ const response = await listGgufVariants(repoId, hfToken || undefined, {
+ preferLocalCache,
+ localPath: localVariantPath,
+ signal: controller.signal,
+ });
+ if (controller.signal.aborted) return;
+ setState({
+ key: variantKey,
+ scopeKey: variantScopeKey,
+ variants: response.variants,
+ defaultVariant: response.default_variant,
+ loading: false,
+ error: null,
+ refreshError: null,
+ });
+ } catch (error) {
+ if (controller.signal.aborted || isAbortError(error)) return;
+ setState((prev) => {
+ const sameScope = prev.scopeKey === variantScopeKey;
+ const variants = sameScope ? prev.variants : null;
+ const hasUsableVariants = !!variants && variants.length > 0;
+ const message = error instanceof Error ? error.message : errorFallback;
+ return {
+ key: variantKey,
+ scopeKey: variantScopeKey,
+ variants,
+ defaultVariant: sameScope ? prev.defaultVariant : null,
+ loading: false,
+ error: hasUsableVariants ? null : message,
+ refreshError: hasUsableVariants ? message : null,
+ };
+ });
+ } finally {
+ if (abortRef.current === controller) {
+ abortRef.current = null;
+ }
+ }
+ }, [
+ enabled,
+ errorFallback,
+ hfToken,
+ localVariantPath,
+ preferLocalCache,
+ repoId,
+ variantScopeKey,
+ variantKey,
+ ]);
+
+ useEffect(() => {
+ const timer = window.setTimeout(() => void refresh(), 0);
+ return () => {
+ window.clearTimeout(timer);
+ abortRef.current?.abort();
+ abortRef.current = null;
+ };
+ }, [refresh]);
+
+ if (state.key === variantKey) {
+ return { ...state, refresh };
+ }
+ if (state.scopeKey === variantScopeKey) {
+ return {
+ ...state,
+ key: variantKey,
+ loading: true,
+ error: null,
+ refreshError: null,
+ refresh,
+ };
+ }
+ return {
+ key: variantKey,
+ scopeKey: variantScopeKey,
+ variants: null,
+ defaultVariant: null,
+ loading: enabled,
+ error: null,
+ refreshError: null,
+ refresh,
+ };
+}
diff --git a/studio/frontend/src/features/hub/components/hf-token-indicator.tsx b/studio/frontend/src/features/hub/components/hf-token-indicator.tsx
new file mode 100644
index 00000000000..35020de5b19
--- /dev/null
+++ b/studio/frontend/src/features/hub/components/hf-token-indicator.tsx
@@ -0,0 +1,108 @@
+// 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 {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { useSettingsDialogStore } from "@/features/settings";
+import { cn } from "@/lib/utils";
+import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";
+import { AiSecurity03Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+
+interface HfTokenIndicatorProps {
+ // true: chip with label (Train wizard); false: icon-only pill (Hub header).
+ showLabel?: boolean;
+}
+
+// Compact "set / not set" indicator for the app-wide Hugging Face token; click
+// opens Settings -> General. Shared by the Hub header and Train wizard.
+export function HfTokenIndicator({ showLabel = false }: HfTokenIndicatorProps = {}) {
+ const hfToken = useHfTokenStore((s) => s.token);
+ const openDialog = useSettingsDialogStore((s) => s.openDialog);
+ const hasToken = Boolean(hfToken && hfToken.trim());
+
+ const ariaLabel = hasToken
+ ? "Hugging Face token configured"
+ : "Set Hugging Face token";
+ const tipText = hasToken
+ ? "Token set. Allows access to private and gated repos."
+ : "Set a token to access private and gated repos.";
+
+ if (showLabel) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => openDialog("general")}
+ aria-label={ariaLabel}
+ className={cn(
+ "hub-menu-trigger field-soft inline-flex h-9 w-full items-center justify-between gap-2 rounded-[12px] py-0 pl-1.5 pr-3 text-[12.5px] font-medium text-foreground transition-colors",
+ "focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0",
+ )}
+ >
+ <span className="flex min-w-0 items-center gap-2">
+ <span
+ aria-hidden="true"
+ className={cn(
+ "inline-flex size-6 items-center justify-center rounded-full transition-colors",
+ hasToken
+ ? "bg-primary/15 text-primary"
+ : "bg-foreground/[0.07] text-muted-foreground dark:bg-white/[0.07]",
+ )}
+ >
+ <HugeiconsIcon
+ icon={AiSecurity03Icon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </span>
+ <span className="truncate">HF Token</span>
+ </span>
+ <span
+ className={cn(
+ "shrink-0 text-[11px] font-normal tabular-nums",
+ hasToken ? "text-primary" : "text-muted-foreground/70",
+ )}
+ >
+ {hasToken ? "Set" : "Add"}
+ </span>
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={6} className="tooltip-compact">
+ {tipText}
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => openDialog("general")}
+ aria-label={ariaLabel}
+ className={cn(
+ "inline-flex items-center justify-center px-2.5 py-1 text-[11.5px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ hasToken
+ ? "hub-tag-soft text-muted-foreground hover:text-foreground/80"
+ : "rounded-[11px] bg-destructive text-destructive-foreground hover:bg-destructive/90",
+ )}
+ >
+ <HugeiconsIcon
+ icon={AiSecurity03Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={6} className="tooltip-compact">
+ {tipText}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/studio/frontend/src/features/hub/components/page-heading.tsx b/studio/frontend/src/features/hub/components/page-heading.tsx
new file mode 100644
index 00000000000..0b9c3d27286
--- /dev/null
+++ b/studio/frontend/src/features/hub/components/page-heading.tsx
@@ -0,0 +1,27 @@
+// 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 { ReactNode } from "react";
+
+import { cn } from "@/lib/utils";
+
+type PageHeadingProps = {
+ title: ReactNode;
+ subtitle?: ReactNode;
+ className?: string;
+};
+
+export function PageHeading({ title, subtitle, className }: PageHeadingProps) {
+ return (
+ <div className={cn("page-title-halo min-w-0", className)}>
+ <h1 className="text-[30px] font-semibold leading-[1.04] tracking-[-0.028em] text-foreground sm:text-[34px]">
+ {title}
+ </h1>
+ {subtitle ? (
+ <p className="mt-2 text-[13px] leading-[19px] text-muted-foreground">
+ {subtitle}
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/components/train-icon.ts b/studio/frontend/src/features/hub/components/train-icon.ts
new file mode 100644
index 00000000000..1b59bc4835f
--- /dev/null
+++ b/studio/frontend/src/features/hub/components/train-icon.ts
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { TestTube01Icon } from "@hugeicons/core-free-icons";
+
+// Slice to the first three paths to drop TestTube01Icon's two interior bubbles,
+// keeping the outline + cap + liquid line. Shared so the Train icon stays identical app-wide.
+export const TrainIcon = TestTube01Icon.slice(0, 3) as typeof TestTube01Icon;
diff --git a/studio/frontend/src/features/hub/download-manager/api.ts b/studio/frontend/src/features/hub/download-manager/api.ts
new file mode 100644
index 00000000000..ca987f1643b
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/api.ts
@@ -0,0 +1,455 @@
+// 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 { authFetch } from "@/features/auth";
+import { formatFastApiDetail } from "@/lib/format-fastapi-error";
+import { hubTokenHeader } from "../lib/hub-token-header";
+import { abortError, withAbort } from "../lib/abort-signals";
+import type { TransportMode } from "./constants";
+
+function parseErrorText(status: number, body: unknown): string {
+ if (body && typeof body === "object") {
+ const detail = (body as { detail?: unknown }).detail;
+ const formatted = formatFastApiDetail(detail);
+ if (status === 405) {
+ return `${formatted || "Method Not Allowed"} - the Studio backend did not accept this API method. Restart Studio so the frontend and backend are on the same build.`;
+ }
+ if (formatted) return formatted;
+ const message = (body as { message?: unknown }).message;
+ if (typeof message === "string" && message) return message;
+ }
+ if (status === 405) {
+ return "Method Not Allowed - the Studio backend did not accept this API method. Restart Studio so the frontend and backend are on the same build.";
+ }
+ return `Request failed (${status})`;
+}
+
+async function parseJsonOrThrow<T>(response: Response): Promise<T> {
+ const body = await response.json().catch(() => null);
+ if (!response.ok) {
+ throw new Error(parseErrorText(response.status, body));
+ }
+ return body as T;
+}
+
+export type DownloadJobState =
+ | "idle"
+ | "running"
+ | "complete"
+ | "error"
+ | "cancelled"
+ | "cancelling";
+
+export interface DownloadJobStatus {
+ state: DownloadJobState;
+ error?: string | null;
+ generation?: number;
+}
+
+export type DownloadStartState = DownloadJobState | "deleting";
+
+export interface DownloadStartResult {
+ state: DownloadStartState;
+ accepted: boolean;
+ generation?: number;
+}
+
+export interface ActiveModelDownload {
+ repo_id?: string;
+ variant: string | null;
+ transport?: TransportMode | null;
+ state: DownloadJobState;
+ generation?: number;
+}
+
+export interface ActiveDatasetDownload {
+ repo_id: string;
+ variant: null;
+ transport?: TransportMode | null;
+ state: DownloadJobState;
+ generation?: number;
+}
+
+type ActiveModelDownloadsOptions = {
+ fresh?: boolean;
+};
+
+const ACTIVE_MODEL_DOWNLOADS_DEDUPE_MS = 750;
+const ACTIVE_MODEL_DOWNLOADS_CACHE_MAX = 200;
+const activeModelDownloadsInFlight = new Map<
+ string,
+ Promise<readonly ActiveModelDownload[]>
+>();
+const activeModelDownloadsCache = new Map<
+ string,
+ { expiresAt: number; downloads: readonly ActiveModelDownload[] }
+>();
+
+function pruneActiveModelDownloadsCache(now = Date.now()): void {
+ for (const [key, entry] of activeModelDownloadsCache) {
+ if (entry.expiresAt <= now) activeModelDownloadsCache.delete(key);
+ }
+ while (activeModelDownloadsCache.size > ACTIVE_MODEL_DOWNLOADS_CACHE_MAX) {
+ const oldest = activeModelDownloadsCache.keys().next().value;
+ if (oldest === undefined) break;
+ activeModelDownloadsCache.delete(oldest);
+ }
+}
+
+export type TransportMarker = TransportMode | null;
+
+export interface TransportStatus {
+ has_partial: boolean;
+ last_transport: TransportMarker;
+ resumable: boolean;
+}
+
+export interface DownloadTransportCapability {
+ available: boolean | null;
+ reason: string | null;
+}
+
+export interface DownloadTransportCapabilities {
+ http: DownloadTransportCapability;
+ xet: DownloadTransportCapability;
+}
+
+export interface DownloadProgressResponse {
+ downloaded_bytes: number;
+ completed_bytes: number;
+ complete_on_disk: boolean;
+ expected_bytes: number;
+ progress: number;
+ cache_path: string | null;
+}
+
+export type DownloadProgressOptions = {
+ signal?: AbortSignal;
+ hfToken?: string | null;
+ expectedBytes?: number;
+};
+
+export type GgufDownloadProgressOptions = DownloadProgressOptions & {
+ variant: string;
+};
+
+const DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK: DownloadTransportCapabilities = {
+ http: { available: true, reason: null },
+ xet: {
+ available: null,
+ reason: "Couldn't verify Xet support with the Studio backend.",
+ },
+};
+let downloadTransportCapabilitiesCache: DownloadTransportCapabilities | null =
+ null;
+let downloadTransportCapabilitiesInFlight: Promise<DownloadTransportCapabilities> | null =
+ null;
+
+function normalizeDownloadTransportCapability(
+ value: unknown,
+ fallback: DownloadTransportCapability,
+): DownloadTransportCapability {
+ if (!value || typeof value !== "object") {
+ return fallback;
+ }
+ const candidate = value as { available?: unknown; reason?: unknown };
+ return {
+ available:
+ typeof candidate.available === "boolean"
+ ? candidate.available
+ : fallback.available,
+ reason:
+ typeof candidate.reason === "string"
+ ? candidate.reason
+ : candidate.reason === null
+ ? null
+ : fallback.reason,
+ };
+}
+
+function normalizeDownloadTransportCapabilities(
+ value: unknown,
+): DownloadTransportCapabilities {
+ if (!value || typeof value !== "object") {
+ return DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK;
+ }
+ const candidate = value as { http?: unknown; xet?: unknown };
+ return {
+ http: normalizeDownloadTransportCapability(candidate.http, {
+ available: true,
+ reason: null,
+ }),
+ xet: normalizeDownloadTransportCapability(
+ candidate.xet,
+ DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK.xet,
+ ),
+ };
+}
+
+export async function getDownloadTransportCapabilities(options: {
+ force?: boolean;
+} = {}): Promise<DownloadTransportCapabilities> {
+ if (!options.force && downloadTransportCapabilitiesCache) {
+ return downloadTransportCapabilitiesCache;
+ }
+ if (!options.force && downloadTransportCapabilitiesInFlight) {
+ return downloadTransportCapabilitiesInFlight;
+ }
+ const request = authFetch("/api/studio/download-transport-capabilities")
+ .then(parseJsonOrThrow<unknown>)
+ .then(normalizeDownloadTransportCapabilities)
+ .then((capabilities) => {
+ downloadTransportCapabilitiesCache = capabilities;
+ return capabilities;
+ })
+ .catch(() => DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK)
+ .finally(() => {
+ if (downloadTransportCapabilitiesInFlight === request) {
+ downloadTransportCapabilitiesInFlight = null;
+ }
+ });
+ downloadTransportCapabilitiesInFlight = request;
+ return request;
+}
+
+export function __resetDownloadTransportCapabilitiesForTests(): void {
+ downloadTransportCapabilitiesCache = null;
+ downloadTransportCapabilitiesInFlight = null;
+}
+
+export async function startModelDownload(payload: {
+ repo_id: string;
+ gguf_variant?: string | null;
+ hf_token?: string | null;
+ use_xet?: boolean;
+}): Promise<DownloadStartResult & { job_key: string }> {
+ const { hf_token, ...body } = payload;
+ const headers = {
+ "Content-Type": "application/json",
+ ...hubTokenHeader(hf_token),
+ };
+ const response = await authFetch("/api/hub/download", {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ });
+ return parseJsonOrThrow(response);
+}
+
+export async function cancelModelDownload(payload: {
+ repo_id: string;
+ gguf_variant?: string | null;
+ generation?: number | null;
+ signal?: AbortSignal;
+}): Promise<{ job_key: string; state: DownloadJobState }> {
+ const { signal, ...body } = payload;
+ const response = await authFetch("/api/hub/download/cancel", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ signal,
+ });
+ return parseJsonOrThrow(response);
+}
+
+export async function getModelDownloadStatus(
+ repoId: string,
+ ggufVariant?: string | null,
+ signal?: AbortSignal,
+): Promise<DownloadJobStatus> {
+ const params = new URLSearchParams({ repo_id: repoId });
+ if (ggufVariant) params.set("gguf_variant", ggufVariant);
+ const response = await authFetch(`/api/hub/download-status?${params}`, {
+ signal,
+ });
+ return parseJsonOrThrow<DownloadJobStatus>(response);
+}
+
+export async function getActiveModelDownloads(
+ repoId: string,
+ signal?: AbortSignal,
+ options: ActiveModelDownloadsOptions = {},
+): Promise<readonly ActiveModelDownload[]> {
+ return getActiveModelDownloadsForKey(repoId, signal, options);
+}
+
+export async function getAllActiveModelDownloads(
+ signal?: AbortSignal,
+ options: ActiveModelDownloadsOptions = {},
+): Promise<readonly ActiveModelDownload[]> {
+ return getActiveModelDownloadsForKey(null, signal, options);
+}
+
+async function getActiveModelDownloadsForKey(
+ repoId: string | null,
+ signal?: AbortSignal,
+ options: ActiveModelDownloadsOptions = {},
+): Promise<readonly ActiveModelDownload[]> {
+ const trimmedRepoId = repoId?.trim() ?? "";
+ const key = trimmedRepoId ? trimmedRepoId.toLowerCase() : "*";
+ if (signal?.aborted) return Promise.reject(abortError(signal));
+ const useCachedResult = !options.fresh;
+ const cached = useCachedResult ? activeModelDownloadsCache.get(key) : undefined;
+ const now = Date.now();
+ if (cached && cached.expiresAt > now) {
+ return withAbort(Promise.resolve(cached.downloads), signal);
+ }
+
+ let request = useCachedResult ? activeModelDownloadsInFlight.get(key) : undefined;
+ if (!request) {
+ const fetchRequest = (async () => {
+ const params = new URLSearchParams();
+ if (trimmedRepoId) params.set("repo_id", trimmedRepoId);
+ const query = params.toString();
+ const response = await authFetch(
+ `/api/hub/active-downloads${query ? `?${query}` : ""}`,
+ options.fresh && signal ? { signal } : undefined,
+ );
+ const data = await parseJsonOrThrow<{
+ downloads: ActiveModelDownload[];
+ }>(response);
+ activeModelDownloadsCache.set(key, {
+ expiresAt: Date.now() + ACTIVE_MODEL_DOWNLOADS_DEDUPE_MS,
+ downloads: data.downloads,
+ });
+ pruneActiveModelDownloadsCache();
+ return data.downloads;
+ })();
+ request = useCachedResult
+ ? fetchRequest.finally(() => {
+ activeModelDownloadsInFlight.delete(key);
+ })
+ : fetchRequest;
+ if (useCachedResult) {
+ activeModelDownloadsInFlight.set(key, request);
+ }
+ }
+ return withAbort(request, signal);
+}
+
+export async function getActiveDatasetDownloads(
+ signal?: AbortSignal,
+): Promise<ActiveDatasetDownload[]> {
+ const response = await authFetch("/api/hub/datasets/active-downloads", {
+ signal,
+ });
+ const data = await parseJsonOrThrow<{
+ downloads: ActiveDatasetDownload[];
+ }>(response);
+ return data.downloads;
+}
+
+export async function startDatasetDownload(payload: {
+ repo_id: string;
+ hf_token?: string | null;
+ use_xet?: boolean;
+}): Promise<DownloadStartResult & { repo_id: string }> {
+ const { hf_token, ...body } = payload;
+ const headers = {
+ "Content-Type": "application/json",
+ ...hubTokenHeader(hf_token),
+ };
+ const response = await authFetch("/api/hub/datasets/download", {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ });
+ return parseJsonOrThrow(response);
+}
+
+export async function cancelDatasetDownload(payload: {
+ repo_id: string;
+ generation?: number | null;
+ signal?: AbortSignal;
+}): Promise<{ repo_id: string; state: DownloadJobState }> {
+ const { signal, ...body } = payload;
+ const response = await authFetch("/api/hub/datasets/download/cancel", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ signal,
+ });
+ return parseJsonOrThrow(response);
+}
+
+export async function getDatasetDownloadStatus(
+ repoId: string,
+ signal?: AbortSignal,
+): Promise<DownloadJobStatus> {
+ const params = new URLSearchParams({ repo_id: repoId });
+ const response = await authFetch(`/api/hub/datasets/download-status?${params}`, {
+ signal,
+ });
+ return parseJsonOrThrow<DownloadJobStatus>(response);
+}
+
+export async function getModelTransportStatus(
+ repoId: string,
+ ggufVariant?: string | null,
+ hfToken?: string | null,
+ signal?: AbortSignal,
+): Promise<TransportStatus> {
+ const params = new URLSearchParams({ repo_id: repoId });
+ if (ggufVariant) params.set("gguf_variant", ggufVariant);
+ const response = await authFetch(`/api/hub/transport-status?${params}`, {
+ headers: hubTokenHeader(hfToken),
+ signal,
+ });
+ return parseJsonOrThrow<TransportStatus>(response);
+}
+
+export async function getDatasetTransportStatus(
+ repoId: string,
+ signal?: AbortSignal,
+): Promise<TransportStatus> {
+ const params = new URLSearchParams({ repo_id: repoId });
+ const response = await authFetch(`/api/hub/datasets/transport-status?${params}`, {
+ signal,
+ });
+ return parseJsonOrThrow<TransportStatus>(response);
+}
+
+export async function getGgufDownloadProgress(
+ repoId: string,
+ options: GgufDownloadProgressOptions,
+): Promise<DownloadProgressResponse> {
+ const { expectedBytes = 0, hfToken, signal, variant } = options;
+ const params = new URLSearchParams({
+ repo_id: repoId,
+ variant,
+ expected_bytes: String(expectedBytes),
+ });
+ const response = await authFetch(`/api/hub/gguf-download-progress?${params}`, {
+ headers: hubTokenHeader(hfToken),
+ signal,
+ });
+ return parseJsonOrThrow(response);
+}
+
+export async function getDownloadProgress(
+ repoId: string,
+ options: DownloadProgressOptions,
+): Promise<DownloadProgressResponse> {
+ const { expectedBytes = 0, hfToken, signal } = options;
+ const params = new URLSearchParams({ repo_id: repoId });
+ if (expectedBytes > 0) params.set("expected_bytes", String(expectedBytes));
+ const response = await authFetch(`/api/hub/download-progress?${params}`, {
+ headers: hubTokenHeader(hfToken),
+ signal,
+ });
+ return parseJsonOrThrow(response);
+}
+
+export async function getDatasetDownloadProgress(
+ repoId: string,
+ options: DownloadProgressOptions,
+): Promise<DownloadProgressResponse> {
+ const { expectedBytes = 0, hfToken, signal } = options;
+ const params = new URLSearchParams({ repo_id: repoId });
+ if (expectedBytes > 0) params.set("expected_bytes", String(expectedBytes));
+ const response = await authFetch(`/api/hub/datasets/download-progress?${params}`, {
+ headers: hubTokenHeader(hfToken),
+ signal,
+ });
+ return parseJsonOrThrow(response);
+}
diff --git a/studio/frontend/src/features/hub/download-manager/constants.ts b/studio/frontend/src/features/hub/download-manager/constants.ts
new file mode 100644
index 00000000000..3f772cb196f
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/constants.ts
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export const TRANSPORT = {
+ HTTP: "http",
+ XET: "xet",
+} as const;
+
+export const TRANSPORT_MODES = [TRANSPORT.HTTP, TRANSPORT.XET] as const;
+export type TransportMode = (typeof TRANSPORT_MODES)[number];
+export const DEFAULT_TRANSPORT_MODE: TransportMode = TRANSPORT.HTTP;
+
+export function isTransportMode(value: unknown): value is TransportMode {
+ return (
+ typeof value === "string" &&
+ (TRANSPORT_MODES as readonly string[]).includes(value)
+ );
+}
+
+export const DOWNLOAD_KIND = {
+ MODEL: "model",
+ DATASET: "dataset",
+} as const;
+
+export const DOWNLOAD_KINDS = [
+ DOWNLOAD_KIND.MODEL,
+ DOWNLOAD_KIND.DATASET,
+] as const;
+export type DownloadKind = (typeof DOWNLOAD_KINDS)[number];
+
+export function isDownloadKind(value: unknown): value is DownloadKind {
+ return (
+ typeof value === "string" &&
+ (DOWNLOAD_KINDS as readonly string[]).includes(value)
+ );
+}
diff --git a/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts b/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts
new file mode 100644
index 00000000000..6942dfbbb9b
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts
@@ -0,0 +1,244 @@
+// 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 { getHfToken } from "../stores/hf-token-store";
+import { toast } from "@/lib/toast";
+import {
+ type DownloadStartResult,
+ type DownloadStartState,
+ cancelDatasetDownload,
+ cancelModelDownload,
+ getDatasetDownloadProgress,
+ getDatasetDownloadStatus,
+ getDatasetTransportStatus,
+ getDownloadProgress,
+ getDownloadTransportCapabilities,
+ getGgufDownloadProgress,
+ getModelDownloadStatus,
+ getModelTransportStatus,
+ startDatasetDownload,
+ startModelDownload,
+} from "./api";
+import {
+ POLL_REQUEST_TIMEOUT_MS,
+ TRANSPORT_STATUS_RETRY_DELAY_MS,
+ TRANSPORT_STATUS_TIMEOUT_MS,
+} from "./download-manager-config";
+import { DOWNLOAD_KIND, TRANSPORT, type TransportMode } from "./constants";
+import type {
+ DownloadRequest,
+ ManagedDownload,
+ ProgressLike,
+} from "./download-manager-types";
+import {
+ type PollSignal,
+ disposableTimeoutSignal,
+ pollSignal,
+} from "../lib/abort-signals";
+
+let lastXetUnavailableWarningReason: string | null = null;
+
+export async function withPollRequestTimeout<T>(
+ parent: AbortController | null,
+ request: (signal: AbortSignal) => Promise<T>,
+): Promise<T> {
+ const poll: PollSignal = parent
+ ? pollSignal(parent.signal, POLL_REQUEST_TIMEOUT_MS)
+ : disposableTimeoutSignal(POLL_REQUEST_TIMEOUT_MS);
+ try {
+ return await request(poll.signal);
+ } finally {
+ poll.dispose();
+ }
+}
+
+export function apiGetStatus(job: ManagedDownload, signal: AbortSignal) {
+ return job.kind === DOWNLOAD_KIND.DATASET
+ ? getDatasetDownloadStatus(job.repoId, signal)
+ : getModelDownloadStatus(job.repoId, job.variant, signal);
+}
+
+export function apiGetProgress(
+ job: ManagedDownload,
+ signal: AbortSignal,
+): Promise<ProgressLike> {
+ const token = getHfToken() || null;
+ if (job.kind === DOWNLOAD_KIND.DATASET) {
+ return getDatasetDownloadProgress(job.repoId, {
+ signal,
+ hfToken: token,
+ expectedBytes: job.expectedBytes,
+ });
+ }
+ if (job.variant) {
+ return getGgufDownloadProgress(job.repoId, {
+ variant: job.variant,
+ expectedBytes: job.expectedBytes,
+ hfToken: token,
+ signal,
+ });
+ }
+ return getDownloadProgress(job.repoId, {
+ signal,
+ hfToken: token,
+ expectedBytes: job.expectedBytes,
+ });
+}
+
+export function apiStart(
+ req: DownloadRequest,
+ useXet: boolean,
+ hfToken: string | null,
+): Promise<DownloadStartResult> {
+ return req.kind === DOWNLOAD_KIND.DATASET
+ ? startDatasetDownload({
+ repo_id: req.repoId,
+ hf_token: hfToken,
+ use_xet: useXet,
+ })
+ : startModelDownload({
+ repo_id: req.repoId,
+ gguf_variant: req.variant,
+ hf_token: hfToken,
+ use_xet: useXet,
+ });
+}
+
+export function apiCancel(job: ManagedDownload, signal?: AbortSignal) {
+ const generation = Number.isSafeInteger(job.serverGeneration)
+ ? job.serverGeneration
+ : undefined;
+ return job.kind === DOWNLOAD_KIND.DATASET
+ ? cancelDatasetDownload({ repo_id: job.repoId, generation, signal })
+ : cancelModelDownload({
+ repo_id: job.repoId,
+ gguf_variant: job.variant,
+ generation,
+ signal,
+ });
+}
+
+export function apiCancelRequest(
+ req: DownloadRequest,
+ generation: number | undefined,
+ signal?: AbortSignal,
+) {
+ if (!Number.isSafeInteger(generation)) return Promise.resolve();
+ return req.kind === DOWNLOAD_KIND.DATASET
+ ? cancelDatasetDownload({ repo_id: req.repoId, generation, signal })
+ : cancelModelDownload({
+ repo_id: req.repoId,
+ gguf_variant: req.variant,
+ generation,
+ signal,
+ });
+}
+
+function apiTransportStatus(
+ req: DownloadRequest,
+ signal?: AbortSignal,
+) {
+ const token = getHfToken() || null;
+ return req.kind === DOWNLOAD_KIND.DATASET
+ ? getDatasetTransportStatus(req.repoId, signal)
+ : getModelTransportStatus(req.repoId, req.variant, token, signal);
+}
+
+function wait(ms: number): Promise<void> {
+ return new Promise((resolve) => {
+ globalThis.setTimeout(resolve, ms);
+ });
+}
+
+export async function apiTransportStatusWithRetry(
+ req: DownloadRequest,
+): Promise<Awaited<ReturnType<typeof apiTransportStatus>>> {
+ const request = async () => {
+ const timeout = disposableTimeoutSignal(TRANSPORT_STATUS_TIMEOUT_MS);
+ try {
+ return await apiTransportStatus(req, timeout.signal);
+ } finally {
+ timeout.dispose();
+ }
+ };
+ try {
+ return await request();
+ } catch {
+ await wait(TRANSPORT_STATUS_RETRY_DELAY_MS);
+ return request();
+ }
+}
+
+export async function effectiveTransportMode(
+ preferred: TransportMode,
+): Promise<TransportMode> {
+ if (preferred !== TRANSPORT.XET) {
+ return preferred;
+ }
+ const capabilities = await getDownloadTransportCapabilities();
+ if (capabilities.xet.available === true) {
+ lastXetUnavailableWarningReason = null;
+ return preferred;
+ }
+ if (capabilities.xet.available === null) {
+ return preferred;
+ }
+ const reason =
+ capabilities.xet.reason ?? "Studio will use HTTP downloads instead.";
+ if (lastXetUnavailableWarningReason !== reason) {
+ lastXetUnavailableWarningReason = reason;
+ toast.warning("Xet download transport unavailable", {
+ description: reason,
+ });
+ }
+ return TRANSPORT.HTTP;
+}
+
+export function describeUnacceptedStart(state: DownloadStartState): string {
+ switch (state) {
+ case "deleting":
+ return "This repository is being removed. Try again once it finishes.";
+ case "running":
+ case "cancelling":
+ return "Another download for this repository is already in progress. Wait for it to finish or cancel it first.";
+ default:
+ return "The download could not be started. Try again in a moment.";
+ }
+}
+
+export function accessErrorMessage(raw: string): string | null {
+ const lower = raw.toLowerCase();
+ const hasAccessSignal =
+ lower.includes("unauthorized") ||
+ lower.includes("forbidden") ||
+ lower.includes("gated") ||
+ lower.includes("repository not found");
+ if (!hasAccessSignal) return null;
+ return "Couldn't access this Hugging Face repo with the token used for this download. Update the HF token and restart the download, or delete the partial download if you no longer need it.";
+}
+
+export const pollAccessErrorMessage = accessErrorMessage;
+
+export function normalizeDownloadError(
+ error: unknown,
+ fallback = "Failed to start download",
+): string {
+ const raw =
+ error instanceof Error
+ ? error.message
+ : typeof error === "string"
+ ? error
+ : fallback;
+ return accessErrorMessage(raw) ?? raw;
+}
+
+export function isRequestTimeout(error: unknown): boolean {
+ return (
+ error instanceof Error &&
+ (error.name === "AbortError" || error.name === "TimeoutError")
+ );
+}
+
+export function resetDownloadApiAdapterState(): void {
+ lastXetUnavailableWarningReason = null;
+}
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-config.ts b/studio/frontend/src/features/hub/download-manager/download-manager-config.ts
new file mode 100644
index 00000000000..dce0c6cf307
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-config.ts
@@ -0,0 +1,37 @@
+// 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 { DownloadJobState } from "./api";
+
+export const POLL_INTERVAL_MS = 500;
+export const POLL_BACKOFF_AFTER_MS = 60_000;
+export const POLL_BACKOFF_INTERVAL_MS = 1_500;
+export const HIDDEN_POLL_INTERVAL_MS = 10_000;
+export const POLL_JITTER_MS = 50;
+export const PROGRESS_POLL_INTERVAL_MS = 1_000;
+export const PROGRESS_POLL_BACKOFF_INTERVAL_MS = 2_000;
+export const POLL_REQUEST_TIMEOUT_MS = 15_000;
+export const POLL_DEGRADED_AFTER_MS = 30_000;
+export const POLL_DEGRADED_MESSAGE =
+ "Couldn't update download status. The download may still be running.";
+export const TRANSPORT_STATUS_TIMEOUT_MS = 3_000;
+export const SPEED_EMA_WEIGHT = 0.7;
+export const MAX_PROGRESS_FRACTION = 0.99;
+export const CANCEL_WATCHDOG_MS = 20_000;
+export const IDLE_EVICT_GRACE_MS = 60_000;
+export const COMPLETE_LINGER_MS = 6_000;
+export const CANCELLED_LINGER_MS = 6_000;
+export const ERROR_LINGER_MS = 12_000;
+export const INVENTORY_BUMP_DEBOUNCE_MS = 250;
+export const TRANSPORT_STATUS_RETRY_DELAY_MS = 300;
+
+export const ACTIVE_STATES: ReadonlySet<DownloadJobState> = new Set([
+ "running",
+ "cancelling",
+]);
+
+export const TERMINAL_DISPLAY_STATES: ReadonlySet<DownloadJobState> = new Set([
+ "complete",
+ "error",
+ "cancelled",
+]);
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts b/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts
new file mode 100644
index 00000000000..abfeaf3c0dc
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts
@@ -0,0 +1,72 @@
+// 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 {
+ createDownloadManagerInitialState,
+ removeJob,
+ setState,
+} from "./download-manager-state";
+import { resetDownloadApiAdapterState } from "./download-api-adapter";
+import {
+ hydrateDownloadManager,
+ resetHydrationState,
+} from "./hydration";
+import { cancelJob, probeAndAdopt, setExpected } from "./poll-loop";
+import { runtimeRegistry } from "./runtime-registry";
+import {
+ cancelConflict,
+ requestStart,
+ restartConflict,
+ resumeConflict,
+} from "./transport-conflict";
+
+export type { DownloadKind } from "./constants";
+export {
+ clearCompletedInventoryHint,
+ jobKeyOf,
+ repoKeyOf,
+ selectActiveJob,
+ subscribeJobListeners,
+ useDownloadManagerStore,
+} from "./download-manager-state";
+export type {
+ DownloadRequest,
+ JobListeners,
+ ManagedDownload,
+} from "./download-manager-types";
+export { hydrateDownloadManager };
+
+export function __resetDownloadManagerForTests(): void {
+ runtimeRegistry.reset();
+ resetDownloadApiAdapterState();
+ resetHydrationState();
+ setState(createDownloadManagerInitialState());
+}
+
+export interface DownloadManagerController {
+ requestStart: typeof requestStart;
+ cancel: typeof cancelJob;
+ probeAndAdopt: typeof probeAndAdopt;
+ setExpected: typeof setExpected;
+ resumeConflict: typeof resumeConflict;
+ restartConflict: typeof restartConflict;
+ cancelConflict: typeof cancelConflict;
+ dismiss: typeof removeJob;
+}
+
+export const downloadManager: DownloadManagerController = {
+ requestStart,
+ cancel: cancelJob,
+ probeAndAdopt,
+ setExpected,
+ resumeConflict,
+ restartConflict,
+ cancelConflict,
+ dismiss: removeJob,
+};
+
+if (import.meta.hot) {
+ import.meta.hot.dispose(() => {
+ __resetDownloadManagerForTests();
+ });
+}
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx
new file mode 100644
index 00000000000..e01cd6b5cc1
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx
@@ -0,0 +1,255 @@
+// 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 {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { hasAuthToken, mustChangePassword } from "@/features/auth/session";
+import { isTauri } from "@/lib/api-base";
+import { cn } from "@/lib/utils";
+import {
+ Alert02Icon,
+ ArrowDown01Icon,
+ Cancel01Icon,
+ CheckmarkCircle02Icon,
+ Download01Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useRouterState } from "@tanstack/react-router";
+import { useEffect, useMemo, useState } from "react";
+import { DownloadProgressBar } from "./download-progress-bar";
+import {
+ type ManagedDownload,
+ downloadManager,
+ hydrateDownloadManager,
+ useDownloadManagerStore,
+} from "./download-manager-controller";
+
+function createOrderedJobKeysSelector(): (state: {
+ jobs: Record<string, ManagedDownload>;
+}) => string[] {
+ let cache: { signature: string; keys: string[] } = {
+ signature: "",
+ keys: [],
+ };
+ return (state) => {
+ const ordered = Object.values(state.jobs)
+ .map((job) => ({ key: job.key, startedAt: job.startedAt }))
+ .sort((a, b) => a.startedAt - b.startedAt);
+ const signature = ordered
+ .map((job) => `${job.key}\u0001${job.startedAt}`)
+ .join("\u0002");
+ if (signature === cache.signature) {
+ return cache.keys;
+ }
+ const keys = ordered.map((job) => job.key);
+ cache = { signature, keys };
+ return keys;
+ };
+}
+
+function selectActiveJobCount(state: {
+ jobs: Record<string, ManagedDownload>;
+}): number {
+ let count = 0;
+ for (const job of Object.values(state.jobs)) {
+ if (job.state === "running" || job.state === "cancelling") count += 1;
+ }
+ return count;
+}
+
+function canUseDownloadManager(pathname: string): boolean {
+ if (isTauri) return true;
+ if (
+ pathname === "/login" ||
+ pathname === "/change-password" ||
+ pathname === "/signup"
+ ) {
+ return false;
+ }
+ return hasAuthToken() && !mustChangePassword();
+}
+
+function variantSuffix(job: ManagedDownload): string {
+ return job.variant ? ` · ${job.variant}` : "";
+}
+
+function StatusLine({ job }: { job: ManagedDownload }) {
+ if (job.state === "complete") {
+ return <span className="text-status-success">Downloaded</span>;
+ }
+ if (job.state === "cancelled") {
+ return <span>Cancelled. Partial files kept.</span>;
+ }
+ if (job.state === "error") {
+ return (
+ <span className="text-destructive">{job.error ?? "Download failed"}</span>
+ );
+ }
+ if (job.state === "cancelling") {
+ return <span>Cancelling…</span>;
+ }
+ if (job.error) {
+ return <span className="text-status-warning">{job.error}</span>;
+ }
+ return null;
+}
+
+function DownloadRow({ jobKey }: { jobKey: string }) {
+ const job = useDownloadManagerStore((state) => state.jobs[jobKey]);
+ if (!job) return null;
+ const active = job.state === "running" || job.state === "cancelling";
+ const terminal =
+ job.state === "complete" ||
+ job.state === "cancelled" ||
+ job.state === "error";
+ return (
+ <li className="flex flex-col gap-1.5 px-3 py-2.5">
+ <div className="flex items-center gap-2">
+ <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-foreground">
+ {job.repoId}
+ <span className="text-muted-foreground">{variantSuffix(job)}</span>
+ </span>
+ {job.state === "complete" && (
+ <HugeiconsIcon
+ icon={CheckmarkCircle02Icon}
+ strokeWidth={2}
+ className="size-4 shrink-0 text-status-success"
+ />
+ )}
+ {job.state === "error" && (
+ <HugeiconsIcon
+ icon={Alert02Icon}
+ strokeWidth={2}
+ className="size-4 shrink-0 text-destructive"
+ />
+ )}
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={active ? "Cancel download" : "Dismiss"}
+ disabled={job.state === "cancelling"}
+ onClick={() =>
+ active
+ ? void downloadManager.cancel(job.key)
+ : downloadManager.dismiss(job.key)
+ }
+ className={cn(
+ "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-[7px] text-muted-foreground transition-colors",
+ "hover:bg-foreground/[0.06] hover:text-foreground disabled:cursor-default disabled:opacity-50 dark:hover:bg-white/[0.06]",
+ )}
+ >
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" sideOffset={4}>
+ {active ? "Cancel download" : "Dismiss"}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ {active ? (
+ <DownloadProgressBar
+ progress={{
+ expectedBytes: job.expectedBytes,
+ downloadedBytes: job.downloadedBytes,
+ fraction: job.fraction,
+ }}
+ bytesPerSec={job.bytesPerSec}
+ />
+ ) : null}
+ {terminal || job.state === "cancelling" || job.error ? (
+ <div className="px-0 text-[11px] text-muted-foreground tabular-nums">
+ <StatusLine job={job} />
+ </div>
+ ) : null}
+ </li>
+ );
+}
+
+export function DownloadManagerPanel() {
+ const pathname = useRouterState({ select: (s) => s.location.pathname });
+ const enabled = canUseDownloadManager(pathname);
+ const [collapsed, setCollapsed] = useState(false);
+
+ useEffect(() => {
+ if (!enabled) return;
+ hydrateDownloadManager();
+ }, [enabled]);
+
+ const selectOrderedJobKeys = useMemo(createOrderedJobKeysSelector, []);
+ const jobKeys = useDownloadManagerStore(selectOrderedJobKeys);
+ const activeCount = useDownloadManagerStore(selectActiveJobCount);
+
+ if (!enabled || jobKeys.length === 0) return null;
+
+ const headerLabel =
+ activeCount > 0
+ ? `Downloading ${activeCount} ${activeCount === 1 ? "item" : "items"}`
+ : "Downloads";
+
+ return (
+ <div className="pointer-events-none fixed bottom-4 right-4 z-50">
+ {collapsed ? (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={headerLabel}
+ onClick={() => setCollapsed(false)}
+ className="hub-download-fab pointer-events-auto"
+ >
+ <HugeiconsIcon
+ icon={Download01Icon}
+ strokeWidth={1.75}
+ className="size-[18px]"
+ />
+ {activeCount > 0 && (
+ <span className="hub-download-fab-badge">{activeCount}</span>
+ )}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="left" sideOffset={6}>
+ {headerLabel}
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <div className="hub-download-panel pointer-events-auto w-[min(360px,calc(100vw-2rem))] overflow-hidden">
+ <div className="flex items-center gap-2 border-b border-foreground/[0.07] px-3 py-2">
+ <HugeiconsIcon
+ icon={Download01Icon}
+ strokeWidth={1.75}
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ <span className="min-w-0 flex-1 truncate text-[12.5px] font-semibold text-foreground">
+ {headerLabel}
+ </span>
+ <button
+ type="button"
+ aria-label="Collapse downloads"
+ onClick={() => setCollapsed(true)}
+ className="inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-[7px] text-muted-foreground transition-colors hover:bg-foreground/[0.06] hover:text-foreground dark:hover:bg-white/[0.06]"
+ >
+ <HugeiconsIcon
+ icon={ArrowDown01Icon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </button>
+ </div>
+ <ul className="max-h-[60vh] divide-y divide-foreground/[0.06] overflow-y-auto [scrollbar-width:thin]">
+ {jobKeys.map((jobKey) => (
+ <DownloadRow key={jobKey} jobKey={jobKey} />
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ );
+}
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
new file mode 100644
index 00000000000..5699fd62fb2
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
@@ -0,0 +1,526 @@
+// 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 { INVENTORY_HINT_KIND } from "../inventory/constants";
+import { inventoryHintKey } from "../inventory/inventory-hints";
+import type { InventoryHint } from "../inventory/types";
+import { create } from "zustand";
+import {
+ type StateStorage,
+ createJSONStorage,
+ persist,
+} from "zustand/middleware";
+import type { DownloadJobState } from "./api";
+import {
+ ACTIVE_STATES,
+ MAX_PROGRESS_FRACTION,
+} from "./download-manager-config";
+import {
+ DOWNLOAD_KIND,
+ type DownloadKind,
+ isDownloadKind,
+} from "./constants";
+import {
+ type DownloadManagerState,
+ type JobListeners,
+ type ManagedDownload,
+} from "./download-manager-types";
+import {
+ clearRuntimeTimer,
+ pruneSuppressedCompletedInventoryHints as pruneRuntimeSuppressedHints,
+ runtimeRegistry,
+ teardownRuntime,
+} from "./runtime-registry";
+
+const PERSIST_KEY = "unsloth.studio.downloads";
+const PERSIST_VERSION = 1;
+const PERSIST_THROTTLE_MS = 1_000;
+
+const noopStorage: StateStorage = {
+ getItem: () => null,
+ setItem: () => undefined,
+ removeItem: () => undefined,
+};
+
+function createThrottledStorage(
+ base: StateStorage,
+ delayMs: number,
+): StateStorage {
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let pending: { name: string; value: string } | null = null;
+ const flush = (): void => {
+ if (timer !== null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ if (pending) {
+ base.setItem(pending.name, pending.value);
+ pending = null;
+ }
+ };
+ if (typeof window !== "undefined") {
+ window.addEventListener("pagehide", flush);
+ }
+ return {
+ getItem: (name) => base.getItem(name),
+ setItem: (name, value) => {
+ pending = { name, value };
+ if (timer === null) timer = setTimeout(flush, delayMs);
+ },
+ removeItem: (name) => {
+ pending = null;
+ if (timer !== null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ base.removeItem(name);
+ },
+ };
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+function finiteNumber(value: unknown, fallback: number): number {
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
+}
+
+function nonNegativeNumber(value: unknown, fallback = 0): number {
+ return Math.max(0, finiteNumber(value, fallback));
+}
+
+function sanitizePersistedJob(value: unknown): ManagedDownload | null {
+ if (!isRecord(value)) return null;
+ const kind = isDownloadKind(value.kind) ? value.kind : null;
+ const repoId = typeof value.repoId === "string" ? value.repoId : null;
+ const state = value.state as DownloadJobState;
+ if (!kind || !repoId || !ACTIVE_STATES.has(state)) return null;
+
+ const variant = typeof value.variant === "string" ? value.variant : null;
+ const key = jobKeyOf(kind, repoId, variant);
+ return {
+ key,
+ kind,
+ repoId,
+ variant,
+ state,
+ downloadedBytes: nonNegativeNumber(value.downloadedBytes),
+ completedBytes: nonNegativeNumber(value.completedBytes),
+ completeOnDisk: false,
+ expectedBytes: nonNegativeNumber(value.expectedBytes),
+ fraction: Math.min(Math.max(finiteNumber(value.fraction, 0), 0), 1),
+ bytesPerSec: 0,
+ error: typeof value.error === "string" ? value.error : null,
+ startedAt: nonNegativeNumber(value.startedAt, Date.now()),
+ ...(Number.isSafeInteger(value.serverGeneration)
+ ? { serverGeneration: Number(value.serverGeneration) }
+ : {}),
+ };
+}
+
+function sanitizePersistedState(
+ persisted: unknown,
+): Partial<DownloadManagerState> {
+ if (!isRecord(persisted) || !isRecord(persisted.jobs)) {
+ return { jobs: {}, conflicts: {} };
+ }
+ const jobs: Record<string, ManagedDownload> = {};
+ for (const value of Object.values(persisted.jobs)) {
+ const job = sanitizePersistedJob(value);
+ if (job) jobs[job.key] = job;
+ }
+ return {
+ jobs,
+ conflicts: {},
+ };
+}
+
+function toPersistedJob(
+ job: ManagedDownload,
+): Omit<ManagedDownload, "bytesPerSec" | "completeOnDisk"> {
+ return {
+ key: job.key,
+ kind: job.kind,
+ repoId: job.repoId,
+ variant: job.variant,
+ state: job.state,
+ downloadedBytes: job.downloadedBytes,
+ completedBytes: job.completedBytes,
+ expectedBytes: job.expectedBytes,
+ fraction: job.fraction,
+ error: job.error,
+ startedAt: job.startedAt,
+ ...(job.serverGeneration !== undefined
+ ? { serverGeneration: job.serverGeneration }
+ : {}),
+ };
+}
+
+// Mirrors the backend's normalize_repo_key (strip().lower()) so two casings of
+// one repo share a key (else duplicate jobs / mismatched listeners). Keys only —
+// `repoId` keeps original casing for display and API calls.
+function normalizeRepoIdentity(repoId: string): string {
+ return repoId.trim().toLowerCase();
+}
+
+function normalizeVariantIdentity(variant: string | null | undefined): string {
+ return variant?.trim().toLowerCase() ?? "";
+}
+
+export function repoKeyOf(kind: DownloadKind, repoId: string): string {
+ return `${kind}:${normalizeRepoIdentity(repoId)}`;
+}
+
+export function jobKeyOf(
+ kind: DownloadKind,
+ repoId: string,
+ variant: string | null,
+): string {
+ const base = repoKeyOf(kind, repoId);
+ const variantKey = normalizeVariantIdentity(variant);
+ return variantKey ? `${base}#${variantKey}` : base;
+}
+
+function completedInventoryHintKind(
+ kind: DownloadKind,
+ variant: string | null,
+): InventoryHint["kind"] {
+ return kind === DOWNLOAD_KIND.DATASET
+ ? INVENTORY_HINT_KIND.DATASET
+ : variant
+ ? INVENTORY_HINT_KIND.GGUF
+ : INVENTORY_HINT_KIND.MODEL;
+}
+
+function liveCompletedInventoryHintKeys(): Set<string> {
+ const keys = new Set<string>();
+ for (const job of Object.values(getState().jobs)) {
+ if (job.state !== "complete") continue;
+ keys.add(
+ inventoryHintKey(
+ completedInventoryHintKind(job.kind, job.variant),
+ job.repoId,
+ ),
+ );
+ }
+ return keys;
+}
+
+function collectCompletedInventoryHints(
+ jobs: Record<string, ManagedDownload>,
+): InventoryHint[] {
+ return Object.values(jobs).flatMap((job) => {
+ if (job.state !== "complete") return [];
+ const kind = completedInventoryHintKind(job.kind, job.variant);
+ if (
+ runtimeRegistry.suppressedCompletedInventoryHints.has(
+ inventoryHintKey(kind, job.repoId),
+ )
+ ) {
+ return [];
+ }
+ const bytes = Math.max(job.downloadedBytes, job.expectedBytes, 0);
+ return [
+ {
+ kind,
+ repoId: job.repoId,
+ ...(bytes > 0 ? { bytes } : {}),
+ },
+ ];
+ });
+}
+
+function buildCompletedHintSignature(hints: readonly InventoryHint[]): string {
+ return hints
+ .map((hint) => `${hint.kind}:${hint.repoId}:${hint.bytes ?? ""}`)
+ .sort()
+ .join("|");
+}
+
+export function createDownloadManagerInitialState(): DownloadManagerState {
+ return {
+ jobs: {},
+ conflicts: {},
+ completedHintSignature: "",
+ completedInventoryHints: [],
+ };
+}
+
+export const useDownloadManagerStore = create<DownloadManagerState>()(
+ persist(createDownloadManagerInitialState, {
+ name: PERSIST_KEY,
+ version: PERSIST_VERSION,
+ storage: createJSONStorage(() =>
+ typeof window === "undefined"
+ ? noopStorage
+ : createThrottledStorage(window.localStorage, PERSIST_THROTTLE_MS),
+ ),
+ migrate: (persisted) => sanitizePersistedState(persisted),
+ merge: (persisted, current) => ({
+ ...current,
+ ...sanitizePersistedState(persisted),
+ }),
+ partialize: (state) => ({
+ jobs: Object.fromEntries(
+ Object.entries(state.jobs)
+ .filter(([, job]) => ACTIVE_STATES.has(job.state))
+ .map(([key, job]) => [key, toPersistedJob(job)] as const),
+ ),
+ conflicts: {},
+ }),
+ }),
+);
+
+export const setState = useDownloadManagerStore.setState;
+export const getState = useDownloadManagerStore.getState;
+
+function withCompletedHintSignature(
+ state: DownloadManagerState,
+): DownloadManagerState {
+ const completedInventoryHints = collectCompletedInventoryHints(state.jobs);
+ const completedHintSignature = buildCompletedHintSignature(
+ completedInventoryHints,
+ );
+ if (state.completedHintSignature === completedHintSignature) return state;
+ return { ...state, completedHintSignature, completedInventoryHints };
+}
+
+function isPreferredRepoActiveJob(
+ candidate: ManagedDownload,
+ current: ManagedDownload | null | undefined,
+): boolean {
+ if (!current || !ACTIVE_STATES.has(current.state)) return true;
+ if (candidate.startedAt !== current.startedAt) {
+ return candidate.startedAt > current.startedAt;
+ }
+ return candidate.key < current.key;
+}
+
+export function findActiveJobForRepo(
+ jobs: Record<string, ManagedDownload>,
+ kind: DownloadKind,
+ repoId: string,
+): ManagedDownload | null {
+ let selected: ManagedDownload | null = null;
+ const repoIdentity = normalizeRepoIdentity(repoId);
+ for (const job of Object.values(jobs)) {
+ if (job.kind !== kind || normalizeRepoIdentity(job.repoId) !== repoIdentity)
+ continue;
+ if (!ACTIVE_STATES.has(job.state)) continue;
+ if (isPreferredRepoActiveJob(job, selected)) {
+ selected = job;
+ }
+ }
+ return selected;
+}
+
+function hasRuntimePeerForRepo(
+ kind: DownloadKind,
+ repoId: string,
+ key: string,
+): boolean {
+ const repoIdentity = normalizeRepoIdentity(repoId);
+ for (const [runtimeKey, runtime] of runtimeRegistry.runtimes) {
+ if (runtimeKey === key) continue;
+ if (runtime.kind === kind && normalizeRepoIdentity(runtime.repoId) === repoIdentity)
+ return true;
+ }
+ return false;
+}
+
+// Shared rule for what blocks a fresh GGUF variant start. Peer guard passes
+// includeOwnRuntime:false (runs after this start made its own runtime); requestStart
+// passes both true (runs before any runtime or job exists).
+export function hasVariantRepoActivity(
+ kind: DownloadKind,
+ repoId: string,
+ key: string,
+ opts: { includeOwnRuntime: boolean; includePending: boolean },
+): boolean {
+ const state = getState();
+ const own = state.jobs[key];
+ if (own && ACTIVE_STATES.has(own.state)) return true;
+ if (selectActiveJob(state, kind, repoId, null)) return true;
+ const snapshotKey = jobKeyOf(kind, repoId, null);
+ if (runtimeRegistry.runtimes.has(snapshotKey)) return true;
+ if (opts.includeOwnRuntime && runtimeRegistry.runtimes.has(key)) return true;
+ if (opts.includePending) {
+ if (runtimeRegistry.pendingStartRepoKeys.has(key)) return true;
+ if (runtimeRegistry.pendingStartRepoKeys.has(snapshotKey)) return true;
+ }
+ return false;
+}
+
+export function hasActiveRepoPeer(
+ kind: DownloadKind,
+ repoId: string,
+ key: string,
+ variant?: string | null,
+): boolean {
+ if (kind === DOWNLOAD_KIND.MODEL && variant) {
+ return hasVariantRepoActivity(kind, repoId, key, {
+ includeOwnRuntime: false,
+ includePending: false,
+ });
+ }
+ const active = findActiveJobForRepo(getState().jobs, kind, repoId);
+ if (active && active.key !== key) return true;
+ return hasRuntimePeerForRepo(kind, repoId, key);
+}
+
+function refreshCompletedHintSignature(): void {
+ setState((state) => withCompletedHintSignature(state));
+}
+
+export function patchJob(key: string, patch: Partial<ManagedDownload>): void {
+ setState((state) => {
+ const job = state.jobs[key];
+ if (!job) return state;
+ const nextJob = { ...job, ...patch };
+ const nextState = {
+ ...state,
+ jobs: { ...state.jobs, [key]: nextJob },
+ };
+ if (job.state !== "complete" && nextJob.state !== "complete") {
+ return nextState;
+ }
+ return withCompletedHintSignature(nextState);
+ });
+}
+
+export function putJob(job: ManagedDownload): void {
+ runtimeRegistry.clearRemovalTimer(job.key);
+ const suppressionChanged =
+ runtimeRegistry.suppressedCompletedInventoryHints.delete(
+ inventoryHintKey(
+ completedInventoryHintKind(job.kind, job.variant),
+ job.repoId,
+ ),
+ );
+ setState((state) => {
+ const existing = state.jobs[job.key];
+ const nextState = {
+ ...state,
+ jobs: { ...state.jobs, [job.key]: job },
+ };
+ if (
+ !suppressionChanged &&
+ existing?.state !== "complete" &&
+ job.state !== "complete"
+ ) {
+ return nextState;
+ }
+ return withCompletedHintSignature(nextState);
+ });
+}
+
+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;
+ return withCompletedHintSignature(nextState);
+ });
+}
+
+export function setConflict(
+ key: string,
+ entry: DownloadManagerState["conflicts"][string] | null,
+): void {
+ setState((state) => {
+ const next = { ...state.conflicts };
+ if (entry) next[key] = entry;
+ else delete next[key];
+ return { ...state, conflicts: next };
+ });
+}
+
+export function isCurrent(key: string, epoch: number): boolean {
+ const rt = runtimeRegistry.runtimes.get(key);
+ return rt != null && rt.epoch === epoch && key in getState().jobs;
+}
+
+export function scheduleRemoval(key: string, delayMs: number): void {
+ const existing = runtimeRegistry.removalTimers.get(key);
+ if (existing != null) clearRuntimeTimer(existing);
+ const startedAt = getState().jobs[key]?.startedAt;
+ const timer = window.setTimeout(() => {
+ runtimeRegistry.removalTimers.delete(key);
+ if (getState().jobs[key]?.startedAt === startedAt) removeJob(key);
+ }, delayMs);
+ runtimeRegistry.removalTimers.set(key, timer);
+}
+
+export function selectActiveJob(
+ state: DownloadManagerState,
+ kind: DownloadKind,
+ repoId: string,
+ variant?: string | null,
+): ManagedDownload | null {
+ if (variant !== undefined) {
+ const job = state.jobs[jobKeyOf(kind, repoId, variant)];
+ return job && ACTIVE_STATES.has(job.state) ? job : null;
+ }
+ return findActiveJobForRepo(state.jobs, kind, repoId);
+}
+
+export function clearCompletedInventoryHint(hint: InventoryHint): void {
+ const key = inventoryHintKey(hint.kind, hint.repoId);
+ runtimeRegistry.suppressedCompletedInventoryHints.delete(key);
+ runtimeRegistry.suppressedCompletedInventoryHints.add(key);
+ pruneRuntimeSuppressedHints(liveCompletedInventoryHintKeys());
+ refreshCompletedHintSignature();
+}
+
+export function subscribeJobListeners(
+ kind: DownloadKind,
+ repoId: string,
+ handlers: JobListeners,
+): () => void {
+ const key = repoKeyOf(kind, repoId);
+ let set = runtimeRegistry.listeners.get(key);
+ if (!set) {
+ set = new Set();
+ runtimeRegistry.listeners.set(key, set);
+ }
+ set.add(handlers);
+ return () => {
+ const current = runtimeRegistry.listeners.get(key);
+ if (!current) return;
+ current.delete(handlers);
+ if (current.size === 0) runtimeRegistry.listeners.delete(key);
+ };
+}
+
+export function setExpectedBytesForJob(
+ kind: DownloadKind,
+ repoId: string,
+ variant: string | null,
+ bytes: number,
+): void {
+ const job = selectActiveJob(getState(), kind, repoId, variant);
+ if (!job || job.state !== "running" || bytes <= job.expectedBytes) return;
+ patchJob(job.key, {
+ expectedBytes: bytes,
+ fraction:
+ job.fraction > 0
+ ? job.fraction
+ : Math.min(job.downloadedBytes / bytes, MAX_PROGRESS_FRACTION),
+ });
+}
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
new file mode 100644
index 00000000000..27b8161eab1
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
@@ -0,0 +1,81 @@
+// 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 { InventoryHint } from "../inventory/types";
+import type { DownloadJobState } from "./api";
+import type { DownloadKind } from "./constants";
+import type { TransportConflictInfo } from "./types";
+
+export interface ManagedDownload {
+ key: string;
+ kind: DownloadKind;
+ repoId: string;
+ variant: string | null;
+ state: DownloadJobState;
+ downloadedBytes: number;
+ // Finalized bytes on disk (excludes the in-progress `.incomplete` portion in
+ // `downloadedBytes`). The idle/registry-loss completion fallback keys off this
+ // so a partial can't be marked complete.
+ completedBytes: number;
+ // Server-verified completion; not trusted across reloads (hydration re-probes).
+ completeOnDisk: boolean;
+ expectedBytes: number;
+ fraction: number;
+ bytesPerSec: number;
+ error: string | null;
+ startedAt: number;
+ serverGeneration?: number;
+}
+
+export interface DownloadRequest {
+ kind: DownloadKind;
+ repoId: string;
+ variant: string | null;
+ expectedBytes: number;
+}
+
+export interface JobListeners {
+ onComplete?: (variant: string | null, bytes: number) => unknown;
+ onCancelled?: (variant: string | null) => unknown;
+ onError?: (variant: string | null) => unknown;
+}
+
+export interface ConflictEntry {
+ info: TransportConflictInfo;
+ pending: DownloadRequest;
+}
+
+export interface DownloadManagerState {
+ jobs: Record<string, ManagedDownload>;
+ conflicts: Record<string, ConflictEntry>;
+ completedHintSignature: string;
+ completedInventoryHints: InventoryHint[];
+}
+
+export interface JobRuntime {
+ kind: DownloadKind;
+ repoId: string;
+ epoch: number;
+ pollTimer: number | null;
+ pollStartedAt: number;
+ pollingStarted: boolean;
+ abort: AbortController | null;
+ inFlight: boolean;
+ cancelRequested: boolean;
+ watchdog: number | null;
+ speedSample: { bytes: number; tMs: number } | null;
+ idleSinceMs: number | null;
+ lastProgressPollAt: number | null;
+ pollFailureStartedAt: number | null;
+ visibilityListener: (() => void) | null;
+}
+
+export interface ProgressLike {
+ downloaded_bytes: number;
+ completed_bytes?: number;
+ complete_on_disk?: boolean;
+ expected_bytes: number;
+ progress: number;
+}
+
+export type Terminal = "complete" | "cancelled" | "error" | "gone";
diff --git a/studio/frontend/src/features/hub/download-manager/download-progress-bar.tsx b/studio/frontend/src/features/hub/download-manager/download-progress-bar.tsx
new file mode 100644
index 00000000000..66293056094
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/download-progress-bar.tsx
@@ -0,0 +1,56 @@
+// 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 { formatBytes, formatEta, formatRate } from "@/features/hub/lib/format";
+
+export interface DownloadProgress {
+ expectedBytes: number;
+ downloadedBytes: number;
+ fraction: number;
+}
+
+export function DownloadProgressBar({
+ progress,
+ bytesPerSec,
+}: {
+ progress: DownloadProgress;
+ bytesPerSec: number;
+}) {
+ const exactPercent = Math.min(Math.max(progress.fraction, 0), 1) * 100;
+ const totalLabel =
+ progress.expectedBytes > 0 ? formatBytes(progress.expectedBytes) : null;
+ const rateLabel = formatRate(bytesPerSec);
+ const remainingBytes = Math.max(
+ progress.expectedBytes - progress.downloadedBytes,
+ 0,
+ );
+ const etaLabel =
+ bytesPerSec > 0 && remainingBytes > 0
+ ? formatEta(remainingBytes / bytesPerSec)
+ : "";
+ return (
+ <div className="flex flex-col gap-1.5 px-3 pb-1">
+ <div className="relative h-[3px] overflow-hidden rounded-full bg-foreground/[0.06] dark:bg-white/[0.06]">
+ <div
+ className="h-full rounded-full bg-status-warning/80 transition-[width] duration-500 ease-linear"
+ style={{ width: `${exactPercent}%` }}
+ />
+ <span
+ aria-hidden="true"
+ className="pointer-events-none absolute top-1/2 size-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-status-warning ring-2 ring-status-warning/30 transition-[left] duration-500 ease-linear"
+ style={{ left: `${exactPercent}%` }}
+ />
+ </div>
+ <div className="flex items-center justify-between gap-2 text-[10.5px] text-muted-foreground tabular-nums">
+ <span>
+ {formatBytes(progress.downloadedBytes)}
+ {totalLabel && ` / ${totalLabel}`}
+ </span>
+ <span className="flex items-center gap-2">
+ {rateLabel && <span>{rateLabel}</span>}
+ {etaLabel && <span>{etaLabel}</span>}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/download-manager/hydration.ts b/studio/frontend/src/features/hub/download-manager/hydration.ts
new file mode 100644
index 00000000000..a222fc4574b
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/hydration.ts
@@ -0,0 +1,281 @@
+// 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 { disposableTimeoutSignal } from "../lib/abort-signals";
+import {
+ getActiveDatasetDownloads,
+ getAllActiveModelDownloads,
+ type DownloadJobState,
+} from "./api";
+import { DOWNLOAD_KIND } from "./constants";
+import { ACTIVE_STATES, POLL_REQUEST_TIMEOUT_MS } from "./download-manager-config";
+import {
+ apiGetProgress,
+ apiGetStatus,
+ isRequestTimeout,
+} from "./download-api-adapter";
+import type {
+ DownloadRequest,
+ ManagedDownload,
+} from "./download-manager-types";
+import {
+ getState,
+ jobKeyOf,
+ removeJob,
+ repoKeyOf,
+} from "./download-manager-state";
+import {
+ adoptJob,
+ applyProgressUpdate,
+ finalize,
+ hasObservedExpectedBytes,
+} from "./poll-loop";
+import { runtimeRegistry } from "./runtime-registry";
+
+const HYDRATE_STATUS_TIMEOUT_RETRIES = 4;
+const HYDRATE_STATUS_RETRY_MS = 2_500;
+const HYDRATE_ADOPTION_RETRY_MS = 2_500;
+const HYDRATE_ADOPTION_MAX_RETRIES = 12;
+
+let hydrated = false;
+
+type HydratedIdleProbeResult = "active" | "gone" | "settled";
+
+function safeGeneration(value: number | undefined): number | undefined {
+ return Number.isSafeInteger(value) ? value : undefined;
+}
+
+async function withHydrationTimeout<T>(
+ request: (signal: AbortSignal) => Promise<T>,
+): Promise<T> {
+ const timeout = disposableTimeoutSignal(POLL_REQUEST_TIMEOUT_MS);
+ try {
+ return await request(timeout.signal);
+ } finally {
+ timeout.dispose();
+ }
+}
+
+function removeLocalActivePeers(
+ kind: DownloadRequest["kind"],
+ repoId: string,
+ variant: string | null,
+): void {
+ const activeRepoKey = repoKeyOf(kind, repoId);
+ const activeJobKey = jobKeyOf(kind, repoId, variant);
+ const snapshotJobKey = jobKeyOf(kind, repoId, null);
+ for (const job of Object.values(getState().jobs)) {
+ if (!ACTIVE_STATES.has(job.state)) continue;
+ if (repoKeyOf(job.kind, job.repoId) !== activeRepoKey) continue;
+ if (variant !== null && kind === DOWNLOAD_KIND.MODEL) {
+ if (job.key === activeJobKey) continue;
+ if (job.key === snapshotJobKey) removeJob(job.key);
+ continue;
+ }
+ if (job.key !== activeJobKey) removeJob(job.key);
+ }
+}
+
+async function adoptActiveModelDownloads(): Promise<void> {
+ const downloads = await withHydrationTimeout((signal) =>
+ getAllActiveModelDownloads(signal),
+ );
+ for (const download of downloads) {
+ const repoId = download.repo_id?.trim();
+ if (!repoId || !ACTIVE_STATES.has(download.state)) continue;
+ removeLocalActivePeers(
+ DOWNLOAD_KIND.MODEL,
+ repoId,
+ download.variant ?? null,
+ );
+ adoptJob(
+ {
+ kind: DOWNLOAD_KIND.MODEL,
+ repoId,
+ variant: download.variant ?? null,
+ expectedBytes: 0,
+ },
+ safeGeneration(download.generation),
+ download.state,
+ );
+ }
+}
+
+async function adoptActiveDatasetDownloads(): Promise<void> {
+ const downloads = await withHydrationTimeout((signal) =>
+ getActiveDatasetDownloads(signal),
+ );
+ for (const download of downloads) {
+ const repoId = download.repo_id?.trim();
+ if (!repoId || !ACTIVE_STATES.has(download.state)) continue;
+ removeLocalActivePeers(DOWNLOAD_KIND.DATASET, repoId, null);
+ adoptJob(
+ {
+ kind: DOWNLOAD_KIND.DATASET,
+ repoId,
+ variant: null,
+ expectedBytes: 0,
+ },
+ safeGeneration(download.generation),
+ download.state,
+ );
+ }
+}
+
+type BackendAdoptionSide = "model" | "dataset";
+
+const BACKEND_ADOPTERS: Record<BackendAdoptionSide, () => Promise<void>> = {
+ model: adoptActiveModelDownloads,
+ dataset: adoptActiveDatasetDownloads,
+};
+
+// Adopt backend-running downloads this client doesn't know about. Retry only the
+// failed side(s) so transient backend readiness settles without duplicating jobs.
+async function hydrateBackendActiveDownloads(
+ attempt = 0,
+ sides: readonly BackendAdoptionSide[] = ["model", "dataset"],
+): Promise<void> {
+ const results = await Promise.allSettled(
+ sides.map((side) => BACKEND_ADOPTERS[side]()),
+ );
+ const pending = sides.filter(
+ (_, index) => results[index].status === "rejected",
+ );
+ if (pending.length === 0 || attempt >= HYDRATE_ADOPTION_MAX_RETRIES) return;
+ scheduleBackendAdoptionRetry(attempt + 1, pending);
+}
+
+function scheduleBackendAdoptionRetry(
+ attempt: number,
+ sides: readonly BackendAdoptionSide[],
+): void {
+ const timer = window.setTimeout(() => {
+ runtimeRegistry.hydrationRetryTimers.delete(timer);
+ void hydrateBackendActiveDownloads(attempt, sides);
+ }, HYDRATE_ADOPTION_RETRY_MS);
+ runtimeRegistry.hydrationRetryTimers.add(timer);
+}
+
+async function probeHydratedIdleProgress(
+ key: string,
+ job: ManagedDownload,
+): Promise<HydratedIdleProbeResult> {
+ try {
+ const progressResp = await withHydrationTimeout((signal) =>
+ apiGetProgress(job, signal),
+ );
+ const current = getState().jobs[key];
+ if (!current || !ACTIVE_STATES.has(current.state)) return "settled";
+ const { downloadedBytes } = applyProgressUpdate(key, current, progressResp);
+ const updated = getState().jobs[key];
+ if (!updated || !ACTIVE_STATES.has(updated.state)) return "settled";
+ if (hasObservedExpectedBytes(updated)) {
+ finalize(key, "complete", { bytes: updated.downloadedBytes });
+ return "settled";
+ }
+ return downloadedBytes > 0 ? "active" : "gone";
+ } catch {
+ return "active";
+ }
+}
+
+async function settleHydratedJob(
+ key: string,
+ req: DownloadRequest,
+ status: {
+ state: DownloadJobState;
+ error?: string | null;
+ generation?: number;
+ },
+): Promise<void> {
+ if (status.state === "running" || status.state === "cancelling") {
+ adoptJob(req, safeGeneration(status.generation), status.state);
+ } else if (status.state === "complete") {
+ finalize(key, "complete");
+ } else if (status.state === "cancelled") {
+ finalize(key, "cancelled");
+ } else if (status.state === "error") {
+ finalize(key, "error", { error: status.error ?? null });
+ } else {
+ const job = getState().jobs[key];
+ if (job && hasObservedExpectedBytes(job)) {
+ finalize(key, "complete", { bytes: job.downloadedBytes });
+ } else if (job?.state === "running" || job?.state === "cancelling") {
+ const probeResult = await probeHydratedIdleProgress(key, job);
+ if (probeResult === "settled") return;
+ if (probeResult === "active" && job.state === "running") {
+ adoptJob(req);
+ return;
+ }
+ const latest = getState().jobs[key];
+ if (latest && hasObservedExpectedBytes(latest)) {
+ finalize(key, "complete", { bytes: latest.downloadedBytes });
+ } else {
+ finalize(key, job.state === "cancelling" ? "cancelled" : "gone");
+ }
+ } else {
+ finalize(key, "gone");
+ }
+ }
+}
+
+function scheduleHydrationProbeRetry(
+ key: string,
+ req: DownloadRequest,
+ attempt: number,
+): void {
+ const timer = window.setTimeout(() => {
+ runtimeRegistry.hydrationRetryTimers.delete(timer);
+ const job = getState().jobs[key];
+ if (!job || !ACTIVE_STATES.has(job.state)) return;
+ void probeHydratedJob(key, req, attempt);
+ }, HYDRATE_STATUS_RETRY_MS);
+ runtimeRegistry.hydrationRetryTimers.add(timer);
+}
+
+async function probeHydratedJob(
+ key: string,
+ req: DownloadRequest,
+ attempt: number,
+): Promise<void> {
+ const job = getState().jobs[key];
+ if (!job || !ACTIVE_STATES.has(job.state)) return;
+ try {
+ const status = await withHydrationTimeout((signal) =>
+ apiGetStatus(job, signal),
+ );
+ const current = getState().jobs[key];
+ if (!current || !ACTIVE_STATES.has(current.state)) return;
+ await settleHydratedJob(key, req, status);
+ } catch (error) {
+ if (isRequestTimeout(error) && attempt < HYDRATE_STATUS_TIMEOUT_RETRIES) {
+ scheduleHydrationProbeRetry(key, req, attempt + 1);
+ return;
+ }
+ adoptJob(req);
+ }
+}
+
+export function hydrateDownloadManager(): void {
+ if (hydrated) return;
+ hydrated = true;
+ void hydrateBackendActiveDownloads();
+ const jobs = Object.values(getState().jobs);
+ for (const job of jobs) {
+ if (!ACTIVE_STATES.has(job.state)) {
+ removeJob(job.key);
+ continue;
+ }
+ const req: DownloadRequest = {
+ kind: job.kind,
+ repoId: job.repoId,
+ variant: job.variant,
+ expectedBytes: job.expectedBytes,
+ };
+ void probeHydratedJob(job.key, req, 0);
+ }
+}
+
+export function resetHydrationState(): void {
+ hydrated = false;
+}
diff --git a/studio/frontend/src/features/hub/download-manager/index.ts b/studio/frontend/src/features/hub/download-manager/index.ts
new file mode 100644
index 00000000000..60ef3851f89
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/index.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export * from "./api";
+export { DownloadManagerPanel } from "./download-manager-panel";
+export {
+ DownloadProgressBar,
+ type DownloadProgress,
+} from "./download-progress-bar";
+export {
+ DEFAULT_TRANSPORT_MODE,
+ DOWNLOAD_KIND,
+ DOWNLOAD_KINDS,
+ TRANSPORT,
+ TRANSPORT_MODES,
+ isDownloadKind,
+ isTransportMode,
+ type DownloadKind,
+ type TransportMode,
+} from "./constants";
+export {
+ __resetDownloadManagerForTests,
+ clearCompletedInventoryHint,
+ downloadManager,
+ hydrateDownloadManager,
+ jobKeyOf,
+ repoKeyOf,
+ selectActiveJob,
+ subscribeJobListeners,
+ useDownloadManagerStore,
+ type DownloadManagerController,
+ type DownloadRequest,
+ type JobListeners,
+ type ManagedDownload,
+} from "./download-manager-controller";
+export {
+ useRepoDownload,
+ type DownloadJob,
+ type DownloadJobProgress,
+ type RepoDownloadConfig,
+} from "./use-repo-download";
+export {
+ getTransportMode,
+ useDownloadTransportCapabilities,
+ useTransportMode,
+} from "./transport-preference";
+export type { TransportConflictInfo } from "./types";
diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
new file mode 100644
index 00000000000..95df4afd31f
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
@@ -0,0 +1,955 @@
+// 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 { invalidateGgufVariantsCache } from "../inventory/api";
+import { getHfToken } from "../stores/hf-token-store";
+import { bumpInventoryVersion } from "../stores/inventory-events";
+import { toast } from "@/lib/toast";
+import {
+ getActiveModelDownloads,
+ getDatasetDownloadStatus,
+ type ActiveModelDownload,
+ type DownloadJobState,
+} from "./api";
+import {
+ CANCELLED_LINGER_MS,
+ CANCEL_WATCHDOG_MS,
+ COMPLETE_LINGER_MS,
+ ERROR_LINGER_MS,
+ HIDDEN_POLL_INTERVAL_MS,
+ IDLE_EVICT_GRACE_MS,
+ INVENTORY_BUMP_DEBOUNCE_MS,
+ MAX_PROGRESS_FRACTION,
+ POLL_BACKOFF_AFTER_MS,
+ POLL_BACKOFF_INTERVAL_MS,
+ POLL_DEGRADED_AFTER_MS,
+ POLL_DEGRADED_MESSAGE,
+ POLL_INTERVAL_MS,
+ POLL_JITTER_MS,
+ PROGRESS_POLL_BACKOFF_INTERVAL_MS,
+ PROGRESS_POLL_INTERVAL_MS,
+ SPEED_EMA_WEIGHT,
+ ACTIVE_STATES,
+ TERMINAL_DISPLAY_STATES,
+} from "./download-manager-config";
+import {
+ DOWNLOAD_KIND,
+ TRANSPORT,
+ type DownloadKind,
+ type TransportMode,
+} from "./constants";
+import {
+ apiCancel,
+ apiCancelRequest,
+ apiGetProgress,
+ apiGetStatus,
+ apiStart,
+ describeUnacceptedStart,
+ effectiveTransportMode,
+ normalizeDownloadError,
+ pollAccessErrorMessage,
+ withPollRequestTimeout,
+} from "./download-api-adapter";
+import type {
+ DownloadRequest,
+ JobListeners,
+ JobRuntime,
+ ManagedDownload,
+ ProgressLike,
+ Terminal,
+} from "./download-manager-types";
+import {
+ getState,
+ hasActiveRepoPeer,
+ isCurrent,
+ jobKeyOf,
+ patchJob,
+ putJob,
+ removeJob,
+ repoKeyOf,
+ scheduleRemoval,
+ setExpectedBytesForJob,
+} from "./download-manager-state";
+import {
+ clearWatchdog,
+ runtimeRegistry,
+ teardownRuntime,
+} from "./runtime-registry";
+import { getTransportMode } from "./transport-preference";
+
+function notify(
+ job: ManagedDownload,
+ event: keyof JobListeners,
+ bytes: number,
+): void {
+ const set = runtimeRegistry.listeners.get(repoKeyOf(job.kind, job.repoId));
+ if (!set) return;
+ for (const handlers of [...set]) {
+ try {
+ if (event === "onComplete")
+ void handlers.onComplete?.(job.variant, bytes);
+ else if (event === "onCancelled")
+ void handlers.onCancelled?.(job.variant);
+ else void handlers.onError?.(job.variant);
+ } catch (error) {
+ console.warn("Download job listener failed", {
+ kind: job.kind,
+ repoId: job.repoId,
+ variant: job.variant,
+ event,
+ error,
+ });
+ }
+ }
+}
+
+function scheduleInventoryBump(): void {
+ if (typeof window === "undefined") {
+ bumpInventoryVersion();
+ return;
+ }
+ if (runtimeRegistry.inventoryBumpTimer !== null) {
+ window.clearTimeout(runtimeRegistry.inventoryBumpTimer);
+ }
+ runtimeRegistry.inventoryBumpTimer = window.setTimeout(() => {
+ runtimeRegistry.inventoryBumpTimer = null;
+ bumpInventoryVersion();
+ }, INVENTORY_BUMP_DEBOUNCE_MS);
+}
+
+function withDownloadTimeout<T>(
+ request: (signal: AbortSignal) => Promise<T>,
+): Promise<T> {
+ return withPollRequestTimeout(null, request);
+}
+
+export function hasObservedExpectedBytes(job: ManagedDownload): boolean {
+ // Finalized bytes only: a partial whose `.incomplete` blob merely reached the
+ // expected size must not count as finished; the backend must also verify it on disk.
+ return (
+ job.expectedBytes > 0 &&
+ job.completedBytes >= job.expectedBytes &&
+ job.completeOnDisk
+ );
+}
+
+export function resolveProgressUpdate(
+ job: ManagedDownload,
+ progressResp: ProgressLike,
+ opts: { resetMonotonic?: boolean } = {},
+): {
+ expected: number;
+ downloadedBytes: number;
+ completedBytes: number;
+ completeOnDisk: boolean;
+ fraction: number;
+ madeProgress: boolean;
+} {
+ const reported = progressResp.expected_bytes;
+ const isGgufVariantJob =
+ job.kind === DOWNLOAD_KIND.MODEL && job.variant !== null;
+ const backendOwnsGgufProgress = isGgufVariantJob && reported > 0;
+ // GGUF totals are backend-owned (non-monotonic). Snapshots keep the displayed
+ // total monotonic to absorb jitter, but a fresh attempt (generation changed:
+ // XET redownload, restart, re-adoption) drops the stale high-water mark.
+ const trustBackend = backendOwnsGgufProgress || opts.resetMonotonic === true;
+ const expected = trustBackend
+ ? reported > 0
+ ? reported
+ : job.expectedBytes
+ : Math.max(reported > 0 ? reported : job.expectedBytes, job.expectedBytes);
+ const previousDownloadedBytes = job.downloadedBytes;
+ const downloadedBytes = trustBackend
+ ? Math.max(0, progressResp.downloaded_bytes)
+ : Math.max(previousDownloadedBytes, progressResp.downloaded_bytes);
+ const completedBytes = trustBackend
+ ? Math.max(0, progressResp.completed_bytes ?? 0)
+ : Math.max(job.completedBytes, progressResp.completed_bytes ?? 0);
+ const completeOnDisk = progressResp.complete_on_disk === true;
+ const madeProgress =
+ opts.resetMonotonic === true ||
+ downloadedBytes > previousDownloadedBytes ||
+ expected !== job.expectedBytes;
+ const rawFraction =
+ progressResp.progress > 0
+ ? progressResp.progress
+ : expected > 0
+ ? downloadedBytes / expected
+ : 0;
+ const cappedFraction = Math.min(rawFraction, MAX_PROGRESS_FRACTION);
+ // Keep the GGUF variant bar monotonic: its backend progress is recomputed from
+ // the shared per-repo blobs/ dir each poll, so a sibling quant or generation
+ // bump can make one reading dip. A fresh download resets via startJob's seed.
+ const fraction = isGgufVariantJob
+ ? Math.max(cappedFraction, job.fraction)
+ : cappedFraction;
+ return {
+ expected,
+ downloadedBytes,
+ completedBytes,
+ completeOnDisk,
+ fraction,
+ madeProgress,
+ };
+}
+
+export function applyProgressUpdate(
+ key: string,
+ job: ManagedDownload,
+ progressResp: ProgressLike,
+): ReturnType<typeof resolveProgressUpdate> {
+ const resolved = resolveProgressUpdate(job, progressResp);
+ patchJob(key, {
+ expectedBytes: resolved.expected,
+ downloadedBytes: resolved.downloadedBytes,
+ completedBytes: resolved.completedBytes,
+ completeOnDisk: resolved.completeOnDisk,
+ fraction: resolved.fraction,
+ });
+ return resolved;
+}
+
+function progressPollDelayMs(rt: JobRuntime): number {
+ return Date.now() - rt.pollStartedAt >= POLL_BACKOFF_AFTER_MS
+ ? PROGRESS_POLL_BACKOFF_INTERVAL_MS
+ : PROGRESS_POLL_INTERVAL_MS;
+}
+
+function shouldPollProgress(rt: JobRuntime, force: boolean): boolean {
+ if (force || rt.lastProgressPollAt === null) {
+ return true;
+ }
+ return Date.now() - rt.lastProgressPollAt >= progressPollDelayMs(rt);
+}
+
+function markPollSuccess(key: string, rt: JobRuntime): void {
+ rt.pollFailureStartedAt = null;
+ const job = getState().jobs[key];
+ if (job?.error === POLL_DEGRADED_MESSAGE && ACTIVE_STATES.has(job.state)) {
+ patchJob(key, { error: null });
+ }
+}
+
+function markPollFailure(key: string, rt: JobRuntime): void {
+ const now = Date.now();
+ rt.pollFailureStartedAt ??= now;
+ if (now - rt.pollFailureStartedAt < POLL_DEGRADED_AFTER_MS) return;
+ rt.speedSample = null;
+ patchJob(key, {
+ error: POLL_DEGRADED_MESSAGE,
+ bytesPerSec: 0,
+ });
+}
+
+export function finalize(
+ key: string,
+ outcome: Terminal,
+ opts: { bytes?: number; error?: string | null } = {},
+): void {
+ const job = getState().jobs[key];
+ teardownRuntime(key);
+ if (!job) return;
+ if (TERMINAL_DISPLAY_STATES.has(job.state)) return;
+ if (job.kind === DOWNLOAD_KIND.MODEL) {
+ invalidateGgufVariantsCache(job.repoId);
+ }
+ if (outcome === "gone") {
+ notify(job, "onCancelled", 0);
+ removeJob(key);
+ } else if (outcome === "complete") {
+ // Reconcile to the largest known figure so a terminal status arriving before
+ // the final progress poll doesn't leave a stale sub-total: downloaded ==
+ // completed >= expected, fraction 1, and report that figure to listeners.
+ const bytes = Math.max(
+ opts.bytes ?? 0,
+ job.downloadedBytes,
+ job.completedBytes,
+ job.expectedBytes,
+ );
+ patchJob(key, {
+ state: "complete",
+ fraction: 1,
+ downloadedBytes: bytes,
+ completedBytes: bytes,
+ completeOnDisk: true,
+ bytesPerSec: 0,
+ error: null,
+ });
+ notify(job, "onComplete", bytes);
+ scheduleRemoval(key, COMPLETE_LINGER_MS);
+ } else if (outcome === "cancelled") {
+ patchJob(key, { state: "cancelled", bytesPerSec: 0, error: null });
+ notify(job, "onCancelled", 0);
+ scheduleRemoval(key, CANCELLED_LINGER_MS);
+ } else {
+ const rawError =
+ typeof opts.error === "string" && opts.error
+ ? opts.error
+ : "Download failed";
+ patchJob(key, {
+ state: "error",
+ error:
+ opts.error === null ? null : (pollAccessErrorMessage(rawError) ?? rawError),
+ bytesPerSec: 0,
+ });
+ notify(job, "onError", 0);
+ scheduleRemoval(key, ERROR_LINGER_MS);
+ }
+ scheduleInventoryBump();
+}
+
+type PollStatus = Awaited<ReturnType<typeof apiGetStatus>>;
+
+function terminalKindFromState(state: DownloadJobState): Terminal | null {
+ return state === "complete"
+ ? "complete"
+ : state === "error"
+ ? "error"
+ : state === "cancelled"
+ ? "cancelled"
+ : null;
+}
+
+function syncServerGeneration(
+ key: string,
+ job: ManagedDownload,
+ status: PollStatus,
+): boolean {
+ const statusGeneration = status.generation;
+ const previousGeneration = job.serverGeneration;
+ const generationChanged =
+ typeof statusGeneration === "number" &&
+ Number.isSafeInteger(statusGeneration) &&
+ typeof previousGeneration === "number" &&
+ Number.isSafeInteger(previousGeneration) &&
+ statusGeneration !== previousGeneration;
+ if (
+ typeof statusGeneration === "number" &&
+ Number.isSafeInteger(statusGeneration)
+ ) {
+ patchJob(key, { serverGeneration: statusGeneration });
+ }
+ return generationChanged;
+}
+
+async function finalizeTerminalStatus(
+ key: string,
+ terminalKind: Terminal,
+ status: PollStatus,
+ abort: AbortController | null,
+ epoch: number,
+): Promise<void> {
+ const current = getState().jobs[key];
+ if (!current) return;
+ if (terminalKind === "complete") {
+ let finalBytes = current.downloadedBytes;
+ try {
+ const progressResp = await withPollRequestTimeout(abort, (signal) =>
+ apiGetProgress(current, signal),
+ );
+ if (!isCurrent(key, epoch)) return;
+ const latest = getState().jobs[key];
+ if (latest) {
+ const { downloadedBytes } = applyProgressUpdate(key, latest, progressResp);
+ finalBytes = downloadedBytes;
+ }
+ } catch {
+ // Terminal status is authoritative; progress reconciliation is best-effort.
+ }
+ finalize(key, "complete", { bytes: finalBytes });
+ } else if (terminalKind === "error") {
+ finalize(key, "error", { error: status.error ?? null });
+ } else {
+ finalize(key, "cancelled");
+ }
+}
+
+function applySpeedSample(
+ rt: JobRuntime,
+ current: ManagedDownload,
+ downloadedBytes: number,
+ nowMs: number,
+): number {
+ const last = rt.speedSample;
+ let bytesPerSec = last ? current.bytesPerSec : 0;
+ if (last) {
+ const dt = (nowMs - last.tMs) / 1000;
+ const db = Math.max(0, downloadedBytes - last.bytes);
+ if (dt > 0) {
+ const sample = db / dt;
+ bytesPerSec =
+ bytesPerSec > 0
+ ? bytesPerSec * SPEED_EMA_WEIGHT + sample * (1 - SPEED_EMA_WEIGHT)
+ : sample;
+ }
+ }
+ rt.speedSample = { bytes: downloadedBytes, tMs: nowMs };
+ return bytesPerSec;
+}
+
+function reconcileProgressAndSpeed(
+ rt: JobRuntime,
+ key: string,
+ current: ManagedDownload,
+ progressResp: ProgressLike,
+ generationChanged: boolean,
+): { madeProgress: boolean } {
+ const { expected, downloadedBytes, completedBytes, completeOnDisk, fraction, madeProgress } =
+ resolveProgressUpdate(current, progressResp, {
+ resetMonotonic: generationChanged,
+ });
+ const bytesPerSec = applySpeedSample(rt, current, downloadedBytes, Date.now());
+ patchJob(key, {
+ expectedBytes: expected,
+ downloadedBytes,
+ completedBytes,
+ completeOnDisk,
+ fraction,
+ bytesPerSec,
+ });
+ markPollSuccess(key, rt);
+ return { madeProgress };
+}
+
+function handleIdleAfterProgress(
+ rt: JobRuntime,
+ key: string,
+ madeProgress: boolean,
+): void {
+ const updatedJob = getState().jobs[key];
+ if (updatedJob && hasObservedExpectedBytes(updatedJob)) {
+ finalize(key, "complete", { bytes: updatedJob.downloadedBytes });
+ } else if (rt.cancelRequested) {
+ finalize(key, "cancelled");
+ } else if (madeProgress) {
+ rt.idleSinceMs = null;
+ } else {
+ rt.idleSinceMs ??= Date.now();
+ if (Date.now() - rt.idleSinceMs >= IDLE_EVICT_GRACE_MS) {
+ finalize(key, "gone");
+ }
+ }
+}
+
+function handleTickError(
+ key: string,
+ rt: JobRuntime,
+ epoch: number,
+ error: unknown,
+): void {
+ if (!isCurrent(key, epoch)) return;
+ const accessMessage = pollAccessErrorMessage(
+ error instanceof Error ? error.message : String(error ?? ""),
+ );
+ if (accessMessage) {
+ finalize(key, "error", { error: accessMessage });
+ return;
+ }
+ markPollFailure(key, rt);
+}
+
+async function tick(key: string): Promise<void> {
+ const rt = runtimeRegistry.runtimes.get(key);
+ if (!rt) return;
+ const job = getState().jobs[key];
+ if (!job) {
+ teardownRuntime(key);
+ return;
+ }
+ if (typeof document !== "undefined" && document.hidden) {
+ rt.speedSample = null;
+ return;
+ }
+ if (rt.inFlight) return;
+ rt.inFlight = true;
+ const epoch = rt.epoch;
+ const abort = rt.abort;
+ try {
+ const status = await withPollRequestTimeout(abort, (signal) =>
+ apiGetStatus(job, signal),
+ );
+ if (!isCurrent(key, epoch)) return;
+
+ const generationChanged = syncServerGeneration(key, job, status);
+
+ const terminalKind = terminalKindFromState(status.state);
+ if (terminalKind !== null) {
+ await finalizeTerminalStatus(key, terminalKind, status, abort, epoch);
+ return;
+ }
+
+ if (status.state === "idle") {
+ const observedJob = getState().jobs[key];
+ if (observedJob && hasObservedExpectedBytes(observedJob)) {
+ finalize(key, "complete", { bytes: observedJob.downloadedBytes });
+ return;
+ }
+ }
+
+ const forceProgress = status.state === "idle";
+ if (!shouldPollProgress(rt, forceProgress)) {
+ rt.idleSinceMs = null;
+ markPollSuccess(key, rt);
+ return;
+ }
+ rt.lastProgressPollAt = Date.now();
+ const jobForProgress = getState().jobs[key] ?? job;
+ const progressResp = await withPollRequestTimeout(abort, (signal) =>
+ apiGetProgress(jobForProgress, signal),
+ );
+ if (!isCurrent(key, epoch)) return;
+ const current = getState().jobs[key];
+ if (!current) return;
+
+ const { madeProgress } = reconcileProgressAndSpeed(
+ rt,
+ key,
+ current,
+ progressResp,
+ generationChanged,
+ );
+
+ if (status.state === "idle") {
+ handleIdleAfterProgress(rt, key, madeProgress);
+ } else {
+ rt.idleSinceMs = null;
+ }
+ } catch (error) {
+ handleTickError(key, rt, epoch, error);
+ } finally {
+ rt.inFlight = false;
+ }
+}
+
+function pollDelayMs(rt: JobRuntime): number {
+ if (typeof document !== "undefined" && document.hidden) {
+ return HIDDEN_POLL_INTERVAL_MS;
+ }
+ const elapsedMs = Date.now() - rt.pollStartedAt;
+ const base =
+ elapsedMs >= POLL_BACKOFF_AFTER_MS
+ ? POLL_BACKOFF_INTERVAL_MS
+ : POLL_INTERVAL_MS;
+ const jitter = Math.round((Math.random() * 2 - 1) * POLL_JITTER_MS);
+ return Math.max(100, base + jitter);
+}
+
+async function runPollTick(key: string): Promise<void> {
+ const startedRuntime = runtimeRegistry.runtimes.get(key);
+ const epoch = startedRuntime?.epoch;
+ try {
+ await tick(key);
+ } finally {
+ const rt = runtimeRegistry.runtimes.get(key);
+ if (
+ startedRuntime !== undefined &&
+ epoch !== undefined &&
+ rt === startedRuntime &&
+ isCurrent(key, epoch)
+ ) {
+ rt.pollTimer = window.setTimeout(
+ () => void runPollTick(key),
+ pollDelayMs(rt),
+ );
+ }
+ }
+}
+
+function beginPolling(key: string, rt: JobRuntime): void {
+ rt.pollingStarted = true;
+ if (typeof document !== "undefined") {
+ const epoch = rt.epoch;
+ rt.visibilityListener = () => {
+ if (document.hidden || !isCurrent(key, epoch)) return;
+ const live = runtimeRegistry.runtimes.get(key);
+ if (live !== rt) return;
+ if (live.inFlight) return;
+ if (live.pollTimer != null) {
+ window.clearTimeout(live.pollTimer);
+ live.pollTimer = null;
+ }
+ void runPollTick(key);
+ };
+ document.addEventListener("visibilitychange", rt.visibilityListener);
+ }
+ void runPollTick(key);
+}
+
+function reissueDroppedStartCancel(
+ req: DownloadRequest,
+ generation: number | undefined,
+): void {
+ if (!Number.isSafeInteger(generation)) {
+ return;
+ }
+ void withDownloadTimeout(async (signal) => {
+ await apiCancelRequest(req, generation, signal);
+ }).catch(() => {});
+}
+
+export async function startJob(
+ req: DownloadRequest,
+ opts: {
+ adopt?: boolean;
+ useXet?: boolean;
+ generation?: number;
+ state?: DownloadJobState;
+ } = {},
+): Promise<void> {
+ const key = jobKeyOf(req.kind, req.repoId, req.variant);
+ // Peer guard stops a FRESH start from double-starting a variant already
+ // downloading (or colliding with a no-variant snapshot). Skipped when ADOPTING:
+ // the restored own entry would look like a peer and freeze the bar; adoptJob's
+ // `pollingStarted` guard already prevents double-polling the same key.
+ if (!opts.adopt && hasActiveRepoPeer(req.kind, req.repoId, key, req.variant)) {
+ return;
+ }
+ const nextEpoch = (runtimeRegistry.runtimes.get(key)?.epoch ?? 0) + 1;
+ teardownRuntime(key);
+ const existing = getState().jobs[key];
+ const adoptingCancel =
+ opts.adopt === true &&
+ (opts.state === "cancelling" ||
+ (opts.state === undefined && existing?.state === "cancelling"));
+ const rt: JobRuntime = {
+ kind: req.kind,
+ repoId: req.repoId,
+ epoch: nextEpoch,
+ pollTimer: null,
+ pollStartedAt: Date.now(),
+ pollingStarted: false,
+ abort: new AbortController(),
+ inFlight: false,
+ cancelRequested: adoptingCancel,
+ watchdog: null,
+ speedSample: null,
+ idleSinceMs: null,
+ lastProgressPollAt: null,
+ pollFailureStartedAt: null,
+ visibilityListener: null,
+ };
+ runtimeRegistry.runtimes.set(key, rt);
+ const epoch = rt.epoch;
+
+ const expected = Math.max(existing?.expectedBytes ?? 0, req.expectedBytes);
+ const hfToken = getHfToken() || null;
+ const requestedUseXet = opts.useXet ?? (getTransportMode() === TRANSPORT.XET);
+ const requestedMode: TransportMode = requestedUseXet
+ ? TRANSPORT.XET
+ : TRANSPORT.HTTP;
+ let mode: TransportMode;
+ try {
+ mode = opts.adopt
+ ? TRANSPORT.HTTP
+ : await effectiveTransportMode(requestedMode);
+ } catch (error) {
+ teardownRuntime(key);
+ throw error;
+ }
+ const seedDownloaded = opts.adopt ? (existing?.downloadedBytes ?? 0) : 0;
+ const seedCompleted = opts.adopt ? (existing?.completedBytes ?? 0) : 0;
+ const seedFraction = opts.adopt ? (existing?.fraction ?? 0) : 0;
+ // An adopted job never called apiStart, so it learns the run's generation from
+ // the probe (or persisted value) to scope a later cancel to this exact run.
+ const seedGeneration = opts.adopt
+ ? Number.isSafeInteger(opts.generation)
+ ? opts.generation
+ : existing?.serverGeneration
+ : undefined;
+ if (!opts.adopt && hasActiveRepoPeer(req.kind, req.repoId, key, req.variant)) {
+ teardownRuntime(key);
+ return;
+ }
+ putJob({
+ key,
+ kind: req.kind,
+ repoId: req.repoId,
+ variant: req.variant,
+ state: adoptingCancel ? "cancelling" : "running",
+ downloadedBytes: seedDownloaded,
+ completedBytes: seedCompleted,
+ completeOnDisk: false,
+ expectedBytes: expected,
+ fraction: seedFraction,
+ bytesPerSec: 0,
+ error: null,
+ startedAt: opts.adopt ? (existing?.startedAt ?? Date.now()) : Date.now(),
+ ...(Number.isSafeInteger(seedGeneration)
+ ? { serverGeneration: seedGeneration }
+ : {}),
+ });
+
+ if (!opts.adopt) {
+ let result;
+ try {
+ result = await apiStart(req, mode === TRANSPORT.XET, hfToken);
+ } catch (err) {
+ if (!isCurrent(key, epoch)) return;
+ finalize(key, "error", {
+ error: normalizeDownloadError(err),
+ });
+ return;
+ }
+ // A cancel pressed during this apiStart round-trip can land before the job is
+ // claimable; re-issue against the accepted generation.
+ if (rt.cancelRequested && result.accepted) {
+ reissueDroppedStartCancel(req, result.generation);
+ }
+ if (!isCurrent(key, epoch)) return;
+ if (!result.accepted) {
+ finalize(key, "error", { error: describeUnacceptedStart(result.state) });
+ return;
+ }
+ if (Number.isSafeInteger(result.generation)) {
+ patchJob(key, { serverGeneration: result.generation });
+ }
+ }
+
+ beginPolling(key, rt);
+}
+
+function armCancelWatchdog(
+ key: string,
+ rt: JobRuntime,
+ cancelEpoch: number,
+): void {
+ rt.watchdog = window.setTimeout(() => {
+ void resolveCancelWatchdog(key, cancelEpoch);
+ }, CANCEL_WATCHDOG_MS);
+}
+
+async function resolveCancelWatchdog(
+ key: string,
+ cancelEpoch: number,
+): Promise<void> {
+ const rt = runtimeRegistry.runtimes.get(key);
+ if (!rt || rt.epoch !== cancelEpoch || !rt.cancelRequested) return;
+ const job = getState().jobs[key];
+ if (!job) return;
+ const probe = await probeCancelOutcome(key, job, rt, cancelEpoch);
+ if (probe === "stale") return;
+ const live = runtimeRegistry.runtimes.get(key);
+ if (!live || live.epoch !== cancelEpoch || !live.cancelRequested) return;
+ if (probe.terminal === "complete") {
+ finalize(key, "complete", { bytes: getState().jobs[key]?.downloadedBytes ?? 0 });
+ } else if (probe.terminal === "error") {
+ finalize(key, "error", { error: probe.error });
+ } else {
+ finalize(key, "cancelled");
+ }
+}
+
+function applyCancelResult(
+ key: string,
+ cancelEpoch: number,
+ result: { state: DownloadJobState },
+): void {
+ const live = runtimeRegistry.runtimes.get(key);
+ if (live && live.epoch !== cancelEpoch) return;
+ if (result.state === "cancelling" || result.state === "cancelled") {
+ if (!live || !live.pollingStarted) finalize(key, "cancelled");
+ return;
+ }
+ if (live) {
+ if (result.state !== "idle") {
+ live.cancelRequested = false;
+ }
+ clearWatchdog(live);
+ }
+ if (result.state === "complete") {
+ finalize(key, "complete", {
+ bytes: getState().jobs[key]?.downloadedBytes ?? 0,
+ });
+ } else if (result.state === "error") {
+ finalize(key, "error");
+ } else if (result.state === "idle") {
+ const current = getState().jobs[key];
+ finalize(
+ key,
+ current && hasObservedExpectedBytes(current) ? "complete" : "cancelled",
+ );
+ } else if (live?.pollingStarted) {
+ patchJob(key, { state: "running" });
+ toast.error("Couldn't cancel the download. It's still running.");
+ } else {
+ finalize(key, "cancelled");
+ }
+}
+
+type CancelProbeResult = { terminal: Terminal | null; error: string | null };
+
+async function probeCancelOutcome(
+ key: string,
+ job: ManagedDownload,
+ rt: JobRuntime | undefined,
+ cancelEpoch: number,
+): Promise<CancelProbeResult | "stale"> {
+ try {
+ const probe = await withDownloadTimeout((signal) => apiGetStatus(job, signal));
+ if (probe.state === "complete") {
+ return { terminal: "complete", error: null };
+ }
+ if (probe.state === "error") {
+ return { terminal: "error", error: probe.error ?? null };
+ }
+ if (probe.state === "cancelled") {
+ return { terminal: "cancelled", error: null };
+ }
+ if (probe.state === "idle") {
+ const current = getState().jobs[key];
+ if (current && hasObservedExpectedBytes(current)) {
+ return { terminal: "complete", error: null };
+ }
+ if (current) {
+ try {
+ const progressResp = await withDownloadTimeout((signal) =>
+ apiGetProgress(current, signal),
+ );
+ const liveAfterProgress = runtimeRegistry.runtimes.get(key);
+ if (rt && liveAfterProgress && liveAfterProgress.epoch !== cancelEpoch) {
+ return "stale";
+ }
+ const latest = getState().jobs[key];
+ if (latest) {
+ applyProgressUpdate(key, latest, progressResp);
+ const updated = getState().jobs[key];
+ return {
+ terminal:
+ updated && hasObservedExpectedBytes(updated)
+ ? "complete"
+ : "cancelled",
+ error: null,
+ };
+ }
+ return { terminal: "cancelled", error: null };
+ } catch {
+ return { terminal: "cancelled", error: null };
+ }
+ }
+ return { terminal: "cancelled", error: null };
+ }
+ return { terminal: null, error: null };
+ } catch {
+ return { terminal: null, error: null };
+ }
+}
+
+export async function cancelJob(key: string): Promise<void> {
+ const job = getState().jobs[key];
+ if (!job) return;
+ const rt = runtimeRegistry.runtimes.get(key);
+ const cancelEpoch = rt?.epoch ?? 0;
+ if (rt) rt.cancelRequested = true;
+ patchJob(key, { state: "cancelling" });
+ clearWatchdog(rt);
+ if (rt) armCancelWatchdog(key, rt, cancelEpoch);
+ try {
+ const result = await withDownloadTimeout<{ state: DownloadJobState }>(
+ (signal) => apiCancel(job, signal),
+ );
+ applyCancelResult(key, cancelEpoch, result);
+ } catch (err) {
+ const liveAtError = runtimeRegistry.runtimes.get(key);
+ if (rt && liveAtError && liveAtError.epoch !== cancelEpoch) return;
+ // apiCancel failed; the probe below is authoritative. Disarm the watchdog so
+ // it can't finalize "cancelled" mid-probe and tear down a still-running worker.
+ clearWatchdog(liveAtError);
+
+ const probe = await probeCancelOutcome(key, job, rt, cancelEpoch);
+ if (probe === "stale") return;
+
+ const live = runtimeRegistry.runtimes.get(key);
+ if (rt && (!live || live.epoch !== cancelEpoch)) return;
+
+ if (probe.terminal !== null) {
+ if (probe.terminal === "complete") {
+ const current = getState().jobs[key];
+ finalize(key, "complete", { bytes: current?.downloadedBytes ?? 0 });
+ } else if (probe.terminal === "error") {
+ finalize(key, "error", { error: probe.error });
+ } else {
+ finalize(key, "cancelled");
+ }
+ return;
+ }
+
+ if (live) {
+ live.cancelRequested = false;
+ }
+ patchJob(key, { state: "running" });
+ toast.error("Couldn't cancel the download. It's still running.");
+ console.warn("Failed to cancel download", err);
+ }
+}
+
+export function adoptJob(
+ req: DownloadRequest,
+ generation?: number,
+ state?: DownloadJobState,
+): void {
+ const key = jobKeyOf(req.kind, req.repoId, req.variant);
+ if (runtimeRegistry.runtimes.get(key)?.pollingStarted) return;
+ void startJob(req, { adopt: true, generation, state });
+}
+
+type ProbeAndAdoptOptions = {
+ includeVariants?: boolean;
+ fresh?: boolean;
+ onModelAdopt?: (download: ActiveModelDownload) => void;
+};
+
+export async function probeAndAdopt(
+ kind: DownloadKind,
+ repoId: string,
+ signal: AbortSignal,
+ options: ProbeAndAdoptOptions = {},
+): Promise<void> {
+ try {
+ if (kind === DOWNLOAD_KIND.MODEL) {
+ const downloads = await getActiveModelDownloads(repoId, signal, {
+ fresh: options.fresh,
+ });
+ if (signal.aborted) return;
+ const activeDownloads = downloads.filter(
+ (download) =>
+ (options.includeVariants || download.variant === null) &&
+ (download.state === "running" || download.state === "cancelling"),
+ );
+ for (const active of activeDownloads) {
+ options.onModelAdopt?.(active);
+ adoptJob(
+ { kind, repoId, variant: active.variant, expectedBytes: 0 },
+ active.generation,
+ active.state,
+ );
+ }
+ return;
+ }
+
+ const status = await getDatasetDownloadStatus(repoId, signal);
+ if (signal.aborted) return;
+ if (status.state === "running" || status.state === "cancelling") {
+ adoptJob(
+ { kind, repoId, variant: null, expectedBytes: 0 },
+ status.generation,
+ status.state,
+ );
+ }
+ } catch (error) {
+ if (signal.aborted) {
+ return;
+ }
+ if (import.meta.env.DEV) {
+ console.debug("Download adoption probe failed", { kind, repoId, error });
+ }
+ }
+}
+
+export function setExpected(
+ kind: DownloadKind,
+ repoId: string,
+ variant: string | null,
+ bytes: number,
+): void {
+ setExpectedBytesForJob(kind, repoId, variant, bytes);
+}
diff --git a/studio/frontend/src/features/hub/download-manager/runtime-registry.ts b/studio/frontend/src/features/hub/download-manager/runtime-registry.ts
new file mode 100644
index 00000000000..0f203070b7a
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/runtime-registry.ts
@@ -0,0 +1,83 @@
+// 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 { JobListeners, JobRuntime } from "./download-manager-types";
+import { evictOldestUnprotected } from "../lib/lru-map";
+
+const MAX_SUPPRESSED_COMPLETED_INVENTORY_HINTS = 64;
+
+class DownloadManagerRuntimeRegistry {
+ readonly runtimes = new Map<string, JobRuntime>();
+ readonly listeners = new Map<string, Set<JobListeners>>();
+ readonly removalTimers = new Map<string, number>();
+ readonly hydrationRetryTimers = new Set<number>();
+ readonly suppressedCompletedInventoryHints = new Set<string>();
+ readonly pendingStartRepoKeys = new Set<string>();
+ inventoryBumpTimer: number | null = null;
+
+ clearRemovalTimer(key: string): void {
+ const timer = this.removalTimers.get(key);
+ if (timer === undefined) return;
+ clearRuntimeTimer(timer);
+ this.removalTimers.delete(key);
+ }
+
+ reset(): void {
+ for (const key of Array.from(this.runtimes.keys())) {
+ teardownRuntime(key);
+ }
+ for (const timer of this.removalTimers.values()) {
+ clearRuntimeTimer(timer);
+ }
+ for (const timer of this.hydrationRetryTimers) {
+ clearRuntimeTimer(timer);
+ }
+ clearRuntimeTimer(this.inventoryBumpTimer);
+ this.runtimes.clear();
+ this.listeners.clear();
+ this.removalTimers.clear();
+ this.hydrationRetryTimers.clear();
+ this.suppressedCompletedInventoryHints.clear();
+ this.pendingStartRepoKeys.clear();
+ this.inventoryBumpTimer = null;
+ }
+}
+
+export const runtimeRegistry = new DownloadManagerRuntimeRegistry();
+
+export function clearRuntimeTimer(timer: number | null): void {
+ if (timer === null) return;
+ if (typeof window !== "undefined") {
+ window.clearTimeout(timer);
+ } else {
+ globalThis.clearTimeout(timer);
+ }
+}
+
+export function clearWatchdog(rt: JobRuntime | undefined): void {
+ if (rt?.watchdog == null) return;
+ clearRuntimeTimer(rt.watchdog);
+ rt.watchdog = null;
+}
+
+export function teardownRuntime(key: string): void {
+ const rt = runtimeRegistry.runtimes.get(key);
+ if (!rt) return;
+ clearRuntimeTimer(rt.pollTimer);
+ if (rt.visibilityListener != null && typeof document !== "undefined") {
+ document.removeEventListener("visibilitychange", rt.visibilityListener);
+ }
+ rt.abort?.abort();
+ clearWatchdog(rt);
+ runtimeRegistry.runtimes.delete(key);
+}
+
+export function pruneSuppressedCompletedInventoryHints(
+ liveCompletedKeys: Set<string>,
+): void {
+ evictOldestUnprotected(
+ runtimeRegistry.suppressedCompletedInventoryHints,
+ MAX_SUPPRESSED_COMPLETED_INVENTORY_HINTS,
+ (key) => liveCompletedKeys.has(key),
+ );
+}
diff --git a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts
new file mode 100644
index 00000000000..684ef544a2b
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts
@@ -0,0 +1,201 @@
+// 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 { toast } from "@/lib/toast";
+import { disposableTimeoutSignal } from "../lib/abort-signals";
+import { getActiveModelDownloads } from "./api";
+import { TRANSPORT, type TransportMode } from "./constants";
+import {
+ apiTransportStatusWithRetry,
+ effectiveTransportMode,
+} from "./download-api-adapter";
+import type { DownloadRequest } from "./download-manager-types";
+import {
+ findActiveJobForRepo,
+ getState,
+ hasVariantRepoActivity,
+ jobKeyOf,
+ repoKeyOf,
+ setConflict,
+} from "./download-manager-state";
+import { startJob } from "./poll-loop";
+import { runtimeRegistry } from "./runtime-registry";
+import { getTransportMode } from "./transport-preference";
+import { ACTIVE_STATES, TRANSPORT_STATUS_TIMEOUT_MS } from "./download-manager-config";
+
+function reportConflictStartError(error: unknown): void {
+ const description =
+ error instanceof Error ? error.message : String(error || "Unknown error");
+ toast.error("Couldn't start download", { description });
+}
+
+function pendingStartKey(req: DownloadRequest): string {
+ return jobKeyOf(req.kind, req.repoId, req.variant);
+}
+
+function hasPendingStartForRepo(repoKey: string): boolean {
+ for (const key of runtimeRegistry.pendingStartRepoKeys) {
+ if (key === repoKey || key.startsWith(`${repoKey}#`)) return true;
+ }
+ return false;
+}
+
+function hasActiveOrPendingStart(req: DownloadRequest): boolean {
+ const key = pendingStartKey(req);
+ if (req.kind === "model" && req.variant) {
+ return hasVariantRepoActivity(req.kind, req.repoId, key, {
+ includeOwnRuntime: true,
+ includePending: true,
+ });
+ }
+ if (runtimeRegistry.pendingStartRepoKeys.has(key)) return true;
+ const repoKey = repoKeyOf(req.kind, req.repoId);
+ if (hasPendingStartForRepo(repoKey)) return true;
+ return (
+ Boolean(findActiveJobForRepo(getState().jobs, req.kind, req.repoId)) ||
+ Boolean(runtimeRegistry.runtimes.get(repoKey))
+ );
+}
+
+function asTransportMode(value: unknown): TransportMode | null {
+ return value === TRANSPORT.HTTP || value === TRANSPORT.XET ? value : null;
+}
+
+async function activeSiblingTransport(
+ req: DownloadRequest,
+): Promise<TransportMode | null> {
+ if (req.kind !== "model" || !req.variant) return null;
+ const timeout = disposableTimeoutSignal(TRANSPORT_STATUS_TIMEOUT_MS);
+ const downloads = await getActiveModelDownloads(req.repoId, timeout.signal, {
+ fresh: true,
+ }).finally(() => timeout.dispose());
+ const variant = req.variant.trim().toLowerCase();
+ for (const download of downloads) {
+ const siblingVariant = download.variant?.trim().toLowerCase();
+ if (!siblingVariant || siblingVariant === variant) continue;
+ if (!ACTIVE_STATES.has(download.state)) continue;
+ const transport = asTransportMode(download.transport);
+ if (transport) return transport;
+ }
+ return null;
+}
+
+async function runWithPendingStartGuard(
+ req: DownloadRequest,
+ action: () => Promise<void>,
+): Promise<void> {
+ const startKey = pendingStartKey(req);
+ if (hasActiveOrPendingStart(req)) return;
+ runtimeRegistry.pendingStartRepoKeys.add(startKey);
+ try {
+ await action();
+ } catch (error) {
+ reportConflictStartError(error);
+ } finally {
+ runtimeRegistry.pendingStartRepoKeys.delete(startKey);
+ }
+}
+
+export async function requestStart(req: DownloadRequest): Promise<void> {
+ await runWithPendingStartGuard(req, async () => {
+ let mode: TransportMode = getTransportMode();
+ try {
+ mode = await effectiveTransportMode(mode);
+ } catch (err) {
+ console.warn(
+ "Transport capability check failed; using the selected transport.",
+ err,
+ );
+ }
+ let siblingTransport: TransportMode | null = null;
+ let siblingProbed = false;
+ try {
+ siblingTransport = await activeSiblingTransport(req);
+ siblingProbed = true;
+ if (siblingTransport && siblingTransport !== mode) {
+ toast.info("Another variant is already downloading", {
+ description:
+ siblingTransport === TRANSPORT.XET
+ ? "This repository is currently downloading with Xet. Switch to Xet or wait for it to finish."
+ : "This repository is currently downloading with HTTP. Switch to HTTP or wait for it to finish.",
+ });
+ return;
+ }
+ } catch (err) {
+ console.warn("Active download transport check failed.", err);
+ }
+ try {
+ const status = await apiTransportStatusWithRetry(req);
+ if (
+ status.has_partial &&
+ status.last_transport &&
+ status.last_transport !== mode
+ ) {
+ setConflict(jobKeyOf(req.kind, req.repoId, req.variant), {
+ info: {
+ previous: status.last_transport,
+ next: mode,
+ resumable: status.resumable,
+ },
+ pending: req,
+ });
+ return;
+ }
+ if (status.has_partial && !status.last_transport) {
+ toast.info("Restarting this download", {
+ description:
+ "An earlier partial download can't be resumed, so it will start again from the beginning.",
+ });
+ }
+ } catch (err) {
+ console.warn(
+ "Transport status check failed; starting without partial-conflict preflight.",
+ err,
+ );
+ // Fail safe: Xet purges any partial unconditionally, so when we couldn't
+ // verify the partial we downgrade this one start to HTTP (resumes an HTTP
+ // partial, harmless for a fresh download); the Xet preference is kept for
+ // next time. Only downgrade once we confirmed no sibling variant is
+ // downloading, since a live sibling may be mid-transfer on Xet.
+ if (mode === TRANSPORT.XET && siblingProbed && !siblingTransport) {
+ toast.warning("Couldn't verify existing partial download", {
+ description:
+ "Starting with HTTP so an existing partial is not discarded. Switch transport to retry with Xet.",
+ });
+ await startJob(req, { useXet: false });
+ return;
+ }
+ toast.warning("Couldn't verify existing partial download", {
+ description:
+ "Starting with the selected transport. If a partial from another transport exists, it may be restarted from the beginning.",
+ });
+ }
+ await startJob(req, { useXet: mode === TRANSPORT.XET });
+ });
+}
+
+export function resumeConflict(conflictKey: string): void {
+ const entry = getState().conflicts[conflictKey];
+ if (!entry) return;
+ setConflict(conflictKey, null);
+ void runWithPendingStartGuard(entry.pending, () =>
+ startJob(entry.pending, {
+ useXet: entry.info.previous === TRANSPORT.XET,
+ }),
+ );
+}
+
+export function restartConflict(conflictKey: string): void {
+ const entry = getState().conflicts[conflictKey];
+ if (!entry) return;
+ setConflict(conflictKey, null);
+ void runWithPendingStartGuard(entry.pending, () =>
+ startJob(entry.pending, {
+ useXet: entry.info.next === TRANSPORT.XET,
+ }),
+ );
+}
+
+export function cancelConflict(conflictKey: string): void {
+ setConflict(conflictKey, null);
+}
diff --git a/studio/frontend/src/features/hub/download-manager/transport-preference.ts b/studio/frontend/src/features/hub/download-manager/transport-preference.ts
new file mode 100644
index 00000000000..a1af2a24703
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/transport-preference.ts
@@ -0,0 +1,110 @@
+// 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 { useCallback, useEffect, useState } from "react";
+import { toast } from "@/lib/toast";
+import {
+ type DownloadTransportCapabilities,
+ getDownloadTransportCapabilities,
+} from "./api";
+import {
+ DEFAULT_TRANSPORT_MODE,
+ type TransportMode,
+ isTransportMode,
+} from "./constants";
+export type { TransportMode } from "./constants";
+
+const STORAGE_KEY = "unsloth.studio.transportMode";
+const CHANGE_EVENT = "unsloth:transport-preference-change";
+
+type TransportCapabilitiesState = {
+ capabilities: DownloadTransportCapabilities | null;
+ isLoading: boolean;
+};
+
+function readStored(): TransportMode {
+ if (typeof window === "undefined") {
+ return DEFAULT_TRANSPORT_MODE;
+ }
+ try {
+ const raw = window.localStorage.getItem(STORAGE_KEY);
+ return isTransportMode(raw) ? raw : DEFAULT_TRANSPORT_MODE;
+ } catch {
+ return DEFAULT_TRANSPORT_MODE;
+ }
+}
+
+export function getTransportMode(): TransportMode {
+ return readStored();
+}
+
+export function useTransportMode(): [
+ TransportMode,
+ (next: TransportMode) => void,
+] {
+ const [mode, setMode] = useState<TransportMode>(readStored);
+
+ useEffect(() => {
+ const handleLocal = () => setMode(readStored());
+ const handleStorage = (event: StorageEvent) => {
+ if (event.storageArea !== window.localStorage) {
+ return;
+ }
+ if (event.key !== null && event.key !== STORAGE_KEY) {
+ return;
+ }
+ setMode(readStored());
+ };
+ window.addEventListener(CHANGE_EVENT, handleLocal);
+ window.addEventListener("storage", handleStorage);
+ return () => {
+ window.removeEventListener(CHANGE_EVENT, handleLocal);
+ window.removeEventListener("storage", handleStorage);
+ };
+ }, []);
+
+ const set = useCallback((next: TransportMode) => {
+ // Persist first, reflect after: the engine reads getTransportMode() fresh from
+ // localStorage at download time, so an optimistic setMode() before a failed
+ // write would show the new transport while downloads still used the old one.
+ try {
+ window.localStorage.setItem(STORAGE_KEY, next);
+ } catch {
+ toast.error("Couldn't save the download transport preference.");
+ return;
+ }
+ setMode(next);
+ window.dispatchEvent(new Event(CHANGE_EVENT));
+ }, []);
+
+ return [mode, set];
+}
+
+export function useDownloadTransportCapabilities(): TransportCapabilitiesState {
+ const [state, setState] = useState<TransportCapabilitiesState>({
+ capabilities: null,
+ isLoading: true,
+ });
+
+ useEffect(() => {
+ let cancelled = false;
+ getDownloadTransportCapabilities()
+ .then((capabilities) => {
+ if (cancelled) {
+ return;
+ }
+ setState({ capabilities, isLoading: false });
+ })
+ .catch(() => {
+ if (cancelled) {
+ return;
+ }
+ setState({ capabilities: null, isLoading: false });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ return state;
+}
diff --git a/studio/frontend/src/features/hub/download-manager/types.ts b/studio/frontend/src/features/hub/download-manager/types.ts
new file mode 100644
index 00000000000..b2bf9d6a961
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/types.ts
@@ -0,0 +1,10 @@
+// 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 { TransportMode } from "./constants";
+
+export interface TransportConflictInfo {
+ previous: TransportMode;
+ next: TransportMode;
+ resumable: boolean;
+}
diff --git a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts b/studio/frontend/src/features/hub/download-manager/use-repo-download.ts
new file mode 100644
index 00000000000..374e6b1f449
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/use-repo-download.ts
@@ -0,0 +1,190 @@
+// 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 { useCallback, useEffect, useMemo } from "react";
+import { useShallow } from "zustand/react/shallow";
+import { useLatestRef } from "../hooks/use-latest-ref";
+import type { TransportConflictInfo } from "./types";
+import {
+ type DownloadKind,
+ type JobListeners,
+ downloadManager,
+ jobKeyOf,
+ selectActiveJob,
+ subscribeJobListeners,
+ useDownloadManagerStore,
+} from "./download-manager-controller";
+
+export interface DownloadJobProgress {
+ variant: string | null;
+ expectedBytes: number;
+ downloadedBytes: number;
+ fraction: number;
+}
+
+export interface DownloadJob {
+ progress: DownloadJobProgress | null;
+ bytesPerSec: number;
+ cancelling: boolean;
+ repoPeerActive: boolean;
+ transportConflict: TransportConflictInfo | null;
+ requestStartDownload: (
+ variant: string | null,
+ expectedBytes: number,
+ ) => Promise<void>;
+ cancelDownload: (variant: string | null) => void;
+ setExpectedBytes: (bytes: number, variant?: string | null) => void;
+ resumeConflict: () => void;
+ restartConflict: () => void;
+ cancelConflict: () => void;
+}
+
+export interface RepoDownloadConfig {
+ kind: DownloadKind;
+ repoId: string;
+ activeVariant?: string | null;
+ onComplete?: JobListeners["onComplete"];
+ onCancelled?: JobListeners["onCancelled"];
+ onError?: JobListeners["onError"];
+ // Attach to a no-variant backend download already running (GGUF surfaces adopt their own variant).
+ autoAdopt?: boolean;
+}
+
+/**
+ * Binds a single download surface (one repo, optionally per GGUF variant) to the
+ * global download manager. Job state and polling live in the store, so a download
+ * keeps running and stays visible after the card unmounts.
+ */
+export function useRepoDownload(config: RepoDownloadConfig): DownloadJob {
+ const {
+ kind,
+ repoId,
+ activeVariant,
+ onComplete,
+ onCancelled,
+ onError,
+ autoAdopt,
+ } = config;
+
+ const handlersRef = useLatestRef<JobListeners>({
+ onComplete,
+ onCancelled,
+ onError,
+ });
+ useEffect(() => {
+ return subscribeJobListeners(kind, repoId, {
+ onComplete: (variant, bytes) =>
+ handlersRef.current.onComplete?.(variant, bytes),
+ onCancelled: (variant) => handlersRef.current.onCancelled?.(variant),
+ onError: (variant) => handlersRef.current.onError?.(variant),
+ });
+ }, [handlersRef, kind, repoId]);
+
+ useEffect(() => {
+ if (!autoAdopt) return;
+ const controller = new AbortController();
+ void downloadManager.probeAndAdopt(kind, repoId, controller.signal);
+ return () => controller.abort();
+ }, [autoAdopt, kind, repoId]);
+
+ const activeState = useDownloadManagerStore(
+ useShallow((state) => {
+ if (activeVariant === undefined) {
+ return {
+ active: selectActiveJob(state, kind, repoId),
+ repoPeerActive: false,
+ };
+ }
+ const active = selectActiveJob(state, kind, repoId, activeVariant);
+ const repoActive = selectActiveJob(state, kind, repoId);
+ return {
+ active,
+ repoPeerActive: Boolean(repoActive && repoActive.key !== active?.key),
+ };
+ }),
+ );
+ const active = activeState.active;
+ const conflictKey = useMemo(
+ () => jobKeyOf(kind, repoId, activeVariant ?? null),
+ [activeVariant, kind, repoId],
+ );
+ const transportConflict = useDownloadManagerStore(
+ (state) => state.conflicts[conflictKey]?.info ?? null,
+ );
+
+ useEffect(
+ () => () => {
+ downloadManager.cancelConflict(conflictKey);
+ },
+ [conflictKey],
+ );
+
+ const requestStartDownload = useCallback(
+ (variant: string | null, expectedBytes: number) => {
+ return downloadManager.requestStart({
+ kind,
+ repoId,
+ variant,
+ expectedBytes,
+ });
+ },
+ [kind, repoId],
+ );
+
+ const cancelDownload = useCallback(
+ (variant: string | null) => {
+ const state = useDownloadManagerStore.getState();
+ const activeJob = selectActiveJob(state, kind, repoId, variant);
+ void downloadManager.cancel(
+ activeJob?.key ?? jobKeyOf(kind, repoId, variant),
+ );
+ },
+ [kind, repoId],
+ );
+
+ const setExpectedBytes = useCallback(
+ (bytes: number, variant: string | null = null) =>
+ downloadManager.setExpected(kind, repoId, variant, bytes),
+ [kind, repoId],
+ );
+
+ const resumeConflict = useCallback(
+ () => downloadManager.resumeConflict(conflictKey),
+ [conflictKey],
+ );
+ const restartConflict = useCallback(
+ () => downloadManager.restartConflict(conflictKey),
+ [conflictKey],
+ );
+ const cancelConflict = useCallback(
+ () => downloadManager.cancelConflict(conflictKey),
+ [conflictKey],
+ );
+
+ const progress = useMemo<DownloadJobProgress | null>(
+ () =>
+ active
+ ? {
+ variant: active.variant,
+ expectedBytes: active.expectedBytes,
+ downloadedBytes: active.downloadedBytes,
+ fraction: active.fraction,
+ }
+ : null,
+ [active],
+ );
+
+ return {
+ progress,
+ bytesPerSec: active?.bytesPerSec ?? 0,
+ cancelling: active?.state === "cancelling",
+ repoPeerActive: activeState.repoPeerActive,
+ transportConflict,
+ requestStartDownload,
+ cancelDownload,
+ setExpectedBytes,
+ resumeConflict,
+ restartConflict,
+ cancelConflict,
+ };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-copy-feedback.ts b/studio/frontend/src/features/hub/hooks/use-copy-feedback.ts
new file mode 100644
index 00000000000..58686850ff9
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-copy-feedback.ts
@@ -0,0 +1,30 @@
+// 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 { useCallback, useEffect, useRef, useState } from "react";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+
+export function useCopyFeedback(resetMs = 1500) {
+ const [copied, setCopied] = useState(false);
+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(
+ () => () => {
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
+ },
+ [],
+ );
+
+ const copy = useCallback(
+ async (value: string) => {
+ const ok = await copyToClipboard(value);
+ if (!ok) return;
+ setCopied(true);
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
+ timeoutRef.current = setTimeout(() => setCopied(false), resetMs);
+ },
+ [resetMs],
+ );
+
+ return { copied, copy };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-dataset-size.ts b/studio/frontend/src/features/hub/hooks/use-dataset-size.ts
new file mode 100644
index 00000000000..db4623da47d
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-dataset-size.ts
@@ -0,0 +1,40 @@
+// 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 { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
+import { fingerprintToken } from "@/features/hub/lib/token-fingerprint";
+import { useEffect, useState } from "react";
+import {
+ type DatasetSizeInfo,
+ fetchDatasetSize,
+} from "../lib/dataset-size";
+
+export function useDatasetSize(
+ repoId: string | null | undefined,
+ options: { enabled?: boolean; token?: string | null } = {},
+): DatasetSizeInfo | null {
+ const online = useOnlineStatus();
+ const enabled = options.enabled ?? true;
+ const token = options.token || undefined;
+ const repoKey = repoId ?? "";
+ const key = repoKey ? `${repoKey}::${fingerprintToken(token)}` : "";
+ const [state, setState] = useState<{
+ key: string;
+ value: DatasetSizeInfo | null;
+ }>(() => ({ key, value: null }));
+
+ useEffect(() => {
+ if (!repoKey || !enabled || !online) return;
+ const controller = new AbortController();
+ void fetchDatasetSize(repoKey, token, controller.signal).then((value) => {
+ if (!controller.signal.aborted) {
+ setState({ key, value });
+ }
+ });
+ return () => {
+ controller.abort();
+ };
+ }, [enabled, key, online, repoKey, token]);
+
+ return state.key === key ? state.value : null;
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-discover-search.ts b/studio/frontend/src/features/hub/hooks/use-discover-search.ts
new file mode 100644
index 00000000000..6c11ca8dc4d
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-discover-search.ts
@@ -0,0 +1,212 @@
+// 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 { useCallback, useEffect, useMemo, useRef } from "react";
+import { toast } from "@/lib/toast";
+import {
+ type HfModelResult,
+ type HfSortDirection,
+ type HfSortKey,
+ useHubModelSearch,
+} from "./use-hub-model-search";
+import {
+ type HfDatasetResult,
+ useHubDatasetSearch,
+} from "./use-hub-dataset-search";
+import type { ChannelPreset } from "../lib/channels";
+
+export interface DiscoverSearch {
+ results: HfModelResult[];
+ datasetResults: HfDatasetResult[];
+ scannedCount: number;
+ isLoading: boolean;
+ isLoadingMore: boolean;
+ hasMore: boolean;
+ fetchMore: () => boolean;
+ searchError: string | null;
+ handleRetrySearch: () => void;
+}
+
+type DiscoverErrorKind = "offline" | "auth" | "rate-limited" | "server" | "unknown";
+
+const RECONNECT_RETRY_COOLDOWN_MS = 90_000;
+
+function classifyDiscoverError(
+ message: string,
+ online: boolean,
+): DiscoverErrorKind {
+ if (!online) return "offline";
+ const lower = message.toLowerCase();
+ if (
+ lower.includes("429") ||
+ lower.includes("rate limit") ||
+ lower.includes("too many requests")
+ ) {
+ return "rate-limited";
+ }
+ if (
+ lower.includes("401") ||
+ lower.includes("403") ||
+ lower.includes("unauthorized") ||
+ lower.includes("forbidden") ||
+ (lower.includes("token") && !lower.includes("unexpected token")) ||
+ lower.includes("authentication")
+ ) {
+ return "auth";
+ }
+ if (
+ lower.includes("500") ||
+ lower.includes("502") ||
+ lower.includes("503") ||
+ lower.includes("504") ||
+ lower.includes("server")
+ ) {
+ return "server";
+ }
+ return "unknown";
+}
+
+function discoverErrorTitle(kind: DiscoverErrorKind): string {
+ switch (kind) {
+ case "offline":
+ return "You're offline";
+ case "auth":
+ return "Hugging Face auth failed";
+ case "rate-limited":
+ return "Hugging Face rate limit";
+ default:
+ return "Couldn't reach Hugging Face";
+ }
+}
+
+export function useDiscoverSearch({
+ debouncedQuery,
+ accessToken,
+ isDiscoverTab,
+ isDatasetMode,
+ sortBy,
+ direction,
+ activeChannel,
+ online,
+}: {
+ debouncedQuery: string;
+ accessToken: string | undefined;
+ isDiscoverTab: boolean;
+ isDatasetMode: boolean;
+ sortBy: HfSortKey;
+ direction: HfSortDirection;
+ activeChannel: ChannelPreset | null;
+ online: boolean;
+}): DiscoverSearch {
+ const channelOption = useMemo(
+ () =>
+ activeChannel
+ ? {
+ owner: activeChannel.owner,
+ tags: activeChannel.tags,
+ query: activeChannel.query,
+ idSuffix: activeChannel.idSuffix,
+ }
+ : null,
+ [activeChannel],
+ );
+
+ const modelSearch = useHubModelSearch(debouncedQuery, {
+ accessToken,
+ sortBy,
+ sortDirection: direction,
+ pinUnslothFirst:
+ sortBy === "trendingScore" && direction === "desc" && !activeChannel,
+ enabled: online && isDiscoverTab && !isDatasetMode,
+ keepUnsupportedTags: true,
+ channel: channelOption,
+ });
+ const datasetSearch = useHubDatasetSearch(debouncedQuery, {
+ accessToken,
+ enabled: online && isDiscoverTab && isDatasetMode,
+ sortBy,
+ sortDirection: direction,
+ });
+
+ const results = isDatasetMode ? [] : modelSearch.results;
+ const isLoading = isDatasetMode ? datasetSearch.isLoading : modelSearch.isLoading;
+ const isLoadingMore = isDatasetMode
+ ? datasetSearch.isLoadingMore
+ : modelSearch.isLoadingMore;
+ const hasMore = isDatasetMode ? datasetSearch.hasMore : modelSearch.hasMore;
+ const scannedCount = isDatasetMode
+ ? datasetSearch.scannedCount
+ : modelSearch.scannedCount;
+ const rawFetchMore = isDatasetMode
+ ? datasetSearch.fetchMore
+ : modelSearch.fetchMore;
+ const rawSearchError = isDatasetMode ? datasetSearch.error : modelSearch.error;
+ const retrySearch = isDatasetMode ? datasetSearch.retry : modelSearch.retry;
+ const searchError = isDiscoverTab && online ? rawSearchError : null;
+ const fetchMore = useCallback(() => {
+ if (!online || !hasMore) return false;
+ return rawFetchMore();
+ }, [online, hasMore, rawFetchMore]);
+
+ const handleRetrySearch = useCallback(() => {
+ if (!online) {
+ toast.error("You're offline", {
+ description: "Reconnect to the internet to browse Hugging Face.",
+ });
+ return;
+ }
+ retrySearch();
+ toast.message("Retrying…", {
+ description: "Reaching Hugging Face for the latest models.",
+ });
+ }, [online, retrySearch]);
+
+ const lastErrorRef = useRef<DiscoverErrorKind | null>(null);
+ useEffect(() => {
+ if (!isDiscoverTab) {
+ lastErrorRef.current = null;
+ return;
+ }
+ if (!searchError) {
+ lastErrorRef.current = null;
+ return;
+ }
+ const errorKind = classifyDiscoverError(searchError, online);
+ if (lastErrorRef.current === errorKind) return;
+ lastErrorRef.current = errorKind;
+ toast.error(discoverErrorTitle(errorKind), {
+ description: online
+ ? searchError
+ : "Reconnect to the internet to browse models.",
+ action: { label: "Retry", onClick: handleRetrySearch },
+ });
+ }, [isDiscoverTab, searchError, online, handleRetrySearch]);
+
+ const wasOfflineRef = useRef(!online);
+ const lastReconnectAtRef = useRef(0);
+ useEffect(() => {
+ if (online && wasOfflineRef.current && isDiscoverTab) {
+ const now = Date.now();
+ if (now - lastReconnectAtRef.current > RECONNECT_RETRY_COOLDOWN_MS) {
+ lastReconnectAtRef.current = now;
+ toast.success("Back online", {
+ description: "Refreshing the discovery feed.",
+ });
+ retrySearch();
+ }
+ }
+ wasOfflineRef.current = !online;
+ }, [online, retrySearch, isDiscoverTab]);
+
+ return {
+ results,
+ datasetResults: datasetSearch.results,
+ scannedCount,
+ isLoading,
+ isLoadingMore,
+ hasMore,
+ fetchMore,
+ searchError,
+ handleRetrySearch,
+ };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts
new file mode 100644
index 00000000000..a232c0730af
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts
@@ -0,0 +1,432 @@
+// 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 { fetchWithTimeout } from "../lib/network";
+import type { HubModelType } from "../types";
+import { listDatasets } from "@huggingface/hub";
+import { useCallback, useMemo } from "react";
+import { useHubPaginatedSearch } from "./use-hub-paginated-search";
+
+interface DatasetInfoSplit {
+ name: string;
+ // biome-ignore lint/style/useNamingConvention: external schema
+ num_bytes: number;
+ // biome-ignore lint/style/useNamingConvention: external schema
+ num_examples: number;
+}
+
+interface CardDataWithInfo {
+ size_categories?: string[];
+ pretty_name?: string;
+ dataset_info?:
+ | {
+ splits?: DatasetInfoSplit[];
+ download_size?: number;
+ dataset_size?: number;
+ }
+ | Array<{ splits?: DatasetInfoSplit[] }>;
+}
+
+function extractTotalExamples(
+ cardData: CardDataWithInfo | undefined,
+): number | undefined {
+ if (!cardData?.dataset_info) {
+ return undefined;
+ }
+
+ const infos = Array.isArray(cardData.dataset_info)
+ ? cardData.dataset_info
+ : [cardData.dataset_info];
+
+ const examples = infos
+ .flatMap((info) => info.splits ?? [])
+ .filter((s) => typeof s.num_examples === "number")
+ .map((s) => s.num_examples);
+
+ return examples.length > 0 ? examples.reduce((a, b) => a + b, 0) : undefined;
+}
+
+export interface HfDatasetResult {
+ id: string;
+ downloads: number;
+ likes: number;
+ totalExamples?: number;
+ sizeCategory?: string;
+ taskCategories: string[];
+ plainTags: string[];
+}
+
+function mapDataset(raw: unknown): HfDatasetResult {
+ const ds = raw as {
+ name: string;
+ downloads?: number;
+ likes?: number;
+ tags?: string[];
+ cardData?: unknown;
+ };
+ const card = ds.cardData as CardDataWithInfo | undefined;
+ const tags = ds.tags ?? [];
+ const taskCategories = tags
+ .filter((t) => t.startsWith("task_categories:"))
+ .map((t) => t.slice("task_categories:".length));
+ const plainTags = tags.filter((t) => !t.includes(":"));
+ return {
+ id: ds.name,
+ downloads: ds.downloads ?? 0,
+ likes: ds.likes ?? 0,
+ totalExamples: extractTotalExamples(card),
+ sizeCategory: card?.size_categories?.[0],
+ taskCategories,
+ plainTags,
+ };
+}
+
+type DatasetSortKey =
+ | "trendingScore"
+ | "downloads"
+ | "likes"
+ | "lastModified"
+ | "createdAt";
+type DatasetSortDirection = "desc" | "asc";
+
+const DESC_ONLY_DATASET_SORTS = new Set<DatasetSortKey>(["trendingScore"]);
+const HF_DATASET_SEARCH_TIMEOUT_MS = 15_000;
+
+function makeDatasetSortFetch(
+ sortBy: DatasetSortKey,
+ direction: DatasetSortDirection,
+ signal?: AbortSignal,
+): typeof fetch {
+ return (input, init) => {
+ const rawUrl =
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url;
+ const url = new URL(rawUrl);
+
+ if (!url.searchParams.has("sort")) {
+ url.searchParams.set("sort", sortBy);
+ }
+ const effectiveSort = (url.searchParams.get("sort") ?? sortBy) as
+ | DatasetSortKey
+ | undefined;
+ const effectiveDir =
+ effectiveSort && DESC_ONLY_DATASET_SORTS.has(effectiveSort)
+ ? "desc"
+ : direction;
+ url.searchParams.set("direction", effectiveDir === "asc" ? "1" : "-1");
+
+ return fetchWithTimeout(
+ url,
+ signal ? { ...init, signal } : init,
+ HF_DATASET_SEARCH_TIMEOUT_MS,
+ );
+ };
+}
+
+type DatasetRelevance = "incompatible" | "neutral" | "boosted";
+
+const BOOSTED_TASK_CATEGORIES: Record<HubModelType, Set<string>> = {
+ text: new Set([
+ "text-generation",
+ "text2text-generation",
+ "question-answering",
+ "summarization",
+ "conversational",
+ ]),
+ vision: new Set([
+ "image-text-to-text",
+ "visual-question-answering",
+ "image-to-text",
+ "image-captioning",
+ ]),
+ audio: new Set([
+ "text-to-speech",
+ "text-to-audio",
+ "automatic-speech-recognition",
+ ]),
+ embeddings: new Set([
+ "feature-extraction",
+ "sentence-similarity",
+ "text-retrieval",
+ ]),
+};
+
+const INCOMPATIBLE_TASKS_ALL_MODELS = new Set([
+ "text-to-3d",
+ "image-to-3d",
+ "robotics",
+ "reinforcement-learning",
+ "tabular-classification",
+ "tabular-regression",
+ "time-series-forecasting",
+]);
+
+const PRETRAINING_PLAIN_TAGS = new Set(["pretraining", "pre-training"]);
+const OCR_PLAIN_TAGS = new Set(["ocr", "document-ocr"]);
+
+const PRETRAINING_SIZE_CATEGORIES = new Set([
+ "5M<n<10M",
+ "10M<n<100M",
+ "100M<n<1B",
+ "1B<n<10B",
+ "10B<n<100B",
+ "100B<n<1T",
+ "n>1T",
+]);
+
+const OCR_OR_VISION_TEXT_TASKS = new Set([
+ "image-to-text",
+ "image-captioning",
+ "visual-question-answering",
+ "document-question-answering",
+]);
+
+const CURATED_EMPTY_QUERY_DATASET_IDS: Partial<Record<HubModelType, string[]>> = {
+ text: [
+ "unsloth/alpaca-cleaned",
+ "unsloth/OpenMathReasoning-mini",
+ "mlabonne/FineTome-100k",
+ "openai/gsm8k",
+ "philschmid/guanaco-sharegpt-style",
+ "open-r1/DAPO-Math-17k-Processed",
+ "HuggingFaceH4/Multilingual-Thinking",
+ "HuggingFaceH4/ultrafeedback_binarized",
+ "reciperesearch/dolphin-sft-v0.1-preference",
+ "roneneldan/TinyStories",
+ "FreedomIntelligence/alpaca-gpt4-korean",
+ "Goedel-LM/SFT_dataset_v2",
+ "allenai/tulu-3-sft-mixture",
+ "HuggingFaceH4/no_robots",
+ "Magpie-Align/Magpie-Air-300K-Filtered",
+ "teknium/OpenHermes-2.5",
+ "databricks/databricks-dolly-15k",
+ "tatsu-lab/alpaca",
+ "garage-bAInd/Open-Platypus",
+ "microsoft/orca-math-word-problems-200k",
+ "Open-Orca/OpenOrca",
+ "openbmb/UltraInteract_sft",
+ ],
+ vision: [
+ "unsloth/LaTeX_OCR",
+ "unsloth/llava-instruct-mix-vsft-mini",
+ "unsloth/Radiology_mini",
+ "AI4Math/MathVista",
+ "AI4Math/MathVerse",
+ "ChongyanChen/VQAonline",
+ "lmms-lab/VQAv2",
+ "hezarai/parsynth-ocr-200k",
+ ],
+ audio: [
+ "MrDragonFox/Elise",
+ "keithito/lj_speech",
+ "parler-tts/mls_eng_10k",
+ "parler-tts/libritts-r-filtered-speaker-descriptions",
+ "openslr/librispeech_asr",
+ "MikhailT/hifi-tts",
+ "mozilla-foundation/common_voice_17_0",
+ "facebook/voxpopuli",
+ "speechcolab/gigaspeech",
+ "kth-tmh/vctk",
+ "Wenetspeech4TTS/WenetSpeech4TTS",
+ ],
+ embeddings: [
+ "electroglyph/technical",
+ ],
+};
+
+const INCOMPATIBLE_TASKS_BY_MODEL: Record<HubModelType, Set<string>> = {
+ text: new Set([
+ "text-to-image",
+ "image-to-image",
+ "image-to-video",
+ "text-to-video",
+ "image-classification",
+ "image-feature-extraction",
+ "image-text-to-image",
+ "zero-shot-image-classification",
+ "keypoint-detection",
+ "object-detection",
+ "image-segmentation",
+ "depth-estimation",
+ "text-to-speech",
+ "text-to-audio",
+ "audio-classification",
+ "audio-to-audio",
+ "automatic-speech-recognition",
+ "video-classification",
+ "visual-document-retrieval",
+ ]),
+ vision: new Set([
+ "text-to-speech",
+ "text-to-audio",
+ "audio-classification",
+ "audio-to-audio",
+ "automatic-speech-recognition",
+ ]),
+ audio: new Set([
+ "text-to-image",
+ "image-to-image",
+ "image-to-video",
+ "text-to-video",
+ "image-classification",
+ "image-feature-extraction",
+ "image-text-to-image",
+ "zero-shot-image-classification",
+ "keypoint-detection",
+ "object-detection",
+ "image-segmentation",
+ "depth-estimation",
+ "video-classification",
+ "visual-document-retrieval",
+ ]),
+ embeddings: new Set([
+ "text-to-image",
+ "image-to-image",
+ "image-to-video",
+ "text-to-video",
+ "image-classification",
+ "image-feature-extraction",
+ "image-text-to-image",
+ "zero-shot-image-classification",
+ "keypoint-detection",
+ "object-detection",
+ "image-segmentation",
+ "depth-estimation",
+ "text-to-speech",
+ "text-to-audio",
+ "audio-classification",
+ "audio-to-audio",
+ "automatic-speech-recognition",
+ "video-classification",
+ "visual-document-retrieval",
+ ]),
+};
+
+function isPretrainingDataset(dataset: HfDatasetResult): boolean {
+ if (dataset.plainTags.some((t) => PRETRAINING_PLAIN_TAGS.has(t.toLowerCase())))
+ return true;
+ if (
+ dataset.sizeCategory &&
+ PRETRAINING_SIZE_CATEGORIES.has(dataset.sizeCategory)
+ )
+ return true;
+ return false;
+}
+
+function rankDatasetRelevance(
+ dataset: HfDatasetResult,
+ modelType: HubModelType,
+): DatasetRelevance {
+ if (isPretrainingDataset(dataset)) return "incompatible";
+
+ // Keep OCR / vision-text corpora out of non-vision defaults.
+ if (modelType !== "vision") {
+ if (
+ dataset.plainTags.some((t) => OCR_PLAIN_TAGS.has(t.toLowerCase())) ||
+ dataset.taskCategories.some((t) => OCR_OR_VISION_TEXT_TASKS.has(t))
+ ) {
+ return "incompatible";
+ }
+ }
+
+ const { taskCategories } = dataset;
+ if (taskCategories.length === 0) return "neutral";
+
+ const boosted = BOOSTED_TASK_CATEGORIES[modelType];
+ const modelIncompat = INCOMPATIBLE_TASKS_BY_MODEL[modelType];
+
+ if (taskCategories.some((t) => boosted.has(t))) return "boosted";
+ if (
+ taskCategories.every(
+ (t) => INCOMPATIBLE_TASKS_ALL_MODELS.has(t) || modelIncompat.has(t),
+ )
+ )
+ return "incompatible";
+ return "neutral";
+}
+
+function isOcrOrVisionTextDataset(dataset: HfDatasetResult): boolean {
+ return (
+ dataset.plainTags.some((t) => OCR_PLAIN_TAGS.has(t.toLowerCase())) ||
+ dataset.taskCategories.some((t) => OCR_OR_VISION_TEXT_TASKS.has(t))
+ );
+}
+
+function toCuratedDatasetResult(id: string): HfDatasetResult {
+ // Curated defaults are id-only; this fills the shared result shape without extra HF requests.
+ return {
+ id,
+ downloads: 0,
+ likes: 0,
+ taskCategories: [],
+ plainTags: [],
+ };
+}
+
+export function useHubDatasetSearch(
+ query: string,
+ options?: {
+ modelType?: HubModelType | null;
+ accessToken?: string;
+ enabled?: boolean;
+ sortBy?: DatasetSortKey;
+ sortDirection?: DatasetSortDirection;
+ },
+) {
+ const {
+ modelType,
+ accessToken,
+ enabled = true,
+ sortBy = "trendingScore",
+ sortDirection = "desc",
+ } = options ?? {};
+ const hasQuery = query.trim().length > 0;
+ const useCuratedOnly = !hasQuery && !!modelType;
+ const createIter = useCallback(
+ (signal: AbortSignal) => {
+ if (useCuratedOnly) {
+ return (async function* empty() {})() as AsyncGenerator<unknown>;
+ }
+ return listDatasets({
+ search: hasQuery ? { query } : {},
+ additionalFields: ["cardData", "tags"],
+ fetch: makeDatasetSortFetch(sortBy, sortDirection, signal),
+ ...(accessToken ? { credentials: { accessToken } } : {}),
+ }) as AsyncGenerator<unknown>;
+ },
+ [useCuratedOnly, hasQuery, query, accessToken, sortBy, sortDirection],
+ );
+
+ const search = useHubPaginatedSearch(createIter, mapDataset, { enabled });
+
+ const results = useMemo(() => {
+ if (!enabled) return [];
+ const hideOcr = modelType !== "vision";
+ const baseResults = hideOcr
+ ? search.results.filter((ds) => !isOcrOrVisionTextDataset(ds))
+ : search.results;
+
+ if (!hasQuery && modelType) {
+ const curatedIds = CURATED_EMPTY_QUERY_DATASET_IDS[modelType] ?? [];
+ return curatedIds.map(toCuratedDatasetResult);
+ }
+
+ if (!modelType) return baseResults;
+
+ const boosted: HfDatasetResult[] = [];
+ const neutral: HfDatasetResult[] = [];
+
+ for (const ds of baseResults) {
+ const relevance = rankDatasetRelevance(ds, modelType);
+ if (relevance === "boosted") boosted.push(ds);
+ else if (relevance !== "incompatible") neutral.push(ds);
+ }
+
+ return [...boosted, ...neutral];
+ }, [enabled, search.results, modelType, query]);
+
+ return { ...search, results };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-infinite-scroll.ts b/studio/frontend/src/features/hub/hooks/use-hub-infinite-scroll.ts
new file mode 100644
index 00000000000..2f37e2e713e
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-hub-infinite-scroll.ts
@@ -0,0 +1,245 @@
+// 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 { useCallback, useEffect, useRef, useState } from "react";
+
+/**
+ * IntersectionObserver sentinel for infinite scroll, plus a ResizeObserver
+ * fallback that auto-fetches while the scroll container doesn't yet overflow.
+ * `signal` (typically results.length) is a dep so the fit check re-runs after a
+ * fetch even when the page filter rejected every new row and the DOM didn't change.
+ */
+// Hard backstop on no-overflow auto-fetches, capping a runaway sweep of the full listing.
+const DEFAULT_MAX_AUTO_FILL_FETCHES = 40;
+
+export interface InfiniteScrollOptions {
+ enabled?: boolean;
+ onFetchIntent?: () => void;
+ resultCount?: number;
+ resetKey?: string | number | boolean | null;
+ maxAutoFillFetches?: number;
+ manualFetchAfterAutoFill?: boolean;
+ isFetching?: boolean;
+}
+
+function hasScrollableOverflow(root: HTMLElement): boolean {
+ return root.scrollHeight > root.clientHeight + 4;
+}
+
+export function useHubInfiniteScroll(
+ fetchMore: () => boolean | void,
+ signal: number,
+ options: InfiniteScrollOptions = {},
+) {
+ const enabled = options.enabled ?? true;
+ const onFetchIntent = options.onFetchIntent;
+ const resultCount = options.resultCount ?? signal;
+ const resetKey = options.resetKey ?? null;
+ const maxAutoFillFetches =
+ options.maxAutoFillFetches ?? DEFAULT_MAX_AUTO_FILL_FETCHES;
+ const manualFetchAfterAutoFill = options.manualFetchAfterAutoFill ?? false;
+ const isFetching = options.isFetching ?? false;
+
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const sentinelRef = useRef<HTMLDivElement>(null);
+
+ const fetchMoreRef = useRef(fetchMore);
+ const onFetchIntentRef = useRef(onFetchIntent);
+ const enabledRef = useRef(enabled);
+ const isFetchingRef = useRef(isFetching);
+ useEffect(() => {
+ fetchMoreRef.current = fetchMore;
+ }, [fetchMore]);
+ useEffect(() => {
+ onFetchIntentRef.current = onFetchIntent;
+ }, [onFetchIntent]);
+ useEffect(() => {
+ enabledRef.current = enabled;
+ }, [enabled]);
+ useEffect(() => {
+ isFetchingRef.current = isFetching;
+ }, [isFetching]);
+
+ const autoFireCountRef = useRef(0);
+ const prevSignalRef = useRef(signal);
+ const prevResultCountRef = useRef(resultCount);
+ const resetKeyRef = useRef(resetKey);
+ const wasEnabledRef = useRef(false);
+ const manualFetchAvailableRef = useRef(false);
+ const manualStateTimerRef = useRef<ReturnType<
+ typeof globalThis.setTimeout
+ > | null>(null);
+ const [manualFetchAvailable, setManualFetchAvailableState] = useState(false);
+
+ const setManualFetchAvailable = useCallback((next: boolean) => {
+ manualFetchAvailableRef.current = next;
+ if (manualStateTimerRef.current !== null) {
+ globalThis.clearTimeout(manualStateTimerRef.current);
+ }
+ manualStateTimerRef.current = globalThis.setTimeout(() => {
+ manualStateTimerRef.current = null;
+ setManualFetchAvailableState((current) =>
+ current === next ? current : next,
+ );
+ }, 0);
+ }, []);
+
+ const requestFetchMore = useCallback(() => {
+ const accepted = fetchMoreRef.current() !== false;
+ if (accepted) {
+ onFetchIntentRef.current?.();
+ }
+ return accepted;
+ }, []);
+
+ const fetchMoreManually = useCallback(() => {
+ if (!enabledRef.current || isFetchingRef.current) return;
+ if (requestFetchMore()) {
+ setManualFetchAvailable(false);
+ }
+ }, [requestFetchMore, setManualFetchAvailable]);
+
+ useEffect(
+ () => () => {
+ if (manualStateTimerRef.current !== null) {
+ globalThis.clearTimeout(manualStateTimerRef.current);
+ }
+ },
+ [],
+ );
+
+ // Fires when the stable sentinel scrolls into view. Omits `signal` on purpose:
+ // rebuilding per batch could drop an intersection. Refills fall to the auto-fire effect.
+ useEffect(() => {
+ if (!enabled) return;
+ const sentinel = sentinelRef.current;
+ if (!sentinel) return;
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ if (entry.isIntersecting) {
+ const root = scrollRef.current;
+ if (
+ !root ||
+ isFetchingRef.current ||
+ manualFetchAvailableRef.current ||
+ !hasScrollableOverflow(root)
+ ) {
+ continue;
+ }
+ if (autoFireCountRef.current >= maxAutoFillFetches) {
+ setManualFetchAvailable(manualFetchAfterAutoFill);
+ continue;
+ }
+ if (requestFetchMore()) {
+ autoFireCountRef.current += 1;
+ }
+ }
+ }
+ },
+ {
+ threshold: 0,
+ root: scrollRef.current,
+ rootMargin: "200px 0px",
+ },
+ );
+ observer.observe(sentinel);
+ return () => observer.disconnect();
+ }, [
+ enabled,
+ manualFetchAfterAutoFill,
+ maxAutoFillFetches,
+ requestFetchMore,
+ setManualFetchAvailable,
+ ]);
+
+ // Auto-fire fallback: keep requesting batches while the container doesn't yet
+ // overflow (initial empty state or aggressive filters). Driven only off
+ // `enabled`/`signal` and a ResizeObserver on the scroll root, so it wakes on
+ // listing-shape changes rather than thrashing the main thread every frame
+ // (the prior childList/subtree observer was the dominant Hub lag source).
+ useEffect(() => {
+ if (!enabled) {
+ wasEnabledRef.current = false;
+ setManualFetchAvailable(false);
+ return;
+ }
+ // Fresh enable or a shrinking list clears the backstop so loading can refill the viewport.
+ if (
+ !wasEnabledRef.current ||
+ signal < prevSignalRef.current ||
+ resultCount < prevResultCountRef.current ||
+ resetKey !== resetKeyRef.current
+ ) {
+ autoFireCountRef.current = 0;
+ setManualFetchAvailable(false);
+ } else if (resultCount > prevResultCountRef.current) {
+ autoFireCountRef.current = 0;
+ setManualFetchAvailable(false);
+ }
+ wasEnabledRef.current = true;
+ prevSignalRef.current = signal;
+ prevResultCountRef.current = resultCount;
+ resetKeyRef.current = resetKey;
+
+ const root = scrollRef.current;
+ if (!root) return;
+
+ const tryFire = () => {
+ const sentinel = sentinelRef.current;
+ if (!sentinel?.isConnected) return;
+ if (manualFetchAvailableRef.current) return;
+ // Once content overflows, the IntersectionObserver takes over — stop polling.
+ if (hasScrollableOverflow(root)) {
+ setManualFetchAvailable(false);
+ return;
+ }
+ if (isFetchingRef.current) return;
+ if (autoFireCountRef.current >= maxAutoFillFetches) {
+ setManualFetchAvailable(manualFetchAfterAutoFill);
+ return;
+ }
+ if (requestFetchMore()) {
+ setManualFetchAvailable(false);
+ autoFireCountRef.current += 1;
+ }
+ };
+
+ let frame: number | null = null;
+ const schedule = () => {
+ if (frame !== null) return;
+ frame = requestAnimationFrame(() => {
+ frame = null;
+ tryFire();
+ });
+ };
+
+ schedule();
+
+ const ro = new ResizeObserver(schedule);
+ ro.observe(root);
+
+ return () => {
+ if (frame !== null) cancelAnimationFrame(frame);
+ ro.disconnect();
+ };
+ }, [
+ enabled,
+ isFetching,
+ manualFetchAfterAutoFill,
+ maxAutoFillFetches,
+ resetKey,
+ requestFetchMore,
+ resultCount,
+ setManualFetchAvailable,
+ signal,
+ ]);
+
+ return {
+ scrollRef,
+ sentinelRef,
+ manualFetchAvailable,
+ fetchMoreManually,
+ };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts
new file mode 100644
index 00000000000..ebce58e9d84
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts
@@ -0,0 +1,623 @@
+// 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 { PipelineType } from "@huggingface/hub";
+import { listModels } from "@huggingface/hub";
+import {
+ type CachedResult,
+ cachedModelInfo,
+ primeCacheFromListing,
+} from "../lib/hf-cache";
+import { fetchWithTimeout } from "../lib/network";
+import {
+ startTransition,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { useHubPaginatedSearch } from "./use-hub-paginated-search";
+import { usePlatformStore } from "@/config/env";
+import {
+ EMBEDDING_TAGS,
+ estimateSizeFromDtypes,
+} from "../lib/hf-model-meta";
+import { isGgufLike } from "../lib/model-identifiers";
+import {
+ classifyUnslothSupport,
+ excludedFormatTagsForDevice,
+ type UnslothSupport,
+ type UnslothSupportStatus,
+} from "../lib/unsloth-support";
+
+const ALL_FIELDS: ("safetensors" | "tags")[] = ["safetensors", "tags"];
+
+export { classifyUnslothSupport };
+export type { UnslothSupport, UnslothSupportStatus };
+
+export type HfSortKey =
+ | "trendingScore"
+ | "downloads"
+ | "likes"
+ | "lastModified"
+ | "createdAt";
+
+export type HfSortDirection = "desc" | "asc";
+export type HfTaskFilter = PipelineType | readonly PipelineType[] | undefined;
+
+function normalizeTaskFilter(task: HfTaskFilter): readonly PipelineType[] {
+ if (!task) return [];
+ return typeof task === "string" ? [task] : task;
+}
+
+function taskMatches(
+ pipelineTag: string | undefined,
+ tasks: readonly PipelineType[],
+): boolean {
+ return (
+ tasks.length === 0 ||
+ !pipelineTag ||
+ tasks.includes(pipelineTag as PipelineType)
+ );
+}
+
+async function* mergeTaskIterators(
+ tasks: readonly PipelineType[],
+ createIter: (task?: PipelineType) => AsyncGenerator<unknown>,
+): AsyncGenerator<unknown> {
+ const seen = new Set<string>();
+ const taskList = tasks.length > 0 ? tasks : [undefined];
+ for (const task of taskList) {
+ for await (const model of createIter(task)) {
+ const name = (model as { name?: string }).name;
+ if (name) {
+ const key = name.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ }
+ yield model;
+ }
+ }
+}
+
+export interface HfModelResult {
+ id: string;
+ downloads: number;
+ likes: number;
+ totalParams?: number;
+ estimatedSizeBytes?: number;
+ isGguf: boolean;
+ tags?: string[];
+ pipelineTag?: string;
+ updatedAt?: string;
+ libraryName?: string;
+ quantMethod?: string;
+}
+
+// HF rejects direction=1 (asc) for trendingScore — only descending is supported.
+const DESC_ONLY_SORTS = new Set<HfSortKey>(["trendingScore"]);
+const HF_SEARCH_TIMEOUT_MS = 15_000;
+
+function makeHfFetch(signal?: AbortSignal): typeof fetch {
+ return (input, init) =>
+ fetchWithTimeout(
+ input,
+ signal ? { ...init, signal } : init,
+ HF_SEARCH_TIMEOUT_MS,
+ );
+}
+
+function makeSortFetch(
+ sortBy: HfSortKey | undefined,
+ direction: HfSortDirection,
+ signal?: AbortSignal,
+): typeof fetch {
+ return (input, init) => {
+ const rawUrl =
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url;
+ const url = new URL(rawUrl);
+
+ if (sortBy && !url.searchParams.has("sort")) {
+ url.searchParams.set("sort", sortBy);
+ }
+ const effectiveSort = (url.searchParams.get("sort") ?? sortBy) as
+ | HfSortKey
+ | undefined;
+ const effectiveDir =
+ effectiveSort && DESC_ONLY_SORTS.has(effectiveSort) ? "desc" : direction;
+ url.searchParams.set("direction", effectiveDir === "asc" ? "1" : "-1");
+
+ return fetchWithTimeout(
+ url,
+ signal ? { ...init, signal } : init,
+ HF_SEARCH_TIMEOUT_MS,
+ );
+ };
+}
+
+function makeMapModel(
+ excludeGguf: boolean,
+ excludedTags: ReadonlySet<string>,
+ keepUnsupportedTags: boolean,
+ idSuffix: string,
+ deviceType: string | null,
+) {
+ const suffixLower = idSuffix.toLowerCase();
+ return (raw: unknown): HfModelResult | null => {
+ const m = raw as {
+ name: string;
+ downloads?: number;
+ likes?: number;
+ task?: string;
+ pipeline_tag?: string;
+ library_name?: string;
+ updatedAt?: Date | string;
+ safetensors?: { total: number; parameters?: Record<string, number> };
+ gguf?: { total?: number; architecture?: string };
+ tags?: string[];
+ config?: { quantization_config?: { quant_method?: string } };
+ };
+ if (suffixLower && !m.name?.toLowerCase().endsWith(suffixLower)) {
+ return null;
+ }
+ const isEmbedding = m.tags?.some((t) => EMBEDDING_TAGS.has(t));
+ if (
+ !keepUnsupportedTags &&
+ !isEmbedding &&
+ m.tags?.some((t) => excludedTags.has(t))
+ ) {
+ return null;
+ }
+ const isGguf =
+ Boolean(m.tags?.some((tag) => tag.toLowerCase() === "gguf")) ||
+ isGgufLike(m.name);
+ if (excludeGguf && isGguf) {
+ return null;
+ }
+ const pipelineTag = m.task ?? m.pipeline_tag;
+ const quantMethod = m.config?.quantization_config?.quant_method;
+ // Drops runtime-unloadable models before they reach the row list. Discover
+ // opts out via keepUnsupportedTags to render them with a "may not be supported"
+ // dot. Embeddings skip the gate: their pipeline tag is unsupported for chat but trainable.
+ if (!keepUnsupportedTags && !isEmbedding) {
+ const support = classifyUnslothSupport({
+ modelId: m.name,
+ pipelineTag,
+ tags: m.tags,
+ libraryName: m.library_name,
+ deviceType,
+ quantMethod,
+ });
+ if (support.status === "unsupported") return null;
+ }
+ const updatedAtIso =
+ m.updatedAt instanceof Date
+ ? m.updatedAt.toISOString()
+ : typeof m.updatedAt === "string"
+ ? m.updatedAt
+ : undefined;
+ return {
+ id: m.name,
+ downloads: m.downloads ?? 0,
+ likes: m.likes ?? 0,
+ totalParams: m.safetensors?.total ?? m.gguf?.total,
+ estimatedSizeBytes: estimateSizeFromDtypes(m.safetensors?.parameters),
+ isGguf,
+ tags: m.tags,
+ pipelineTag,
+ updatedAt: updatedAtIso,
+ libraryName: m.library_name,
+ quantMethod,
+ };
+ };
+}
+
+/** Unsloth results pulled up-front before yielding general results. */
+const UNSLOTH_PREFETCH = 20;
+/** With a typed query, float only a few unsloth results before the general listing. */
+const UNSLOTH_QUERY_PREFETCH = 3;
+/** With a publisher query, fewer unsloth results before the pinned publisher model. */
+const UNSLOTH_PINNED_PREFETCH = 4;
+const PUBLISHER_RE = /^([^/\s]+)\/([^/\s]+)$/;
+
+/**
+ * Prime the hf-cache from a listModels result. For public models also prime the
+ * anonymous slot so the VRAM hook gets cache hits; gated/private models are cached
+ * only under the caller's token to avoid auth leakage.
+ */
+function primeFromListing(
+ name: string,
+ accessToken: string | undefined,
+ model: unknown,
+): void {
+ const data = model as CachedResult;
+ primeCacheFromListing(name, accessToken, data);
+ if (accessToken && !data.private && !data.gated) {
+ primeCacheFromListing(name, undefined, data);
+ }
+}
+
+/** Merged generator yielding unsloth-owned models first, then deduped general results. */
+async function* mergedModelIterator(
+ query: string,
+ task?: HfTaskFilter,
+ accessToken?: string,
+ pinnedId?: string,
+ sortBy: HfSortKey = "downloads",
+ direction: HfSortDirection = "desc",
+ signal?: AbortSignal,
+): AsyncGenerator<unknown> {
+ const sortFetch = makeSortFetch(sortBy, direction, signal);
+ const tasks = normalizeTaskFilter(task);
+ const common = {
+ additionalFields: ALL_FIELDS,
+ fetch: sortFetch,
+ ...(accessToken ? { credentials: { accessToken } } : {}),
+ };
+
+ const unslothIter = mergeTaskIterators(tasks, (task) =>
+ listModels({
+ search: { query, owner: "unsloth", ...(task ? { task } : {}) },
+ ...common,
+ }) as AsyncGenerator<unknown>,
+ );
+ const generalIter = mergeTaskIterators(tasks, (task) =>
+ listModels({
+ search: { query, ...(task ? { task } : {}) },
+ ...common,
+ }) as AsyncGenerator<unknown>,
+ );
+
+ // Start the pinned lookup now so it runs in parallel with Phase 1 instead of blocking Phase 2.
+ const pinnedPromise = pinnedId
+ ? cachedModelInfo({
+ name: pinnedId,
+ additionalFields: ALL_FIELDS,
+ fetch: makeHfFetch(signal),
+ ...(accessToken ? { credentials: { accessToken } } : {}),
+ }).catch(() => null)
+ : null;
+
+ const limit = pinnedId
+ ? UNSLOTH_PINNED_PREFETCH
+ : query.trim()
+ ? UNSLOTH_QUERY_PREFETCH
+ : UNSLOTH_PREFETCH;
+
+ // Phase 1: unsloth models first
+ const seen = new Set<string>();
+ let count = 0;
+ for await (const model of unslothIter) {
+ const m = model as { name?: string };
+ if (m.name) {
+ seen.add(m.name);
+ primeFromListing(m.name, accessToken, model);
+ }
+ yield model;
+ count++;
+ if (count >= limit) break;
+ }
+
+ // Phase 1b: pinned publisher model before general results
+ if (pinnedId && !seen.has(pinnedId) && pinnedPromise) {
+ const pinned = await pinnedPromise;
+ if (pinned) {
+ // Record raw input and HF's canonical name so Phase 2 dedup survives casing differences.
+ seen.add(pinnedId);
+ const canonicalName = (pinned as { name?: string }).name;
+ if (canonicalName && canonicalName !== pinnedId) {
+ seen.add(canonicalName);
+ }
+ yield pinned;
+ }
+ }
+
+ // Phase 2: general results, skipping already-seen models
+ for await (const model of generalIter) {
+ const m = model as { name?: string };
+ if (m.name && seen.has(m.name)) continue;
+ if (m.name) {
+ primeFromListing(m.name, accessToken, model);
+ }
+ yield model;
+ }
+}
+
+/** Yields priority models (fetched individually for full metadata), then the unsloth listing. */
+async function* priorityThenListingIterator(
+ priorityIds: readonly string[],
+ task?: HfTaskFilter,
+ accessToken?: string,
+ sortBy: HfSortKey = "downloads",
+ direction: HfSortDirection = "desc",
+ signal?: AbortSignal,
+): AsyncGenerator<unknown> {
+ const tasks = normalizeTaskFilter(task);
+ const common = {
+ additionalFields: ALL_FIELDS,
+ fetch: makeSortFetch(sortBy, direction, signal),
+ ...(accessToken ? { credentials: { accessToken } } : {}),
+ };
+
+ // Phase 1: priority models in parallel via modelInfo
+ const seen = new Set<string>();
+ const settled = await Promise.allSettled(
+ priorityIds.map((id) =>
+ cachedModelInfo({
+ name: id,
+ additionalFields: ALL_FIELDS,
+ fetch: makeHfFetch(signal),
+ ...(accessToken ? { credentials: { accessToken } } : {}),
+ }),
+ ),
+ );
+ for (const result of settled) {
+ if (result.status === "fulfilled") {
+ const m = result.value as { name?: string; pipeline_tag?: string };
+ if (!taskMatches(m.pipeline_tag, tasks)) continue;
+ if (m.name) seen.add(m.name);
+ yield result.value;
+ }
+ }
+
+ const generalIter = mergeTaskIterators(tasks, (task) =>
+ listModels({
+ search: { owner: "unsloth", ...(task ? { task } : {}) },
+ ...common,
+ }) as AsyncGenerator<unknown>,
+ );
+ for await (const model of generalIter) {
+ const m = model as { name?: string };
+ if (m.name && seen.has(m.name)) continue;
+ if (m.name) {
+ primeFromListing(m.name, accessToken, model);
+ }
+ yield model;
+ }
+}
+
+export interface HfModelSearchChannel {
+ owner?: string;
+ tags?: readonly string[];
+ /** Free-text query injected into the HF listModels search.query field. */
+ query?: string;
+ /** Strict client-side filter: drop results whose id doesn't end with this. */
+ idSuffix?: string;
+}
+
+export function useHubModelSearch(
+ query: string,
+ options?: {
+ task?: HfTaskFilter;
+ accessToken?: string;
+ excludeGguf?: boolean;
+ priorityIds?: readonly string[];
+ sortBy?: HfSortKey;
+ sortDirection?: HfSortDirection;
+ pinUnslothFirst?: boolean;
+ enabled?: boolean;
+ keepUnsupportedTags?: boolean;
+ channel?: HfModelSearchChannel | null;
+ },
+) {
+ const {
+ task,
+ accessToken,
+ excludeGguf = false,
+ priorityIds,
+ sortBy = "downloads",
+ sortDirection = "desc",
+ pinUnslothFirst = true,
+ enabled = true,
+ keepUnsupportedTags = false,
+ channel = null,
+ } = options ?? {};
+
+ const channelOwner = channel?.owner ?? null;
+ const channelTagsKey = channel?.tags ? channel.tags.join("|") : "";
+ const channelQuery = channel?.query ?? "";
+ const channelIdSuffix = channel?.idSuffix ?? "";
+ const priorityIdsKey = priorityIds?.join("|") ?? "";
+ const stablePriorityIds = useMemo(
+ () => (priorityIdsKey ? priorityIdsKey.split("|") : undefined),
+ [priorityIdsKey],
+ );
+
+ // Parse publisher detection once, shared between the iterator factory and the secondary sort gate.
+ const { isPublisherQuery, searchQuery, pinnedId, trimmed } = useMemo(() => {
+ const t = query.trim();
+ const m = PUBLISHER_RE.exec(t);
+ const is = !!m && m[1].toLowerCase() !== "unsloth";
+ return {
+ isPublisherQuery: is,
+ searchQuery: is ? m![2] : t,
+ pinnedId: is ? t : undefined,
+ trimmed: t,
+ };
+ }, [query]);
+
+ const createIter = useCallback(
+ (signal: AbortSignal) => {
+ // Channel scoping bypasses the unsloth-merge iterator: a hard owner/tag
+ // filter shows just that curated slice, with the user's text query forwarded into it.
+ if (channelOwner || channelTagsKey || channelQuery) {
+ const channelTags = channelTagsKey ? channelTagsKey.split("|") : undefined;
+ // User text query takes precedence over channel.query; without it, the
+ // channel's own query (e.g. "bnb-4bit") narrows the listing server-side.
+ const queryString = trimmed || channelQuery || undefined;
+ return listModels({
+ search: {
+ ...(queryString ? { query: queryString } : {}),
+ ...(channelOwner ? { owner: channelOwner } : {}),
+ ...(channelTags ? { tags: channelTags } : {}),
+ },
+ additionalFields: ALL_FIELDS,
+ fetch: makeSortFetch(sortBy, sortDirection, signal),
+ sort: sortBy,
+ ...(accessToken ? { credentials: { accessToken } } : {}),
+ }) as AsyncGenerator<unknown>;
+ }
+ if (!trimmed) {
+ // No query: priority models first (full metadata), then the general unsloth listing.
+ if (stablePriorityIds && stablePriorityIds.length > 0) {
+ return priorityThenListingIterator(
+ stablePriorityIds,
+ task,
+ accessToken,
+ sortBy,
+ sortDirection,
+ signal,
+ ) as AsyncGenerator<unknown>;
+ }
+ return mergeTaskIterators(normalizeTaskFilter(task), (task) =>
+ listModels({
+ search: { ...(task ? { task } : {}) },
+ additionalFields: ALL_FIELDS,
+ fetch: makeSortFetch(sortBy, sortDirection, signal),
+ sort: sortBy,
+ ...(accessToken ? { credentials: { accessToken } } : {}),
+ }) as AsyncGenerator<unknown>,
+ );
+ }
+ // Typed query: drop the task filter so searched models appear despite
+ // wrong/missing HF task metadata. For an "owner/repo" query, strip the org
+ // prefix so unsloth variants surface, then pin the original publisher model.
+ // Unsloth-owned queries are left as-is for the full prefetch + secondary sort.
+ return mergedModelIterator(
+ searchQuery,
+ undefined,
+ accessToken,
+ pinnedId,
+ sortBy,
+ sortDirection,
+ signal,
+ ) as AsyncGenerator<unknown>;
+ },
+ [
+ trimmed,
+ searchQuery,
+ pinnedId,
+ task,
+ accessToken,
+ stablePriorityIds,
+ sortBy,
+ sortDirection,
+ channelOwner,
+ channelTagsKey,
+ channelQuery,
+ ],
+ );
+
+ const deviceType = usePlatformStore((s) => s.deviceType);
+ const excludedTags = excludedFormatTagsForDevice(deviceType);
+ const mapModel = useMemo(
+ () =>
+ makeMapModel(
+ excludeGguf,
+ excludedTags,
+ keepUnsupportedTags,
+ channelIdSuffix,
+ deviceType,
+ ),
+ [excludeGguf, excludedTags, keepUnsupportedTags, channelIdSuffix, deviceType],
+ );
+ const search = useHubPaginatedSearch(createIter, mapModel, { enabled });
+
+ // Secondary sort only with no user query (merged iterator already floats
+ // unsloth results; re-sorting would bury matches) and outside channel scoping.
+ //
+ // STABLE-APPEND CONTRACT: when a later page lands, keep the sorted prefix
+ // verbatim and append only the new tail. Re-sorting the whole array would let
+ // a late unsloth/* repo jump to an earlier index and bump the viewport during
+ // infinite scroll, so we only sort when the listing resets (length shrinks or
+ // zeros), where re-ordering is safe.
+ const channelActive = Boolean(channelOwner || channelTagsKey);
+ const [stableCache, setStableCache] = useState<{
+ source: HfModelResult[] | null;
+ length: number;
+ results: HfModelResult[];
+ sorted: boolean;
+ }>({ source: null, length: 0, results: [], sorted: false });
+
+ const incoming = search.results;
+ const sortingDisabled =
+ !pinUnslothFirst || isPublisherQuery || trimmed || channelActive;
+ const { results, nextCache } = useMemo(() => {
+ let results: HfModelResult[];
+ let nextCache = stableCache;
+
+ if (sortingDisabled) {
+ results = incoming;
+ if (stableCache.results !== incoming || stableCache.sorted) {
+ nextCache = {
+ source: incoming,
+ length: incoming.length,
+ results: incoming,
+ sorted: false,
+ };
+ }
+ } else if (incoming.length === 0) {
+ results = incoming;
+ if (
+ stableCache.length !== 0 ||
+ stableCache.results !== incoming ||
+ !stableCache.sorted
+ ) {
+ nextCache = {
+ source: incoming,
+ length: 0,
+ results: incoming,
+ sorted: true,
+ };
+ }
+ } else if (
+ !stableCache.sorted ||
+ stableCache.length === 0 ||
+ incoming.length < stableCache.length ||
+ (incoming.length === stableCache.length && stableCache.source !== incoming)
+ ) {
+ const sorted = [...incoming].sort((a, b) => {
+ const aFirst = a.id.startsWith("unsloth/") ? 0 : 1;
+ const bFirst = b.id.startsWith("unsloth/") ? 0 : 1;
+ return aFirst - bFirst;
+ });
+ results = sorted;
+ nextCache = {
+ source: incoming,
+ length: incoming.length,
+ results: sorted,
+ sorted: true,
+ };
+ } else if (incoming.length === stableCache.length) {
+ results = stableCache.results;
+ } else {
+ const newTail = incoming.slice(stableCache.length);
+ const merged = stableCache.results.concat(newTail);
+ results = merged;
+ nextCache = {
+ source: incoming,
+ length: incoming.length,
+ results: merged,
+ sorted: true,
+ };
+ }
+
+ return { results, nextCache };
+ }, [incoming, sortingDisabled, stableCache]);
+
+ const cacheNeedsUpdate = nextCache !== stableCache;
+ useEffect(() => {
+ if (!cacheNeedsUpdate) return;
+ startTransition(() => {
+ setStableCache((current) =>
+ current === stableCache ? nextCache : current,
+ );
+ });
+ }, [cacheNeedsUpdate, nextCache, stableCache]);
+
+ return { ...search, results };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-model-vram.ts b/studio/frontend/src/features/hub/hooks/use-hub-model-vram.ts
new file mode 100644
index 00000000000..db20d09a15e
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-hub-model-vram.ts
@@ -0,0 +1,50 @@
+// 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 { useMemo } from "react";
+import type { GpuInfo } from "@/hooks/use-gpu-info";
+import {
+ type VramFitStatus,
+ checkVramFit,
+ estimateLoadingVram,
+} from "@/lib/vram";
+import { formatBytes } from "@/features/hub/lib/format";
+import type { SelectedModelView } from "../types";
+
+export interface ModelVramInfo {
+ est: number;
+ status: VramFitStatus;
+}
+
+export function useHubModelVram(
+ selectedModel: SelectedModelView | null,
+ gpu: GpuInfo,
+): { vramInfo: ModelVramInfo | null; minMemory: string | null } {
+ const vramInfo = useMemo<ModelVramInfo | null>(() => {
+ if (!selectedModel || selectedModel.isGguf || !selectedModel.totalParams) {
+ return null;
+ }
+ const est = estimateLoadingVram(selectedModel.totalParams, "qlora");
+ const status = checkVramFit(est, gpu.available ? gpu.memoryTotalGb : 0);
+ return status ? { est, status } : null;
+ }, [gpu, selectedModel]);
+
+ const minMemory = useMemo(() => {
+ if (!selectedModel) return null;
+ if (selectedModel.isGguf) {
+ if (selectedModel.cachedBytes)
+ return formatBytes(selectedModel.cachedBytes);
+ if (selectedModel.estimatedSizeBytes)
+ return formatBytes(selectedModel.estimatedSizeBytes);
+ return null;
+ }
+ if (selectedModel.estimatedSizeBytes)
+ return formatBytes(selectedModel.estimatedSizeBytes);
+ if (vramInfo) return `~${vramInfo.est} GB`;
+ if (selectedModel.cachedBytes)
+ return formatBytes(selectedModel.cachedBytes);
+ return null;
+ }, [selectedModel, vramInfo]);
+
+ return { vramInfo, minMemory };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts
new file mode 100644
index 00000000000..2d6214d4427
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts
@@ -0,0 +1,355 @@
+// 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 { useCallback, useEffect, useRef, useState } from "react";
+
+interface HfPaginatedState<T> {
+ results: T[];
+ scannedCount: number;
+ isLoading: boolean;
+ isLoadingMore: boolean;
+ hasMore: boolean;
+ error: string | null;
+}
+
+const INITIAL: HfPaginatedState<never> = {
+ results: [],
+ scannedCount: 0,
+ isLoading: false,
+ isLoadingMore: false,
+ hasMore: false,
+ error: null,
+};
+const BATCH = 20;
+const MAX_RAW_ITEMS_PER_BATCH = BATCH * 4;
+type BusyKind = "initial" | "more";
+
+/**
+ * Min gap between fetchMore() calls. Two observers can fire in one tick and React
+ * commits the in-flight flag asynchronously, so this caps the worst case at one
+ * request per window. Pairs with a trailing-edge schedule: a blocked call queues
+ * one fire at the window end so filters that starve the visible list keep paginating.
+ */
+const MIN_FETCH_INTERVAL_MS = 1000;
+
+// Preserved results older than this are refetched on re-enable so the feed can't
+// lag the Hub. Reset by every successful pull (idle time only). Mirrors hf-cache TTL.
+const STALE_AFTER_MS = 5 * 60 * 1000;
+
+async function pullBatch<T>(
+ iter: AsyncGenerator<unknown>,
+ mapItem: (raw: unknown) => T | null,
+ size: number,
+) {
+ const items: T[] = [];
+ let scanned = 0;
+ while (items.length < size && scanned < MAX_RAW_ITEMS_PER_BATCH) {
+ const result = await iter.next();
+ if (result.done) {
+ return { items, done: true, scanned };
+ }
+ scanned += 1;
+ const mapped = mapItem(result.value);
+ if (mapped !== null) {
+ items.push(mapped);
+ }
+ }
+ return { items, done: false, scanned };
+}
+
+function isAbortError(err: unknown): boolean {
+ return err instanceof DOMException && err.name === "AbortError";
+}
+
+function isDocumentHidden(): boolean {
+ return typeof document !== "undefined" && document.hidden;
+}
+
+export function useHubPaginatedSearch<T>(
+ createIter: (signal: AbortSignal) => AsyncGenerator<unknown>,
+ mapItem: (raw: unknown) => T | null,
+ options?: { enabled?: boolean },
+): HfPaginatedState<T> & { fetchMore: () => boolean; retry: () => void } {
+ const enabled = options?.enabled ?? true;
+ const [state, setState] = useState<HfPaginatedState<T>>(
+ INITIAL as HfPaginatedState<T>,
+ );
+ const [retryNonce, setRetryNonce] = useState(0);
+ const stateRef = useRef(state);
+ useEffect(() => {
+ stateRef.current = state;
+ }, [state]);
+
+ const iterRef = useRef<AsyncGenerator<unknown> | null>(null);
+ const versionRef = useRef(0);
+ // Aborts the live iterator's in-flight fetches; replaced when a new query
+ // supersedes the feed so the abandoned listing stops fetching/priming.
+ const abortRef = useRef<AbortController | null>(null);
+
+ // Identity of the last-fetched query. A fetch (re)starts only when one of these
+ // changes, never just on `enabled` toggling — keeps tab switches instant.
+ const loadedFactoryRef = useRef<typeof createIter | null>(null);
+ const loadedMapItemRef = useRef<typeof mapItem | null>(null);
+ const loadedNonceRef = useRef(-1);
+ const loadedAtRef = useRef(0);
+
+ // Synchronous in-flight guard, set before any setState so back-to-back
+ // fetchMore() calls can't both pass the gate while React batches the commit.
+ const busyRef = useRef(false);
+ const busyKindRef = useRef<BusyKind | null>(null);
+ const busyTokenRef = useRef(0);
+ // Timestamp of the last accepted request; with the trailing-edge timer below,
+ // enforces at most one accepted request per MIN_FETCH_INTERVAL_MS.
+ const lastFireAtRef = useRef(0);
+ // Pending trailing-edge fire (idempotent) so a time-gated request isn't lost
+ // when no later DOM event would re-trigger us.
+ const trailingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // One follow-up request queued behind an in-flight "load more" pull; scroll
+ // observers fire repeatedly at the bottom but only one should wait.
+ const queuedAfterBusyRef = useRef(false);
+ const queuedWhileHiddenRef = useRef(false);
+
+ const cancelTrailing = useCallback(() => {
+ if (trailingTimerRef.current !== null) {
+ clearTimeout(trailingTimerRef.current);
+ trailingTimerRef.current = null;
+ }
+ }, []);
+
+ const clearDeferredFetch = useCallback(() => {
+ cancelTrailing();
+ queuedAfterBusyRef.current = false;
+ queuedWhileHiddenRef.current = false;
+ }, [cancelTrailing]);
+
+ useEffect(
+ () => () => {
+ abortRef.current?.abort();
+ clearDeferredFetch();
+ },
+ [clearDeferredFetch],
+ );
+
+ useEffect(() => {
+ if (!enabled) {
+ clearDeferredFetch();
+ if (busyRef.current) {
+ versionRef.current += 1;
+ busyTokenRef.current += 1;
+ abortRef.current?.abort();
+ abortRef.current = null;
+ iterRef.current = null;
+ loadedAtRef.current = 0;
+ busyRef.current = false;
+ busyKindRef.current = null;
+ }
+ setState((prev) =>
+ prev.isLoading || prev.isLoadingMore || prev.error
+ ? {
+ ...prev,
+ isLoading: false,
+ isLoadingMore: false,
+ error: null,
+ }
+ : prev,
+ );
+ return;
+ }
+
+ // Same query, still fresh: reuse what we have. Stale results refetch.
+ const sameQuery =
+ loadedFactoryRef.current === createIter &&
+ loadedMapItemRef.current === mapItem &&
+ loadedNonceRef.current === retryNonce;
+ const fresh = Date.now() - loadedAtRef.current < STALE_AFTER_MS;
+ if (sameQuery && fresh && iterRef.current !== null) {
+ return;
+ }
+ loadedFactoryRef.current = createIter;
+ loadedMapItemRef.current = mapItem;
+ loadedNonceRef.current = retryNonce;
+
+ const v = ++versionRef.current;
+ iterRef.current = null;
+ const busyToken = ++busyTokenRef.current;
+ busyRef.current = true;
+ busyKindRef.current = "initial";
+ clearDeferredFetch();
+ abortRef.current?.abort();
+ const controller = new AbortController();
+ abortRef.current = controller;
+ lastFireAtRef.current = Date.now();
+ setState({
+ ...(INITIAL as HfPaginatedState<T>),
+ isLoading: true,
+ });
+
+ const iter = createIter(controller.signal);
+ iterRef.current = iter;
+
+ pullBatch(iter, mapItem, BATCH)
+ .then(({ items, done, scanned }) => {
+ if (versionRef.current !== v) return;
+ loadedAtRef.current = Date.now();
+ setState({
+ results: items,
+ scannedCount: scanned,
+ isLoading: false,
+ isLoadingMore: false,
+ hasMore: !done,
+ error: null,
+ });
+ })
+ .catch((err) => {
+ if (versionRef.current !== v || isAbortError(err)) return;
+ setState({
+ results: [],
+ scannedCount: 0,
+ isLoading: false,
+ isLoadingMore: false,
+ hasMore: false,
+ error: err instanceof Error ? err.message : "Search failed",
+ });
+ })
+ .finally(() => {
+ if (busyTokenRef.current === busyToken) {
+ busyRef.current = false;
+ busyKindRef.current = null;
+ }
+ });
+
+ return () => {
+ clearDeferredFetch();
+ };
+ }, [createIter, mapItem, enabled, retryNonce, clearDeferredFetch]);
+
+ const retry = useCallback(() => {
+ setRetryNonce((n) => n + 1);
+ }, []);
+
+ const fetchMore = useCallback(function fetchMoreInner(): boolean {
+ if (!enabled) {
+ queuedAfterBusyRef.current = false;
+ queuedWhileHiddenRef.current = false;
+ return false;
+ }
+ // Synchronous in-flight gate before any setState, so concurrent fires from
+ // sibling observers all see the same truth and only one proceeds.
+ if (busyRef.current) {
+ if (busyKindRef.current === "more" && stateRef.current.isLoadingMore) {
+ if (queuedAfterBusyRef.current) return false;
+ queuedAfterBusyRef.current = true;
+ return true;
+ }
+ return false;
+ }
+
+ const iter = iterRef.current;
+ const { hasMore } = stateRef.current;
+ if (!iter || !hasMore) {
+ queuedAfterBusyRef.current = false;
+ queuedWhileHiddenRef.current = false;
+ return false;
+ }
+
+ if (isDocumentHidden()) {
+ queuedAfterBusyRef.current = false;
+ if (queuedWhileHiddenRef.current) return false;
+ queuedWhileHiddenRef.current = true;
+ return true;
+ }
+
+ const now = Date.now();
+ const elapsed = now - lastFireAtRef.current;
+
+ if (elapsed < MIN_FETCH_INTERVAL_MS) {
+ // Trailing-edge schedule: calls during the window collapse to one timer.
+ if (trailingTimerRef.current === null) {
+ trailingTimerRef.current = setTimeout(
+ () => {
+ trailingTimerRef.current = null;
+ fetchMoreInner();
+ },
+ MIN_FETCH_INTERVAL_MS - elapsed,
+ );
+ return true;
+ }
+ return false;
+ }
+
+ cancelTrailing();
+ queuedAfterBusyRef.current = false;
+ queuedWhileHiddenRef.current = false;
+ const busyToken = ++busyTokenRef.current;
+ busyRef.current = true;
+ busyKindRef.current = "more";
+ lastFireAtRef.current = now;
+
+ const v = versionRef.current;
+ let shouldScheduleFollowUp = false;
+ setState((prev) => ({ ...prev, isLoadingMore: true }));
+
+ pullBatch(iter, mapItem, BATCH)
+ .then(({ items, done, scanned }) => {
+ if (versionRef.current !== v) return;
+ shouldScheduleFollowUp = !done && queuedAfterBusyRef.current;
+ loadedAtRef.current = Date.now();
+ setState((prev) => ({
+ ...prev,
+ results: [...prev.results, ...items],
+ scannedCount: prev.scannedCount + scanned,
+ isLoadingMore: false,
+ hasMore: !done,
+ // Clear any error left by a prior failed page.
+ error: null,
+ }));
+ })
+ .catch((err) => {
+ if (versionRef.current !== v || isAbortError(err)) return;
+ shouldScheduleFollowUp = false;
+ setState((prev) => ({
+ ...prev,
+ isLoadingMore: false,
+ // Keep results and hasMore=true: the iterator is still valid, so the next
+ // fetchMore() resumes the failed page without discarding the list (retry() restarts from page 1).
+ error: err instanceof Error ? err.message : "Failed to load more",
+ }));
+ })
+ .finally(() => {
+ if (busyTokenRef.current === busyToken) {
+ busyRef.current = false;
+ busyKindRef.current = null;
+ if (
+ shouldScheduleFollowUp &&
+ trailingTimerRef.current === null
+ ) {
+ queuedAfterBusyRef.current = false;
+ const elapsed = Date.now() - lastFireAtRef.current;
+ trailingTimerRef.current = setTimeout(
+ () => {
+ trailingTimerRef.current = null;
+ fetchMoreInner();
+ },
+ Math.max(0, MIN_FETCH_INTERVAL_MS - elapsed),
+ );
+ }
+ }
+ });
+ return true;
+ }, [enabled, mapItem, cancelTrailing]);
+
+ useEffect(() => {
+ if (!enabled || typeof document === "undefined") return;
+ const handleVisibilityChange = () => {
+ if (document.hidden || !queuedWhileHiddenRef.current) return;
+ queuedWhileHiddenRef.current = false;
+ fetchMore();
+ };
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+ return () => {
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
+ };
+ }, [enabled, fetchMore]);
+
+ return { ...state, fetchMore, retry };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-is-hub-desktop.ts b/studio/frontend/src/features/hub/hooks/use-is-hub-desktop.ts
new file mode 100644
index 00000000000..cfbf7c1e4e6
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-is-hub-desktop.ts
@@ -0,0 +1,22 @@
+// 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 { useSyncExternalStore } from "react";
+
+const HUB_DESKTOP_QUERY = "(min-width: 1024px)";
+
+function getSnapshot(): boolean {
+ if (typeof window === "undefined") return true;
+ return window.matchMedia(HUB_DESKTOP_QUERY).matches;
+}
+
+function subscribe(callback: () => void): () => void {
+ if (typeof window === "undefined") return () => {};
+ const mql = window.matchMedia(HUB_DESKTOP_QUERY);
+ mql.addEventListener("change", callback);
+ return () => mql.removeEventListener("change", callback);
+}
+
+export function useIsHubDesktop(): boolean {
+ return useSyncExternalStore(subscribe, getSnapshot, () => true);
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-latest-ref.ts b/studio/frontend/src/features/hub/hooks/use-latest-ref.ts
new file mode 100644
index 00000000000..d760dfb2994
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-latest-ref.ts
@@ -0,0 +1,10 @@
+// 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 { useRef, type MutableRefObject } from "react";
+
+export function useLatestRef<T>(value: T): MutableRefObject<T> {
+ const ref = useRef(value);
+ ref.current = value;
+ return ref;
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-models-selection.ts b/studio/frontend/src/features/hub/hooks/use-models-selection.ts
new file mode 100644
index 00000000000..ad86e454e0c
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-models-selection.ts
@@ -0,0 +1,283 @@
+// 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 InventoryResourceFormatHint,
+ findCompleteHfCacheLocalRow,
+ resolveInventoryResource,
+} from "@/features/hub/inventory";
+import type { HfModelResult } from "@/features/hub/hooks/use-hub-model-search";
+import {
+ useCallback,
+ useDeferredValue,
+ useMemo,
+ useState,
+} from "react";
+import {
+ resolveDiscoverSelection,
+ resolveDownloadedSelection,
+} from "../lib/selection-resolution";
+import type {
+ CachedInventoryRow,
+ DiscoverRow,
+ LocalInventoryRow,
+ SelectedModelView,
+} from "../types";
+import { useSelectedModelMetadata } from "./use-selected-model-metadata";
+import { useSelectedModelView } from "./use-selected-model-view";
+
+export interface ModelsSelection {
+ selectedId: string | null;
+ setSelected: (id: string) => void;
+ selectedModel: SelectedModelView | null;
+ metadataUnavailable: boolean;
+ selectionHiddenByFilters: boolean;
+}
+
+function preferredLocalRow(
+ rows: readonly LocalInventoryRow[],
+): LocalInventoryRow | null {
+ return (
+ rows.find((row) => !row.partial && row.source !== "hf_cache") ??
+ rows.find((row) => !row.partial) ??
+ rows[0] ??
+ null
+ );
+}
+
+export function useModelsSelection({
+ isDiscoverTab,
+ isDatasetMode,
+ discoverRows,
+ cachedRows,
+ localRows,
+ filteredDiscoverRows,
+ filteredCachedRows,
+ filteredLocalRows,
+ results,
+ accessToken,
+ online,
+}: {
+ isDiscoverTab: boolean;
+ isDatasetMode: boolean;
+ discoverRows: DiscoverRow[];
+ cachedRows: CachedInventoryRow[];
+ localRows: LocalInventoryRow[];
+ filteredDiscoverRows: DiscoverRow[];
+ filteredCachedRows: CachedInventoryRow[];
+ filteredLocalRows: LocalInventoryRow[];
+ results: HfModelResult[];
+ accessToken: string | undefined;
+ online: boolean;
+}): ModelsSelection {
+ // Per-tab selection so switching keeps each list's highlighted row.
+ const [discoverSelectedId, setDiscoverSelectedId] = useState<string | null>(
+ null,
+ );
+ const [downloadedSelectedId, setDownloadedSelectedId] = useState<
+ string | null
+ >(null);
+ const [discoverSelectedSnapshot, setDiscoverSelectedSnapshot] =
+ useState<DiscoverRow | null>(null);
+
+ const [prevDatasetMode, setPrevDatasetMode] = useState(isDatasetMode);
+ if (prevDatasetMode !== isDatasetMode) {
+ setPrevDatasetMode(isDatasetMode);
+ setDiscoverSelectedId(null);
+ setDiscoverSelectedSnapshot(null);
+ }
+
+ const discoverRowById = useMemo(
+ () => new Map(discoverRows.map((row) => [row.id, row])),
+ [discoverRows],
+ );
+ const cachedRowById = useMemo(
+ () => new Map(cachedRows.map((row) => [row.id, row])),
+ [cachedRows],
+ );
+ const localRowById = useMemo(
+ () => new Map(localRows.map((row) => [row.id, row])),
+ [localRows],
+ );
+ const localRowsByRepo = useMemo(() => {
+ const map = new Map<string, LocalInventoryRow[]>();
+ for (const row of localRows) {
+ if (!row.repoId) {
+ continue;
+ }
+ const key = row.repoId.toLowerCase();
+ const rows = map.get(key);
+ if (rows) {
+ rows.push(row);
+ } else {
+ map.set(key, [row]);
+ }
+ }
+ return map;
+ }, [localRows]);
+ const resultByRepo = useMemo(
+ () => new Map(results.map((row) => [row.id.toLowerCase(), row])),
+ [results],
+ );
+
+ const discoverResolution = useMemo(
+ () =>
+ resolveDiscoverSelection({
+ selectedId: discoverSelectedId,
+ discoverRows,
+ filteredDiscoverRows,
+ selectedSnapshotId: discoverSelectedSnapshot?.id ?? null,
+ }),
+ [
+ discoverRows,
+ discoverSelectedId,
+ discoverSelectedSnapshot,
+ filteredDiscoverRows,
+ ],
+ );
+ const downloadedResolution = useMemo(
+ () =>
+ resolveDownloadedSelection({
+ selectedId: downloadedSelectedId,
+ cachedRows,
+ localRows,
+ filteredCachedRows,
+ filteredLocalRows,
+ }),
+ [
+ cachedRows,
+ downloadedSelectedId,
+ filteredCachedRows,
+ filteredLocalRows,
+ localRows,
+ ],
+ );
+ const selectedId = isDiscoverTab
+ ? discoverResolution.selectedId
+ : downloadedResolution.selectedId;
+ const selectionHiddenByFilters = isDiscoverTab
+ ? discoverResolution.hiddenByFilters
+ : downloadedResolution.hiddenByFilters;
+ const detailSelectedId = useDeferredValue(selectedId);
+ const setSelected = useCallback(
+ (id: string) => {
+ if (isDiscoverTab) {
+ setDiscoverSelectedId(id);
+ setDiscoverSelectedSnapshot(discoverRowById.get(id) ?? null);
+ } else {
+ setDownloadedSelectedId(id);
+ }
+ },
+ [discoverRowById, isDiscoverTab],
+ );
+
+ const selectedDiscoverRow = useMemo(
+ () =>
+ isDiscoverTab && detailSelectedId
+ ? (discoverRowById.get(detailSelectedId) ??
+ (discoverSelectedSnapshot?.id === detailSelectedId
+ ? discoverSelectedSnapshot
+ : null))
+ : null,
+ [
+ detailSelectedId,
+ discoverRowById,
+ discoverSelectedSnapshot,
+ isDiscoverTab,
+ ],
+ );
+
+ const selectedDiscoverResource = useMemo(() => {
+ if (!selectedDiscoverRow) return null;
+ const formatHint: InventoryResourceFormatHint = isDatasetMode
+ ? null
+ : selectedDiscoverRow.result.isGguf
+ ? "gguf"
+ : "non-gguf";
+ return resolveInventoryResource({
+ repoId: selectedDiscoverRow.result.id,
+ cachedRows,
+ localRows,
+ formatHint,
+ });
+ }, [cachedRows, isDatasetMode, localRows, selectedDiscoverRow]);
+
+ const selectedCachedRow = useMemo(() => {
+ if (selectedDiscoverResource) return selectedDiscoverResource.cachedRow;
+ if (!detailSelectedId) return null;
+ const cached = cachedRowById.get(detailSelectedId) ?? null;
+ if (!cached?.partial) return cached;
+ const completeLocal = findCompleteHfCacheLocalRow(cached, localRows);
+ return completeLocal ? null : cached;
+ }, [cachedRowById, detailSelectedId, localRows, selectedDiscoverResource]);
+
+ const selectedLocalRow = useMemo(() => {
+ if (selectedDiscoverResource) return selectedDiscoverResource.localRow;
+ if (!detailSelectedId) return null;
+ const direct = localRowById.get(detailSelectedId);
+ if (direct) return direct;
+ const cached = cachedRowById.get(detailSelectedId);
+ if (cached?.partial) {
+ return findCompleteHfCacheLocalRow(cached, localRows);
+ }
+ const repoKey = isDiscoverTab
+ ? selectedDiscoverRow?.result.id.toLowerCase()
+ : detailSelectedId.toLowerCase();
+ return repoKey ? preferredLocalRow(localRowsByRepo.get(repoKey) ?? []) : null;
+ }, [
+ detailSelectedId,
+ cachedRowById,
+ isDiscoverTab,
+ localRowById,
+ localRows,
+ localRowsByRepo,
+ selectedDiscoverResource,
+ selectedDiscoverRow,
+ ]);
+
+ const selectedHubRepoId =
+ selectedDiscoverRow?.result.id ??
+ selectedCachedRow?.repoId ??
+ (selectedLocalRow?.source === "hf_cache"
+ ? selectedLocalRow.repoId
+ : null) ??
+ null;
+ const selectedMetadataRepoId =
+ selectedHubRepoId ?? selectedLocalRow?.baseModelHubId ?? null;
+
+ const selectedResultFromFeed = useMemo(
+ () =>
+ selectedMetadataRepoId
+ ? (resultByRepo.get(selectedMetadataRepoId.toLowerCase()) ?? null)
+ : null,
+ [resultByRepo, selectedMetadataRepoId],
+ );
+
+ const selectedRepoMetadata = useSelectedModelMetadata(selectedMetadataRepoId, {
+ accessToken,
+ enabled: !isDatasetMode && !selectedResultFromFeed,
+ online,
+ });
+ const selectedHfResult = selectedResultFromFeed ?? selectedRepoMetadata.result;
+ const metadataUnavailable =
+ !isDatasetMode &&
+ !selectedResultFromFeed &&
+ !!selectedHubRepoId &&
+ selectedRepoMetadata.error;
+
+ const selectedModel = useSelectedModelView({
+ selectedDiscoverRow,
+ selectedCachedRow,
+ selectedLocalRow,
+ selectedHfResult,
+ isDatasetMode,
+ });
+
+ return {
+ selectedId,
+ setSelected,
+ selectedModel,
+ metadataUnavailable,
+ selectionHiddenByFilters,
+ };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-online-status.ts b/studio/frontend/src/features/hub/hooks/use-online-status.ts
new file mode 100644
index 00000000000..cf73a74fc81
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-online-status.ts
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ getBrowserOfflineRetryDelayMs,
+ isHuggingFaceOffline,
+ subscribeNetworkStatus,
+} from "@/features/hub/lib/network";
+import { useSyncExternalStore } from "react";
+
+function getOnlineSnapshot(): boolean {
+ return !isHuggingFaceOffline();
+}
+
+function getServerOnlineSnapshot(): boolean {
+ return true;
+}
+
+function subscribeOnlineStatus(onStoreChange: () => void): () => void {
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const clearRetryTimer = () => {
+ if (timer === null) {
+ return;
+ }
+ clearTimeout(timer);
+ timer = null;
+ };
+ const scheduleRetry = () => {
+ clearRetryTimer();
+ const retryDelay = getBrowserOfflineRetryDelayMs();
+ if (retryDelay > 0) {
+ timer = setTimeout(handleChange, retryDelay + 50);
+ }
+ };
+ const handleChange = () => {
+ onStoreChange();
+ scheduleRetry();
+ };
+ const unsubscribe = subscribeNetworkStatus(handleChange);
+ scheduleRetry();
+ return () => {
+ clearRetryTimer();
+ unsubscribe();
+ };
+}
+
+export function useOnlineStatus(): boolean {
+ return useSyncExternalStore(
+ subscribeOnlineStatus,
+ getOnlineSnapshot,
+ getServerOnlineSnapshot,
+ );
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-selected-model-metadata.ts b/studio/frontend/src/features/hub/hooks/use-selected-model-metadata.ts
new file mode 100644
index 00000000000..2072f37d557
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-selected-model-metadata.ts
@@ -0,0 +1,74 @@
+// 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 { HfModelResult } from "@/features/hub/hooks/use-hub-model-search";
+import { cachedModelInfo } from "../lib/hf-cache";
+import { useEffect, useState } from "react";
+import { toHfModelResult } from "../lib/view-models";
+
+type SelectedModelMetadataResult = ReturnType<typeof toHfModelResult>;
+
+export function useSelectedModelMetadata(
+ repoId: string | null,
+ {
+ accessToken,
+ enabled,
+ online,
+ }: {
+ accessToken: string | undefined;
+ enabled: boolean;
+ online: boolean;
+ },
+): { result: SelectedModelMetadataResult; error: boolean } {
+ const [state, setState] = useState<{
+ repoId: string;
+ result: HfModelResult | null;
+ error: boolean;
+ }>(() => ({ repoId: "", result: null, error: false }));
+
+ useEffect(() => {
+ if (!(repoId && enabled && online)) {
+ return;
+ }
+
+ // No AbortController: cachedModelInfo shares one in-flight request per repo
+ // across callers (hf-cache.ts), so aborting would cancel it for everyone.
+ // The `cancelled` flag plus the state.repoId guard prevent stale writes.
+ let cancelled = false;
+
+ cachedModelInfo({
+ name: repoId,
+ ...(accessToken ? { accessToken } : {}),
+ })
+ .then((result) => {
+ if (cancelled) {
+ return;
+ }
+ setState({
+ repoId,
+ result: toHfModelResult(result),
+ error: false,
+ });
+ })
+ .catch(() => {
+ if (cancelled) {
+ return;
+ }
+ setState({
+ repoId,
+ result: null,
+ error: true,
+ });
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [repoId, accessToken, enabled, online]);
+
+ if (state.repoId !== repoId) {
+ return { result: null, error: false };
+ }
+
+ return { result: state.result, error: state.error };
+}
diff --git a/studio/frontend/src/features/hub/hooks/use-selected-model-view.ts b/studio/frontend/src/features/hub/hooks/use-selected-model-view.ts
new file mode 100644
index 00000000000..4616aba4bd9
--- /dev/null
+++ b/studio/frontend/src/features/hub/hooks/use-selected-model-view.ts
@@ -0,0 +1,391 @@
+// 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 { useMemo } from "react";
+import { detectCapabilities, detectLicense } from "../lib/model-capabilities";
+import { buildSummary, localSourceLabel, toHfModelResult } from "../lib/view-models";
+import type {
+ CachedInventoryRow,
+ DiscoverRow,
+ LocalInventoryRow,
+ SelectedResourceRef,
+ SelectedModelView,
+} from "../types";
+
+type HfResult = ReturnType<typeof toHfModelResult>;
+
+function detectViewCapabilities(
+ tags: string[] | undefined,
+ pipelineTag: string | undefined,
+ ...identifiers: Array<string | null | undefined>
+) {
+ const modelId = identifiers.filter(Boolean).join(" ");
+ return detectCapabilities(tags, pipelineTag, modelId);
+}
+
+function cachedResource(row: CachedInventoryRow): SelectedResourceRef {
+ return {
+ repoId: row.repoId,
+ localPath: row.cachePath ?? null,
+ source: "hub_cache",
+ cacheState: row.partial ? "partial" : "cached",
+ runId: row.loadId,
+ trainId: row.loadId,
+ };
+}
+
+function localResource(
+ row: LocalInventoryRow,
+ repoId: string | null = row.repoId,
+): SelectedResourceRef {
+ const cacheState = row.partial
+ ? "partial"
+ : row.source === "hf_cache"
+ ? "cached"
+ : "local";
+ const id =
+ row.source === "hf_cache" && repoId && !row.partial ? repoId : row.loadId;
+ return {
+ repoId,
+ localPath: row.path,
+ source: row.source,
+ cacheState,
+ runId: id,
+ trainId: id,
+ };
+}
+
+function remoteResource(row: DiscoverRow): SelectedResourceRef {
+ return {
+ repoId: row.result.id,
+ localPath: null,
+ source: "huggingface",
+ cacheState: row.isPartialOnDevice ? "partial" : "remote",
+ runId: row.result.id,
+ trainId: row.result.id,
+ };
+}
+
+function localFormatLabel(row: LocalInventoryRow): string {
+ if (row.modelFormat === "gguf") return "local GGUF";
+ if (row.modelFormat === "adapter") return "local adapter";
+ if (row.modelFormat === "safetensors") return "local safetensors model";
+ if (row.modelFormat === "checkpoint") return "local checkpoint";
+ return "local model";
+}
+
+export function useSelectedModelView({
+ selectedDiscoverRow,
+ selectedCachedRow,
+ selectedLocalRow,
+ selectedHfResult,
+ isDatasetMode,
+}: {
+ selectedDiscoverRow: DiscoverRow | null;
+ selectedCachedRow: CachedInventoryRow | null;
+ selectedLocalRow: LocalInventoryRow | null;
+ selectedHfResult: HfResult;
+ isDatasetMode: boolean;
+}): SelectedModelView | null {
+ return useMemo<SelectedModelView | null>(() => {
+ if (selectedDiscoverRow) {
+ if (
+ !selectedCachedRow &&
+ selectedLocalRow &&
+ selectedLocalRow.source !== "hf_cache"
+ ) {
+ const resource = localResource(
+ selectedLocalRow,
+ selectedDiscoverRow.result.id,
+ );
+ return {
+ id: resource.runId,
+ kind: "local",
+ resource,
+ displayId: selectedDiscoverRow.id,
+ hubRepoId: selectedDiscoverRow.result.id,
+ owner: selectedDiscoverRow.owner,
+ title: selectedDiscoverRow.repo,
+ summary: selectedHfResult
+ ? buildSummary(selectedHfResult)
+ : selectedDiscoverRow.summary,
+ sourceLabel: selectedLocalRow.sourceLabel,
+ path: selectedLocalRow.path,
+ localSource: selectedLocalRow.source,
+ isLocal: true,
+ isGguf: selectedLocalRow.isGguf || selectedDiscoverRow.result.isGguf,
+ requiresVariant: selectedLocalRow.capabilities.requiresVariant,
+ modelFormat:
+ selectedLocalRow.modelFormat !== "unknown"
+ ? selectedLocalRow.modelFormat
+ : selectedDiscoverRow.result.isGguf
+ ? "gguf"
+ : null,
+ isDownloaded: !selectedLocalRow.partial,
+ isPartial: selectedLocalRow.partial ?? false,
+ partialTransport: selectedLocalRow.partialTransport ?? null,
+ runtimeCapabilities: selectedLocalRow.capabilities,
+ capabilities: selectedDiscoverRow.capabilities,
+ license: detectLicense(selectedDiscoverRow.result.tags),
+ pipelineTag: selectedDiscoverRow.result.pipelineTag,
+ libraryName: selectedDiscoverRow.result.libraryName,
+ downloads: selectedDiscoverRow.result.downloads,
+ likes: selectedDiscoverRow.result.likes,
+ totalParams: selectedDiscoverRow.result.totalParams,
+ estimatedSizeBytes: selectedDiscoverRow.result.estimatedSizeBytes,
+ updatedAt: selectedDiscoverRow.result.updatedAt,
+ localUpdatedAt: selectedLocalRow.updatedAt,
+ tags: selectedDiscoverRow.result.tags,
+ quantMethod: selectedDiscoverRow.result.quantMethod,
+ };
+ }
+
+ const onDevicePath =
+ selectedCachedRow?.cachePath ?? selectedLocalRow?.path ?? null;
+ const resource = selectedCachedRow
+ ? cachedResource(selectedCachedRow)
+ : selectedLocalRow?.source === "hf_cache"
+ ? localResource(selectedLocalRow, selectedDiscoverRow.result.id)
+ : remoteResource(selectedDiscoverRow);
+ const isResolvedPartial = resource.cacheState === "partial";
+ const isResolvedOnDevice =
+ resource.cacheState === "cached" || resource.cacheState === "local";
+ const resolvedModelFormat =
+ selectedCachedRow?.modelFormat ??
+ (selectedLocalRow?.modelFormat && selectedLocalRow.modelFormat !== "unknown"
+ ? selectedLocalRow.modelFormat
+ : selectedDiscoverRow.result.isGguf
+ ? "gguf"
+ : null);
+ return {
+ id: selectedDiscoverRow.id,
+ kind: "discover",
+ resource,
+ displayId: selectedDiscoverRow.id,
+ hubRepoId: selectedDiscoverRow.result.id,
+ owner: selectedDiscoverRow.owner,
+ title: selectedDiscoverRow.repo,
+ summary: selectedDiscoverRow.summary,
+ sourceLabel: isResolvedOnDevice
+ ? "On device"
+ : isResolvedPartial
+ ? "Partial on device"
+ : "Hugging Face",
+ path: onDevicePath,
+ isLocal: false,
+ isGguf:
+ selectedCachedRow?.isGguf ??
+ selectedLocalRow?.isGguf ??
+ selectedDiscoverRow.result.isGguf,
+ requiresVariant:
+ selectedCachedRow?.capabilities.requiresVariant ??
+ selectedLocalRow?.capabilities.requiresVariant ??
+ selectedDiscoverRow.result.isGguf,
+ modelFormat: resolvedModelFormat,
+ isDownloaded: isResolvedOnDevice,
+ isPartial: isResolvedPartial,
+ partialTransport:
+ selectedCachedRow?.partialTransport ??
+ selectedLocalRow?.partialTransport ??
+ null,
+ runtimeCapabilities:
+ selectedCachedRow?.capabilities ?? selectedLocalRow?.capabilities,
+ capabilities: selectedDiscoverRow.capabilities,
+ license: detectLicense(selectedDiscoverRow.result.tags),
+ pipelineTag: selectedDiscoverRow.result.pipelineTag,
+ libraryName: selectedDiscoverRow.result.libraryName,
+ downloads: selectedDiscoverRow.result.downloads,
+ likes: selectedDiscoverRow.result.likes,
+ totalParams: selectedDiscoverRow.result.totalParams,
+ estimatedSizeBytes: selectedDiscoverRow.result.estimatedSizeBytes,
+ cachedBytes: selectedCachedRow?.bytes,
+ updatedAt: selectedDiscoverRow.result.updatedAt,
+ tags: selectedDiscoverRow.result.tags,
+ quantMethod: selectedDiscoverRow.result.quantMethod,
+ };
+ }
+
+ if (selectedCachedRow) {
+ const resource = cachedResource(selectedCachedRow);
+ const cachedSummary = isDatasetMode
+ ? "Cached dataset, ready to use."
+ : selectedCachedRow.isGguf
+ ? "Cached GGUF repository ready for local inference."
+ : "Cached checkpoint repository ready for local inference.";
+ const mergedTags = selectedHfResult?.tags ?? selectedCachedRow.tags;
+ const mergedPipelineTag =
+ selectedHfResult?.pipelineTag ?? selectedCachedRow.pipelineTag ?? undefined;
+ const mergedLibraryName =
+ selectedHfResult?.libraryName ?? selectedCachedRow.libraryName ?? undefined;
+ const mergedQuantMethod =
+ selectedHfResult?.quantMethod ?? selectedCachedRow.quantMethod ?? undefined;
+ return {
+ id: selectedCachedRow.repoId,
+ kind: "cache",
+ resource,
+ displayId: selectedCachedRow.repoId,
+ hubRepoId: selectedCachedRow.repoId,
+ owner: selectedCachedRow.owner,
+ title: selectedCachedRow.repo,
+ summary: selectedHfResult
+ ? buildSummary(selectedHfResult)
+ : cachedSummary,
+ sourceLabel: "Hub cache",
+ path: selectedCachedRow.cachePath ?? null,
+ isLocal: false,
+ isGguf: selectedCachedRow.isGguf,
+ requiresVariant: selectedCachedRow.capabilities.requiresVariant,
+ modelFormat: selectedCachedRow.modelFormat,
+ isDownloaded: !selectedCachedRow.partial,
+ isPartial: selectedCachedRow.partial ?? false,
+ partialTransport: selectedCachedRow.partialTransport ?? null,
+ runtimeCapabilities: selectedCachedRow.capabilities,
+ capabilities: detectViewCapabilities(
+ mergedTags,
+ mergedPipelineTag,
+ selectedCachedRow.repoId,
+ selectedCachedRow.loadId,
+ selectedCachedRow.repo,
+ ),
+ license: detectLicense(mergedTags),
+ pipelineTag: mergedPipelineTag,
+ libraryName: mergedLibraryName,
+ downloads: selectedHfResult?.downloads,
+ likes: selectedHfResult?.likes,
+ totalParams: selectedHfResult?.totalParams,
+ estimatedSizeBytes: selectedHfResult?.estimatedSizeBytes,
+ cachedBytes: selectedCachedRow.bytes,
+ updatedAt: selectedHfResult?.updatedAt,
+ tags: mergedTags,
+ quantMethod: mergedQuantMethod,
+ };
+ }
+
+ if (selectedLocalRow) {
+ const localHubRepoId =
+ selectedLocalRow.source === "hf_cache" ? selectedLocalRow.repoId : null;
+ const resource = localResource(selectedLocalRow, localHubRepoId);
+ const localDisplayId = selectedLocalRow.repoId ?? selectedLocalRow.loadId;
+ const isPartialHubCache =
+ selectedLocalRow.source === "hf_cache" &&
+ !!selectedLocalRow.partial &&
+ !!selectedLocalRow.repoId;
+ const mergedTags = selectedHfResult?.tags ?? selectedLocalRow.tags;
+ const mergedPipelineTag =
+ selectedHfResult?.pipelineTag ??
+ selectedLocalRow.pipelineTag ??
+ undefined;
+ const mergedLibraryName =
+ selectedHfResult?.libraryName ??
+ selectedLocalRow.libraryName ??
+ undefined;
+ const mergedQuantMethod =
+ selectedHfResult?.quantMethod ??
+ selectedLocalRow.quantMethod ??
+ undefined;
+ const baseModelSummary = selectedLocalRow.baseModel && selectedHfResult
+ ? buildSummary(selectedHfResult)
+ : null;
+ const localHubMetadata = localHubRepoId ? selectedHfResult : null;
+
+ if (isPartialHubCache && selectedLocalRow.repoId) {
+ return {
+ id: selectedLocalRow.repoId,
+ kind: "cache",
+ resource,
+ displayId: selectedLocalRow.repoId,
+ hubRepoId: selectedLocalRow.repoId,
+ owner: selectedLocalRow.owner,
+ title: selectedLocalRow.title,
+ summary: selectedHfResult
+ ? buildSummary(selectedHfResult)
+ : "Partial download. Resume to finish or delete to free space.",
+ sourceLabel: "Hub cache",
+ path: selectedLocalRow.path,
+ isLocal: false,
+ isGguf: selectedLocalRow.isGguf,
+ requiresVariant: selectedLocalRow.capabilities.requiresVariant,
+ modelFormat: selectedLocalRow.modelFormat,
+ isDownloaded: false,
+ isPartial: true,
+ partialTransport: selectedLocalRow.partialTransport ?? null,
+ runtimeCapabilities: selectedLocalRow.capabilities,
+ capabilities: detectViewCapabilities(
+ mergedTags,
+ mergedPipelineTag,
+ selectedLocalRow.repoId,
+ selectedLocalRow.loadId,
+ selectedLocalRow.title,
+ selectedLocalRow.path,
+ ),
+ license: detectLicense(mergedTags),
+ pipelineTag: mergedPipelineTag,
+ libraryName: mergedLibraryName,
+ downloads: selectedHfResult?.downloads,
+ likes: selectedHfResult?.likes,
+ totalParams: selectedHfResult?.totalParams,
+ estimatedSizeBytes: selectedHfResult?.estimatedSizeBytes,
+ updatedAt: selectedHfResult?.updatedAt,
+ localUpdatedAt: selectedLocalRow.updatedAt,
+ tags: mergedTags,
+ quantMethod: mergedQuantMethod,
+ };
+ }
+
+ return {
+ id: selectedLocalRow.loadId,
+ kind: "local",
+ resource,
+ displayId: localDisplayId,
+ hubRepoId: localHubRepoId,
+ owner: selectedLocalRow.owner,
+ title: selectedLocalRow.title,
+ summary: `${localSourceLabel(selectedLocalRow.source)} · ${localFormatLabel(
+ selectedLocalRow,
+ )}`,
+ sourceLabel: selectedLocalRow.sourceLabel,
+ path: selectedLocalRow.path,
+ localSource: selectedLocalRow.source,
+ isLocal: true,
+ isGguf: selectedLocalRow.isGguf,
+ requiresVariant: selectedLocalRow.capabilities.requiresVariant,
+ modelFormat: selectedLocalRow.modelFormat,
+ baseModel: selectedLocalRow.baseModel ?? null,
+ baseModelSource: selectedLocalRow.baseModelSource ?? null,
+ baseModelHubId: selectedLocalRow.baseModelHubId ?? null,
+ baseModelSummary,
+ adapterType: selectedLocalRow.adapterType ?? null,
+ trainingMethod: selectedLocalRow.trainingMethod ?? null,
+ isDownloaded: true,
+ runtimeCapabilities: selectedLocalRow.capabilities,
+ capabilities: detectViewCapabilities(
+ mergedTags,
+ mergedPipelineTag,
+ selectedLocalRow.repoId ?? selectedLocalRow.title,
+ selectedLocalRow.baseModel,
+ selectedLocalRow.loadId,
+ selectedLocalRow.path,
+ ),
+ license: detectLicense(mergedTags),
+ pipelineTag: mergedPipelineTag,
+ libraryName: mergedLibraryName,
+ downloads: localHubMetadata?.downloads,
+ likes: localHubMetadata?.likes,
+ totalParams: localHubMetadata?.totalParams,
+ estimatedSizeBytes: localHubMetadata?.estimatedSizeBytes,
+ updatedAt: localHubMetadata?.updatedAt,
+ localUpdatedAt: selectedLocalRow.updatedAt,
+ tags: mergedTags,
+ quantMethod: mergedQuantMethod,
+ };
+ }
+
+ return null;
+ }, [
+ isDatasetMode,
+ selectedCachedRow,
+ selectedDiscoverRow,
+ selectedHfResult,
+ selectedLocalRow,
+ ]);
+}
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
new file mode 100644
index 00000000000..f606a9941ae
--- /dev/null
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -0,0 +1,770 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Hub page: browse + download surface only. Train CTA hidden until Hub->train picker ships.
+import { useHubInventory } from "@/features/hub/inventory";
+import { useDebouncedValue } from "@/hooks/use-debounced-value";
+import { useGpuInfo } from "@/hooks/use-gpu-info";
+import {
+ type HfSortDirection,
+ type HfSortKey,
+} from "@/features/hub/hooks/use-hub-model-search";
+import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
+import { useIsHubDesktop } from "@/features/hub/hooks/use-is-hub-desktop";
+import { useHubInfiniteScroll } from "@/features/hub/hooks/use-hub-infinite-scroll";
+import { modelIdsMatch } from "@/features/hub/lib/model-identity";
+import { cn } from "@/lib/utils";
+import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";
+import { ArrowLeft01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+import {
+ useCallback,
+ useDeferredValue,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { ModelInspector } from "./catalog/model-inspector";
+import {
+ ModelsCatalog,
+ type ModelsCatalogHandlers,
+ type ModelsCatalogPagination,
+ type ModelsCatalogState,
+} from "./catalog/models-catalog";
+import { ModelsHeader } from "./catalog/models-header";
+import { ModelsToolbar } from "./catalog/models-toolbar";
+import { ExternalLinkConfirmDialog } from "./catalog/external-link-confirm-dialog";
+import { OnDeviceFoldersDialog } from "./catalog/on-device-folders-dialog";
+import { useDiscoverSearch } from "./hooks/use-discover-search";
+import { useHubModelVram } from "./hooks/use-hub-model-vram";
+import { useModelsSelection } from "./hooks/use-models-selection";
+import {
+ type ChannelId,
+ type ChannelPreset,
+ findChannel,
+} from "./lib/channels";
+import { inventoryRowMatches, tokenizeQuery } from "./lib/inventory-search";
+import {
+ buildDiscoverRows,
+ matchesCapability,
+ matchesFormat,
+} from "./lib/view-models";
+import type {
+ CachedInventoryRow,
+ CapabilityFilter,
+ DiscoverRow,
+ LocalInventoryRow,
+ ModelFormatFilter,
+ ModelsTab,
+ ResourceTypeFilter,
+ SelectedModelView,
+} from "./types";
+
+const MODELS_TAB_STORAGE_KEY = "unsloth.hub.modelsTab";
+
+const DEFAULT_DISCOVER_CHANNEL: ChannelId = "unsloth-trending";
+
+type ModelLoadOptions = { ggufVariant?: string; expectedBytes?: number };
+
+function discoveryInventorySignature(
+ cachedRows: readonly CachedInventoryRow[],
+ localRows: readonly LocalInventoryRow[],
+): string {
+ const parts: string[] = [];
+ for (const row of cachedRows) {
+ parts.push(
+ `c:${row.repoId.toLowerCase()}:${row.modelFormat}:${row.partial ? "p" : "c"}`,
+ );
+ }
+ for (const row of localRows) {
+ parts.push(
+ `l:${(row.repoId ?? row.id).toLowerCase()}:${row.modelFormat}:${row.partial ? "p" : "c"}`,
+ );
+ }
+ return parts.sort().join("|");
+}
+
+function readModelsTabPreference(): ModelsTab | null {
+ if (typeof window === "undefined") {
+ return null;
+ }
+ try {
+ const value = window.localStorage.getItem(MODELS_TAB_STORAGE_KEY);
+ return value === "discover" || value === "downloaded" ? value : null;
+ } catch {
+ return null;
+ }
+}
+
+function writeModelsTabPreference(tab: ModelsTab): void {
+ if (typeof window === "undefined") {
+ return;
+ }
+ try {
+ window.localStorage.setItem(MODELS_TAB_STORAGE_KEY, tab);
+ } catch {
+ return;
+ }
+}
+
+function useModelsTabState(): {
+ tab: ModelsTab;
+ setTab: (tab: ModelsTab) => void;
+} {
+ const navigate = useNavigate();
+ const search = useSearch({ from: "/hub" });
+ const urlTab: ModelsTab | null = search.tab ?? null;
+ const [fallbackTab, setFallbackTab] = useState<ModelsTab>(
+ () => readModelsTabPreference() ?? "downloaded",
+ );
+ const tab = urlTab ?? fallbackTab;
+
+ useEffect(() => {
+ if (urlTab !== null) return;
+ void navigate({
+ to: "/hub",
+ search: (prev) => ({ ...prev, tab: fallbackTab }),
+ replace: true,
+ });
+ }, [urlTab, fallbackTab, navigate]);
+
+ const setTab = useCallback(
+ (next: ModelsTab) => {
+ setFallbackTab(next);
+ writeModelsTabPreference(next);
+ void navigate({
+ to: "/hub",
+ search: (prev) => ({ ...prev, tab: next }),
+ replace: true,
+ });
+ },
+ [navigate],
+ );
+
+ return { tab, setTab };
+}
+
+function partitionByMatch<T extends CachedInventoryRow | LocalInventoryRow>(
+ rows: T[],
+ tokens: readonly string[],
+): T[] {
+ if (tokens.length === 0) return rows;
+ const matches: T[] = [];
+ const rest: T[] = [];
+ for (const row of rows) {
+ if (inventoryRowMatches(row, tokens)) matches.push(row);
+ else rest.push(row);
+ }
+ return [...matches, ...rest];
+}
+
+function selectedRepoMatchesRuntime(
+ selectedModel: SelectedModelView | null,
+ runtimeId: string | null,
+ ggufVariant: string | null,
+): boolean {
+ if (!selectedModel || !runtimeId) return false;
+ if (!modelIdsMatch(runtimeId, selectedModel.resource.runId)) return false;
+ if (selectedModel.modelFormat === "gguf") {
+ const localPath =
+ selectedModel.resource.localPath ?? selectedModel.path ?? "";
+ return ggufVariant !== null || localPath.toLowerCase().endsWith(".gguf");
+ }
+ return ggufVariant === null;
+}
+
+export function ModelsPage() {
+ const navigate = useNavigate();
+ const gpu = useGpuInfo();
+ const online = useOnlineStatus();
+
+ // "Use in chat" just navigates to /chat; checkpoint/variant handoff lands with the Hub-aware picker.
+ const activeCheckpoint: string | null = null;
+ const activeGgufVariant: string | null = null;
+ // Stubs so the inspector + load-status memo still typecheck; cast keeps the shape from narrowing to `never`.
+ const loadingModel = null as { id: string } | null;
+ const loadProgress = null as {
+ phase?: "downloading" | "starting";
+ } | null;
+
+ const { tab, setTab: setModelsTab } = useModelsTabState();
+ const [query, setQuery] = useState("");
+ const [sortBy, setSortBy] = useState<HfSortKey>(
+ () => findChannel(DEFAULT_DISCOVER_CHANNEL)?.sort ?? "trendingScore",
+ );
+ const [direction, setDirection] = useState<HfSortDirection>("desc");
+ const [resourceType, setResourceType] =
+ useState<ResourceTypeFilter>("models");
+ const [activeChannelId, setActiveChannelId] = useState<ChannelId | null>(
+ DEFAULT_DISCOVER_CHANNEL,
+ );
+ const activeChannel: ChannelPreset | null = useMemo(
+ () => findChannel(activeChannelId),
+ [activeChannelId],
+ );
+ const [discoverFormat, setDiscoverFormat] = useState<ModelFormatFilter>(
+ () => findChannel(DEFAULT_DISCOVER_CHANNEL)?.format ?? "gguf",
+ );
+ const [downloadedFormat, setDownloadedFormat] =
+ useState<ModelFormatFilter>("all");
+ const isDiscoverTab = tab === "discover";
+ const isDatasetMode = resourceType === "datasets";
+ const formatFilter = isDiscoverTab ? discoverFormat : downloadedFormat;
+ const setFormatFilter = useCallback(
+ (next: ModelFormatFilter) => {
+ if (isDiscoverTab) {
+ setDiscoverFormat(next);
+ } else {
+ setDownloadedFormat(next);
+ }
+ },
+ [isDiscoverTab],
+ );
+ const [capabilityFilter, setCapabilityFilter] =
+ useState<CapabilityFilter>("all");
+ const [mobileInspectorOpen, setMobileInspectorOpen] = useState(false);
+ const isHubDesktop = useIsHubDesktop();
+ const [foldersDialogOpen, setFoldersDialogOpen] = useState(false);
+ const [discoverFetchIntent, setDiscoverFetchIntent] = useState(0);
+
+ const handleTabChange = useCallback(
+ (next: ModelsTab) => {
+ setMobileInspectorOpen(false);
+ setModelsTab(next);
+ },
+ [setModelsTab],
+ );
+
+ const handleResourceTypeChange = useCallback(
+ (next: ResourceTypeFilter) => {
+ if (next === resourceType) return;
+ setResourceType(next);
+ setDownloadedFormat("all");
+ setCapabilityFilter("all");
+ if (next === "models") {
+ const preset = findChannel(DEFAULT_DISCOVER_CHANNEL);
+ setActiveChannelId(DEFAULT_DISCOVER_CHANNEL);
+ setDiscoverFormat(preset?.format ?? "gguf");
+ setSortBy(preset?.sort ?? "trendingScore");
+ setDirection("desc");
+ } else {
+ setActiveChannelId(null);
+ }
+ },
+ [resourceType],
+ );
+
+ const handleChannelSelect = useCallback((next: ChannelId | null) => {
+ setActiveChannelId(next);
+ setCapabilityFilter("all");
+ setQuery("");
+ const preset = findChannel(next);
+ if (preset) {
+ setDiscoverFormat(preset.format);
+ setSortBy(preset.sort);
+ setDirection("desc");
+ }
+ }, []);
+
+ const handleSortChange = useCallback((next: HfSortKey) => {
+ setSortBy(next);
+ if (next === "trendingScore") setDirection("desc");
+ }, []);
+
+ const debouncedQuery = useDebouncedValue(query);
+ const deferredDebouncedQuery = useDeferredValue(debouncedQuery);
+ const hfToken = useHfTokenStore((s) => s.token);
+ const debouncedHfToken = useDebouncedValue(hfToken, 500);
+ const effectiveSort: HfSortKey = sortBy;
+ const deferredFormatFilter = useDeferredValue(formatFilter);
+ const deferredCapabilityFilter = useDeferredValue(capabilityFilter);
+
+ const {
+ results,
+ datasetResults,
+ scannedCount,
+ isLoading,
+ isLoadingMore,
+ hasMore,
+ fetchMore,
+ searchError,
+ handleRetrySearch,
+ } = useDiscoverSearch({
+ debouncedQuery,
+ accessToken: debouncedHfToken || undefined,
+ isDiscoverTab,
+ isDatasetMode,
+ sortBy: effectiveSort,
+ direction,
+ activeChannel,
+ online,
+ });
+
+ const {
+ cachedRows: effectiveCachedRows,
+ localRows: effectiveLocalRows,
+ availableSet,
+ partialSet,
+ downloadedReady,
+ inventoryError,
+ inventoryWarning,
+ refreshInventory,
+ } = useHubInventory({ kind: isDatasetMode ? "datasets" : "models" });
+
+ const modelDiscoveryInventorySignature = useMemo(
+ () =>
+ discoveryInventorySignature(effectiveCachedRows, effectiveLocalRows),
+ [effectiveCachedRows, effectiveLocalRows],
+ );
+ const modelDiscoverRows = useMemo<DiscoverRow[]>(
+ () => buildDiscoverRows(results, effectiveCachedRows, effectiveLocalRows),
+ [results, modelDiscoveryInventorySignature],
+ );
+
+ const datasetDiscoverRows = useMemo<DiscoverRow[]>(() => {
+ if (!isDatasetMode) return [];
+ return datasetResults.map((ds) => {
+ const owner = ds.id.includes("/") ? ds.id.split("/")[0] : "Hub";
+ const repo = ds.id.includes("/")
+ ? ds.id.split("/").slice(1).join("/")
+ : ds.id;
+ const summaryParts: string[] = [];
+ if (ds.taskCategories.length > 0)
+ summaryParts.push(ds.taskCategories.slice(0, 2).join(", "));
+ if (ds.totalExamples)
+ summaryParts.push(`${ds.totalExamples.toLocaleString()} rows`);
+ else if (ds.sizeCategory) summaryParts.push(ds.sizeCategory);
+ const lower = ds.id.toLowerCase();
+ return {
+ id: ds.id,
+ owner,
+ repo,
+ result: {
+ id: ds.id,
+ downloads: ds.downloads,
+ likes: ds.likes,
+ isGguf: false,
+ tags: ds.plainTags,
+ },
+ isAvailableOnDevice: availableSet.has(lower),
+ isPartialOnDevice: partialSet.has(lower),
+ summary: summaryParts.join(" · ") || "Dataset",
+ capabilities: [],
+ };
+ });
+ }, [isDatasetMode, datasetResults, availableSet, partialSet]);
+
+ const discoverRows = isDatasetMode ? datasetDiscoverRows : modelDiscoverRows;
+
+ const filteredDiscoverRows = useMemo(
+ () =>
+ discoverRows.filter((row) => {
+ if (isDatasetMode) return true;
+ return (
+ matchesFormat(row.result.isGguf, deferredFormatFilter) &&
+ matchesCapability(row.capabilities, deferredCapabilityFilter)
+ );
+ }),
+ [
+ discoverRows,
+ isDatasetMode,
+ deferredFormatFilter,
+ deferredCapabilityFilter,
+ ],
+ );
+
+ const inventoryTokens = useMemo(
+ () => (isDiscoverTab ? [] : tokenizeQuery(deferredDebouncedQuery)),
+ [isDiscoverTab, deferredDebouncedQuery],
+ );
+ // Format filter hard-filters; the text query drives dim-not-filter on the On Device
+ // tab so selection survives typing, with matching rows partitioned to the top.
+ const filteredCachedRows = useMemo(
+ () =>
+ partitionByMatch(
+ effectiveCachedRows.filter(
+ (row) =>
+ isDatasetMode ||
+ matchesFormat(row.modelFormat, deferredFormatFilter),
+ ),
+ inventoryTokens,
+ ),
+ [effectiveCachedRows, isDatasetMode, deferredFormatFilter, inventoryTokens],
+ );
+
+ const filteredLocalRows = useMemo(
+ () =>
+ partitionByMatch(
+ effectiveLocalRows.filter(
+ (row) =>
+ isDatasetMode ||
+ matchesFormat(row.modelFormat, deferredFormatFilter),
+ ),
+ inventoryTokens,
+ ),
+ [effectiveLocalRows, isDatasetMode, deferredFormatFilter, inventoryTokens],
+ );
+
+ const filterResetSignature = useMemo(
+ () =>
+ JSON.stringify([
+ deferredDebouncedQuery,
+ resourceType,
+ deferredFormatFilter,
+ deferredCapabilityFilter,
+ effectiveSort,
+ direction,
+ activeChannelId,
+ ]),
+ [
+ deferredDebouncedQuery,
+ resourceType,
+ deferredFormatFilter,
+ deferredCapabilityFilter,
+ effectiveSort,
+ direction,
+ activeChannelId,
+ ],
+ );
+ const handleClearFilters = useCallback(() => {
+ if (isDiscoverTab) {
+ setActiveChannelId(null);
+ setDiscoverFormat("all");
+ } else {
+ setDownloadedFormat("all");
+ }
+ setCapabilityFilter("all");
+ }, [isDiscoverTab]);
+ const handleDiscoverFetchIntent = useCallback(() => {
+ setDiscoverFetchIntent((value) => value + 1);
+ }, []);
+
+ const {
+ scrollRef,
+ sentinelRef,
+ manualFetchAvailable: discoverManualFetchAvailable,
+ fetchMoreManually: fetchMoreDiscoverManually,
+ } = useHubInfiniteScroll(
+ fetchMore,
+ // Re-evaluate off the raw fetched count, not the filtered one: page-level filters
+ // can reject every incoming row, stalling filteredDiscoverRows while results grow.
+ scannedCount,
+ {
+ enabled: online && isDiscoverTab && hasMore,
+ isFetching: isLoading || isLoadingMore,
+ resultCount: filteredDiscoverRows.length,
+ maxAutoFillFetches: 5,
+ manualFetchAfterAutoFill: true,
+ onFetchIntent: handleDiscoverFetchIntent,
+ resetKey: filterResetSignature,
+ },
+ );
+
+ const {
+ selectedId,
+ setSelected,
+ selectedModel,
+ metadataUnavailable,
+ selectionHiddenByFilters,
+ } = useModelsSelection({
+ isDiscoverTab,
+ isDatasetMode,
+ discoverRows,
+ cachedRows: effectiveCachedRows,
+ localRows: effectiveLocalRows,
+ filteredDiscoverRows,
+ filteredCachedRows,
+ filteredLocalRows,
+ results,
+ accessToken: debouncedHfToken || undefined,
+ online,
+ });
+
+ const handleSelect = useCallback(
+ (id: string) => {
+ setSelected(id);
+ // Only flip the mobile drawer in single-pane layout; on lg+ both panes are
+ // visible and setting state here just churns the catalog's virtualizer.
+ if (
+ typeof window !== "undefined" &&
+ window.matchMedia("(max-width: 1023.98px)").matches
+ ) {
+ setMobileInspectorOpen(true);
+ }
+ },
+ [setSelected],
+ );
+ const handleQueryChange = useCallback(
+ (next: string) => {
+ if (activeChannelId) setActiveChannelId(null);
+ setQuery(next);
+ },
+ [activeChannelId],
+ );
+ const handleManageLocalFolders = useCallback(
+ () => setFoldersDialogOpen(true),
+ [],
+ );
+ const handleSwitchDevice = useCallback(
+ () => handleTabChange("downloaded"),
+ [handleTabChange],
+ );
+
+ const isActive = useMemo(
+ () =>
+ selectedRepoMatchesRuntime(
+ selectedModel,
+ activeCheckpoint,
+ activeGgufVariant,
+ ),
+ [activeCheckpoint, activeGgufVariant, selectedModel],
+ );
+
+ const isLoadingThisModel = useMemo(() => {
+ if (!loadingModel) return false;
+ return selectedRepoMatchesRuntime(selectedModel, loadingModel.id, null);
+ }, [loadingModel, selectedModel]);
+
+ const { vramInfo, minMemory } = useHubModelVram(selectedModel, gpu);
+
+ const gpuLabel = gpu.available
+ ? `${Math.floor(gpu.memoryTotalGb)} GB`
+ : "Unavailable";
+ const ramLabel =
+ gpu.systemRamAvailableGb > 0
+ ? `${Math.floor(gpu.systemRamAvailableGb)} GB`
+ : "Unavailable";
+
+ // Load / use-in-chat / train handlers are stubs; they wire in once the
+ // Hub-aware chat and train pickers ship.
+ const handleLoad = useCallback(
+ (_opts: ModelLoadOptions) => undefined,
+ [],
+ );
+ const handleLoadLocal = useCallback(
+ (_opts: ModelLoadOptions = {}) => undefined,
+ [],
+ );
+ const handleUseInChat = useCallback(() => {
+ void navigate({ to: "/chat" });
+ }, [navigate]);
+ const handleTrain = useCallback(() => {
+ // Train CTA hidden until Hub->train picker ships.
+ }, []);
+
+ const inspectorRuntime = useMemo(
+ () => ({
+ isActive,
+ activeGgufVariant,
+ isLoadingThisModel,
+ loadingPhase: loadProgress?.phase,
+ minMemory,
+ vramInfo,
+ gpuGb: gpu.available ? gpu.memoryTotalGb : undefined,
+ systemRamGb:
+ gpu.systemRamAvailableGb > 0 ? gpu.systemRamAvailableGb : undefined,
+ }),
+ [
+ isActive,
+ activeGgufVariant,
+ isLoadingThisModel,
+ loadProgress?.phase,
+ minMemory,
+ vramInfo,
+ gpu.available,
+ gpu.memoryTotalGb,
+ gpu.systemRamAvailableGb,
+ ],
+ );
+
+ const inspectorActions = useMemo(
+ () => ({
+ onLoad: handleLoad,
+ onLoadLocal: handleLoadLocal,
+ onUseInChat: handleUseInChat,
+ onTrain: handleTrain,
+ onInventoryChange: refreshInventory,
+ }),
+ [
+ handleLoad,
+ handleLoadLocal,
+ handleUseInChat,
+ handleTrain,
+ refreshInventory,
+ ],
+ );
+
+ const catalogState = useMemo<ModelsCatalogState>(
+ () => ({
+ tab,
+ discoverRows: filteredDiscoverRows,
+ cachedRows: filteredCachedRows,
+ localRows: filteredLocalRows,
+ selectedId,
+ isLoading,
+ downloadedReady,
+ inventoryError,
+ inventoryWarning,
+ query,
+ activeCheckpoint,
+ activeGgufVariant,
+ searchError,
+ online,
+ isDataset: isDatasetMode,
+ inventoryTokens,
+ scannedCount,
+ loadingIntentCount: discoverFetchIntent,
+ hasMore,
+ manualFetchAvailable: discoverManualFetchAvailable,
+ hasActiveFilters:
+ deferredFormatFilter !== "all" || deferredCapabilityFilter !== "all",
+ }),
+ [
+ tab,
+ filteredDiscoverRows,
+ filteredCachedRows,
+ filteredLocalRows,
+ selectedId,
+ isLoading,
+ downloadedReady,
+ inventoryError,
+ inventoryWarning,
+ query,
+ activeCheckpoint,
+ activeGgufVariant,
+ searchError,
+ online,
+ isDatasetMode,
+ inventoryTokens,
+ scannedCount,
+ discoverFetchIntent,
+ hasMore,
+ discoverManualFetchAvailable,
+ deferredFormatFilter,
+ deferredCapabilityFilter,
+ ],
+ );
+
+ const catalogPagination = useMemo<ModelsCatalogPagination>(
+ () => ({
+ scrollRef,
+ sentinelRef,
+ isLoadingMore,
+ }),
+ [scrollRef, sentinelRef, isLoadingMore],
+ );
+
+ const catalogHandlers = useMemo<ModelsCatalogHandlers>(
+ () => ({
+ onSelect: handleSelect,
+ onFetchMore: fetchMoreDiscoverManually,
+ onClearFilters: handleClearFilters,
+ onRetry: handleRetrySearch,
+ onInventoryChange: refreshInventory,
+ onSwitchDevice: handleSwitchDevice,
+ }),
+ [
+ handleSelect,
+ fetchMoreDiscoverManually,
+ handleClearFilters,
+ handleRetrySearch,
+ refreshInventory,
+ handleSwitchDevice,
+ ],
+ );
+
+ return (
+ <div className="hub-page flex h-full min-h-0 flex-col bg-background">
+ <div className="mx-auto flex w-full max-w-[1180px] flex-1 min-h-0 flex-col gap-6 px-5 pt-8 pb-16 sm:px-9 sm:pt-10 sm:pb-24">
+ <ModelsHeader
+ cachedCount={effectiveCachedRows.length}
+ localCount={effectiveLocalRows.length}
+ isDataset={isDatasetMode}
+ gpuLabel={gpuLabel}
+ ramLabel={ramLabel}
+ activeCheckpoint={activeCheckpoint}
+ activeGgufVariant={activeGgufVariant}
+ onEject={() => undefined}
+ />
+
+ <section className="elevated-card flex min-h-0 flex-1 flex-col overflow-hidden bg-card">
+ <div className="hub-side-surface shrink-0 px-4 pt-4 pb-6">
+ <ModelsToolbar
+ tab={tab}
+ onTabChange={handleTabChange}
+ query={query}
+ onQueryChange={handleQueryChange}
+ isLoading={isLoading}
+ sortBy={effectiveSort}
+ onSortChange={handleSortChange}
+ resourceType={resourceType}
+ onResourceTypeChange={handleResourceTypeChange}
+ formatFilter={formatFilter}
+ onFormatFilterChange={setFormatFilter}
+ capabilityFilter={capabilityFilter}
+ onCapabilityFilterChange={setCapabilityFilter}
+ activeChannelId={activeChannelId}
+ onChannelSelect={handleChannelSelect}
+ onRefresh={handleRetrySearch}
+ onManageLocalFolders={handleManageLocalFolders}
+ />
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col lg:grid lg:grid-cols-[360px_minmax(0,1fr)] xl:grid-cols-[400px_minmax(0,1fr)] 2xl:grid-cols-[440px_minmax(0,1fr)]">
+ <div
+ className={cn(
+ "hub-side-surface flex min-h-0 min-w-0 flex-1 flex-col border-b border-border lg:flex-initial lg:border-b-0 lg:border-r",
+ mobileInspectorOpen && "hidden lg:flex",
+ )}
+ >
+ <ModelsCatalog
+ state={catalogState}
+ pagination={catalogPagination}
+ handlers={catalogHandlers}
+ />
+ </div>
+
+ <div
+ className={cn(
+ "hub-side-surface flex min-h-0 min-w-0 flex-1 flex-col lg:flex-initial",
+ !mobileInspectorOpen && "hidden lg:flex",
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => setMobileInspectorOpen(false)}
+ className="relative z-10 flex h-10 shrink-0 cursor-pointer select-none items-center gap-1.5 border-b border-border bg-transparent px-4 text-[12.5px] font-medium text-muted-foreground transition-colors hover:text-foreground lg:hidden"
+ >
+ <HugeiconsIcon
+ icon={ArrowLeft01Icon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ Back to list
+ </button>
+ <div className="flex min-h-0 flex-1 flex-col">
+ {(isHubDesktop || mobileInspectorOpen) && (
+ <ModelInspector
+ model={selectedModel}
+ isDataset={isDatasetMode}
+ metadataUnavailable={metadataUnavailable}
+ selectionHiddenByFilters={selectionHiddenByFilters}
+ runtime={inspectorRuntime}
+ actions={inspectorActions}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ </section>
+ <OnDeviceFoldersDialog
+ open={foldersDialogOpen}
+ onOpenChange={setFoldersDialogOpen}
+ onInventoryChange={refreshInventory}
+ />
+ <ExternalLinkConfirmDialog />
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/hub.css b/studio/frontend/src/features/hub/hub.css
new file mode 100644
index 00000000000..66e732c7b6b
--- /dev/null
+++ b/studio/frontend/src/features/hub/hub.css
@@ -0,0 +1,756 @@
+/* SPDX-License-Identifier: AGPL-3.0-only */
+/* Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 */
+
+/* Hub feature CSS.
+
+ Lives with the Hub feature module so the styling stays bundled with the
+ Hub. Wired into the build via a single @import in studio/frontend/src/index.css.
+
+ Format/status color tokens are defined at :root and :root.dark so Tailwind
+ utilities like `bg-format-gguf` or `text-status-success` resolve everywhere
+ the Hub UI is rendered. Rule bodies are scoped to .hub-page or hub-prefixed
+ classes so they do not bleed into chat, train or settings surfaces. */
+
+:root {
+ --format-gguf: #60a5fa;
+ --format-checkpoint: #f472b6;
+ --format-adapter: #8b5cf6;
+ --status-warning: #eab308;
+ --status-danger: #ef4444;
+ --status-success: #11b686;
+}
+
+.dark {
+ --format-gguf: #60a5fa;
+ --format-checkpoint: #f472b6;
+ --format-adapter: #a78bfa;
+ --status-warning: #fbbf24;
+ --status-danger: #ef4444;
+ --status-success: #11b686;
+}
+
+@theme inline {
+ --color-format-gguf: var(--format-gguf);
+ --color-format-checkpoint: var(--format-checkpoint);
+ --color-format-adapter: var(--format-adapter);
+ --color-status-warning: var(--status-warning);
+ --color-status-danger: var(--status-danger);
+ --color-status-success: var(--status-success);
+}
+
+@layer base {
+ /* Filled-control surface — Hub search, Hub filter triggers, Train
+ number/text inputs, Train Selects, picker search bars. The same
+ visual identity the Hub search has always had:
+ - Resting: subtle 3% bg + 5% border
+ - Hover / open: 5% bg + 8% border
+ - Focus: 4% bg + 15% border (no solid colour swap)
+ - box-shadow: none on focus to neutralise shadcn's
+ focus-visible green ring (--ring is the brand primary).
+ `!important` is used on focus box-shadow only — Tailwind's
+ `focus-visible:ring-…` utility composes via `--tw-ring-shadow`
+ into the final box-shadow at the same specificity as ours, and
+ without bumping ours we'd lose the cascade tie inconsistently
+ depending on which utility was applied last to the element. */
+ .field-soft {
+ background-color: color-mix(in srgb, var(--foreground) 3%, transparent);
+ border: 1px solid color-mix(in srgb, var(--foreground) 5%, transparent);
+ box-shadow: none;
+ transition:
+ background-color 160ms ease,
+ border-color 160ms ease;
+ }
+
+ .field-soft:hover,
+ .field-soft[data-state="open"] {
+ background-color: color-mix(in srgb, var(--foreground) 5%, transparent);
+ border-color: color-mix(in srgb, var(--foreground) 8%, transparent);
+ }
+
+ .field-soft:focus,
+ .field-soft:focus-visible,
+ .field-soft:focus-within {
+ background-color: color-mix(in srgb, var(--foreground) 4%, transparent);
+ border-color: color-mix(in srgb, var(--foreground) 15%, transparent) !important;
+ box-shadow: none !important;
+ outline: none;
+ }
+
+ .dark .field-soft {
+ background-color: color-mix(in srgb, var(--foreground) 4%, transparent);
+ border-color: color-mix(in srgb, var(--foreground) 6%, transparent);
+ }
+
+ .dark .field-soft:hover,
+ .dark .field-soft[data-state="open"] {
+ background-color: color-mix(in srgb, var(--foreground) 5%, transparent);
+ border-color: color-mix(in srgb, var(--foreground) 8%, transparent);
+ }
+
+ .dark .field-soft:focus,
+ .dark .field-soft:focus-visible,
+ .dark .field-soft:focus-within {
+ background-color: color-mix(in srgb, var(--foreground) 7%, transparent);
+ border-color: color-mix(in srgb, var(--foreground) 15%, transparent) !important;
+ }
+
+ .hub-page .elevated-card {
+ border: 1px solid color-mix(in srgb, var(--foreground) 5%, transparent);
+ border-radius: 20px;
+ box-shadow:
+ 0 12px 48px -8px color-mix(in srgb, var(--foreground) 8%, transparent),
+ 0 0 100px 20px color-mix(in srgb, var(--foreground) 3%, transparent);
+ }
+
+ @media (min-width: 640px) {
+ .hub-page .elevated-card {
+ border-radius: 28px;
+ }
+ }
+
+ @media (min-width: 1024px) {
+ .hub-page .elevated-card {
+ border-radius: 32px;
+ }
+ }
+
+ html.dark .hub-page .elevated-card {
+ border-color: transparent;
+ box-shadow: none;
+ }
+
+ .hub-page .page-title-halo {
+ text-shadow:
+ 0 0 24px #e4e3df,
+ 0 0 56px #ebeae6,
+ 0 0 96px #efeeea;
+ }
+
+ html.dark .hub-page .page-title-halo {
+ text-shadow: none;
+ }
+
+ html:not(.dark) .hub-page {
+ background-color: var(--background);
+ }
+
+ html:not(.dark) .hub-page > div > section .border-b,
+ html:not(.dark) .hub-page > div > section .border-r,
+ html:not(.dark) .hub-page > div > section .border-t.border-border {
+ border-color: color-mix(in srgb, var(--foreground) 6%, transparent);
+ }
+
+ html:not(.dark) .hub-page .hub-side-surface {
+ background-color: var(--background);
+ }
+
+ html:not(.dark) .hub-page .hub-tag-soft,
+ html:not(.dark) .hub-page .hub-tag-meta {
+ background-color: transparent;
+ transition:
+ background-color 160ms ease,
+ border-color 160ms ease;
+ }
+
+ html:not(.dark) .hub-page .hub-tag-soft:hover,
+ html:not(.dark) .hub-page .hub-tag-meta:hover {
+ background-color: color-mix(in srgb, var(--foreground) 4%, transparent);
+ }
+
+ html.dark .hub-page {
+ background-color: var(--background);
+ }
+
+ html.dark .hub-page > div > section [class*="bg-card"],
+ html.dark .hub-page > div > section [class*="bg-background"] {
+ background-color: var(--popover);
+ }
+
+ html.dark .hub-page > div > section .border-b,
+ html.dark .hub-page > div > section .border-r,
+ html.dark .hub-page > div > section .border-t.border-border {
+ border-color: color-mix(in srgb, var(--foreground) 5%, transparent);
+ }
+
+ html.dark .hub-page .hub-side-surface {
+ background-color: transparent;
+ }
+
+ html.dark .hub-page .hub-tag-soft,
+ html.dark .hub-page .hub-tag-meta {
+ background-color: transparent;
+ transition:
+ background-color 160ms ease,
+ border-color 160ms ease;
+ }
+
+ html.dark .hub-page .hub-tag-soft {
+ color: var(--muted-foreground);
+ }
+
+ html.dark .hub-page .hub-tag-meta {
+ color: var(--muted-foreground);
+ }
+
+ html.dark .hub-page .hub-tag-soft:hover,
+ html.dark .hub-page .hub-tag-meta:hover {
+ background-color: color-mix(in srgb, var(--foreground) 4%, transparent);
+ }
+
+ .hub-menu-instant {
+ animation: none !important;
+ transition: none !important;
+ transform: none !important;
+ --tw-translate-x: 0px !important;
+ --tw-translate-y: 0px !important;
+ --tw-scale-x: 1 !important;
+ --tw-scale-y: 1 !important;
+ translate: 0 0 !important;
+ user-select: none;
+ -webkit-user-select: none;
+ will-change: auto !important;
+ }
+
+ .hub-menu-instant.menu-soft-surface {
+ --menu-soft-blur: 18px;
+ --menu-soft-spread: -8px;
+ }
+
+ .hub-menu-instant [data-slot="select-item"]:focus,
+ .hub-menu-instant [data-slot="select-item"][data-highlighted],
+ .hub-menu-instant [role="option"][data-highlighted] {
+ background-color: color-mix(in srgb, var(--foreground) 6%, transparent);
+ color: var(--foreground);
+ }
+
+ html.dark .hub-menu-instant [data-slot="select-item"]:focus,
+ html.dark .hub-menu-instant [data-slot="select-item"][data-highlighted],
+ html.dark .hub-menu-instant [role="option"][data-highlighted] {
+ background-color: color-mix(in srgb, var(--foreground) 8%, transparent);
+ color: var(--foreground);
+ }
+
+ html.dark .hub-menu-instant {
+ background-color: #2e2f31 !important;
+ }
+
+ .hub-menu-instant *,
+ .hub-menu-instant *::before,
+ .hub-menu-instant *::after,
+ .hub-menu-trigger,
+ .hub-menu-trigger * {
+ animation: none !important;
+ transition: none !important;
+ user-select: none;
+ -webkit-user-select: none;
+ }
+
+ html:not(.dark) .hub-page .hub-tab-toggle {
+ background-color: color-mix(in srgb, var(--foreground) 5%, transparent);
+ border: 0;
+ box-shadow: none;
+ }
+
+ html.dark .hub-page .hub-tab-toggle {
+ background-color: color-mix(in srgb, var(--foreground) 4.5%, transparent);
+ border: 0;
+ box-shadow: none;
+ }
+
+ html:not(.dark) .hub-page .hub-tab-toggle-pill {
+ background-color: var(--background);
+ border: 0;
+ box-shadow:
+ 0 1px 2px color-mix(in srgb, var(--foreground) 8%, transparent),
+ 0 4px 10px -3px color-mix(in srgb, var(--foreground) 6%, transparent);
+ }
+
+ html.dark .hub-page .hub-tab-toggle-pill {
+ background-color: color-mix(in srgb, var(--foreground) 10%, transparent);
+ border: 0;
+ box-shadow:
+ 0 1px 2px rgba(0, 0, 0, 0.14),
+ 0 4px 10px -3px rgba(0, 0, 0, 0.1);
+ }
+
+ html:not(.dark) .hub-page .catalog-row {
+ background-color: transparent;
+ border-color: transparent;
+ box-shadow: none;
+ transition: background-color 160ms ease;
+ }
+
+ html:not(.dark) .hub-page .catalog-row:hover {
+ background-color: color-mix(in srgb, var(--foreground) 3.5%, transparent);
+ }
+
+ html:not(.dark) .hub-page .catalog-row[data-selected="true"] {
+ background-color: color-mix(in srgb, var(--foreground) 6%, transparent);
+ }
+
+ /* Currently-loaded checkpoint: a brand-green left stripe plus a faint
+ green wash, orthogonal to the neutral selected tint so a row that is
+ both loaded and selected still reads as loaded. */
+ html:not(.dark) .hub-page .catalog-row[data-active="true"] {
+ background-color: color-mix(in srgb, var(--status-success) 7%, transparent);
+ box-shadow: inset 2px 0 0 0 var(--primary);
+ }
+
+ html.dark .hub-page .catalog-row {
+ background-color: transparent;
+ border-color: transparent;
+ box-shadow: none;
+ transition: background-color 160ms ease;
+ }
+
+ html.dark .hub-page .catalog-row:hover {
+ background-color: color-mix(in srgb, var(--foreground) 3.5%, transparent);
+ }
+
+ html.dark .hub-page .catalog-row[data-selected="true"] {
+ background-color: color-mix(in srgb, var(--foreground) 7%, transparent);
+ }
+
+ html.dark .hub-page .catalog-row[data-active="true"] {
+ background-color: color-mix(in srgb, var(--status-success) 12%, transparent);
+ box-shadow: inset 2px 0 0 0 var(--primary);
+ }
+
+}
+
+@layer utilities {
+ .hub-tag-soft,
+ .hub-tag-meta {
+ @apply min-h-[26px] rounded-[11px] bg-muted/70 ring-1 ring-inset;
+ --tw-ring-color: color-mix(in srgb, var(--foreground) 3.5%, transparent);
+ }
+
+ .dark .hub-tag-soft,
+ .dark .hub-tag-meta {
+ @apply bg-white/[0.05] ring-white/[0.035];
+ }
+ .hub-download-card {
+ @apply flex w-full flex-col gap-2 rounded-[22px] p-2;
+ background-color: color-mix(in srgb, var(--foreground) 3%, transparent);
+ border: 1px solid color-mix(in srgb, var(--foreground) 5.5%, transparent);
+ box-shadow: none;
+ }
+
+ .dark .hub-download-card {
+ background-color: color-mix(in srgb, var(--foreground) 3.5%, transparent);
+ border: 1px solid color-mix(in srgb, var(--foreground) 5.5%, transparent);
+ box-shadow: none;
+ }
+
+ .hub-download-panel {
+ border-radius: 20px;
+ background-color: var(--popover);
+ border: 1px solid color-mix(in srgb, var(--foreground) 6%, transparent);
+ box-shadow:
+ 0 1px 2px color-mix(in srgb, var(--foreground) 7%, transparent),
+ 0 18px 48px -12px color-mix(in srgb, var(--foreground) 22%, transparent);
+ }
+
+ .dark .hub-download-panel {
+ border-color: color-mix(in srgb, var(--foreground) 8%, transparent);
+ box-shadow:
+ 0 1px 2px rgba(0, 0, 0, 0.4),
+ 0 20px 56px -12px rgba(0, 0, 0, 0.6);
+ }
+
+ .hub-download-fab {
+ position: relative;
+ display: inline-flex;
+ width: 2.75rem;
+ height: 2.75rem;
+ cursor: pointer;
+ align-items: center;
+ justify-content: center;
+ border-radius: 9999px;
+ color: var(--muted-foreground);
+ background-color: var(--popover);
+ border: 1px solid color-mix(in srgb, var(--foreground) 6%, transparent);
+ box-shadow:
+ 0 1px 2px color-mix(in srgb, var(--foreground) 7%, transparent),
+ 0 12px 32px -10px color-mix(in srgb, var(--foreground) 22%, transparent);
+ transition:
+ color 150ms ease,
+ background-color 150ms ease,
+ box-shadow 150ms ease,
+ transform 150ms ease;
+ }
+
+ .hub-download-fab:hover {
+ color: var(--foreground);
+ transform: translateY(-1px);
+ box-shadow:
+ 0 2px 4px color-mix(in srgb, var(--foreground) 8%, transparent),
+ 0 16px 40px -10px color-mix(in srgb, var(--foreground) 26%, transparent);
+ }
+
+ .dark .hub-download-fab {
+ border-color: color-mix(in srgb, var(--foreground) 8%, transparent);
+ box-shadow:
+ 0 1px 2px rgba(0, 0, 0, 0.4),
+ 0 14px 36px -10px rgba(0, 0, 0, 0.6);
+ }
+
+ .dark .hub-download-fab:hover {
+ box-shadow:
+ 0 2px 4px rgba(0, 0, 0, 0.45),
+ 0 18px 44px -10px rgba(0, 0, 0, 0.65);
+ }
+
+ .hub-download-fab-badge {
+ position: absolute;
+ top: -3px;
+ right: -3px;
+ display: inline-flex;
+ min-width: 1.125rem;
+ height: 1.125rem;
+ align-items: center;
+ justify-content: center;
+ border-radius: 9999px;
+ padding-inline: 0.3125rem;
+ background-color: var(--status-success);
+ color: var(--primary-foreground);
+ font-size: 10.5px;
+ font-weight: 600;
+ line-height: 1;
+ font-variant-numeric: tabular-nums;
+ border: 2px solid var(--popover);
+ }
+}
+
+@layer base {
+ .hub-avatar-tile {
+ box-shadow: 0 0 0 0.5px color-mix(in srgb, var(--foreground) 6%, transparent);
+ }
+
+ .dark .hub-avatar-tile {
+ box-shadow: 0 0 0 0.5px color-mix(in srgb, var(--foreground) 8%, transparent);
+ }
+
+ /* Verified badge: solid badge shape with a check-shaped hole punched
+ through, so whatever sits behind shows through the check. The badge
+ fill follows currentColor (so `text-primary` makes it Unsloth green;
+ any text-* utility recolors it). Use as: `<span class="hub-verified-badge
+ size-4 text-primary" />`. */
+ .hub-verified-badge {
+ display: inline-block;
+ background-color: currentColor;
+ mask: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><defs><mask id='c'><rect width='24' height='24' fill='white'/><path d='m8.75 12.5 2.5 2.5 4.25-5.25' stroke='black' stroke-width='1.85' stroke-linecap='round' stroke-linejoin='round' fill='none'/></mask></defs><path d='M8.603 3.799A4.49 4.49 0 0 1 12 2.25c1.357 0 2.573.6 3.397 1.549a4.49 4.49 0 0 1 3.498 1.307 4.491 4.491 0 0 1 1.307 3.497A4.49 4.49 0 0 1 21.75 12a4.49 4.49 0 0 1-1.549 3.397 4.491 4.491 0 0 1-1.307 3.497 4.491 4.491 0 0 1-3.497 1.307A4.49 4.49 0 0 1 12 21.75a4.49 4.49 0 0 1-3.397-1.549 4.49 4.49 0 0 1-3.498-1.306 4.491 4.491 0 0 1-1.307-3.498A4.49 4.49 0 0 1 2.25 12c0-1.357.6-2.573 1.549-3.397a4.49 4.49 0 0 1 1.307-3.497 4.49 4.49 0 0 1 3.497-1.307Z' fill='white' mask='url(%23c)'/></svg>") center / contain no-repeat;
+ -webkit-mask: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><defs><mask id='c'><rect width='24' height='24' fill='white'/><path d='m8.75 12.5 2.5 2.5 4.25-5.25' stroke='black' stroke-width='1.85' stroke-linecap='round' stroke-linejoin='round' fill='none'/></mask></defs><path d='M8.603 3.799A4.49 4.49 0 0 1 12 2.25c1.357 0 2.573.6 3.397 1.549a4.49 4.49 0 0 1 3.498 1.307 4.491 4.491 0 0 1 1.307 3.497A4.49 4.49 0 0 1 21.75 12a4.49 4.49 0 0 1-1.549 3.397 4.491 4.491 0 0 1-1.307 3.497 4.491 4.491 0 0 1-3.497 1.307A4.49 4.49 0 0 1 12 21.75a4.49 4.49 0 0 1-3.397-1.549 4.49 4.49 0 0 1-3.498-1.306 4.491 4.491 0 0 1-1.307-3.498A4.49 4.49 0 0 1 2.25 12c0-1.357.6-2.573 1.549-3.397a4.49 4.49 0 0 1 1.307-3.497 4.49 4.49 0 0 1 3.497-1.307Z' fill='white' mask='url(%23c)'/></svg>") center / contain no-repeat;
+ }
+
+
+ @keyframes hub-loading-sweep {
+ 0% {
+ opacity: 0;
+ transform: translate3d(-120%, 0, 0);
+ }
+
+ 16% {
+ opacity: 0.92;
+ }
+
+ 78% {
+ opacity: 0.92;
+ }
+
+ 100% {
+ opacity: 0;
+ transform: translate3d(520%, 0, 0);
+ }
+ }
+
+ .hub-loading-bar {
+ pointer-events: none;
+ position: relative;
+ overflow: hidden;
+ width: 100%;
+ height: 3px;
+ }
+
+ .hub-loading-bar::after {
+ content: "";
+ display: none;
+ position: absolute;
+ inset-block: 0;
+ left: 0;
+ width: 36%;
+ background: linear-gradient(90deg,
+ transparent,
+ color-mix(in srgb, var(--foreground) 20%, transparent),
+ color-mix(in srgb, var(--foreground) 58%, transparent),
+ color-mix(in srgb, var(--foreground) 20%, transparent),
+ transparent);
+ will-change: opacity, transform;
+ }
+
+ html.dark .hub-loading-bar::after {
+ background: linear-gradient(90deg,
+ transparent,
+ color-mix(in srgb, var(--foreground) 22%, transparent),
+ color-mix(in srgb, var(--foreground) 60%, transparent),
+ color-mix(in srgb, var(--foreground) 22%, transparent),
+ transparent);
+ }
+
+ .hub-loading-bar[data-active="true"]::after {
+ display: block;
+ animation: hub-loading-sweep 3s cubic-bezier(0.22, 0.72, 0.18, 1) infinite;
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .hub-loading-bar[data-active="true"]::after {
+ animation-duration: 3s !important;
+ animation-iteration-count: infinite !important;
+ }
+ }
+
+ /* README markdown can be thousands of nodes. Keep its paint/layout work
+ scoped so unrelated overlays, like the sidebar account menu, do less
+ route-wide recalculation while the Hub is open. */
+ .hub-readme-prose {
+ content-visibility: auto;
+ contain-intrinsic-size: auto 640px;
+ }
+
+ .hub-readme-prose > * {
+ content-visibility: auto;
+ contain-intrinsic-size: auto 140px;
+ }
+
+ .hub-readme-prose :is(p, div):has(> a:nth-of-type(2) > img) {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.5rem;
+ }
+
+ .hub-readme-prose :is(p, div):has(> a:nth-of-type(2) > img) > br {
+ display: none;
+ }
+
+ .hub-readme-prose :is(p, div):has(> a:nth-of-type(2) > img) > a {
+ display: inline-flex;
+ align-items: center;
+ }
+
+ .hub-readme-prose :is(p, div):has(> a:nth-of-type(2) > img) img {
+ margin-block: 0;
+ }
+
+ /* Inspector action pills (Download / Run / Train / Cancel) for the hub
+ inspector card. Centralized so all three sections (GGUF, safetensors,
+ datasets) stay in lock-step on type scale, padding, hover surface, and
+ the 16px icon size — mirrors the pattern used for `.sidebar-nav-btn`.
+ Width and disabled tint are layered inline by callers (some buttons
+ are w-24 in a pair, some are w-28 standalone). Raw CSS rather than
+ @apply so the cascade is explicit and predictable. */
+ .hub-action-btn {
+ display: inline-flex;
+ height: 2.25rem;
+ cursor: pointer;
+ align-items: center;
+ justify-content: center;
+ gap: 0.5rem;
+ white-space: nowrap;
+ border-radius: 9999px;
+ background-color: transparent;
+ padding-left: 0.75rem;
+ padding-right: 0.75rem;
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 18px;
+ letter-spacing: -0.025em;
+ color: var(--foreground);
+ transition: color 150ms, background-color 150ms;
+ }
+
+ .hub-action-btn:hover:not(:disabled) {
+ background-color: color-mix(in srgb, var(--foreground) 4%, transparent);
+ }
+
+ .dark .hub-action-btn:hover:not(:disabled) {
+ background-color: color-mix(in srgb, var(--foreground) 5%, transparent);
+ }
+
+ .hub-action-btn:disabled {
+ cursor: not-allowed;
+ }
+
+ /* Every glyph inside a hub action button — explicit icon, spinner, or
+ embedded SVG — locks to 16px so swapping icons or replacing the
+ spinner can't drift the layout. */
+ .hub-action-btn svg {
+ width: 1rem;
+ height: 1rem;
+ flex-shrink: 0;
+ }
+
+ /* Primary "Run" action — confirms loading/running a model. Pill shape
+ (rounded-full) so it reads as the unmistakable CTA in a row of
+ ghost actions and matches the live-model status-success token used
+ elsewhere in the app. Same h-9 geometry, 13px
+ medium type, tracking-tight, and 16px icon slot as .hub-action-btn
+ so the height aligns with adjacent ghost buttons. */
+ .hub-run-action-btn {
+ display: inline-flex;
+ height: 2.25rem;
+ cursor: pointer;
+ align-items: center;
+ justify-content: center;
+ gap: 0.4rem;
+ white-space: nowrap;
+ border-radius: 9999px;
+ background-color: var(--status-success);
+ padding-left: 1rem;
+ padding-right: 1rem;
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 18px;
+ letter-spacing: -0.025em;
+ color: var(--primary-foreground);
+ transition: background-color 150ms, transform 150ms;
+ box-shadow:
+ inset 0 1px 0 color-mix(in srgb, var(--primary-foreground) 18%, transparent),
+ 0 1px 2px color-mix(in srgb, var(--status-success) 22%, transparent);
+ }
+
+ .hub-run-action-btn:hover:not(:disabled) {
+ background-color: color-mix(in srgb, var(--status-success) 88%, black);
+ }
+
+ .hub-run-action-btn:active:not(:disabled) {
+ transform: scale(0.98);
+ }
+
+ .hub-run-action-btn:disabled {
+ cursor: not-allowed;
+ opacity: 0.5;
+ }
+
+ .hub-run-action-btn svg {
+ width: 0.9rem;
+ height: 0.9rem;
+ flex-shrink: 0;
+ }
+
+ /* Spinner-default / cancel-on-hover swap inside `.hub-action-btn`.
+ Two glyphs occupy the same 16×16 slot; the button's :hover toggles
+ their opacities so the percentage label beside them never shifts. */
+ .hub-cta-indicator {
+ position: relative;
+ display: inline-flex;
+ width: 1rem;
+ height: 1rem;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ }
+
+ .hub-cta-indicator-spinner,
+ .hub-cta-indicator-cancel {
+ transition: opacity 150ms;
+ }
+
+ .hub-cta-indicator-cancel {
+ position: absolute;
+ opacity: 0;
+ }
+
+ .hub-action-btn:hover .hub-cta-indicator-spinner {
+ opacity: 0;
+ }
+
+ .hub-action-btn:hover .hub-cta-indicator-cancel {
+ opacity: 1;
+ }
+
+ /* Hover-revealed inline action overlay (used for the row-end trash on
+ downloaded models and datasets in the inspector). Wrapper 28×28 with a
+ 16px glyph — same icon size as `.hub-action-btn` so the destructive
+ affordance reads consistently with the primary actions. Relies on a
+ `.group/dl` ancestor for the hover scope (the Hub download row). */
+ .hub-row-action {
+ position: absolute;
+ right: 0.25rem;
+ top: 50%;
+ display: inline-flex;
+ width: 1.75rem;
+ height: 1.75rem;
+ transform: translateY(-50%);
+ align-items: center;
+ justify-content: center;
+ border-radius: 8px;
+ color: var(--muted-foreground);
+ opacity: 0;
+ cursor: pointer;
+ transition: opacity 150ms, color 150ms;
+ }
+
+ .group\/dl:hover .hub-row-action,
+ .hub-row-action:focus-visible {
+ opacity: 1;
+ }
+
+ .hub-row-action:hover {
+ color: rgb(225 29 72);
+ }
+
+ .dark .hub-row-action:hover {
+ color: rgb(251 113 133);
+ }
+
+ .hub-row-action svg {
+ width: 1rem;
+ height: 1rem;
+ flex-shrink: 0;
+ }
+}
+
+@layer base {
+ .hub-page .field-trigger.field-filter {
+ color: var(--muted-foreground);
+ font-weight: 400;
+ padding-top: 0.25rem;
+ padding-bottom: 0.25rem;
+ line-height: 1.25rem;
+ }
+
+ .hub-page .field-trigger.field-filter:hover {
+ color: var(--foreground);
+ }
+}
+
+html:not(.dark) .hub-page [data-hub-scroll="true"] {
+ scrollbar-color: oklch(0.5 0 0 / 0.22) transparent;
+}
+
+html.dark .hub-page [data-hub-scroll="true"] {
+ scrollbar-color: oklch(0.55 0 0 / 0.16) transparent;
+}
+
+html:not(.dark) .hub-page [data-hub-scroll="true"]::-webkit-scrollbar-thumb {
+ background: oklch(0.5 0 0 / 0.22);
+}
+
+html.dark .hub-page [data-hub-scroll="true"]::-webkit-scrollbar-thumb {
+ background: oklch(0.55 0 0 / 0.16);
+}
+
+/* While a modal dialog is open (delete confirmation, transport-mode swap, the
+ folder manager) Radix locks the background: it sets body[data-scroll-locked]
+ and body { pointer-events: none }. A few Hub affordances (the cached-size
+ chip, the row delete button) opt back into pointer events with
+ `pointer-events-auto` so they can sit above the row's full-bleed click
+ overlay. That opt-in must NOT survive an open modal, or hovering the
+ background fires their tooltips behind the dialog. Re-disable only those
+ opt-ins while the scroll lock is active; everything else is already blocked
+ by the body-level rule, and the dialog's own portaled content never carries
+ this class. */
+body[data-scroll-locked] .hub-modal-pe-guard {
+ pointer-events: none !important;
+}
diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.ts
new file mode 100644
index 00000000000..8ae3f7d3cda
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/api.ts
@@ -0,0 +1,455 @@
+// 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 { authFetch } from "@/features/auth";
+import {
+ disposableTimeoutSignal,
+ withAbort,
+} from "@/features/hub/lib/abort-signals";
+import { hubTokenHeader } from "@/features/hub/lib/hub-token-header";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+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 type { LocalSource } from "./constants";
+import { bumpGgufVariantsCacheVersion } from "./gguf-variants-cache-events";
+
+export type ModelInventoryFormat =
+ | "gguf"
+ | "safetensors"
+ | "adapter"
+ | "checkpoint"
+ | "unknown";
+export type ModelInventoryRuntime =
+ | "llama_cpp"
+ | "transformers"
+ | "adapter"
+ | "unknown";
+export type BaseModelSource = "huggingface" | "local" | "unknown";
+
+export interface BackendModelCapabilities {
+ can_train?: boolean;
+ can_chat?: boolean;
+ can_delete?: boolean;
+ can_download?: boolean;
+ requires_variant?: boolean;
+ supports_lora?: boolean;
+ supports_vision?: boolean;
+}
+
+export interface CachedGgufRepo {
+ repo_id: string;
+ inventory_id?: string | null;
+ load_id?: string | null;
+ model_format?: ModelInventoryFormat | null;
+ runtime?: ModelInventoryRuntime | null;
+ format_variant?: string | null;
+ capabilities?: BackendModelCapabilities | null;
+ size_bytes: number;
+ cache_path?: string;
+ partial?: boolean;
+ partial_transport?: string | null;
+ pipeline_tag?: string | null;
+ tags?: string[];
+ library_name?: string | null;
+}
+
+export interface CachedModelRepo {
+ repo_id: string;
+ inventory_id?: string | null;
+ load_id?: string | null;
+ model_format?: ModelInventoryFormat | null;
+ runtime?: ModelInventoryRuntime | null;
+ format_variant?: string | null;
+ capabilities?: BackendModelCapabilities | null;
+ size_bytes: number;
+ cache_path?: string;
+ partial?: boolean;
+ partial_transport?: string | null;
+ pipeline_tag?: string | null;
+ tags?: string[];
+ library_name?: string | null;
+ quant_method?: string | null;
+}
+
+export interface LocalModelInfo {
+ id: string;
+ inventory_id?: string | null;
+ load_id?: string | null;
+ display_name: string;
+ path: string;
+ size_bytes?: number;
+ model_format?: ModelInventoryFormat | null;
+ runtime?: ModelInventoryRuntime | null;
+ format_variant?: string | null;
+ capabilities?: BackendModelCapabilities | null;
+ source: LocalSource;
+ model_id?: string | null;
+ base_model?: string | null;
+ base_model_source?: BaseModelSource | null;
+ adapter_type?: string | null;
+ training_method?: string | null;
+ updated_at?: number | null;
+ partial?: boolean;
+ partial_transport?: string | null;
+ pipeline_tag?: string | null;
+ tags?: string[];
+ library_name?: string | null;
+ quant_method?: string | null;
+}
+
+export interface LocalModelListResponse {
+ models_dir: string;
+ hf_cache_dir?: string | null;
+ lmstudio_dirs: string[];
+ ollama_dirs?: string[];
+ models: LocalModelInfo[];
+}
+
+export interface CachedDatasetRepo {
+ repo_id: string;
+ size_bytes: number;
+ cache_path?: string;
+ partial?: boolean;
+ partial_transport?: string | null;
+}
+
+export type LocalDatasetInfo = {
+ metadata?: {
+ actual_num_records?: number | null;
+ target_num_records?: number | null;
+ total_num_batches?: number | null;
+ num_completed_batches?: number | null;
+ columns?: string[] | null;
+ } | null;
+ id: string;
+ label: string;
+ path: string;
+ source: "recipe" | "upload";
+ rows?: number | null;
+ updated_at?: number | null;
+};
+
+export type LocalDatasetsResponse = {
+ datasets: LocalDatasetInfo[];
+};
+
+export interface ScanFolderInfo {
+ id: number;
+ path: string;
+ created_at: string;
+}
+
+export interface BrowseEntry {
+ name: string;
+ has_models: boolean;
+ hidden: boolean;
+}
+
+export interface BrowseFoldersResponse {
+ current: string;
+ parent: string | null;
+ entries: BrowseEntry[];
+ suggestions: string[];
+ truncated?: boolean;
+ model_files_here?: number;
+}
+
+export interface GgufVariantDetail {
+ filename: string;
+ quant: string;
+ display_label?: string | null;
+ size_bytes: number;
+ download_size_bytes?: number;
+ downloaded?: boolean;
+ partial?: boolean;
+ partial_transport?: string | null;
+}
+
+export interface GgufVariantsResponse {
+ repo_id: string;
+ variants: GgufVariantDetail[];
+ has_vision: boolean;
+ default_variant: string | null;
+}
+
+async function parseJsonOrThrow<T>(
+ response: Response,
+ fallback?: string,
+): Promise<T> {
+ if (!response.ok) {
+ throw new Error(await readFastApiError(response, fallback));
+ }
+ return response.json();
+}
+
+async function throwIfNotOk(
+ response: Response,
+ fallback?: string,
+): Promise<void> {
+ if (!response.ok) {
+ throw new Error(await readFastApiError(response, fallback));
+ }
+}
+
+const INVENTORY_TIMEOUT_MS = 30_000;
+
+async function withHubTimeout<T>(
+ ms: number,
+ request: (signal: AbortSignal) => Promise<T>,
+): Promise<T> {
+ const timeout = disposableTimeoutSignal(ms);
+ try {
+ return await request(timeout.signal);
+ } finally {
+ timeout.dispose();
+ }
+}
+
+export async function listLocalModels(): Promise<LocalModelListResponse> {
+ const response = await withHubTimeout(INVENTORY_TIMEOUT_MS, (signal) =>
+ authFetch("/api/hub/local", { signal }),
+ );
+ return parseJsonOrThrow<LocalModelListResponse>(response);
+}
+
+export async function listCachedGguf(
+ hfToken?: string | null,
+): Promise<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;
+}
+
+export async function listCachedModels(
+ hfToken?: string | null,
+): Promise<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;
+}
+
+export async function listLocalDatasets(): Promise<LocalDatasetsResponse> {
+ const response = await withHubTimeout(INVENTORY_TIMEOUT_MS, (signal) =>
+ authFetch("/api/hub/datasets/local", { signal }),
+ );
+ return parseJsonOrThrow<LocalDatasetsResponse>(response);
+}
+
+export async function listCachedDatasets(): Promise<CachedDatasetRepo[]> {
+ const response = await withHubTimeout(INVENTORY_TIMEOUT_MS, (signal) =>
+ authFetch("/api/hub/datasets/cached", { signal }),
+ );
+ const data = await parseJsonOrThrow<{ cached: CachedDatasetRepo[] }>(response);
+ return data.cached;
+}
+
+export async function deleteCachedDataset(repoId: string): Promise<void> {
+ const response = await authFetch("/api/hub/datasets/cached", {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ repo_id: repoId }),
+ });
+ await throwIfNotOk(response, `Failed to delete dataset (${response.status})`);
+ bumpInventoryVersion();
+}
+
+export async function deleteCachedModel(
+ repoId: string,
+ variant?: string,
+ hfToken?: string | null,
+): Promise<void> {
+ const payload: Record<string, string> = { repo_id: repoId };
+ if (variant) {
+ payload.variant = variant;
+ }
+ const response = await authFetch("/api/hub/delete-cached", {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json", ...hubTokenHeader(hfToken) },
+ body: JSON.stringify(payload),
+ });
+ try {
+ await throwIfNotOk(response);
+ bumpInventoryVersion();
+ } finally {
+ invalidateGgufVariantsCache(repoId);
+ }
+}
+
+export async function listScanFolders(): Promise<ScanFolderInfo[]> {
+ const response = await authFetch("/api/hub/scan-folders");
+ const data = await parseJsonOrThrow<{ folders: ScanFolderInfo[] }>(response);
+ return data.folders;
+}
+
+export async function addScanFolder(path: string): Promise<ScanFolderInfo> {
+ const response = await authFetch("/api/hub/scan-folders", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ path }),
+ });
+ const folder = await parseJsonOrThrow<ScanFolderInfo>(response);
+ bumpInventoryVersion();
+ return folder;
+}
+
+export async function removeScanFolder(id: number): Promise<void> {
+ const response = await authFetch(`/api/hub/scan-folders/${id}`, {
+ method: "DELETE",
+ });
+ await throwIfNotOk(response);
+ bumpInventoryVersion();
+}
+
+export async function browseFolders(
+ path?: string,
+ showHidden = false,
+ signal?: AbortSignal,
+): Promise<BrowseFoldersResponse> {
+ const params = new URLSearchParams();
+ if (path !== undefined && path !== null) {
+ params.set("path", path);
+ }
+ if (showHidden) {
+ params.set("show_hidden", "true");
+ }
+ const qs = params.toString();
+ const response = await authFetch(
+ `/api/hub/browse-folders${qs ? `?${qs}` : ""}`,
+ signal ? { signal } : undefined,
+ );
+ return parseJsonOrThrow<BrowseFoldersResponse>(response);
+}
+
+const GGUF_VARIANTS_TTL_MS = 30 * 1000;
+const GGUF_VARIANTS_LOCAL_TTL_MS = 10 * 60 * 1000;
+const GGUF_VARIANTS_TIMEOUT_MS = 30_000;
+const GGUF_VARIANTS_CACHE_MAX_ENTRIES = 64;
+
+interface GgufVariantsCacheEntry {
+ expiresAt: number;
+ promise: Promise<GgufVariantsResponse>;
+}
+
+const ggufVariantsCache = new Map<string, GgufVariantsCacheEntry>();
+
+function pruneGgufVariantsCache(now = Date.now()): void {
+ for (const [key, entry] of ggufVariantsCache) {
+ if (entry.expiresAt <= now) {
+ ggufVariantsCache.delete(key);
+ }
+ }
+ while (ggufVariantsCache.size > GGUF_VARIANTS_CACHE_MAX_ENTRIES) {
+ const oldest = ggufVariantsCache.keys().next().value;
+ if (!oldest) {
+ break;
+ }
+ ggufVariantsCache.delete(oldest);
+ }
+}
+
+function ggufVariantsTtlMs(
+ response: GgufVariantsResponse,
+ preferLocalCache: boolean,
+): number {
+ if (
+ preferLocalCache &&
+ response.variants.some((variant) => variant.downloaded)
+ ) {
+ return GGUF_VARIANTS_LOCAL_TTL_MS;
+ }
+ return GGUF_VARIANTS_TTL_MS;
+}
+
+export async function listGgufVariants(
+ repoId: string,
+ hfToken?: string,
+ options?: {
+ preferLocalCache?: boolean;
+ localPath?: string | null;
+ signal?: AbortSignal;
+ },
+): Promise<GgufVariantsResponse> {
+ const offline = isHuggingFaceOffline();
+ const localPath = options?.localPath?.trim() || null;
+ const preferLocalCache = !!options?.preferLocalCache || offline;
+ const signal = options?.signal;
+ const key = `${repoId}::${fingerprintToken(hfToken)}::${
+ preferLocalCache ? "local" : "remote"
+ }::${localPathCacheKey(localPath)}`;
+ const now = Date.now();
+ const hit = ggufVariantsCache.get(key);
+ if (hit && now < hit.expiresAt) {
+ ggufVariantsCache.delete(key);
+ ggufVariantsCache.set(key, hit);
+ return withAbort(hit.promise, signal);
+ }
+ if (hit) {
+ ggufVariantsCache.delete(key);
+ }
+ const params = new URLSearchParams({ repo_id: repoId });
+ if (preferLocalCache) {
+ params.set("prefer_local_cache", "true");
+ }
+ if (localPath) {
+ params.set("local_path", localPath);
+ }
+ if (offline) {
+ params.set("offline", "true");
+ }
+ const requestPromise = withHubTimeout(
+ GGUF_VARIANTS_TIMEOUT_MS,
+ async (signal) => {
+ const response = await authFetch(`/api/hub/gguf-variants?${params}`, {
+ headers: hubTokenHeader(hfToken),
+ signal,
+ });
+ return parseJsonOrThrow<GgufVariantsResponse>(response);
+ },
+ );
+ const promise = requestPromise.then((result) => {
+ const current = ggufVariantsCache.get(key);
+ if (current?.promise === promise) {
+ current.expiresAt =
+ Date.now() + ggufVariantsTtlMs(result, preferLocalCache);
+ }
+ return result;
+ });
+ ggufVariantsCache.set(key, {
+ expiresAt: now + GGUF_VARIANTS_TTL_MS,
+ promise,
+ });
+ pruneGgufVariantsCache(now);
+ promise.catch(() => {
+ if (ggufVariantsCache.get(key)?.promise === promise) {
+ ggufVariantsCache.delete(key);
+ }
+ });
+ return withAbort(promise, signal);
+}
+
+export function invalidateGgufVariantsCache(repoId?: string): void {
+ if (!repoId) {
+ ggufVariantsCache.clear();
+ bumpGgufVariantsCacheVersion();
+ return;
+ }
+ const repoPrefix = `${repoId}::`.toLowerCase();
+ for (const key of ggufVariantsCache.keys()) {
+ if (key.toLowerCase().startsWith(repoPrefix)) {
+ ggufVariantsCache.delete(key);
+ }
+ }
+ bumpGgufVariantsCacheVersion(repoId);
+}
diff --git a/studio/frontend/src/features/hub/inventory/constants.ts b/studio/frontend/src/features/hub/inventory/constants.ts
new file mode 100644
index 00000000000..6482f5f6029
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/constants.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export const LOCAL_MODEL_SOURCE = {
+ MODELS_DIR: "models_dir",
+ HF_CACHE: "hf_cache",
+ LMSTUDIO: "lmstudio",
+ OLLAMA: "ollama",
+ CUSTOM: "custom",
+} as const;
+
+export const LOCAL_MODEL_SOURCES = [
+ LOCAL_MODEL_SOURCE.MODELS_DIR,
+ LOCAL_MODEL_SOURCE.HF_CACHE,
+ LOCAL_MODEL_SOURCE.LMSTUDIO,
+ LOCAL_MODEL_SOURCE.OLLAMA,
+ LOCAL_MODEL_SOURCE.CUSTOM,
+] as const;
+export type LocalSource = (typeof LOCAL_MODEL_SOURCES)[number];
+
+export const INVENTORY_HINT_KIND = {
+ MODEL: "model",
+ GGUF: "gguf",
+ DATASET: "dataset",
+} as const;
+
+export const INVENTORY_HINT_KINDS = [
+ INVENTORY_HINT_KIND.MODEL,
+ INVENTORY_HINT_KIND.GGUF,
+ INVENTORY_HINT_KIND.DATASET,
+] as const;
+export type InventoryHintKind = (typeof INVENTORY_HINT_KINDS)[number];
diff --git a/studio/frontend/src/features/hub/inventory/gguf-variants-cache-events.ts b/studio/frontend/src/features/hub/inventory/gguf-variants-cache-events.ts
new file mode 100644
index 00000000000..d5d8299ffef
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/gguf-variants-cache-events.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+type Listener = () => void;
+
+const listeners = new Set<Listener>();
+const repoVersions = new Map<string, number>();
+const REPO_VERSION_LIMIT = 256;
+let globalVersion = 0;
+let versionSequence = 0;
+
+function repoKey(repoId: string): string {
+ return repoId.trim().toLowerCase();
+}
+
+function emit(): void {
+ for (const listener of [...listeners]) listener();
+}
+
+function nextVersion(): number {
+ versionSequence += 1;
+ return versionSequence;
+}
+
+export function bumpGgufVariantsCacheVersion(repoId?: string): void {
+ const key = repoId ? repoKey(repoId) : "";
+ if (key) {
+ repoVersions.delete(key);
+ repoVersions.set(key, nextVersion());
+ while (repoVersions.size > REPO_VERSION_LIMIT) {
+ const oldest = repoVersions.keys().next().value;
+ if (!oldest) break;
+ repoVersions.delete(oldest);
+ }
+ } else {
+ globalVersion = nextVersion();
+ }
+ emit();
+}
+
+export function getGgufVariantsCacheVersion(repoId?: string | null): string {
+ const key = repoId ? repoKey(repoId) : "";
+ return `${globalVersion}:${key ? (repoVersions.get(key) ?? 0) : 0}`;
+}
+
+export function subscribeGgufVariantsCache(
+ listener: Listener,
+): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
diff --git a/studio/frontend/src/features/hub/inventory/index.ts b/studio/frontend/src/features/hub/inventory/index.ts
new file mode 100644
index 00000000000..dd8e161708d
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/index.ts
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export {
+ INVENTORY_HINT_KIND,
+ INVENTORY_HINT_KINDS,
+ LOCAL_MODEL_SOURCE,
+ LOCAL_MODEL_SOURCES,
+ type InventoryHintKind,
+ type LocalSource,
+} from "./constants";
+export {
+ addScanFolder,
+ browseFolders,
+ listCachedDatasets,
+ listCachedGguf,
+ listCachedModels,
+ deleteCachedDataset,
+ deleteCachedModel,
+ invalidateGgufVariantsCache,
+ listGgufVariants,
+ listLocalDatasets,
+ listLocalModels,
+ listScanFolders,
+ removeScanFolder,
+ type BrowseFoldersResponse,
+ type CachedDatasetRepo,
+ type CachedGgufRepo,
+ type CachedModelRepo,
+ type BaseModelSource,
+ type GgufVariantDetail,
+ type GgufVariantsResponse,
+ type LocalDatasetInfo,
+ type LocalModelInfo,
+ type LocalModelListResponse,
+ type ModelInventoryFormat,
+ type ModelInventoryRuntime,
+ type ScanFolderInfo,
+} from "./api";
+export {
+ buildLocalInventoryRows,
+ buildCachedInventoryRow,
+ defaultCapabilities,
+ formatLocalUpdated,
+ localSourceLabel,
+ normalizeCapabilities,
+ normalizeModelFormat,
+ normalizeRuntime,
+ normalizeTimestamp,
+} from "./view-models";
+export {
+ resolveInventoryResource,
+ type InventoryResourceFormatHint,
+ type ResolvedInventoryResource,
+} from "./resource-resolver";
+export {
+ dedupeSameSourceHubCacheRows,
+ findCompleteHfCacheLocalRow,
+} from "./inventory-dedupe";
+export {
+ fetchInventorySource,
+ useDeviceInventorySources,
+ useDeviceInventoryStore,
+ type DeviceInventoryRows,
+ type DeviceInventorySource,
+ type DeviceInventorySourceState,
+} from "./use-device-inventory";
+export {
+ useHubInventory,
+ type HubInventoryKind,
+ type HubInventory,
+} from "./use-hub-inventory";
+export { useGgufVariantsCacheVersion } from "./use-gguf-variants-cache-version";
+export type {
+ CachedInventoryRow,
+ InventoryHint,
+ InventoryRow,
+ LocalInventoryRow,
+ ModelInventoryCapabilities,
+} from "./types";
diff --git a/studio/frontend/src/features/hub/inventory/inventory-dedupe.ts b/studio/frontend/src/features/hub/inventory/inventory-dedupe.ts
new file mode 100644
index 00000000000..138f83fadb4
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/inventory-dedupe.ts
@@ -0,0 +1,185 @@
+// 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";
+
+function repoFormatKey(
+ repoId: string | null | undefined,
+ modelFormat: string | null | undefined,
+): string | null {
+ const normalizedRepo = repoId?.trim().toLowerCase();
+ if (!normalizedRepo) {
+ return null;
+ }
+ return `${normalizedRepo}\0${modelFormat ?? "unknown"}`;
+}
+
+function repoKey(repoId: string | null | undefined): string | null {
+ return repoId?.trim().toLowerCase() || null;
+}
+
+export function findCompleteHfCacheLocalRow(
+ cachedRow: CachedInventoryRow,
+ localRows: readonly LocalInventoryRow[],
+): LocalInventoryRow | null {
+ const key = repoFormatKey(cachedRow.repoId, cachedRow.modelFormat);
+ if (!key) {
+ return null;
+ }
+ return (
+ localRows.find(
+ (row) =>
+ row.source === "hf_cache" &&
+ !row.partial &&
+ repoFormatKey(row.repoId, row.modelFormat) === key,
+ ) ?? null
+ );
+}
+
+export function partialSetFromRows<T extends { partial?: boolean }>(
+ rows: readonly T[],
+ getRepoId: (row: T) => string | null | undefined,
+): Set<string> {
+ const complete = new Set<string>();
+ for (const row of rows) {
+ const repoId = getRepoId(row);
+ if (repoId && !row.partial) complete.add(repoId.toLowerCase());
+ }
+ const partial = new Set<string>();
+ for (const row of rows) {
+ const repoId = getRepoId(row);
+ if (!repoId) continue;
+ const key = repoId.toLowerCase();
+ if (row.partial && !complete.has(key)) partial.add(key);
+ }
+ return partial;
+}
+
+function preferCachedRow(
+ candidate: CachedInventoryRow,
+ existing: CachedInventoryRow | null | undefined,
+): boolean {
+ if (!existing) {
+ return true;
+ }
+ if (Boolean(candidate.partial) !== Boolean(existing.partial)) {
+ return !candidate.partial;
+ }
+ if (Boolean(candidate.liveDownload) !== Boolean(existing.liveDownload)) {
+ return Boolean(candidate.liveDownload);
+ }
+ return candidate.bytes > existing.bytes;
+}
+
+function dedupeCachedRows(
+ rows: readonly CachedInventoryRow[],
+): CachedInventoryRow[] {
+ const selected = new Map<string, CachedInventoryRow>();
+ const passthrough: CachedInventoryRow[] = [];
+ for (const row of rows) {
+ const key = repoFormatKey(row.repoId, row.modelFormat);
+ if (!key) {
+ passthrough.push(row);
+ continue;
+ }
+ const existing = selected.get(key);
+ if (preferCachedRow(row, existing)) {
+ selected.set(key, row);
+ }
+ }
+ return [...selected.values(), ...passthrough];
+}
+
+export function dedupeSameSourceHubCacheRows({
+ cachedRows,
+ localRows,
+}: {
+ cachedRows: readonly CachedInventoryRow[];
+ localRows: readonly LocalInventoryRow[];
+}): {
+ cachedRows: CachedInventoryRow[];
+ localRows: LocalInventoryRow[];
+} {
+ const uniqueCachedRows = dedupeCachedRows(cachedRows);
+ const completeCachedRepos = new Set<string>();
+ const partialGgufRepos = new Set<string>();
+ for (const row of uniqueCachedRows) {
+ if (row.partial && row.modelFormat === "gguf") {
+ const repo = repoKey(row.repoId);
+ if (repo) partialGgufRepos.add(repo);
+ }
+ if (row.partial) {
+ continue;
+ }
+ const repo = repoKey(row.repoId);
+ if (repo) {
+ completeCachedRepos.add(repo);
+ }
+ }
+
+ const completeHfCacheLocalKeys = new Set<string>();
+ for (const row of localRows) {
+ if (row.partial && row.modelFormat === "gguf") {
+ const repo = repoKey(row.repoId);
+ if (repo) partialGgufRepos.add(repo);
+ }
+ if (row.source !== "hf_cache" || row.partial) {
+ continue;
+ }
+ const key = repoFormatKey(row.repoId, row.modelFormat);
+ if (key) {
+ completeHfCacheLocalKeys.add(key);
+ }
+ }
+
+ const filteredCachedRows = uniqueCachedRows.filter((row) => {
+ const repo = repoKey(row.repoId);
+ if (
+ row.partial &&
+ !row.liveDownload &&
+ row.modelFormat === "unknown" &&
+ repo &&
+ partialGgufRepos.has(repo)
+ ) {
+ return false;
+ }
+ const key = repoFormatKey(row.repoId, row.modelFormat);
+ return !(row.partial && key && completeHfCacheLocalKeys.has(key));
+ });
+ const retainedCachedKeys = new Set(
+ filteredCachedRows.flatMap((row) => {
+ const key = repoFormatKey(row.repoId, row.modelFormat);
+ return key ? [key] : [];
+ }),
+ );
+
+ return {
+ cachedRows: filteredCachedRows,
+ localRows: localRows.filter((row) => {
+ if (row.source !== "hf_cache") {
+ return true;
+ }
+ const key = repoFormatKey(row.repoId, row.modelFormat);
+ if (key && retainedCachedKeys.has(key)) {
+ return false;
+ }
+ const repo = repoKey(row.repoId);
+ if (
+ row.partial &&
+ row.modelFormat === "unknown" &&
+ repo &&
+ partialGgufRepos.has(repo)
+ ) {
+ return false;
+ }
+ if (
+ row.modelFormat === "unknown" &&
+ repo &&
+ completeCachedRepos.has(repo)
+ ) {
+ return false;
+ }
+ return true;
+ }),
+ };
+}
diff --git a/studio/frontend/src/features/hub/inventory/inventory-hint-store.ts b/studio/frontend/src/features/hub/inventory/inventory-hint-store.ts
new file mode 100644
index 00000000000..b56e488519a
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/inventory-hint-store.ts
@@ -0,0 +1,221 @@
+// 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 { create } from "zustand";
+import { INVENTORY_HINT_KINDS } from "./constants.ts";
+import {
+ type InventoryHintReconciliation,
+ type PendingInventoryHints,
+ clonePendingInventoryHints,
+ commitInventoryHintReconciliation,
+ createPendingInventoryHints,
+ pruneExpiredInventoryHints,
+ reconcileInventoryHints,
+ rememberInventoryHint,
+ 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;
+
+type ObservedInventoryKeys = Record<InventoryHint["kind"], Set<string>>;
+
+export type PendingHintReconciliationCommit = {
+ kind: InventoryHint["kind"];
+ reconciliation: Pick<
+ InventoryHintReconciliation,
+ "pending" | "staleCompletedHints" | "observedKeys"
+ >;
+};
+
+type InventoryHintState = {
+ pending: PendingInventoryHints;
+ observedKeys: ObservedInventoryKeys;
+ pruneExpiredHints: () => void;
+ commitReconciliations: (
+ completedHints: readonly InventoryHint[],
+ baseline: PendingInventoryHints,
+ reconciliations: readonly PendingHintReconciliationCommit[],
+ ) => InventoryHint[];
+};
+
+const INVENTORY_HINT_EQUALITY_FIELDS = {
+ kind: true,
+ repoId: true,
+ bytes: true,
+ createdAt: true,
+} satisfies Record<keyof InventoryHint, true>;
+
+const INVENTORY_HINT_EQUALITY_KEYS = Object.keys(
+ INVENTORY_HINT_EQUALITY_FIELDS,
+) as (keyof InventoryHint)[];
+
+function createObservedInventoryKeys(): ObservedInventoryKeys {
+ return {
+ model: new Set(),
+ gguf: new Set(),
+ dataset: new Set(),
+ };
+}
+
+function setEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
+ if (a.size !== b.size) {
+ return false;
+ }
+ for (const value of a) {
+ if (!b.has(value)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function inventoryHintEqual(
+ a: InventoryHint | undefined,
+ b: InventoryHint,
+): boolean {
+ if (a === undefined) {
+ return false;
+ }
+ return INVENTORY_HINT_EQUALITY_KEYS.every((key) => {
+ const left =
+ key === "bytes" || key === "createdAt" ? (a[key] ?? 0) : a[key];
+ const right =
+ key === "bytes" || key === "createdAt" ? (b[key] ?? 0) : b[key];
+ return left === right;
+ });
+}
+
+export function pendingInventoryHintsEqual(
+ a: PendingInventoryHints,
+ b: PendingInventoryHints,
+): boolean {
+ for (const kind of INVENTORY_HINT_KINDS) {
+ if (a[kind].size !== b[kind].size) {
+ return false;
+ }
+ for (const [key, hint] of a[kind]) {
+ if (!inventoryHintEqual(b[kind].get(key), hint)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+export function pendingHintReconciliationNeedsCommit(
+ baseline: PendingInventoryHints,
+ observedKeys: Record<InventoryHint["kind"], ReadonlySet<string>>,
+ commit: PendingHintReconciliationCommit,
+): boolean {
+ if (!pendingInventoryHintsEqual(baseline, commit.reconciliation.pending)) {
+ return true;
+ }
+ if (commit.reconciliation.staleCompletedHints.length > 0) {
+ return true;
+ }
+ return !setEqual(
+ observedKeys[commit.kind],
+ commit.reconciliation.observedKeys,
+ );
+}
+
+function observedInventoryKeysEqual(
+ a: ObservedInventoryKeys,
+ b: ObservedInventoryKeys,
+): boolean {
+ return INVENTORY_HINT_KINDS.every((kind) => setEqual(a[kind], b[kind]));
+}
+
+function pendingHasHint(
+ pending: PendingInventoryHints,
+ hint: InventoryHint,
+): boolean {
+ const existing = pending[hint.kind].get(repoKey(hint.repoId));
+ if (!existing) {
+ return false;
+ }
+ return (existing.bytes ?? 0) >= (hint.bytes ?? 0);
+}
+
+export function pendingWithInventoryHints(
+ pending: PendingInventoryHints,
+ hints: readonly InventoryHint[],
+): PendingInventoryHints {
+ let next = pruneExpiredInventoryHints(pending);
+ for (const hint of hints) {
+ if (!pendingHasHint(next, hint)) {
+ next = rememberInventoryHint(next, hint);
+ }
+ }
+ return next;
+}
+
+function rememberObservedInventoryKeys(
+ current: ObservedInventoryKeys,
+ kind: InventoryHint["kind"],
+ keys: ReadonlySet<string>,
+ pending: PendingInventoryHints,
+): ObservedInventoryKeys {
+ const observed = new Set(current[kind]);
+ for (const key of keys) {
+ observed.delete(key);
+ observed.add(key);
+ }
+ evictOldestUnprotected(
+ observed,
+ MAX_OBSERVED_INVENTORY_KEYS_PER_KIND,
+ (key) => pending[kind].has(key),
+ );
+ if (setEqual(current[kind], observed)) {
+ return current;
+ }
+ return { ...current, [kind]: observed };
+}
+
+export const useInventoryHintStore = create<InventoryHintState>()(
+ (set, get) => ({
+ pending: createPendingInventoryHints(),
+ observedKeys: createObservedInventoryKeys(),
+ pruneExpiredHints: () => {
+ const current = get().pending;
+ const next = pruneExpiredInventoryHints(current);
+ if (!pendingInventoryHintsEqual(current, next)) {
+ set({ pending: clonePendingInventoryHints(next) });
+ }
+ },
+ commitReconciliations: (completedHints, baseline, reconciliations) => {
+ const state = get();
+ let next = pendingWithInventoryHints(state.pending, completedHints);
+ let observedKeys = state.observedKeys;
+ const completedHintsToSuppress: InventoryHint[] = [];
+ for (const { kind, reconciliation } of reconciliations) {
+ const committed = commitInventoryHintReconciliation({
+ current: next,
+ kind,
+ baseline,
+ next: reconciliation.pending,
+ staleCompletedHints: reconciliation.staleCompletedHints,
+ });
+ next = committed.pending;
+ observedKeys = rememberObservedInventoryKeys(
+ observedKeys,
+ kind,
+ reconciliation.observedKeys,
+ next,
+ );
+ completedHintsToSuppress.push(...committed.completedHintsToSuppress);
+ }
+ const unchanged =
+ pendingInventoryHintsEqual(state.pending, next) &&
+ observedInventoryKeysEqual(state.observedKeys, observedKeys);
+ if (!unchanged) {
+ set({ pending: clonePendingInventoryHints(next), observedKeys });
+ }
+ return completedHintsToSuppress;
+ },
+ }),
+);
+
+export { reconcileInventoryHints };
diff --git a/studio/frontend/src/features/hub/inventory/inventory-hints.ts b/studio/frontend/src/features/hub/inventory/inventory-hints.ts
new file mode 100644
index 00000000000..af9f254ab3a
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/inventory-hints.ts
@@ -0,0 +1,273 @@
+// 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 { InventoryHint } from "./types";
+
+export type PendingInventoryHints = Record<
+ InventoryHint["kind"],
+ Map<string, InventoryHint>
+>;
+
+export type InventoryHintRow = {
+ repo_id: string;
+ size_bytes: number;
+ partial?: boolean;
+};
+
+export type InventoryHintReconciliation = {
+ rows: InventoryHintRow[];
+ pending: PendingInventoryHints;
+ staleCompletedHints: InventoryHint[];
+ observedKeys: Set<string>;
+};
+
+type InventoryHintCommit = {
+ pending: PendingInventoryHints;
+ completedHintsToSuppress: InventoryHint[];
+};
+
+export const INVENTORY_HINT_TTL_MS = 5 * 60_000;
+
+function rowRepoId(row: InventoryHintRow): string {
+ return row.repo_id;
+}
+
+function rowSizeBytes(row: InventoryHintRow): number {
+ return row.size_bytes;
+}
+
+function optimisticRow(hint: InventoryHint): InventoryHintRow {
+ return {
+ repo_id: hint.repoId,
+ size_bytes: hint.bytes ?? 0,
+ partial: false,
+ };
+}
+
+function suppressibleInventoryHint(hint: InventoryHint): InventoryHint {
+ return {
+ kind: hint.kind,
+ repoId: hint.repoId,
+ ...(hint.bytes ? { bytes: hint.bytes } : {}),
+ };
+}
+
+export function createPendingInventoryHints(): PendingInventoryHints {
+ return {
+ model: new Map(),
+ gguf: new Map(),
+ dataset: new Map(),
+ };
+}
+
+export function clonePendingInventoryHints(
+ source: PendingInventoryHints,
+): PendingInventoryHints {
+ return {
+ model: new Map(source.model),
+ gguf: new Map(source.gguf),
+ dataset: new Map(source.dataset),
+ };
+}
+
+function clonePendingInventoryHintsForKind(
+ source: PendingInventoryHints,
+ kind: InventoryHint["kind"],
+): PendingInventoryHints {
+ return {
+ ...source,
+ [kind]: new Map(source[kind]),
+ };
+}
+
+export function repoKey(repoId: string): string {
+ return repoId.trim().toLowerCase();
+}
+
+export function inventoryHintKey(
+ kind: InventoryHint["kind"],
+ repoId: string,
+): string {
+ return `${kind}:${repoKey(repoId)}`;
+}
+
+function mergeInventoryHint(
+ rows: InventoryHintRow[],
+ hint: InventoryHint,
+): InventoryHintRow[] {
+ const lower = repoKey(hint.repoId);
+ const seed = optimisticRow(hint);
+ const idx = rows.findIndex((row) => repoKey(rowRepoId(row)) === lower);
+ if (idx === -1) {
+ return [...rows, seed];
+ }
+ const merged = {
+ ...rows[idx],
+ ...seed,
+ size_bytes: Math.max(rowSizeBytes(rows[idx]), rowSizeBytes(seed)),
+ };
+ return [...rows.slice(0, idx), merged, ...rows.slice(idx + 1)];
+}
+
+export function rememberInventoryHint(
+ pending: PendingInventoryHints,
+ hint: InventoryHint,
+): PendingInventoryHints {
+ const next = clonePendingInventoryHints(pending);
+ 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();
+ next[hint.kind].set(key, {
+ kind: hint.kind,
+ repoId: hint.repoId,
+ ...(bytes > 0 ? { bytes } : {}),
+ createdAt,
+ });
+ return next;
+}
+
+function inventoryHintExpired(hint: InventoryHint, now: number): boolean {
+ return (hint.createdAt ?? now) + INVENTORY_HINT_TTL_MS <= now;
+}
+
+export function nextInventoryHintExpiryDelay(
+ pending: PendingInventoryHints,
+ now = Date.now(),
+): number | null {
+ let nextExpiry = Number.POSITIVE_INFINITY;
+ for (const hints of Object.values(pending)) {
+ for (const hint of hints.values()) {
+ if (typeof hint.createdAt !== "number") {
+ continue;
+ }
+ nextExpiry = Math.min(nextExpiry, hint.createdAt + INVENTORY_HINT_TTL_MS);
+ }
+ }
+ return Number.isFinite(nextExpiry) ? Math.max(0, nextExpiry - now) : null;
+}
+
+export function pruneExpiredInventoryHints(
+ pending: PendingInventoryHints,
+ now = Date.now(),
+): PendingInventoryHints {
+ let next = pending;
+ for (const kind of Object.keys(pending) as InventoryHint["kind"][]) {
+ for (const [key, hint] of next[kind]) {
+ if (!inventoryHintExpired(hint, now)) {
+ continue;
+ }
+ if (next === pending) {
+ next = clonePendingInventoryHints(pending);
+ }
+ next[kind].delete(key);
+ }
+ }
+ return next;
+}
+
+function serverRowSatisfiesHint(
+ row: InventoryHintRow,
+ hint: InventoryHint,
+): boolean {
+ if (row.partial) {
+ return false;
+ }
+ return !hint.bytes || rowSizeBytes(row) >= hint.bytes;
+}
+
+export function reconcileInventoryHints<T extends InventoryHintRow>({
+ pending,
+ kind,
+ rows,
+ previouslyObserved,
+}: {
+ pending: PendingInventoryHints;
+ kind: InventoryHint["kind"];
+ rows: T[];
+ previouslyObserved: ReadonlySet<string>;
+}): InventoryHintReconciliation {
+ const pruned = pruneExpiredInventoryHints(pending);
+ const serverRows = new Map(rows.map((row) => [repoKey(rowRepoId(row)), row]));
+ const observedKeys = new Set(serverRows.keys());
+ if (pruned[kind].size === 0) {
+ return {
+ rows,
+ pending: pruned,
+ staleCompletedHints: [],
+ observedKeys,
+ };
+ }
+
+ const nextPending = clonePendingInventoryHintsForKind(pruned, kind);
+ const hints = nextPending[kind];
+ const staleCompletedHints: InventoryHint[] = [];
+
+ for (const [key, hint] of hints) {
+ const serverRow = serverRows.get(key);
+ if (serverRow && serverRowSatisfiesHint(serverRow, hint)) {
+ hints.delete(key);
+ } else if (!serverRow && previouslyObserved.has(key)) {
+ hints.delete(key);
+ staleCompletedHints.push(hint);
+ }
+ }
+
+ let mergedRows: InventoryHintRow[] = rows;
+ for (const hint of hints.values()) {
+ mergedRows = mergeInventoryHint(mergedRows, hint);
+ }
+
+ return {
+ rows: mergedRows,
+ pending: nextPending,
+ staleCompletedHints,
+ observedKeys,
+ };
+}
+
+export function commitInventoryHintReconciliation({
+ current,
+ kind,
+ baseline,
+ next,
+ staleCompletedHints,
+}: {
+ current: PendingInventoryHints;
+ kind: InventoryHint["kind"];
+ baseline: PendingInventoryHints;
+ next: PendingInventoryHints;
+ staleCompletedHints: InventoryHint[];
+}): InventoryHintCommit {
+ const committed = clonePendingInventoryHints(
+ pruneExpiredInventoryHints(current),
+ );
+ const sharedHints = committed[kind];
+ const staleKeys = new Set(
+ staleCompletedHints.map((hint) => repoKey(hint.repoId)),
+ );
+ const completedHintsToSuppress: InventoryHint[] = [];
+
+ for (const [key, baselineHint] of baseline[kind]) {
+ const nextHint = next[kind].get(key);
+ const currentHint = sharedHints.get(key);
+ const currentIsNewer =
+ currentHint && (currentHint.bytes ?? 0) > (baselineHint.bytes ?? 0);
+
+ if (nextHint) {
+ if (!currentIsNewer) {
+ sharedHints.set(key, nextHint);
+ }
+ continue;
+ }
+ if (currentIsNewer) {
+ continue;
+ }
+ sharedHints.delete(key);
+ if (staleKeys.has(key)) {
+ completedHintsToSuppress.push(suppressibleInventoryHint(baselineHint));
+ }
+ }
+
+ return { pending: committed, completedHintsToSuppress };
+}
diff --git a/studio/frontend/src/features/hub/inventory/resource-resolver.ts b/studio/frontend/src/features/hub/inventory/resource-resolver.ts
new file mode 100644
index 00000000000..343c59e758d
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/resource-resolver.ts
@@ -0,0 +1,125 @@
+// 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,
+ ModelInventoryFormat,
+} from "./types";
+
+export type InventoryResourceFormatHint =
+ | ModelInventoryFormat
+ | "non-gguf"
+ | null
+ | undefined;
+
+export type ResolvedInventoryResource = {
+ cachedRow: CachedInventoryRow | null;
+ localRow: LocalInventoryRow | null;
+};
+
+function repoKey(value: string | null | undefined): string {
+ return value?.trim().toLowerCase() ?? "";
+}
+
+function cachedRowMatchesFormat(
+ row: CachedInventoryRow,
+ formatHint: InventoryResourceFormatHint,
+): boolean {
+ if (!formatHint || formatHint === "unknown") return true;
+ if (formatHint === "non-gguf") return row.modelFormat !== "gguf";
+ return row.modelFormat === formatHint;
+}
+
+function localRowMatchesFormat(
+ row: LocalInventoryRow,
+ formatHint: InventoryResourceFormatHint,
+): boolean {
+ if (!formatHint || formatHint === "unknown") return true;
+ if (formatHint === "non-gguf") return row.modelFormat !== "gguf";
+ return row.modelFormat === formatHint;
+}
+
+function hasExplicitFormatHint(
+ formatHint: InventoryResourceFormatHint,
+): boolean {
+ return Boolean(formatHint && formatHint !== "unknown");
+}
+
+function bestCompleteCached(
+ rows: CachedInventoryRow[],
+): CachedInventoryRow | null {
+ return (
+ rows.find((row) => !row.partial && row.modelFormat === "safetensors") ??
+ rows.find((row) => !row.partial && row.modelFormat === "checkpoint") ??
+ rows.find((row) => !row.partial && row.modelFormat === "gguf") ??
+ rows.find((row) => !row.partial && row.modelFormat === "adapter") ??
+ rows.find((row) => !row.partial) ??
+ null
+ );
+}
+
+function bestCompleteLocal(rows: LocalInventoryRow[]): LocalInventoryRow | null {
+ return (
+ rows.find((row) => !row.partial && row.source !== "hf_cache") ??
+ rows.find((row) => !row.partial) ??
+ null
+ );
+}
+
+export function resolveInventoryResource({
+ repoId,
+ cachedRows,
+ localRows,
+ formatHint,
+}: {
+ repoId: string | null | undefined;
+ cachedRows: CachedInventoryRow[];
+ localRows: LocalInventoryRow[];
+ formatHint?: InventoryResourceFormatHint;
+}): ResolvedInventoryResource {
+ const key = repoKey(repoId);
+ if (!key) return { cachedRow: null, localRow: null };
+
+ const repoCachedRows = cachedRows.filter((row) => repoKey(row.repoId) === key);
+ const repoLocalRows = localRows.filter((row) => repoKey(row.repoId) === key);
+ const compatibleCachedRows = repoCachedRows.filter((row) =>
+ cachedRowMatchesFormat(row, formatHint),
+ );
+ const compatibleLocalRows = repoLocalRows.filter((row) =>
+ localRowMatchesFormat(row, formatHint),
+ );
+
+ const completeCached = bestCompleteCached(compatibleCachedRows);
+ if (completeCached) return { cachedRow: completeCached, localRow: null };
+
+ const completeLocal = bestCompleteLocal(compatibleLocalRows);
+ if (completeLocal) return { cachedRow: null, localRow: completeLocal };
+
+ const partialCached =
+ compatibleCachedRows.find((row) => row.partial) ?? null;
+ if (partialCached) return { cachedRow: partialCached, localRow: null };
+
+ const compatibleLocal = compatibleLocalRows[0] ?? null;
+ if (compatibleLocal) return { cachedRow: null, localRow: compatibleLocal };
+
+ if (hasExplicitFormatHint(formatHint)) {
+ return { cachedRow: null, localRow: null };
+ }
+
+ const fallbackCached = bestCompleteCached(repoCachedRows);
+ if (fallbackCached) return { cachedRow: fallbackCached, localRow: null };
+
+ const fallbackLocal = bestCompleteLocal(repoLocalRows);
+ if (fallbackLocal) return { cachedRow: null, localRow: fallbackLocal };
+
+ const fallbackPartialCached = repoCachedRows.find((row) => row.partial) ?? null;
+ if (fallbackPartialCached) {
+ return { cachedRow: fallbackPartialCached, localRow: null };
+ }
+
+ return {
+ cachedRow: null,
+ localRow: repoLocalRows[0] ?? null,
+ };
+}
diff --git a/studio/frontend/src/features/hub/inventory/types.ts b/studio/frontend/src/features/hub/inventory/types.ts
new file mode 100644
index 00000000000..c86ffb1d86a
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/types.ts
@@ -0,0 +1,88 @@
+// 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 { BaseModelSource } from "./api";
+import type { InventoryHintKind, LocalSource } from "./constants";
+
+export type ModelInventoryFormat =
+ | "gguf"
+ | "safetensors"
+ | "adapter"
+ | "checkpoint"
+ | "unknown";
+export type ModelInventoryRuntime =
+ | "llama_cpp"
+ | "transformers"
+ | "adapter"
+ | "unknown";
+
+export interface ModelInventoryCapabilities {
+ canTrain: boolean;
+ canChat: boolean;
+ canDelete: boolean;
+ canDownload: boolean;
+ requiresVariant: boolean;
+ supportsLora: boolean;
+ supportsVision: boolean;
+}
+
+export interface InventoryHint {
+ kind: InventoryHintKind;
+ repoId: string;
+ bytes?: number;
+ createdAt?: number;
+}
+
+export interface CachedInventoryRow {
+ kind: "cache";
+ id: string;
+ loadId: string;
+ repoId: string;
+ owner: string;
+ repo: string;
+ isGguf: boolean;
+ modelFormat: ModelInventoryFormat;
+ runtime: ModelInventoryRuntime;
+ formatVariant?: string | null;
+ capabilities: ModelInventoryCapabilities;
+ bytes: number;
+ cachePath?: string | null;
+ partial?: boolean;
+ partialTransport?: string | null;
+ pipelineTag?: string | null;
+ tags?: string[];
+ libraryName?: string | null;
+ quantMethod?: string | null;
+ liveDownload?: boolean;
+}
+
+export interface LocalInventoryRow {
+ kind: "local";
+ id: string;
+ loadId: string;
+ repoId: string | null;
+ owner: string;
+ title: string;
+ source: LocalSource;
+ sourceLabel: string;
+ path: string;
+ isGguf: boolean;
+ modelFormat: ModelInventoryFormat;
+ runtime: ModelInventoryRuntime;
+ formatVariant?: string | null;
+ capabilities: ModelInventoryCapabilities;
+ baseModel?: string | null;
+ baseModelSource?: BaseModelSource | null;
+ baseModelHubId?: string | null;
+ adapterType?: string | null;
+ trainingMethod?: string | null;
+ updatedAt: number | null;
+ partial?: boolean;
+ partialTransport?: string | null;
+ pipelineTag?: string | null;
+ tags?: string[];
+ libraryName?: string | null;
+ quantMethod?: string | null;
+}
+
+export type InventoryRow = CachedInventoryRow | LocalInventoryRow;
diff --git a/studio/frontend/src/features/hub/inventory/use-device-inventory.ts b/studio/frontend/src/features/hub/inventory/use-device-inventory.ts
new file mode 100644
index 00000000000..c662a582287
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/use-device-inventory.ts
@@ -0,0 +1,359 @@
+// 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 CachedDatasetRepo,
+ type CachedGgufRepo,
+ type CachedModelRepo,
+ type LocalDatasetInfo,
+ type LocalModelInfo,
+ listCachedDatasets,
+ listCachedGguf,
+ listCachedModels,
+ listLocalDatasets,
+ listLocalModels,
+} from "./api";
+import { useDebouncedValue } from "@/hooks/use-debounced-value";
+import { fingerprintToken } from "@/features/hub/lib/token-fingerprint";
+import { useInventoryVersion } from "@/features/hub/stores/inventory-events";
+import { useCallback, useEffect, useMemo } from "react";
+import { create } from "zustand";
+import { useShallow } from "zustand/react/shallow";
+
+export type DeviceInventorySource =
+ | "cachedGguf"
+ | "cachedModels"
+ | "cachedDatasets"
+ | "localModels"
+ | "localDatasets";
+
+export type DeviceInventoryRows = {
+ cachedGguf: CachedGgufRepo[];
+ cachedModels: CachedModelRepo[];
+ cachedDatasets: CachedDatasetRepo[];
+ localModels: LocalModelInfo[];
+ localDatasets: LocalDatasetInfo[];
+};
+
+export type DeviceInventorySourceState<Rows extends readonly unknown[]> = {
+ rows: Rows;
+ loading: boolean;
+ ready: boolean;
+ error: string | null;
+ key: string | null;
+};
+
+type DeviceInventoryState = {
+ [K in DeviceInventorySource]: DeviceInventorySourceState<
+ DeviceInventoryRows[K]
+ >;
+};
+
+type FetchInventorySourceOptions = {
+ hfToken?: string | null;
+ tokenFingerprint?: string;
+ inventoryVersion: number;
+ force?: boolean;
+};
+
+type UseDeviceInventoryOptions = {
+ hfToken?: string | null;
+ enabled?: boolean;
+};
+
+type UseDeviceInventoryResult<
+ Sources extends readonly DeviceInventorySource[],
+> = Pick<DeviceInventoryState, Sources[number]> & {
+ refresh: () => Promise<void>;
+};
+
+const TOKEN_SCOPED_SOURCES = new Set<DeviceInventorySource>([
+ "cachedGguf",
+ "cachedModels",
+]);
+const TOKEN_SCOPED_INVENTORY_DEBOUNCE_MS = 500;
+
+const inFlight = new Map<string, Promise<unknown>>();
+const forceQueue = new Map<string, Promise<unknown>>();
+
+function emptySource<
+ Rows extends readonly unknown[],
+>(): DeviceInventorySourceState<Rows> {
+ return {
+ rows: [] as unknown as Rows,
+ loading: false,
+ ready: false,
+ error: null,
+ key: null,
+ };
+}
+
+export const useDeviceInventoryStore = create<DeviceInventoryState>(() => ({
+ cachedGguf: emptySource<CachedGgufRepo[]>(),
+ cachedModels: emptySource<CachedModelRepo[]>(),
+ cachedDatasets: emptySource<CachedDatasetRepo[]>(),
+ localModels: emptySource<LocalModelInfo[]>(),
+ localDatasets: emptySource<LocalDatasetInfo[]>(),
+}));
+
+function sourceRequestKey(
+ source: DeviceInventorySource,
+ inventoryVersion: number,
+ tokenFingerprint: string,
+): string {
+ const tokenPart = TOKEN_SCOPED_SOURCES.has(source)
+ ? tokenFingerprint
+ : "local";
+ return `${source}:${inventoryVersion}:${tokenPart}`;
+}
+
+function fetchErrorMessage(
+ source: DeviceInventorySource,
+ error: unknown,
+): string {
+ if (error instanceof Error && error.message.trim()) {
+ return error.message;
+ }
+ switch (source) {
+ case "cachedGguf":
+ return "Couldn't scan cached GGUF models";
+ case "cachedModels":
+ return "Couldn't scan cached Hugging Face models";
+ case "cachedDatasets":
+ return "Couldn't scan cached datasets";
+ case "localModels":
+ return "Couldn't scan local models";
+ case "localDatasets":
+ return "Couldn't scan local datasets";
+ default:
+ return "Couldn't scan inventory";
+ }
+}
+
+function logInventorySourceFailure(
+ source: DeviceInventorySource,
+ error: unknown,
+): void {
+ if (!import.meta.env?.DEV) {
+ return;
+ }
+ console.warn(`Inventory source "${source}" failed to refresh:`, error);
+}
+
+async function runSourceFetch<K extends DeviceInventorySource>(
+ source: K,
+ hfToken?: string | null,
+): Promise<DeviceInventoryRows[K]> {
+ switch (source) {
+ case "cachedGguf":
+ return (await listCachedGguf(hfToken)) as DeviceInventoryRows[K];
+ case "cachedModels":
+ return (await listCachedModels(hfToken)) as DeviceInventoryRows[K];
+ case "cachedDatasets":
+ return (await listCachedDatasets()) as DeviceInventoryRows[K];
+ case "localModels":
+ return (await listLocalModels()).models as DeviceInventoryRows[K];
+ case "localDatasets":
+ return (await listLocalDatasets()).datasets as DeviceInventoryRows[K];
+ default:
+ throw new Error("Unsupported inventory source");
+ }
+}
+
+function updateSourceState<K extends DeviceInventorySource>(
+ source: K,
+ patch: Partial<DeviceInventorySourceState<DeviceInventoryRows[K]>>,
+): void {
+ useDeviceInventoryStore.setState((state) => ({
+ [source]: {
+ ...state[source],
+ ...patch,
+ },
+ }));
+}
+
+export function fetchInventorySource<K extends DeviceInventorySource>(
+ source: K,
+ options: FetchInventorySourceOptions,
+): Promise<DeviceInventoryRows[K]> {
+ const tokenFingerprint =
+ options.tokenFingerprint ?? fingerprintToken(options.hfToken);
+ const key = sourceRequestKey(
+ source,
+ options.inventoryVersion,
+ tokenFingerprint,
+ );
+ const current = useDeviceInventoryStore.getState()[
+ source
+ ] as DeviceInventorySourceState<DeviceInventoryRows[K]>;
+ const pending = inFlight.get(key) as
+ | Promise<DeviceInventoryRows[K]>
+ | undefined;
+ if (pending) {
+ if (!options.force) {
+ return pending;
+ }
+ const queued = forceQueue.get(key) as
+ | Promise<DeviceInventoryRows[K]>
+ | undefined;
+ if (queued) {
+ return queued;
+ }
+ const refetch = pending
+ .catch(() => undefined)
+ .then(() => fetchInventorySource(source, options))
+ .finally(() => {
+ if (forceQueue.get(key) === refetch) {
+ forceQueue.delete(key);
+ }
+ });
+ forceQueue.set(key, refetch);
+ return refetch;
+ }
+ if (!options.force && current.ready && current.key === key) {
+ return Promise.resolve(current.rows);
+ }
+
+ // Carry `ready` across refetches so a stale-but-known state doesn't flip to
+ // "loading" on a bump and flash a spinner in every consumer; show prior rows
+ // until the success path lands fresh data.
+ updateSourceState(source, {
+ loading: true,
+ ready: current.ready,
+ error: null,
+ key,
+ });
+
+ const request = runSourceFetch(source, options.hfToken)
+ .then((rows) => {
+ if (useDeviceInventoryStore.getState()[source].key === key) {
+ updateSourceState(source, {
+ rows,
+ loading: false,
+ ready: true,
+ error: null,
+ key,
+ });
+ }
+ return rows;
+ })
+ .catch((error) => {
+ if (useDeviceInventoryStore.getState()[source].key === key) {
+ // Preserve prior `ready` on failure so a transient background-refetch
+ // error doesn't blank consumers that already hold good rows.
+ updateSourceState(source, {
+ loading: false,
+ ready: current.ready,
+ error: fetchErrorMessage(source, error),
+ key,
+ });
+ }
+ throw error;
+ })
+ .finally(() => {
+ if (inFlight.get(key) === request) {
+ inFlight.delete(key);
+ }
+ });
+
+ inFlight.set(key, request);
+ return request;
+}
+
+export function inventoryEmptyRevalidationSignature(
+ sources: readonly Pick<
+ DeviceInventorySourceState<readonly unknown[]>,
+ "error" | "key" | "ready"
+ >[],
+): string {
+ return sources
+ .map((source) =>
+ [
+ source.key ?? "pending",
+ source.ready ? "ready" : "pending",
+ source.error ?? "",
+ ].join("\u0001"),
+ )
+ .join("\u0002");
+}
+
+export function useDeviceInventorySources<
+ const Sources extends readonly DeviceInventorySource[],
+>(
+ sources: Sources,
+ options: UseDeviceInventoryOptions = {},
+): UseDeviceInventoryResult<Sources> {
+ const rawInventoryVersion = useInventoryVersion();
+ const rawHfToken = options.hfToken ?? undefined;
+ const debouncedInventoryVersion = useDebouncedValue(
+ rawInventoryVersion,
+ TOKEN_SCOPED_INVENTORY_DEBOUNCE_MS,
+ );
+ const debouncedHfToken = useDebouncedValue(
+ rawHfToken,
+ TOKEN_SCOPED_INVENTORY_DEBOUNCE_MS,
+ );
+ const enabled = options.enabled ?? true;
+ const sourceKey = sources.join("|");
+ const sourceList = useMemo(
+ () => sourceKey.split("|").filter(Boolean) as DeviceInventorySource[],
+ [sourceKey],
+ );
+ const hasTokenScopedSources = useMemo(
+ () => sourceList.some((source) => TOKEN_SCOPED_SOURCES.has(source)),
+ [sourceList],
+ );
+ const inventoryVersion = hasTokenScopedSources
+ ? debouncedInventoryVersion
+ : rawInventoryVersion;
+ const hfToken = hasTokenScopedSources ? debouncedHfToken : rawHfToken;
+ const tokenFingerprint = useMemo(() => fingerprintToken(hfToken), [hfToken]);
+ const state = useDeviceInventoryStore(
+ useShallow((s) => {
+ const selected = {} as Pick<DeviceInventoryState, Sources[number]>;
+ for (const source of sourceList) {
+ (selected as Partial<DeviceInventoryState>)[source] = s[
+ source
+ ] as never;
+ }
+ return selected;
+ }),
+ );
+
+ const refresh = useCallback(async () => {
+ const results = await Promise.allSettled(
+ sourceList.map((source) =>
+ fetchInventorySource(source, {
+ hfToken,
+ tokenFingerprint,
+ inventoryVersion,
+ force: true,
+ }),
+ ),
+ );
+ for (const [index, result] of results.entries()) {
+ const source = sourceList[index];
+ if (source && result.status === "rejected") {
+ logInventorySourceFailure(source, result.reason);
+ }
+ }
+ }, [sourceList, hfToken, tokenFingerprint, inventoryVersion]);
+
+ useEffect(() => {
+ if (!enabled) {
+ return;
+ }
+ for (const source of sourceList) {
+ fetchInventorySource(source, {
+ hfToken,
+ tokenFingerprint,
+ inventoryVersion,
+ }).catch((error) => logInventorySourceFailure(source, error));
+ }
+ }, [enabled, sourceList, hfToken, tokenFingerprint, inventoryVersion]);
+
+ return {
+ ...state,
+ refresh,
+ } as UseDeviceInventoryResult<Sources>;
+}
diff --git a/studio/frontend/src/features/hub/inventory/use-gguf-variants-cache-version.ts b/studio/frontend/src/features/hub/inventory/use-gguf-variants-cache-version.ts
new file mode 100644
index 00000000000..ad8bfc9fbaf
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/use-gguf-variants-cache-version.ts
@@ -0,0 +1,18 @@
+// 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 { useSyncExternalStore } from "react";
+import {
+ getGgufVariantsCacheVersion,
+ subscribeGgufVariantsCache,
+} from "./gguf-variants-cache-events";
+
+export function useGgufVariantsCacheVersion(
+ repoId?: string | null,
+): string {
+ return useSyncExternalStore(
+ subscribeGgufVariantsCache,
+ () => getGgufVariantsCacheVersion(repoId),
+ () => getGgufVariantsCacheVersion(repoId),
+ );
+}
diff --git a/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts b/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
new file mode 100644
index 00000000000..a7dc7ae3f37
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
@@ -0,0 +1,610 @@
+// 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 {
+ clearCompletedInventoryHint,
+ useDownloadManagerStore,
+ type ManagedDownload,
+} from "@/features/hub/download-manager";
+import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import type { LocalDatasetInfo } from "./api";
+import {
+ dedupeSameSourceHubCacheRows,
+ partialSetFromRows,
+} from "./inventory-dedupe";
+import {
+ type PendingHintReconciliationCommit,
+ pendingHintReconciliationNeedsCommit,
+ pendingInventoryHintsEqual,
+ pendingWithInventoryHints,
+ reconcileInventoryHints,
+ useInventoryHintStore,
+} from "./inventory-hint-store";
+import {
+ type PendingInventoryHints,
+ nextInventoryHintExpiryDelay,
+} from "./inventory-hints";
+import type { CachedInventoryRow, LocalInventoryRow } from "./types";
+import {
+ type DeviceInventorySource,
+ inventoryEmptyRevalidationSignature,
+ useDeviceInventorySources,
+} from "./use-device-inventory";
+import {
+ buildCachedInventoryRow,
+ buildLocalInventoryRows,
+ defaultCapabilities,
+ normalizeTimestamp,
+} from "./view-models";
+
+export interface HubInventory {
+ cachedRows: CachedInventoryRow[];
+ localRows: LocalInventoryRow[];
+ availableSet: Set<string>;
+ partialSet: Set<string>;
+ downloadedReady: boolean;
+ inventoryError: boolean;
+ inventoryWarning: boolean;
+ refreshInventory: () => Promise<void>;
+}
+
+export type HubInventoryKind = "models" | "datasets";
+
+type HubInventoryOptions = {
+ kind?: HubInventoryKind;
+ enabled?: boolean;
+ includeLocal?: boolean;
+};
+
+const MODEL_HUB_CACHE_SOURCES = [
+ "cachedGguf",
+ "cachedModels",
+] as const satisfies readonly DeviceInventorySource[];
+
+const DATASET_HUB_CACHE_SOURCES = [
+ "cachedDatasets",
+] as const satisfies readonly DeviceInventorySource[];
+
+const LOCAL_MODEL_INVENTORY_SOURCE = [
+ "localModels",
+] as const satisfies readonly DeviceInventorySource[];
+
+const LOCAL_DATASET_INVENTORY_SOURCE = [
+ "localDatasets",
+] as const satisfies readonly DeviceInventorySource[];
+
+type LiveInventoryJob = Pick<
+ ManagedDownload,
+ "kind" | "repoId" | "variant" | "state" | "startedAt"
+> & {
+ displayBytes: number;
+};
+
+function compareCachedRows(
+ a: CachedInventoryRow,
+ b: CachedInventoryRow,
+): number {
+ if (Boolean(a.partial) !== Boolean(b.partial)) return a.partial ? 1 : -1;
+ return a.repoId.localeCompare(b.repoId);
+}
+
+function localDatasetSourceLabel(source?: string | null): string {
+ switch (source) {
+ case "recipe":
+ return "Recipe dataset";
+ case "upload":
+ return "Uploaded dataset";
+ default:
+ return "Local dataset";
+ }
+}
+
+function isReadyForDisplay(source: {
+ error: string | null;
+ loading: boolean;
+ ready: boolean;
+ rows: readonly unknown[];
+}): boolean {
+ if (source.error !== null) return true;
+ if (!source.ready) return false;
+ return !(source.loading && source.rows.length === 0);
+}
+
+function liveInventoryRank(job: ManagedDownload): number {
+ if (job.state === "running" || job.state === "cancelling") return 2;
+ if (job.state === "cancelled" || job.state === "error") return 1;
+ return 0;
+}
+
+function shouldSurfaceLiveJob(
+ job: ManagedDownload,
+ isDatasetMode: boolean,
+): boolean {
+ if (isDatasetMode !== (job.kind === "dataset")) return false;
+ if (job.state === "running" || job.state === "cancelling") return true;
+ if (job.state !== "cancelled" && job.state !== "error") return false;
+ return Math.max(job.downloadedBytes, job.completedBytes) > 0;
+}
+
+function liveJobDisplayBytes(job: ManagedDownload): number {
+ if (job.expectedBytes > 0) return job.expectedBytes;
+ if (job.state === "running" || job.state === "cancelling") return 0;
+ return Math.max(job.downloadedBytes, job.completedBytes, 0);
+}
+
+function createLiveInventoryJobsSelector(isDatasetMode: boolean): (state: {
+ jobs: Record<string, ManagedDownload>;
+}) => LiveInventoryJob[] {
+ let cache: { signature: string; jobs: LiveInventoryJob[] } = {
+ signature: "",
+ jobs: [],
+ };
+ return (state) => {
+ const selectedByRepo = new Map<string, ManagedDownload>();
+ for (const job of Object.values(state.jobs)) {
+ if (!shouldSurfaceLiveJob(job, isDatasetMode)) continue;
+ const repoKey = job.repoId.trim().toLowerCase();
+ if (!repoKey) continue;
+ const current = selectedByRepo.get(repoKey);
+ if (
+ !current ||
+ liveInventoryRank(job) > liveInventoryRank(current) ||
+ (liveInventoryRank(job) === liveInventoryRank(current) &&
+ job.startedAt > current.startedAt)
+ ) {
+ selectedByRepo.set(repoKey, job);
+ }
+ }
+ const jobs = [...selectedByRepo.values()]
+ .map((job) => ({
+ kind: job.kind,
+ repoId: job.repoId,
+ variant: job.variant,
+ state: job.state,
+ startedAt: job.startedAt,
+ displayBytes: liveJobDisplayBytes(job),
+ }))
+ .sort((a, b) => a.repoId.localeCompare(b.repoId));
+ const signature = jobs
+ .map(
+ (job) =>
+ `${job.kind}\u0001${job.repoId.toLowerCase()}\u0001${job.variant ?? ""}\u0001${job.state}\u0001${job.startedAt}\u0001${job.displayBytes}`,
+ )
+ .join("\u0002");
+ if (signature === cache.signature) return cache.jobs;
+ cache = { signature, jobs };
+ return jobs;
+ };
+}
+
+function liveDownloadInventoryRows(
+ jobs: readonly LiveInventoryJob[],
+ isDatasetMode: boolean,
+): CachedInventoryRow[] {
+ return jobs.map((job) => {
+ const modelFormat = isDatasetMode
+ ? "unknown"
+ : job.variant
+ ? "gguf"
+ : "safetensors";
+ return {
+ ...buildCachedInventoryRow(
+ {
+ repo_id: job.repoId,
+ inventory_id: `cache:${modelFormat}:${job.repoId}`,
+ load_id: job.repoId,
+ model_format: modelFormat,
+ runtime:
+ modelFormat === "gguf"
+ ? "llama_cpp"
+ : modelFormat === "safetensors"
+ ? "transformers"
+ : "unknown",
+ size_bytes: job.displayBytes,
+ partial: true,
+ partial_transport: null,
+ },
+ modelFormat,
+ ),
+ liveDownload: true,
+ };
+ });
+}
+
+export function useHubInventory(
+ options: HubInventoryOptions = {},
+): HubInventory {
+ const hfToken = useHfTokenStore((state) => state.token) || undefined;
+ const isDatasetMode = (options.kind ?? "models") === "datasets";
+ const enabled = options.enabled ?? true;
+ const includeLocal = options.includeLocal ?? true;
+ const modelInventory = useDeviceInventorySources(MODEL_HUB_CACHE_SOURCES, {
+ hfToken,
+ enabled: enabled && !isDatasetMode,
+ });
+ const datasetInventory = useDeviceInventorySources(
+ DATASET_HUB_CACHE_SOURCES,
+ {
+ hfToken,
+ enabled: enabled && isDatasetMode,
+ },
+ );
+ const localModelInventory = useDeviceInventorySources(
+ LOCAL_MODEL_INVENTORY_SOURCE,
+ {
+ hfToken,
+ enabled: enabled && !isDatasetMode && includeLocal,
+ },
+ );
+ const localDatasetInventory = useDeviceInventorySources(
+ LOCAL_DATASET_INVENTORY_SOURCE,
+ {
+ hfToken,
+ enabled: enabled && isDatasetMode && includeLocal,
+ },
+ );
+ const cachedGgufSource = modelInventory.cachedGguf;
+ const cachedModelsSource = modelInventory.cachedModels;
+ const cachedDatasetsSource = datasetInventory.cachedDatasets;
+ const localModelsSource = localModelInventory.localModels;
+ const localDatasetsSource = localDatasetInventory.localDatasets;
+ const refreshModelInventory = modelInventory.refresh;
+ const refreshDatasetInventory = datasetInventory.refresh;
+ const refreshLocalModelInventory = localModelInventory.refresh;
+ const refreshLocalDatasetInventory = localDatasetInventory.refresh;
+ const pendingHints = useInventoryHintStore((state) => state.pending);
+ const observedInventoryKeys = useInventoryHintStore(
+ (state) => state.observedKeys,
+ );
+ const pruneExpiredPendingHints = useInventoryHintStore(
+ (state) => state.pruneExpiredHints,
+ );
+ const commitPendingHintReconciliations = useInventoryHintStore(
+ (state) => state.commitReconciliations,
+ );
+ const completedHints = useDownloadManagerStore(
+ (state) => state.completedInventoryHints,
+ );
+ const selectLiveInventoryJobs = useMemo(
+ () => createLiveInventoryJobsSelector(isDatasetMode),
+ [isDatasetMode],
+ );
+ const liveInventoryJobs = useDownloadManagerStore(selectLiveInventoryJobs);
+ const emptyRevalidationSignatureRef = useRef<string | null>(null);
+ const pendingForRenderRef = useRef<PendingInventoryHints | null>(null);
+
+ const pendingForRenderNext = useMemo(
+ () => pendingWithInventoryHints(pendingHints, completedHints),
+ [completedHints, pendingHints],
+ );
+ const pendingForRender = useMemo(() => {
+ const current = pendingForRenderRef.current;
+ if (current && pendingInventoryHintsEqual(current, pendingForRenderNext)) {
+ return current;
+ }
+ return pendingForRenderNext;
+ }, [pendingForRenderNext]);
+
+ useEffect(() => {
+ const current = pendingForRenderRef.current;
+ if (!current || !pendingInventoryHintsEqual(current, pendingForRender)) {
+ pendingForRenderRef.current = pendingForRender;
+ }
+ }, [pendingForRender]);
+
+ useEffect(() => {
+ const delay = nextInventoryHintExpiryDelay(pendingHints);
+ if (delay === null) {
+ return;
+ }
+ if (typeof window === "undefined") {
+ pruneExpiredPendingHints();
+ return;
+ }
+ const timer = window.setTimeout(pruneExpiredPendingHints, delay + 1);
+ return () => window.clearTimeout(timer);
+ }, [pendingHints, pruneExpiredPendingHints]);
+
+ const cachedGgufReconciliation = useMemo(
+ () =>
+ reconcileInventoryHints({
+ pending: pendingForRender,
+ kind: "gguf",
+ rows: cachedGgufSource.rows,
+ previouslyObserved: observedInventoryKeys.gguf,
+ }),
+ [cachedGgufSource.rows, observedInventoryKeys.gguf, pendingForRender],
+ );
+ const cachedModelsReconciliation = useMemo(
+ () =>
+ reconcileInventoryHints({
+ pending: pendingForRender,
+ kind: "model",
+ rows: cachedModelsSource.rows,
+ previouslyObserved: observedInventoryKeys.model,
+ }),
+ [cachedModelsSource.rows, observedInventoryKeys.model, pendingForRender],
+ );
+ const cachedDatasetsReconciliation = useMemo(
+ () =>
+ reconcileInventoryHints({
+ pending: pendingForRender,
+ kind: "dataset",
+ rows: cachedDatasetsSource.rows,
+ previouslyObserved: observedInventoryKeys.dataset,
+ }),
+ [
+ cachedDatasetsSource.rows,
+ observedInventoryKeys.dataset,
+ pendingForRender,
+ ],
+ );
+
+ useEffect(() => {
+ const reconciliations: PendingHintReconciliationCommit[] = [];
+ if (!isDatasetMode) {
+ reconciliations.push(
+ {
+ kind: "gguf",
+ reconciliation: cachedGgufReconciliation,
+ },
+ {
+ kind: "model",
+ reconciliation: cachedModelsReconciliation,
+ },
+ );
+ }
+ if (isDatasetMode) {
+ reconciliations.push({
+ kind: "dataset",
+ reconciliation: cachedDatasetsReconciliation,
+ });
+ }
+ if (
+ completedHints.length === 0 &&
+ !reconciliations.some((commit) =>
+ pendingHintReconciliationNeedsCommit(
+ pendingForRender,
+ observedInventoryKeys,
+ commit,
+ ),
+ )
+ ) {
+ return;
+ }
+ const completedHintsToSuppress = commitPendingHintReconciliations(
+ completedHints,
+ pendingForRender,
+ reconciliations,
+ );
+ for (const hint of completedHintsToSuppress) {
+ clearCompletedInventoryHint(hint);
+ }
+ }, [
+ completedHints,
+ commitPendingHintReconciliations,
+ pendingForRender,
+ observedInventoryKeys,
+ isDatasetMode,
+ cachedGgufReconciliation,
+ cachedModelsReconciliation,
+ cachedDatasetsReconciliation,
+ ]);
+
+ const cachedGguf = cachedGgufReconciliation.rows;
+ const cachedModels = cachedModelsReconciliation.rows;
+ const cachedDatasets = cachedDatasetsReconciliation.rows;
+ const liveDownloadRows = useMemo(
+ () => liveDownloadInventoryRows(liveInventoryJobs, isDatasetMode),
+ [isDatasetMode, liveInventoryJobs],
+ );
+
+ const cachedModelRows = useMemo<CachedInventoryRow[]>(
+ () =>
+ [
+ ...(isDatasetMode ? [] : liveDownloadRows),
+ ...cachedGguf.map((row) => buildCachedInventoryRow(row, "gguf")),
+ ...cachedModels.map((row) =>
+ buildCachedInventoryRow(row, "safetensors"),
+ ),
+ ].sort(compareCachedRows),
+ [cachedGguf, cachedModels, isDatasetMode, liveDownloadRows],
+ );
+
+ const cachedDatasetRows = useMemo<CachedInventoryRow[]>(
+ () =>
+ [
+ ...(isDatasetMode ? liveDownloadRows : []),
+ ...cachedDatasets.map((row) => buildCachedInventoryRow(row, "unknown")),
+ ]
+ .sort(compareCachedRows),
+ [cachedDatasets, isDatasetMode, liveDownloadRows],
+ );
+
+ const localRows = useMemo(
+ () => buildLocalInventoryRows(localModelsSource.rows),
+ [localModelsSource.rows],
+ );
+
+ const localDatasetRows = useMemo<LocalInventoryRow[]>(() => {
+ return localDatasetsSource.rows
+ .map((ds: LocalDatasetInfo) => {
+ const repoId = ds.id.includes("/") ? ds.id : null;
+ const owner = repoId ? ds.id.split("/")[0] : "Local";
+ return {
+ kind: "local" as const,
+ id: ds.id,
+ repoId,
+ owner,
+ title: ds.label || ds.id,
+ source: "custom" as const,
+ sourceLabel: localDatasetSourceLabel(ds.source),
+ path: ds.path,
+ isGguf: false,
+ loadId: ds.id,
+ modelFormat: "unknown" as const,
+ runtime: "unknown" as const,
+ formatVariant: null,
+ capabilities: defaultCapabilities("unknown"),
+ updatedAt: normalizeTimestamp(ds.updated_at),
+ };
+ })
+ .sort((a, b) => a.title.localeCompare(b.title));
+ }, [localDatasetsSource.rows]);
+
+ const dedupedModelInventory = useMemo(
+ () =>
+ dedupeSameSourceHubCacheRows({
+ cachedRows: cachedModelRows,
+ localRows,
+ }),
+ [cachedModelRows, localRows],
+ );
+
+ const dedupedDatasetInventory = useMemo(
+ () =>
+ dedupeSameSourceHubCacheRows({
+ cachedRows: cachedDatasetRows,
+ localRows: localDatasetRows,
+ }),
+ [cachedDatasetRows, localDatasetRows],
+ );
+
+ const cachedRows = isDatasetMode
+ ? dedupedDatasetInventory.cachedRows
+ : dedupedModelInventory.cachedRows;
+ const effectiveLocalRows = isDatasetMode
+ ? dedupedDatasetInventory.localRows
+ : dedupedModelInventory.localRows;
+
+ const availableSet = useMemo(() => {
+ const set = new Set<string>();
+ for (const row of cachedRows) set.add(row.repoId.toLowerCase());
+ for (const row of effectiveLocalRows) {
+ if (row.repoId) set.add(row.repoId.toLowerCase());
+ }
+ return set;
+ }, [cachedRows, effectiveLocalRows]);
+
+ const partialSet = useMemo(() => {
+ return partialSetFromRows(
+ [...cachedRows, ...effectiveLocalRows],
+ (row) => row.repoId,
+ );
+ }, [cachedRows, effectiveLocalRows]);
+
+ const modelReady =
+ isReadyForDisplay(cachedGgufSource) &&
+ isReadyForDisplay(cachedModelsSource) &&
+ (!includeLocal || isReadyForDisplay(localModelsSource));
+ const datasetReady =
+ isReadyForDisplay(cachedDatasetsSource) &&
+ (!includeLocal || isReadyForDisplay(localDatasetsSource));
+ const inventoryFailed = isDatasetMode
+ ? Boolean(
+ cachedDatasetsSource.error ||
+ (includeLocal && localDatasetsSource.error),
+ )
+ : Boolean(
+ cachedGgufSource.error ||
+ cachedModelsSource.error ||
+ (includeLocal && localModelsSource.error),
+ );
+ const inventoryWarning =
+ inventoryFailed && (cachedRows.length > 0 || effectiveLocalRows.length > 0);
+
+ const refreshDeviceInventory = useCallback(async () => {
+ if (isDatasetMode) {
+ await Promise.all([
+ refreshDatasetInventory(),
+ ...(includeLocal ? [refreshLocalDatasetInventory()] : []),
+ ]);
+ return;
+ }
+ await Promise.all([
+ refreshModelInventory(),
+ ...(includeLocal ? [refreshLocalModelInventory()] : []),
+ ]);
+ }, [
+ includeLocal,
+ isDatasetMode,
+ refreshDatasetInventory,
+ refreshLocalDatasetInventory,
+ refreshLocalModelInventory,
+ refreshModelInventory,
+ ]);
+ const refreshInventory = useCallback(async () => {
+ await refreshDeviceInventory();
+ }, [refreshDeviceInventory]);
+ const downloadedReady = isDatasetMode ? datasetReady : modelReady;
+ const hasInventoryRows =
+ cachedRows.length > 0 || effectiveLocalRows.length > 0;
+ const hasActiveEmptyRefresh = isDatasetMode
+ ? cachedDatasetsSource.loading ||
+ (includeLocal && localDatasetsSource.loading)
+ : cachedGgufSource.loading ||
+ cachedModelsSource.loading ||
+ (includeLocal && localModelsSource.loading);
+ const emptyRevalidationSignature = useMemo(
+ () =>
+ isDatasetMode
+ ? inventoryEmptyRevalidationSignature([
+ cachedDatasetsSource,
+ ...(includeLocal ? [localDatasetsSource] : []),
+ ])
+ : inventoryEmptyRevalidationSignature([
+ cachedGgufSource,
+ cachedModelsSource,
+ ...(includeLocal ? [localModelsSource] : []),
+ ]),
+ [
+ cachedDatasetsSource,
+ cachedGgufSource,
+ cachedModelsSource,
+ includeLocal,
+ isDatasetMode,
+ localDatasetsSource,
+ localModelsSource,
+ ],
+ );
+
+ useEffect(() => {
+ if (
+ !enabled ||
+ !downloadedReady ||
+ inventoryFailed ||
+ hasInventoryRows ||
+ hasActiveEmptyRefresh
+ ) {
+ return;
+ }
+ if (emptyRevalidationSignatureRef.current === emptyRevalidationSignature) {
+ return;
+ }
+ const timer = window.setTimeout(() => {
+ emptyRevalidationSignatureRef.current = emptyRevalidationSignature;
+ void refreshDeviceInventory();
+ }, 500);
+ return () => window.clearTimeout(timer);
+ }, [
+ downloadedReady,
+ emptyRevalidationSignature,
+ enabled,
+ hasActiveEmptyRefresh,
+ hasInventoryRows,
+ inventoryFailed,
+ refreshDeviceInventory,
+ ]);
+
+ return {
+ cachedRows,
+ localRows: effectiveLocalRows,
+ availableSet,
+ partialSet,
+ downloadedReady,
+ inventoryError: inventoryFailed,
+ inventoryWarning,
+ refreshInventory,
+ };
+}
diff --git a/studio/frontend/src/features/hub/inventory/view-models.ts b/studio/frontend/src/features/hub/inventory/view-models.ts
new file mode 100644
index 00000000000..63d70418bec
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/view-models.ts
@@ -0,0 +1,304 @@
+// 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 { ownerOf, repoOf } from "../lib/format";
+import { looksLikeLocalPath } from "../lib/local-path";
+import { isGgufLike } from "../lib/model-identifiers";
+import type {
+ BackendModelCapabilities,
+ LocalModelInfo,
+ ModelInventoryFormat,
+ ModelInventoryRuntime,
+} from "./api";
+import type {
+ ModelInventoryCapabilities,
+ CachedInventoryRow,
+ LocalInventoryRow,
+} from "./types";
+
+export function localSourceLabel(source: LocalModelInfo["source"]): string {
+ switch (source) {
+ case "lmstudio":
+ return "LM Studio";
+ case "ollama":
+ return "Ollama";
+ case "custom":
+ return "Custom folder";
+ case "models_dir":
+ return "Models folder";
+ case "hf_cache":
+ return "HF Cache";
+ default:
+ return "Local model";
+ }
+}
+
+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";
+ const formatter = new Intl.DateTimeFormat("en", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ });
+ return formatter.format(new Date(normalized));
+}
+
+function getLocalHubId(model: LocalModelInfo): string | null {
+ if (model.source !== "hf_cache") return null;
+ const candidate = model.model_id?.trim();
+ if (candidate?.toLowerCase().startsWith("ollama/")) {
+ return null;
+ }
+ if (candidate && candidate.includes("/") && !looksLikeLocalPath(candidate)) {
+ return candidate;
+ }
+ return null;
+}
+
+function getBaseModelHubId(model: LocalModelInfo): string | null {
+ const baseModel = model.base_model?.trim();
+ return model.base_model_source === "huggingface" && baseModel
+ ? baseModel
+ : null;
+}
+
+function isOllamaInventoryModel(model: LocalModelInfo): boolean {
+ return (
+ model.source === "ollama" ||
+ model.id.toLowerCase().startsWith("ollama-manifest:") ||
+ (model.model_id?.toLowerCase().startsWith("ollama/") ?? false)
+ );
+}
+
+export function normalizeModelFormat(
+ value: string | null | undefined,
+ fallback: ModelInventoryFormat = "unknown",
+): ModelInventoryFormat {
+ if (
+ value === "gguf" ||
+ value === "safetensors" ||
+ value === "adapter" ||
+ value === "checkpoint" ||
+ value === "unknown"
+ ) {
+ return value;
+ }
+ return fallback;
+}
+
+export function normalizeRuntime(
+ value: string | null | undefined,
+ modelFormat: ModelInventoryFormat,
+): ModelInventoryRuntime {
+ if (
+ value === "llama_cpp" ||
+ value === "transformers" ||
+ value === "adapter" ||
+ value === "unknown"
+ ) {
+ return value;
+ }
+ if (modelFormat === "gguf") return "llama_cpp";
+ if (modelFormat === "adapter") return "adapter";
+ if (modelFormat === "safetensors" || modelFormat === "checkpoint") {
+ return "transformers";
+ }
+ return "unknown";
+}
+
+export function defaultCapabilities(
+ modelFormat: ModelInventoryFormat,
+ partial = false,
+ requiresVariant = false,
+): ModelInventoryCapabilities {
+ const complete = !partial;
+ const canChat =
+ complete &&
+ (modelFormat === "gguf" ||
+ modelFormat === "safetensors" ||
+ modelFormat === "adapter" ||
+ modelFormat === "checkpoint");
+ return {
+ canTrain:
+ complete &&
+ (modelFormat === "safetensors" || modelFormat === "checkpoint"),
+ canChat,
+ canDelete: false,
+ canDownload: false,
+ requiresVariant,
+ supportsLora:
+ complete &&
+ (modelFormat === "safetensors" || modelFormat === "checkpoint"),
+ supportsVision: false,
+ };
+}
+
+export function normalizeCapabilities(
+ value: BackendModelCapabilities | null | undefined,
+ modelFormat: ModelInventoryFormat,
+ partial = false,
+ requiresVariant = false,
+): ModelInventoryCapabilities {
+ const fallback = defaultCapabilities(modelFormat, partial, requiresVariant);
+ return {
+ canTrain: value?.can_train ?? fallback.canTrain,
+ canChat: value?.can_chat ?? fallback.canChat,
+ canDelete: value?.can_delete ?? fallback.canDelete,
+ canDownload: value?.can_download ?? fallback.canDownload,
+ requiresVariant: value?.requires_variant ?? fallback.requiresVariant,
+ supportsLora: value?.supports_lora ?? fallback.supportsLora,
+ supportsVision: value?.supports_vision ?? fallback.supportsVision,
+ };
+}
+
+export function buildCachedInventoryRow(
+ row: {
+ repo_id: string;
+ size_bytes: number;
+ cache_path?: string;
+ partial?: boolean;
+ partial_transport?: string | null;
+ pipeline_tag?: string | null;
+ tags?: string[];
+ library_name?: string | null;
+ quant_method?: string | null;
+ inventory_id?: string | null;
+ load_id?: string | null;
+ model_format?: ModelInventoryFormat | null;
+ runtime?: string | null;
+ format_variant?: string | null;
+ capabilities?: BackendModelCapabilities | null;
+ },
+ fallbackFormat: ModelInventoryFormat,
+): CachedInventoryRow {
+ const rawModelFormat = normalizeModelFormat(row.model_format, "unknown");
+ const modelFormat =
+ rawModelFormat === "unknown" ? fallbackFormat : rawModelFormat;
+ const inferredFromEndpoint =
+ rawModelFormat === "unknown" && modelFormat !== "unknown";
+ const requiresVariant = modelFormat === "gguf";
+ return {
+ kind: "cache",
+ id:
+ !inferredFromEndpoint && row.inventory_id
+ ? row.inventory_id
+ : `cache:${modelFormat}:${row.repo_id}`,
+ loadId: row.load_id ?? row.repo_id,
+ repoId: row.repo_id,
+ owner: row.repo_id.includes("/") ? ownerOf(row.repo_id) : "Hub",
+ repo: row.repo_id.includes("/") ? repoOf(row.repo_id) : row.repo_id,
+ isGguf: modelFormat === "gguf",
+ modelFormat,
+ runtime: normalizeRuntime(
+ inferredFromEndpoint ? null : row.runtime,
+ modelFormat,
+ ),
+ formatVariant: row.format_variant ?? null,
+ capabilities: normalizeCapabilities(
+ inferredFromEndpoint ? null : row.capabilities,
+ modelFormat,
+ row.partial ?? false,
+ requiresVariant,
+ ),
+ bytes: row.size_bytes,
+ cachePath: row.cache_path ?? null,
+ partial: row.partial ?? false,
+ partialTransport: row.partial_transport ?? null,
+ pipelineTag: row.pipeline_tag ?? null,
+ tags: row.tags,
+ libraryName: row.library_name ?? null,
+ quantMethod: row.quant_method ?? null,
+ };
+}
+
+function sourceSortWeight(source: LocalModelInfo["source"]): number {
+ switch (source) {
+ case "models_dir":
+ return 0;
+ case "custom":
+ return 1;
+ case "lmstudio":
+ return 2;
+ case "ollama":
+ return 3;
+ case "hf_cache":
+ return 4;
+ default:
+ return 5;
+ }
+}
+
+export function buildLocalInventoryRows(
+ models: LocalModelInfo[],
+): LocalInventoryRow[] {
+ return models
+ .map((model) => {
+ const repoId = getLocalHubId(model);
+ const baseModel = model.base_model?.trim() || null;
+ const owner = repoId ? ownerOf(repoId) : localSourceLabel(model.source);
+ const title = repoId ? repoOf(repoId) : model.display_name;
+ const fallbackIsGguf =
+ isOllamaInventoryModel(model) ||
+ isGgufLike(model.path) ||
+ isGgufLike(model.id) ||
+ isGgufLike(model.model_id) ||
+ isGgufLike(model.display_name);
+ const modelFormat = normalizeModelFormat(
+ model.model_format,
+ fallbackIsGguf ? "gguf" : "unknown",
+ );
+ const fallbackRequiresVariant =
+ modelFormat === "gguf" && !model.path.toLowerCase().endsWith(".gguf");
+ const capabilities = normalizeCapabilities(
+ model.capabilities,
+ modelFormat,
+ model.partial ?? false,
+ fallbackRequiresVariant,
+ );
+ return {
+ kind: "local" as const,
+ id: model.inventory_id ?? model.id,
+ loadId: model.load_id ?? model.id,
+ repoId,
+ owner,
+ title,
+ source: model.source,
+ sourceLabel: localSourceLabel(model.source),
+ path: model.path,
+ isGguf: modelFormat === "gguf",
+ modelFormat,
+ runtime: normalizeRuntime(model.runtime, modelFormat),
+ formatVariant: model.format_variant ?? null,
+ capabilities,
+ baseModel,
+ baseModelSource: model.base_model_source ?? null,
+ baseModelHubId: getBaseModelHubId(model),
+ adapterType: model.adapter_type ?? null,
+ trainingMethod: model.training_method ?? null,
+ updatedAt: normalizeTimestamp(model.updated_at),
+ partial: model.partial ?? false,
+ partialTransport: model.partial_transport ?? null,
+ pipelineTag: model.pipeline_tag ?? null,
+ tags: model.tags,
+ libraryName: model.library_name ?? null,
+ quantMethod: model.quant_method ?? null,
+ };
+ })
+ .sort((a, b) => {
+ if (Boolean(a.partial) !== Boolean(b.partial)) return a.partial ? 1 : -1;
+ const sourceWeight = sourceSortWeight(a.source) - sourceSortWeight(b.source);
+ if (sourceWeight !== 0) return sourceWeight;
+ if (a.updatedAt && b.updatedAt && a.updatedAt !== b.updatedAt) {
+ return b.updatedAt - a.updatedAt;
+ }
+ return a.title.localeCompare(b.title);
+ });
+}
diff --git a/studio/frontend/src/features/hub/lib/abort-signals.ts b/studio/frontend/src/features/hub/lib/abort-signals.ts
new file mode 100644
index 00000000000..fbd00990a7d
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/abort-signals.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// WebView-compatibility shims. AbortSignal.timeout (WebKitGTK < 2.38) and
+// AbortSignal.any (WebKitGTK < 2.44) are missing on older engines Tauri embeds
+// and throw synchronously if called. These ponyfills delegate to the native
+// impl when present, else fall back to an AbortController.
+
+export interface PollSignal {
+ signal: AbortSignal;
+ dispose: () => void;
+}
+
+// Timeout signal paired with a disposer. On the ponyfill path the setTimeout
+// pins the controller until it fires, so callers settling early MUST dispose.
+export function disposableTimeoutSignal(ms: number): PollSignal {
+ if (typeof AbortSignal.timeout === "function") {
+ return { signal: AbortSignal.timeout(ms), dispose: () => {} };
+ }
+ const controller = new AbortController();
+ const timer = setTimeout(
+ () =>
+ controller.abort(
+ new DOMException("The operation timed out.", "TimeoutError"),
+ ),
+ ms,
+ );
+ return { signal: controller.signal, dispose: () => clearTimeout(timer) };
+}
+
+export function timeoutSignal(ms: number): AbortSignal {
+ return disposableTimeoutSignal(ms).signal;
+}
+
+// Callers MUST dispose() once the request settles so abort listeners don't pile up.
+export function combineAbortSignals(signals: AbortSignal[]): PollSignal {
+ if (typeof AbortSignal.any === "function") {
+ return { signal: AbortSignal.any(signals), dispose: () => {} };
+ }
+ const controller = new AbortController();
+ const detachers: Array<() => void> = [];
+ const dispose = () => {
+ while (detachers.length > 0) {
+ detachers.pop()?.();
+ }
+ };
+ const abort = (reason: unknown) => {
+ if (!controller.signal.aborted) controller.abort(reason);
+ dispose();
+ };
+ for (const input of signals) {
+ if (input.aborted) {
+ abort(input.reason);
+ break;
+ }
+ const handler = () => abort(input.reason);
+ input.addEventListener("abort", handler, { once: true });
+ detachers.push(() => input.removeEventListener("abort", handler));
+ }
+ return { signal: controller.signal, dispose };
+}
+
+export function pollSignal(parent: AbortSignal, timeoutMs: number): PollSignal {
+ const timeout = disposableTimeoutSignal(timeoutMs);
+ const combined = combineAbortSignals([parent, timeout.signal]);
+ return {
+ signal: combined.signal,
+ dispose: () => {
+ combined.dispose();
+ timeout.dispose();
+ },
+ };
+}
+
+export function abortError(signal: AbortSignal): DOMException {
+ return signal.reason instanceof DOMException
+ ? signal.reason
+ : new DOMException("The operation was aborted.", "AbortError");
+}
+
+// Rejects the returned promise on abort but never aborts the wrapped promise,
+// so a request shared across callers keeps running when one caller's signal fires.
+export function withAbort<T>(
+ promise: Promise<T>,
+ signal?: AbortSignal,
+): Promise<T> {
+ if (!signal) return promise;
+ if (signal.aborted) return Promise.reject(abortError(signal));
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => reject(abortError(signal));
+ signal.addEventListener("abort", onAbort, { once: true });
+ promise.then(resolve, reject).finally(() => {
+ signal.removeEventListener("abort", onAbort);
+ });
+ });
+}
diff --git a/studio/frontend/src/features/hub/lib/channels.ts b/studio/frontend/src/features/hub/lib/channels.ts
new file mode 100644
index 00000000000..25f8b660ea2
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/channels.ts
@@ -0,0 +1,66 @@
+// 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 {
+ NewReleasesIcon,
+ SlidersHorizontalIcon,
+ SparklesIcon,
+} from "@hugeicons/core-free-icons";
+import type { IconSvgElement } from "@hugeicons/react";
+import type { HfSortKey } from "@/features/hub/hooks/use-hub-model-search";
+import type { ModelFormatFilter } from "../types";
+
+export type ChannelId =
+ | "unsloth-trending"
+ | "unsloth-latest"
+ | "unsloth-safetensors";
+
+export interface ChannelPreset {
+ id: ChannelId;
+ label: string;
+ icon: IconSvgElement;
+ hint: string;
+ owner?: string;
+ tags?: readonly string[];
+ query?: string;
+ idSuffix?: string;
+ format: ModelFormatFilter;
+ sort: HfSortKey;
+}
+
+export const CHANNEL_PRESETS: readonly ChannelPreset[] = [
+ {
+ id: "unsloth-trending",
+ label: "Unsloth Trending",
+ icon: SparklesIcon,
+ hint: "Most trending models published by Unsloth.",
+ owner: "unsloth",
+ format: "gguf",
+ sort: "trendingScore",
+ },
+ {
+ id: "unsloth-latest",
+ label: "Latest Unsloth",
+ icon: NewReleasesIcon,
+ hint: "Freshly released models from the Unsloth channel.",
+ owner: "unsloth",
+ format: "all",
+ sort: "lastModified",
+ },
+ {
+ id: "unsloth-safetensors",
+ label: "Fine-tune ready",
+ icon: SlidersHorizontalIcon,
+ hint: "Latest Unsloth bnb-4bit checkpoints ready to fine-tune.",
+ owner: "unsloth",
+ query: "bnb-4bit",
+ idSuffix: "-bnb-4bit",
+ format: "checkpoint",
+ sort: "lastModified",
+ },
+];
+
+export function findChannel(id: ChannelId | null): ChannelPreset | null {
+ if (!id) return null;
+ return CHANNEL_PRESETS.find((preset) => preset.id === id) ?? null;
+}
diff --git a/studio/frontend/src/features/hub/lib/dataset-size.ts b/studio/frontend/src/features/hub/lib/dataset-size.ts
new file mode 100644
index 00000000000..76ac12d2d67
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/dataset-size.ts
@@ -0,0 +1,356 @@
+// 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 { LruMap } from "./lru-map";
+import { fetchWithTimeout } from "./network";
+import { fingerprintToken } from "./token-fingerprint";
+
+export interface DatasetSizeInfo {
+ numBytesOriginal: number | null;
+ numBytesParquet: number | null;
+ numRows: number | null;
+ numSplits: number | null;
+}
+
+interface DatasetSizeApiResponse {
+ size?: {
+ dataset?: {
+ num_bytes_original_files?: number;
+ num_bytes_parquet_files?: number;
+ num_rows?: number;
+ };
+ splits?: unknown[];
+ };
+}
+
+// Transient (429/5xx/network) misses cache briefly so a rate-limited burst
+// doesn't pin the size to "unknown" until reload. "longlived" covers stable-ish
+// answers like datasets-server 404 ("not processed yet"); "permanent" is a
+// genuinely missing repo (HF models API 404).
+const TRANSIENT_MISS_TTL_MS = 60_000;
+const LONGLIVED_MISS_TTL_MS = 24 * 60 * 60 * 1000;
+const FETCH_TIMEOUT_MS = 10_000;
+
+type SizeCacheEntry<T> =
+ | { kind: "value"; value: T }
+ | { kind: "miss-permanent" }
+ | { kind: "miss-transient"; until: number };
+
+type LoadResult<T> =
+ | { value: T }
+ | { miss: "permanent" | "transient" | "longlived" };
+
+type InflightSizeEntry<T> = {
+ promise: Promise<T | null>;
+ controller: AbortController;
+ consumers: number;
+ settled: boolean;
+ cancelledByConsumers: boolean;
+};
+
+function readSizeCache<T>(
+ cache: LruMap<string, SizeCacheEntry<T>>,
+ key: string,
+): SizeCacheEntry<T> | null {
+ const entry = cache.get(key);
+ if (!entry) return null;
+ if (entry.kind === "miss-transient" && Date.now() >= entry.until) {
+ cache.delete(key);
+ return null;
+ }
+ return entry;
+}
+
+function fetchCachedSize<T>(
+ cacheKey: string,
+ cache: LruMap<string, SizeCacheEntry<T>>,
+ inflight: Map<string, InflightSizeEntry<T>>,
+ load: (signal: AbortSignal) => Promise<LoadResult<T>>,
+ debugContext: { label: string; id: string },
+ signal?: AbortSignal,
+): Promise<T | null> {
+ if (signal?.aborted) {
+ return Promise.resolve(null);
+ }
+ const entry = readSizeCache(cache, cacheKey);
+ if (entry) {
+ return Promise.resolve(entry.kind === "value" ? entry.value : null);
+ }
+ const existing = inflight.get(cacheKey);
+ if (existing) return attachInflight(existing, signal);
+
+ let timedOut = false;
+ const controller = new AbortController();
+ const inflightEntry: InflightSizeEntry<T> = {
+ promise: Promise.resolve(null),
+ controller,
+ consumers: 0,
+ settled: false,
+ cancelledByConsumers: false,
+ };
+ const timeout = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, FETCH_TIMEOUT_MS);
+
+ inflightEntry.promise = (async (): Promise<T | null> => {
+ try {
+ const result = await load(controller.signal);
+ if ("value" in result) {
+ cache.set(cacheKey, { kind: "value", value: result.value });
+ return result.value;
+ }
+ if (result.miss === "permanent") {
+ cache.set(cacheKey, { kind: "miss-permanent" });
+ } else {
+ const ttl =
+ result.miss === "longlived"
+ ? LONGLIVED_MISS_TTL_MS
+ : TRANSIENT_MISS_TTL_MS;
+ cache.set(cacheKey, {
+ kind: "miss-transient",
+ until: Date.now() + ttl,
+ });
+ }
+ return null;
+ } catch (err) {
+ if (
+ import.meta.env.DEV &&
+ (!inflightEntry.cancelledByConsumers || timedOut)
+ ) {
+ console.debug(`${debugContext.label} size lookup failed`, {
+ id: debugContext.id,
+ error: err,
+ });
+ }
+ if (!inflightEntry.cancelledByConsumers || timedOut) {
+ cache.set(cacheKey, {
+ kind: "miss-transient",
+ until: Date.now() + TRANSIENT_MISS_TTL_MS,
+ });
+ }
+ return null;
+ } finally {
+ clearTimeout(timeout);
+ inflightEntry.settled = true;
+ inflight.delete(cacheKey);
+ }
+ })();
+
+ inflight.set(cacheKey, inflightEntry);
+ return attachInflight(inflightEntry, signal);
+}
+
+function attachInflight<T>(
+ entry: InflightSizeEntry<T>,
+ signal?: AbortSignal,
+): Promise<T | null> {
+ entry.consumers += 1;
+ let released = false;
+ const release = () => {
+ if (released) return;
+ released = true;
+ entry.consumers = Math.max(0, entry.consumers - 1);
+ if (entry.consumers === 0 && !entry.settled) {
+ entry.cancelledByConsumers = true;
+ entry.controller.abort();
+ }
+ };
+
+ if (!signal) {
+ return entry.promise.finally(release);
+ }
+
+ if (signal.aborted) {
+ release();
+ return Promise.resolve(null);
+ }
+
+ const activeSignal = signal;
+ return new Promise((resolve) => {
+ function cleanup() {
+ activeSignal.removeEventListener("abort", onAbort);
+ }
+ function onAbort() {
+ cleanup();
+ release();
+ resolve(null);
+ }
+ activeSignal.addEventListener("abort", onAbort, { once: true });
+ entry.promise.then(
+ (value) => {
+ cleanup();
+ release();
+ resolve(value);
+ },
+ () => {
+ cleanup();
+ release();
+ resolve(null);
+ },
+ );
+ });
+}
+
+const datasetCache = new LruMap<string, SizeCacheEntry<DatasetSizeInfo>>(128);
+const datasetInflight = new Map<string, InflightSizeEntry<DatasetSizeInfo>>();
+
+export function fetchDatasetSize(
+ repoId: string,
+ signal?: AbortSignal,
+): Promise<DatasetSizeInfo | null>;
+export function fetchDatasetSize(
+ repoId: string,
+ token?: string,
+ signal?: AbortSignal,
+): Promise<DatasetSizeInfo | null>;
+export function fetchDatasetSize(
+ repoId: string,
+ tokenOrSignal?: string | AbortSignal,
+ signal?: AbortSignal,
+): Promise<DatasetSizeInfo | null> {
+ const resolvedToken =
+ typeof tokenOrSignal === "string" ? tokenOrSignal : undefined;
+ const resolvedSignal =
+ signal ?? (typeof tokenOrSignal === "string" ? undefined : tokenOrSignal);
+ const cacheKey = `${repoId}::${fingerprintToken(resolvedToken)}`;
+ return fetchCachedSize<DatasetSizeInfo>(
+ cacheKey,
+ datasetCache,
+ datasetInflight,
+ async (signal) => {
+ const res = await fetchWithTimeout(
+ `https://datasets-server.huggingface.co/size?dataset=${encodeURIComponent(repoId)}`,
+ {
+ signal,
+ headers: resolvedToken
+ ? { Authorization: `Bearer ${resolvedToken}` }
+ : undefined,
+ },
+ FETCH_TIMEOUT_MS,
+ );
+ if (!res.ok) {
+ // datasets-server 404 often means "not processed yet", not "never".
+ return { miss: res.status === 404 ? "longlived" : "transient" };
+ }
+ const data = (await res.json()) as DatasetSizeApiResponse;
+ const ds = data.size?.dataset;
+ if (!ds) return { miss: "longlived" };
+ return {
+ value: {
+ numBytesOriginal: ds.num_bytes_original_files ?? null,
+ numBytesParquet: ds.num_bytes_parquet_files ?? null,
+ numRows: ds.num_rows ?? null,
+ numSplits: Array.isArray(data.size?.splits)
+ ? (data.size?.splits.length ?? null)
+ : null,
+ },
+ };
+ },
+ { label: "Dataset", id: repoId },
+ resolvedSignal,
+ );
+}
+
+export interface ModelSizeInfo {
+ totalBytes: number | null;
+ weightsBytes: number | null;
+}
+
+interface ModelInfoApiResponse {
+ siblings?: Array<{
+ rfilename?: string;
+ size?: number;
+ }>;
+}
+
+type ModelSibling = NonNullable<ModelInfoApiResponse["siblings"]>[number];
+
+const SNAPSHOT_WEIGHT_FILE_RE =
+ /\.(safetensors|bin|pt|pth|ckpt|h5|msgpack|npz)$/i;
+const SNAPSHOT_NON_BIN_WEIGHT_FILE_RE =
+ /\.(safetensors|pt|pth|ckpt|h5|msgpack|npz)$/i;
+const SNAPSHOT_BIN_WEIGHT_PREFIX_RE = /^(model|pytorch_model|adapter_model).*\.bin$/i;
+
+function basename(path: string): string {
+ return path.split("/").pop() ?? path;
+}
+
+function shipsTransformersWeights(siblings: ModelSibling[]): boolean {
+ return siblings.some((s) => {
+ const base = basename(s.rfilename ?? "").toLowerCase();
+ if (base.startsWith("consolidated")) return false;
+ return (
+ SNAPSHOT_NON_BIN_WEIGHT_FILE_RE.test(base) ||
+ SNAPSHOT_BIN_WEIGHT_PREFIX_RE.test(base)
+ );
+ });
+}
+
+function isSnapshotIgnored(
+ filename: string,
+ skipConsolidated: boolean,
+): boolean {
+ const lower = filename.toLowerCase();
+ return (
+ lower.endsWith(".gguf") ||
+ lower.endsWith(".onnx") ||
+ lower.startsWith("onnx/") ||
+ lower.startsWith("openvino/") ||
+ lower.startsWith("mlx/") ||
+ lower.endsWith(".bin.index.json.bak") ||
+ (skipConsolidated && lower.startsWith("consolidated"))
+ );
+}
+
+const modelCache = new LruMap<string, SizeCacheEntry<ModelSizeInfo>>(128);
+const modelInflight = new Map<string, InflightSizeEntry<ModelSizeInfo>>();
+
+export function fetchModelSize(
+ repoId: string,
+ token?: string,
+ signal?: AbortSignal,
+): Promise<ModelSizeInfo | null> {
+ const cacheKey = `${repoId}::${fingerprintToken(token)}`;
+ return fetchCachedSize<ModelSizeInfo>(
+ cacheKey,
+ modelCache,
+ modelInflight,
+ async (signal) => {
+ const path = repoId.split("/").map(encodeURIComponent).join("/");
+ const res = await fetchWithTimeout(
+ `https://huggingface.co/api/models/${path}?blobs=true`,
+ {
+ signal,
+ headers: token ? { Authorization: `Bearer ${token}` } : undefined,
+ },
+ FETCH_TIMEOUT_MS,
+ );
+ if (!res.ok) {
+ return { miss: res.status === 404 ? "permanent" : "transient" };
+ }
+ const data = (await res.json()) as ModelInfoApiResponse;
+ const siblings = data.siblings ?? [];
+ const skipConsolidated = shipsTransformersWeights(siblings);
+ let total = 0;
+ let weights = 0;
+ for (const s of siblings) {
+ if (typeof s.size !== "number") continue;
+ const filename = s.rfilename ?? "";
+ if (filename && isSnapshotIgnored(filename, skipConsolidated)) continue;
+ total += s.size;
+ if (filename && SNAPSHOT_WEIGHT_FILE_RE.test(filename)) {
+ weights += s.size;
+ }
+ }
+ return {
+ value: {
+ totalBytes: total > 0 ? total : null,
+ weightsBytes: weights > 0 ? weights : null,
+ },
+ };
+ },
+ { label: "Model", id: repoId },
+ signal,
+ );
+}
diff --git a/studio/frontend/src/features/hub/lib/format-filters.ts b/studio/frontend/src/features/hub/lib/format-filters.ts
new file mode 100644
index 00000000000..0fb0d6e0bca
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/format-filters.ts
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type FormatFilterModelFormat =
+ | "gguf"
+ | "safetensors"
+ | "adapter"
+ | "checkpoint"
+ | "unknown";
+
+export type FormatFilterValue = "all" | "gguf" | "checkpoint";
+
+export function matchesFormat(
+ modelFormat: boolean | FormatFilterModelFormat | null | undefined,
+ formatFilter: FormatFilterValue,
+): boolean {
+ if (formatFilter === "all") return true;
+ const normalized =
+ typeof modelFormat === "boolean"
+ ? modelFormat
+ ? "gguf"
+ : "safetensors"
+ : modelFormat;
+ if (formatFilter === "gguf") return normalized === "gguf";
+ return normalized === "safetensors" || normalized === "checkpoint";
+}
diff --git a/studio/frontend/src/features/hub/lib/format.ts b/studio/frontend/src/features/hub/lib/format.ts
new file mode 100644
index 00000000000..862597ff952
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/format.ts
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export function formatBytes(bytes: number): string {
+ if (!Number.isFinite(bytes) || bytes < 0) return "N/A";
+ if (bytes === 0) return "0 B";
+ const units = ["B", "KB", "MB", "GB", "TB"];
+ let i = Math.min(
+ Math.max(Math.floor(Math.log(bytes) / Math.log(1000)), 0),
+ units.length - 1,
+ );
+ let value = bytes / 1000 ** i;
+ let decimals = i > 0 && Number(value.toFixed(1)) < 10 ? 1 : 0;
+ while (i < units.length - 1 && Number(value.toFixed(decimals)) >= 1000) {
+ i += 1;
+ value = bytes / 1000 ** i;
+ decimals = Number(value.toFixed(1)) < 10 ? 1 : 0;
+ }
+ return `${value.toFixed(decimals)} ${units[i]}`;
+}
+
+export function formatRate(bytesPerSec: number): string {
+ if (!Number.isFinite(bytesPerSec) || bytesPerSec <= 0) return "";
+ return `${formatBytes(bytesPerSec)}/s`;
+}
+
+export function formatEta(seconds: number): string {
+ if (!Number.isFinite(seconds) || seconds <= 0) return "";
+ const s = Math.round(seconds);
+ if (s < 60) return `${s}s left`;
+ if (s < 3600) {
+ const m = Math.floor(s / 60);
+ const rem = s % 60;
+ return rem ? `${m}m ${rem}s left` : `${m}m left`;
+ }
+ if (s < 86400) {
+ const h = Math.floor(s / 3600);
+ const rem = Math.floor((s % 3600) / 60);
+ return rem ? `${h}h ${rem}m left` : `${h}h left`;
+ }
+ const d = Math.floor(s / 86400);
+ const rem = Math.floor((s % 86400) / 3600);
+ return rem ? `${d}d ${rem}h left` : `${d}d left`;
+}
+
+export function ownerOf(id: string): string {
+ return id.includes("/") ? id.split("/")[0] : "";
+}
+
+export function repoOf(id: string): string {
+ return id.includes("/") ? id.split("/").slice(1).join("/") : id;
+}
+
+export function formatRelativeShort(iso?: string): string {
+ if (!iso) return "N/A";
+ const then = new Date(iso).getTime();
+ if (Number.isNaN(then)) return "N/A";
+ const diffMs = Math.max(0, Date.now() - then);
+ const minutes = Math.floor(diffMs / 60_000);
+ if (minutes < 1) return "just now";
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ if (days < 30) return `${days}d ago`;
+ if (days < 365) {
+ const months = Math.floor(days / 30);
+ return `${months}mo ago`;
+ }
+ const years = Math.floor(days / 365);
+ return `${years}y ago`;
+}
diff --git a/studio/frontend/src/features/hub/lib/gguf-fit.ts b/studio/frontend/src/features/hub/lib/gguf-fit.ts
new file mode 100644
index 00000000000..8f89b806b1d
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/gguf-fit.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Single source of truth for "will this GGUF fit on the user's GPU?". Mirrors the
+ * backend's GPU selection (llama_cpp.py `_select_gpus`): 90% of GPU memory for
+ * weights + KV cache, else `--fit` CPU offload. One formula so the Hub card and
+ * chat picker can't disagree.
+ */
+
+export type GgufFitClass = "fits" | "marginal" | "partial" | "ram" | "oom";
+
+export interface GgufFitInput {
+ gpuGb?: number;
+ systemRamGb?: number;
+}
+
+/** Fraction of GPU VRAM treated as usable, matching the backend's 0.90 budget. */
+const VRAM_HEADROOM_RATIO = 0.9;
+/** GGUF weights are file size; runtime activations add roughly this fraction. */
+const ACTIVATIONS_RATIO = 0.15;
+/** Flat KV/context allowance at a typical 4K window. */
+const CONTEXT_OVERHEAD_GB = 1.0;
+/** Conservative share of system RAM usable for CPU offload. */
+const RAM_OFFLOAD_USABLE_RATIO = 0.5;
+
+export function requiredGgufMemoryGb(
+ sizeBytes: number,
+ contextOverheadGb = CONTEXT_OVERHEAD_GB,
+): number {
+ const sizeGb = sizeBytes / 1024 ** 3;
+ return sizeGb * (1 + ACTIVATIONS_RATIO) + contextOverheadGb;
+}
+
+export function classifyGgufFit(
+ sizeBytes: number,
+ { gpuGb, systemRamGb }: GgufFitInput,
+): GgufFitClass {
+ const required = requiredGgufMemoryGb(sizeBytes);
+ if (!gpuGb || gpuGb <= 0) {
+ const ramBudget = (systemRamGb ?? 0) * RAM_OFFLOAD_USABLE_RATIO;
+ return required <= ramBudget ? "ram" : "oom";
+ }
+ const budget = gpuGb * VRAM_HEADROOM_RATIO;
+ if (required <= budget) return "fits";
+ if (required <= gpuGb) return "marginal";
+ const combined = gpuGb + (systemRamGb ?? 0) * RAM_OFFLOAD_USABLE_RATIO;
+ if (required <= combined) return "partial";
+ return "oom";
+}
+
diff --git a/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts b/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts
new file mode 100644
index 00000000000..3fe9e040d97
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts
@@ -0,0 +1,89 @@
+// 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 { GgufVariantDetail } from "@/features/hub/inventory";
+import { classifyGgufFit } from "@/features/hub/lib/gguf-fit";
+import { ggufVariantsMatch } from "@/features/hub/lib/model-identity";
+
+type GgufVariantResources = {
+ gpuGb?: number;
+ systemRamGb?: number;
+};
+
+export function ggufVariantDisplayLabel(
+ variant: Pick<GgufVariantDetail, "display_label" | "quant">,
+): string {
+ return variant.display_label?.trim() || variant.quant;
+}
+
+export function ggufVariantDownloadSizeBytes(
+ variant: Pick<GgufVariantDetail, "download_size_bytes" | "size_bytes">,
+): number {
+ return variant.download_size_bytes ?? variant.size_bytes;
+}
+
+export function ggufVariantFitRank(
+ variant: GgufVariantDetail,
+ resources: GgufVariantResources,
+): number {
+ switch (classifyGgufFit(variant.size_bytes, resources)) {
+ case "fits":
+ return 0;
+ case "marginal":
+ return 1;
+ case "partial":
+ case "ram":
+ return 2;
+ default:
+ return 3;
+ }
+}
+
+export function compareGgufVariantFitAndSize(
+ a: GgufVariantDetail,
+ b: GgufVariantDetail,
+ resources: GgufVariantResources,
+): number {
+ const aFit = ggufVariantFitRank(a, resources);
+ const bFit = ggufVariantFitRank(b, resources);
+ if (aFit !== bFit) return aFit - bFit;
+ return aFit === 3 ? a.size_bytes - b.size_bytes : b.size_bytes - a.size_bytes;
+}
+
+export function ggufVariantDownloadStatusRank(
+ variant: GgufVariantDetail,
+): number {
+ if (variant.downloaded) return 0;
+ if (variant.partial) return 1;
+ return 2;
+}
+
+export function sortDownloadableGgufVariants(
+ variants: readonly GgufVariantDetail[],
+ resources: GgufVariantResources,
+): GgufVariantDetail[] {
+ return [...variants].sort((a, b) => {
+ const statusDelta =
+ ggufVariantDownloadStatusRank(a) - ggufVariantDownloadStatusRank(b);
+ if (statusDelta !== 0) return statusDelta;
+ return compareGgufVariantFitAndSize(a, b, resources);
+ });
+}
+
+export function sortLocalGgufVariants(
+ variants: readonly GgufVariantDetail[],
+ options: GgufVariantResources & {
+ activeGgufVariant?: string | null;
+ defaultVariant?: string | null;
+ },
+): GgufVariantDetail[] {
+ return [...variants].sort((a, b) => {
+ const aActive = ggufVariantsMatch(a.quant, options.activeGgufVariant);
+ const bActive = ggufVariantsMatch(b.quant, options.activeGgufVariant);
+ if (aActive !== bActive) return aActive ? -1 : 1;
+ const aDefault = ggufVariantsMatch(a.quant, options.defaultVariant);
+ const bDefault = ggufVariantsMatch(b.quant, options.defaultVariant);
+ if (aDefault !== bDefault) return aDefault ? -1 : 1;
+ return compareGgufVariantFitAndSize(a, b, options);
+ });
+}
diff --git a/studio/frontend/src/features/hub/lib/hf-cache.ts b/studio/frontend/src/features/hub/lib/hf-cache.ts
new file mode 100644
index 00000000000..f2cab8b2ca5
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/hf-cache.ts
@@ -0,0 +1,114 @@
+// 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 ModelEntry, modelInfo } from "@huggingface/hub";
+
+import { LruMap } from "./lru-map";
+import { fingerprintToken } from "./token-fingerprint";
+
+const CACHE_TTL_MS = 5 * 60 * 1000;
+const CACHE_MAX_ENTRIES = 256;
+const MAX_CONCURRENT = 3;
+const ALL_FIELDS: ("safetensors" | "tags")[] = ["safetensors", "tags"];
+
+export type CachedResult = ModelEntry & {
+ safetensors?: { total?: number; parameters?: Record<string, number> };
+ tags?: string[];
+};
+
+interface CacheEntry {
+ data: CachedResult;
+ ts: number;
+}
+
+const cache = new LruMap<string, CacheEntry>(CACHE_MAX_ENTRIES);
+const inflight = new Map<string, Promise<CachedResult>>();
+let active = 0;
+const waiting: Array<() => void> = [];
+
+function acquire(): Promise<void> {
+ if (active < MAX_CONCURRENT) {
+ active++;
+ return Promise.resolve();
+ }
+ return new Promise<void>((resolve) =>
+ waiting.push(() => {
+ active++;
+ resolve();
+ }),
+ );
+}
+
+function release() {
+ active--;
+ const next = waiting.shift();
+ if (next) next();
+}
+
+function isStale(key: string): boolean {
+ const hit = cache.get(key);
+ return !hit || Date.now() - hit.ts >= CACHE_TTL_MS;
+}
+
+function cacheKey(name: string, token: string | undefined): string {
+ return `${name}::${fingerprintToken(token)}`;
+}
+
+function extractToken(
+ params: Parameters<typeof modelInfo>[0],
+): string | undefined {
+ if (params.accessToken) return params.accessToken;
+ if (params.credentials && "accessToken" in params.credentials) {
+ return params.credentials.accessToken;
+ }
+ return undefined;
+}
+
+export function primeCacheFromListing(
+ name: string,
+ token: string | undefined,
+ data: CachedResult,
+): void {
+ if (!name) return;
+ const key = cacheKey(name, token);
+ if (!isStale(key)) return;
+ cache.set(key, { data, ts: Date.now() });
+}
+
+export async function cachedModelInfo(
+ params: Parameters<typeof modelInfo>[0],
+): Promise<CachedResult> {
+ const token = extractToken(params);
+ const key = cacheKey(params.name, token);
+ if (!isStale(key)) return cache.get(key)!.data;
+
+ const flying = inflight.get(key);
+ if (flying) return flying;
+
+ const promise = (async () => {
+ await acquire();
+ try {
+ const result = await modelInfo({
+ ...params,
+ additionalFields: ALL_FIELDS,
+ });
+ const entry = { data: result as CachedResult, ts: Date.now() };
+ cache.set(key, entry);
+ const typed = result as CachedResult & {
+ gated?: false | "auto" | "manual";
+ private?: boolean;
+ };
+ if (token && !typed.private && !typed.gated) {
+ const anonKey = cacheKey(params.name, undefined);
+ if (isStale(anonKey)) cache.set(anonKey, entry);
+ }
+ return result as CachedResult;
+ } finally {
+ release();
+ inflight.delete(key);
+ }
+ })();
+
+ inflight.set(key, promise);
+ return promise;
+}
diff --git a/studio/frontend/src/features/hub/lib/hf-model-meta.ts b/studio/frontend/src/features/hub/lib/hf-model-meta.ts
new file mode 100644
index 00000000000..a390516fbf8
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/hf-model-meta.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export const EMBEDDING_TAGS: ReadonlySet<string> = new Set([
+ "feature-extraction",
+ "sentence-transformers",
+ "sentence-similarity",
+ "text-embeddings-inference",
+ "embeddings",
+]);
+
+export const DTYPE_BYTES: Readonly<Record<string, number>> = {
+ F64: 8,
+ F32: 4,
+ F16: 2,
+ BF16: 2,
+ F8_E4M3: 1,
+ F8_E5M2: 1,
+ I64: 8,
+ U64: 8,
+ I32: 4,
+ U32: 4,
+ I16: 2,
+ U16: 2,
+ I8: 1,
+ U8: 1,
+ BOOL: 1,
+ NF4: 0.5,
+ FP4: 0.5,
+ INT4: 0.5,
+ GPTQ: 0.5,
+};
+
+export function estimateSizeFromDtypes(
+ params: Record<string, number> | undefined,
+): number | undefined {
+ if (!params) return undefined;
+ let total = 0;
+ for (const [dtype, count] of Object.entries(params)) {
+ const bytesPerParam = DTYPE_BYTES[dtype.toUpperCase()] ?? 2;
+ total += count * bytesPerParam;
+ }
+ return total > 0 ? total : undefined;
+}
+
+export { isGgufLike } from "@/features/hub/lib/model-identifiers";
diff --git a/studio/frontend/src/features/hub/lib/hf-owner-avatar.ts b/studio/frontend/src/features/hub/lib/hf-owner-avatar.ts
new file mode 100644
index 00000000000..e3871f4011c
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/hf-owner-avatar.ts
@@ -0,0 +1,208 @@
+// 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 { useEffect, useState } from "react";
+import { LruMap } from "@/features/hub/lib/lru-map";
+import { fetchWithTimeout } from "@/features/hub/lib/network";
+import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
+
+type AvatarCacheEntry =
+ | { kind: "url"; url: string; expiresAt: number }
+ | { kind: "miss-permanent" }
+ | { kind: "miss-transient"; until: number; failures: number };
+
+// Avatars rarely change; after this the cached URL is shown immediately, then
+// refreshed in the background and swapped if changed (stale-while-revalidate).
+const URL_TTL_MS = 24 * 60 * 60 * 1000;
+
+// Transient (429/5xx) avatar failures are negative-cached so they auto-recover.
+// Each consecutive failure doubles the retry delay up to a cap (a success
+// resets it); the backoff lives in the cache entry to survive virtualized-list churn.
+const TRANSIENT_MISS_BASE_TTL_MS = 60_000;
+const TRANSIENT_MISS_MAX_TTL_MS = 30 * 60_000;
+
+// Bound each fetch so a stalled connection can't hold a concurrency permit open
+// forever (which would hang every queued lookup); timeout is treated as transient.
+const AVATAR_FETCH_TIMEOUT_MS = 10_000;
+
+const cache = new LruMap<string, AvatarCacheEntry>(256);
+const inflight = new Map<string, Promise<string | null>>();
+
+// Cap concurrent avatar lookups so a fast scroll doesn't burst past the rate limit.
+const MAX_AVATAR_CONCURRENT = 6;
+let activeFetches = 0;
+const waiting: Array<() => void> = [];
+
+function acquire(): Promise<void> {
+ if (activeFetches < MAX_AVATAR_CONCURRENT) {
+ activeFetches++;
+ return Promise.resolve();
+ }
+ return new Promise<void>((resolve) =>
+ waiting.push(() => {
+ activeFetches++;
+ resolve();
+ }),
+ );
+}
+
+function release(): void {
+ activeFetches--;
+ waiting.shift()?.();
+}
+
+// Expired transient misses report "no entry" so the caller refetches, but the
+// entry is kept so its failure count can escalate the next backoff.
+function readCache(name: string): AvatarCacheEntry | null {
+ const entry = cache.get(name);
+ if (!entry) return null;
+ if (entry.kind === "miss-transient" && Date.now() >= entry.until) {
+ return null;
+ }
+ return entry;
+}
+
+function readCachedUrl(name: string): string | null {
+ if (!name) return null;
+ const entry = readCache(name);
+ return entry?.kind === "url" ? entry.url : null;
+}
+
+function transientMiss(name: string): AvatarCacheEntry {
+ const prev = cache.get(name);
+ const failures = prev?.kind === "miss-transient" ? prev.failures + 1 : 1;
+ const ttl = Math.min(
+ TRANSIENT_MISS_BASE_TTL_MS * 2 ** (failures - 1),
+ TRANSIENT_MISS_MAX_TTL_MS,
+ );
+ return { kind: "miss-transient", until: Date.now() + ttl, failures };
+}
+
+async function fetchAvatarUrl(
+ name: string,
+): Promise<{ url: string | null; transient: boolean }> {
+ const candidates = [
+ `https://huggingface.co/api/organizations/${encodeURIComponent(name)}/overview`,
+ `https://huggingface.co/api/users/${encodeURIComponent(name)}/overview`,
+ ];
+
+ let sawTransient = false;
+ for (const url of candidates) {
+ try {
+ const res = await fetchWithTimeout(
+ url,
+ {
+ credentials: "omit",
+ },
+ AVATAR_FETCH_TIMEOUT_MS,
+ );
+ if (res.ok) {
+ const data = (await res.json()) as { avatarUrl?: string };
+ if (data.avatarUrl) {
+ const resolved = data.avatarUrl.startsWith("http")
+ ? data.avatarUrl
+ : `https://huggingface.co${data.avatarUrl}`;
+ return { url: resolved, transient: false };
+ }
+ continue;
+ }
+ if (res.status === 404) {
+ continue;
+ }
+ sawTransient = true;
+ } catch {
+ sawTransient = true;
+ }
+ }
+ return { url: null, transient: sawTransient };
+}
+
+function loadAvatar(name: string): Promise<string | null> {
+ const existing = inflight.get(name);
+ if (existing) return existing;
+ const promise = acquire()
+ .then(() => fetchAvatarUrl(name))
+ .finally(release)
+ .then(
+ ({ url, transient }) => {
+ if (url) {
+ cache.set(name, { kind: "url", url, expiresAt: Date.now() + URL_TTL_MS });
+ } else if (transient) {
+ cache.set(name, transientMiss(name));
+ } else {
+ cache.set(name, { kind: "miss-permanent" });
+ }
+ inflight.delete(name);
+ return url;
+ },
+ () => {
+ cache.set(name, transientMiss(name));
+ inflight.delete(name);
+ return null;
+ },
+ );
+ inflight.set(name, promise);
+ return promise;
+}
+
+export function useHfOwnerAvatar(owner: string | null | undefined): string | null {
+ const key = owner?.trim() ?? "";
+ const online = useOnlineStatus();
+ const [state, setState] = useState<{ key: string; url: string | null }>(() => {
+ return { key, url: readCachedUrl(key) };
+ });
+ const url = state.key === key ? state.url : readCachedUrl(key);
+
+ useEffect(() => {
+ if (!key || !online) return;
+ let cancelled = false;
+ let retryTimer: ReturnType<typeof setTimeout> | null = null;
+
+ const scheduleRetry = (until: number) => {
+ const wait = Math.max(until - Date.now(), 0) + 100;
+ retryTimer = setTimeout(() => {
+ if (!cancelled) void attempt();
+ }, wait);
+ };
+
+ const attempt = async () => {
+ const cached = readCache(key);
+ if (cached?.kind === "url") {
+ if (!cancelled) setState({ key, url: cached.url });
+ if (cached.expiresAt <= Date.now()) {
+ void loadAvatar(key).then((next) => {
+ if (!cancelled && next) setState({ key, url: next });
+ });
+ }
+ return;
+ }
+ if (cached?.kind === "miss-permanent") {
+ if (!cancelled) setState({ key, url: null });
+ return;
+ }
+ if (cached?.kind === "miss-transient") {
+ if (!cancelled) setState({ key, url: null });
+ scheduleRetry(cached.until);
+ return;
+ }
+ const next = await loadAvatar(key);
+ if (cancelled) return;
+ setState({ key, url: next });
+ if (next == null) {
+ const post = readCache(key);
+ if (post?.kind === "miss-transient") {
+ scheduleRetry(post.until);
+ }
+ }
+ };
+
+ void attempt();
+
+ return () => {
+ cancelled = true;
+ if (retryTimer != null) clearTimeout(retryTimer);
+ };
+ }, [key, online]);
+
+ return url;
+}
diff --git a/studio/frontend/src/features/hub/lib/hf-readme.ts b/studio/frontend/src/features/hub/lib/hf-readme.ts
new file mode 100644
index 00000000000..89cb5590dc7
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/hf-readme.ts
@@ -0,0 +1,194 @@
+// 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 { LruMap } from "@/features/hub/lib/lru-map";
+import { fetchWithTimeout } from "@/features/hub/lib/network";
+import { fingerprintToken } from "@/features/hub/lib/token-fingerprint";
+import { defaultUrlTransform, type UrlTransform } from "streamdown";
+
+export type ReadmeKind = "model" | "dataset";
+
+export interface FetchedReadme {
+ markdown: string;
+ branch: "main" | "master";
+}
+
+interface ReadmeCacheEntry {
+ promise: Promise<FetchedReadme | null>;
+ // Epoch ms after which the result is refetched. 404s and transient failures
+ // are cached briefly (transient shorter) so absence/outage can recover;
+ // positive results and pending requests never expire within the session.
+ staleAt: number;
+}
+
+const cache = new LruMap<string, ReadmeCacheEntry>(64);
+
+// Bound each request so a stalled HF connection aborts and surfaces as a transient failure.
+const README_FETCH_TIMEOUT_MS = 10_000;
+const README_NEGATIVE_TTL_MS = 5 * 60_000;
+const README_TRANSIENT_TTL_MS = 30_000;
+
+function readmePrefix(kind: ReadmeKind): string {
+ return kind === "dataset" ? "datasets/" : "";
+}
+
+export function readmeBaseUrl(
+ repoId: string,
+ kind: ReadmeKind,
+ branch: "main" | "master" = "main",
+): string {
+ return `https://huggingface.co/${readmePrefix(kind)}${repoId}/resolve/${branch}/`;
+}
+
+async function fetchReadmeOnce(
+ repoId: string,
+ kind: ReadmeKind,
+ token: string | null,
+): Promise<FetchedReadme | null> {
+ const prefix = readmePrefix(kind);
+ const headers: HeadersInit = {};
+ if (token) headers.Authorization = `Bearer ${token}`;
+ let transient = false;
+ for (const branch of ["main", "master"] as const) {
+ try {
+ const url = `https://huggingface.co/${prefix}${repoId}/raw/${branch}/README.md`;
+ const res = await fetchWithTimeout(
+ url,
+ {
+ mode: "cors",
+ headers,
+ },
+ README_FETCH_TIMEOUT_MS,
+ );
+ if (res.ok) {
+ return { markdown: await res.text(), branch };
+ }
+ if (res.status !== 404) transient = true;
+ } catch {
+ transient = true;
+ }
+ }
+ if (transient) {
+ throw new Error(`Failed to fetch README for ${repoId}`);
+ }
+ return null;
+}
+
+export function fetchReadme(
+ repoId: string,
+ kind: ReadmeKind = "model",
+ token: string | null = null,
+): Promise<FetchedReadme | null> {
+ const key = `${kind}::${repoId}::${fingerprintToken(token)}`;
+ const cached = cache.get(key);
+ if (cached && Date.now() < cached.staleAt) return cached.promise;
+
+ const entry: ReadmeCacheEntry = {
+ promise: Promise.resolve(null),
+ staleAt: Number.POSITIVE_INFINITY,
+ };
+ entry.promise = fetchReadmeOnce(repoId, kind, token)
+ .then((result) => {
+ if (result === null) entry.staleAt = Date.now() + README_NEGATIVE_TTL_MS;
+ return result;
+ })
+ .catch((err) => {
+ entry.staleAt = Date.now() + README_TRANSIENT_TTL_MS;
+ throw err;
+ });
+ cache.set(key, entry);
+ return entry.promise;
+}
+
+const ABSOLUTE_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|data:|mailto:|tel:)/i;
+const BLOCKED_README_PROTOCOLS = new Set(["javascript:", "vbscript:"]);
+
+function resolveAgainstBase(src: string, baseUrl: string): string {
+ if (!src) return src;
+ if (ABSOLUTE_URL_RE.test(src)) return src;
+ try {
+ return new URL(src, baseUrl).toString();
+ } catch {
+ return src;
+ }
+}
+
+function readmeUrlProtocol(src: string): string | null {
+ try {
+ return new URL(src, "https://huggingface.co").protocol.toLowerCase();
+ } catch {
+ return null;
+ }
+}
+
+function isBlockedReadmeUrl(
+ src: string,
+ node: Readonly<{ tagName?: unknown }>,
+): boolean {
+ const protocol = readmeUrlProtocol(src.trim());
+ if (!protocol) return false;
+ if (BLOCKED_README_PROTOCOLS.has(protocol)) return true;
+ if (protocol !== "data:") return false;
+ return String(node.tagName ?? "").toLowerCase() !== "img";
+}
+
+// Resolves relative asset URLs against the repo base, then delegates to
+// defaultUrlTransform so unsafe schemes (javascript:, etc.) stay stripped.
+export function createReadmeUrlTransform(baseUrl: string): UrlTransform {
+ return (url, key, node) => {
+ const resolved = resolveAgainstBase(url, baseUrl);
+ if (isBlockedReadmeUrl(resolved, node)) {
+ return undefined;
+ }
+ return defaultUrlTransform(resolved, key, node);
+ };
+}
+
+const FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
+
+export function stripFrontmatter(markdown: string): {
+ body: string;
+ frontmatter: string | null;
+} {
+ const match = FRONTMATTER_RE.exec(markdown);
+ if (match) {
+ return {
+ body: markdown.slice(match[0].length),
+ frontmatter: match[1],
+ };
+ }
+ return { body: markdown, frontmatter: null };
+}
+
+/**
+ * Drop heading lines that duplicate the inspector's chrome (`# Model Card …`,
+ * standalone `Details` / `Model Card` / `Dataset Card`, etc.), since the page
+ * header already shows the repo name and section context.
+ */
+export function stripChromeHeadings(markdown: string): string {
+ const RE_HEADING = /^(#{1,6})\s+(.+?)\s*$/;
+ const isChromeTitle = (text: string): boolean => {
+ const t = text
+ .toLowerCase()
+ .replace(/[*_`]/g, "")
+ .replace(/\s+/g, " ")
+ .trim();
+ return (
+ t === "details" ||
+ t === "model card" ||
+ t === "dataset card" ||
+ t.startsWith("model card for") ||
+ t.startsWith("dataset card for") ||
+ t.startsWith("card for")
+ );
+ };
+
+ const lines = markdown.split(/\r?\n/);
+ const out: string[] = [];
+ for (const line of lines) {
+ const m = RE_HEADING.exec(line);
+ if (m && isChromeTitle(m[2])) continue;
+ out.push(line);
+ }
+ return out.join("\n");
+}
diff --git a/studio/frontend/src/features/hub/lib/hub-feature-flags.ts b/studio/frontend/src/features/hub/lib/hub-feature-flags.ts
new file mode 100644
index 00000000000..cf284037253
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/hub-feature-flags.ts
@@ -0,0 +1,8 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Hub feature flags for staged rollout. Each gates a CTA whose integration ships
+// in a later PR; JSX/wiring stay in place so flipping here is the only re-enable edit.
+
+// Post-download Run / chat / Train CTAs, hidden until the Hub-aware chat and train pickers ship.
+export const HUB_POST_DOWNLOAD_ACTIONS_VISIBLE = false;
diff --git a/studio/frontend/src/features/hub/lib/hub-token-header.ts b/studio/frontend/src/features/hub/lib/hub-token-header.ts
new file mode 100644
index 00000000000..27b5693eeec
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/hub-token-header.ts
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Internal Unsloth API header; direct Hugging Face calls use Authorization.
+
+export const HUB_HF_TOKEN_HEADER = "X-Unsloth-HF-Token";
+
+export function hubTokenHeader(
+ token?: string | null,
+): Record<string, string> {
+ return token ? { [HUB_HF_TOKEN_HEADER]: token } : {};
+}
diff --git a/studio/frontend/src/features/hub/lib/inventory-search.ts b/studio/frontend/src/features/hub/lib/inventory-search.ts
new file mode 100644
index 00000000000..dd9e12ae5fd
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/inventory-search.ts
@@ -0,0 +1,62 @@
+// 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 {
+ matchTokens,
+ normalizeForSearch,
+ tokenizeQuery,
+} from "@/features/hub/lib/search-text";
+import type { CachedInventoryRow, LocalInventoryRow } from "../types";
+
+export { tokenizeQuery };
+
+function inventoryRowName(row: CachedInventoryRow | LocalInventoryRow): string {
+ return row.kind === "cache" ? row.repoId : row.title;
+}
+
+function inventoryRowHaystack(
+ row: CachedInventoryRow | LocalInventoryRow,
+): string {
+ if (row.kind === "cache")
+ return [
+ row.repoId,
+ row.modelFormat,
+ row.pipelineTag ?? "",
+ row.libraryName ?? "",
+ ...(row.tags ?? []),
+ ].join(" ");
+ return [
+ row.title,
+ row.owner,
+ row.sourceLabel,
+ row.path,
+ row.loadId,
+ row.modelFormat,
+ row.repoId ?? "",
+ ].join(" ");
+}
+
+export function inventoryRowMatches(
+ row: CachedInventoryRow | LocalInventoryRow,
+ tokens: readonly string[],
+): boolean {
+ if (tokens.length === 0) return true;
+ return matchTokens(inventoryRowHaystack(row), tokens);
+}
+
+export function scoreInventoryRow(
+ row: CachedInventoryRow | LocalInventoryRow,
+ tokens: readonly string[],
+): number {
+ if (tokens.length === 0) return 0;
+ const name = normalizeForSearch(inventoryRowName(row));
+ const haystack = normalizeForSearch(inventoryRowHaystack(row));
+ let score = 0;
+ for (const token of tokens) {
+ if (name.startsWith(token)) score += 3;
+ else if (name.includes(token)) score += 2;
+ else if (haystack.includes(token)) score += 1;
+ else return 0;
+ }
+ return score;
+}
diff --git a/studio/frontend/src/features/hub/lib/local-path.ts b/studio/frontend/src/features/hub/lib/local-path.ts
new file mode 100644
index 00000000000..aeb6a9a437c
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/local-path.ts
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+const LOCAL_PATH_PREFIX_RE =
+ /^(?:\/|\.{1,2}(?:$|[\\/])|~(?:$|[\\/])|~[^\\/]+[\\/]|[A-Za-z]:[\\/]|\\\\)/;
+const WINDOWS_PATH_SEPARATOR_RE = /\\/g;
+const TRAILING_PATH_SEPARATOR_RE = /\/+$/;
+
+export function looksLikeLocalPath(input: string): boolean {
+ const value = input.trim();
+ return value.length > 0 && LOCAL_PATH_PREFIX_RE.test(value);
+}
+
+export function localPathCacheKey(path: string | null | undefined): string {
+ return (
+ path
+ ?.replace(WINDOWS_PATH_SEPARATOR_RE, "/")
+ .replace(TRAILING_PATH_SEPARATOR_RE, "") ?? ""
+ );
+}
diff --git a/studio/frontend/src/features/hub/lib/lru-map.ts b/studio/frontend/src/features/hub/lib/lru-map.ts
new file mode 100644
index 00000000000..348a255b504
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/lru-map.ts
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Insertion-ordered map with a maximum size. Reads and writes move a key to
+ * the most-recent position; once over capacity the least-recently-used key is
+ * evicted. Bounds memory for module-level caches that live for the tab's
+ * lifetime (HF READMEs, dataset sizes, owner avatars).
+ */
+export class LruMap<K, V> {
+ private readonly map = new Map<K, V>();
+ private readonly max: number;
+
+ constructor(max: number) {
+ this.max = max;
+ }
+
+ has(key: K): boolean {
+ return this.map.has(key);
+ }
+
+ get(key: K): V | undefined {
+ if (!this.map.has(key)) return undefined;
+ const value = this.map.get(key) as V;
+ this.map.delete(key);
+ this.map.set(key, value);
+ return value;
+ }
+
+ set(key: K, value: V): void {
+ this.map.delete(key);
+ this.map.set(key, value);
+ if (this.map.size > this.max) {
+ const oldest = this.map.keys().next().value;
+ if (oldest !== undefined) this.map.delete(oldest);
+ }
+ }
+
+ delete(key: K): void {
+ this.map.delete(key);
+ }
+
+ clear(): void {
+ this.map.clear();
+ }
+}
+
+/**
+ * Trim an insertion-ordered Set to `max` entries, evicting oldest-first but
+ * never an entry `isProtected` reports as still live. Protected entries are
+ * re-inserted at the back; `protectedScans` caps the walk at one full pass so
+ * a fully-protected set over capacity exits instead of looping forever.
+ */
+export function evictOldestUnprotected(
+ set: Set<string>,
+ max: number,
+ isProtected: (key: string) => boolean,
+): void {
+ let protectedScans = 0;
+ while (set.size > max && protectedScans < set.size) {
+ const oldest = set.values().next().value;
+ if (oldest === undefined) break;
+ if (isProtected(oldest)) {
+ set.delete(oldest);
+ set.add(oldest);
+ protectedScans += 1;
+ continue;
+ }
+ set.delete(oldest);
+ protectedScans = 0;
+ }
+}
diff --git a/studio/frontend/src/features/hub/lib/model-capabilities.ts b/studio/frontend/src/features/hub/lib/model-capabilities.ts
new file mode 100644
index 00000000000..bbfc2174dfb
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/model-capabilities.ts
@@ -0,0 +1,162 @@
+// 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 { EMBEDDING_TAGS } from "./hf-model-meta";
+
+export type CapabilityKey =
+ | "vision"
+ | "audio"
+ | "tools"
+ | "reasoning"
+ | "code"
+ | "embedding"
+ | "multilingual";
+
+export interface Capability {
+ key: CapabilityKey;
+ label: string;
+}
+
+const VISION_TAGS = new Set([
+ "vision",
+ "vision-language",
+ "image-text-to-text",
+ "image-to-text",
+ "visual-question-answering",
+ "image-classification",
+ "image-segmentation",
+ "object-detection",
+ "any-to-any",
+ "multimodal",
+ "vlm",
+ "llava",
+]);
+
+const AUDIO_TAGS = new Set([
+ "audio",
+ "audio-text-to-text",
+ "automatic-speech-recognition",
+ "text-to-speech",
+ "audio-classification",
+ "voice-activity-detection",
+ "asr",
+ "tts",
+]);
+
+const TOOL_TAGS = new Set([
+ "tool-use",
+ "tools",
+ "tool-calling",
+ "function-calling",
+ "function-call",
+ "agent",
+ "agentic",
+]);
+
+const REASONING_TAGS = new Set([
+ "reasoning",
+ "thinking",
+ "chain-of-thought",
+ "math-reasoning",
+ "step-by-step",
+]);
+
+const CODE_TAGS = new Set([
+ "code",
+ "code-generation",
+ "code-completion",
+ "code-llm",
+ "programming",
+]);
+
+const COMMON_LANGUAGE_TAGS = new Set([
+ "en", "fr", "de", "es", "it", "pt", "nl", "ru", "pl", "uk", "tr", "cs",
+ "sv", "no", "da", "fi", "el", "ro", "bg", "hu", "hr", "sr", "sl", "sk",
+ "zh", "ja", "ko", "ar", "he", "fa", "hi", "bn", "ta", "te", "th", "vi",
+ "id", "ms", "tl", "sw", "ur", "ca", "eu", "is", "lv", "lt", "et",
+]);
+
+function lower(values: string[] | undefined): Set<string> {
+ if (!values) return new Set();
+ return new Set(values.map((v) => v.toLowerCase()));
+}
+
+export function detectCapabilities(
+ tags: string[] | undefined,
+ pipelineTag: string | undefined,
+ modelId: string,
+): Capability[] {
+ const tagSet = lower(tags);
+ const pipeline = pipelineTag?.toLowerCase();
+ const lowerId = modelId.toLowerCase();
+ const out: Capability[] = [];
+
+ const hasAny = (set: ReadonlySet<string>) => {
+ for (const t of set) {
+ if (tagSet.has(t)) return true;
+ }
+ return pipeline ? set.has(pipeline) : false;
+ };
+
+ if (
+ hasAny(VISION_TAGS) ||
+ /[-_/]vl[-_]|vision|multimodal|llava|kosmos|qwen2[-_]?vl|cogvlm/.test(
+ lowerId,
+ )
+ ) {
+ out.push({ key: "vision", label: "Vision" });
+ }
+ if (
+ hasAny(AUDIO_TAGS) ||
+ /audio|whisper|speech|tts|stt|asr|parler|sesame|bark|wav2vec|hubert|musicgen|speecht5|vocos|encodec|clap|ultravox|kyutai|moshi/.test(
+ lowerId,
+ )
+ ) {
+ out.push({ key: "audio", label: "Audio" });
+ }
+ if (hasAny(TOOL_TAGS) || /tool[-_]use|function[-_]call/.test(lowerId)) {
+ out.push({ key: "tools", label: "Tool use" });
+ }
+ if (
+ hasAny(REASONING_TAGS) ||
+ /think|reason|qwq|deepseek[-_]?r|gpt[-_]?oss|(?:^|[-_/])o1(?:[-_]|$)|nemotron[-_]reasoning/.test(
+ lowerId,
+ )
+ ) {
+ out.push({ key: "reasoning", label: "Reasoning" });
+ }
+ if (
+ hasAny(CODE_TAGS) ||
+ /(?:^|[-_/])coder(?:[-_/]|$)|(?:^|[-_/])code(?:[-_]|$)|starcoder|codellama|deepseek[-_]coder/.test(
+ lowerId,
+ )
+ ) {
+ out.push({ key: "code", label: "Code" });
+ }
+ if (
+ hasAny(EMBEDDING_TAGS) ||
+ /embed|embedding|retriever|reranker|bge[-_]|e5[-_]|gte[-_]|colbert|sentence[-_]?transformer|sentence[-_]?similarity|jina[-_]?embeddings?|nomic[-_]?embed|arctic[-_]?embed|qwen3[-_]?embedding|qwen3[-_]?reranker|text[-_]?embedding/.test(
+ lowerId,
+ )
+ ) {
+ out.push({ key: "embedding", label: "Embeddings" });
+ }
+ const languageCodes = new Set<string>();
+ for (const tag of tags ?? []) {
+ const lower = tag.toLowerCase();
+ const code = lower.startsWith("language:")
+ ? lower.slice("language:".length)
+ : lower;
+ if (COMMON_LANGUAGE_TAGS.has(code)) languageCodes.add(code);
+ }
+ if (tagSet.has("multilingual") || languageCodes.size >= 3) {
+ out.push({ key: "multilingual", label: "Multilingual" });
+ }
+ return out;
+}
+
+export function detectLicense(tags: string[] | undefined): string | null {
+ if (!tags) return null;
+ const license = tags.find((t) => t.startsWith("license:"));
+ return license ? license.slice("license:".length) : null;
+}
diff --git a/studio/frontend/src/features/hub/lib/model-identifiers.ts b/studio/frontend/src/features/hub/lib/model-identifiers.ts
new file mode 100644
index 00000000000..4c7b2031ec9
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/model-identifiers.ts
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+const GGUF_REPO_SUFFIX_PATTERN = /-GGUF$/i;
+
+function normalizedLeaf(value: string): string {
+ const normalized = value.trim().replace(/[\\/]+$/, "");
+ return normalized.split(/[\\/]/).pop() ?? normalized;
+}
+
+export function hasGgufRepoSuffix(value: string | undefined | null): boolean {
+ if (!value) return false;
+ const leaf = normalizedLeaf(value);
+ return leaf.length > 0 && GGUF_REPO_SUFFIX_PATTERN.test(leaf);
+}
+
+export function isGgufFilename(value: string | undefined | null): boolean {
+ if (!value) return false;
+ return normalizedLeaf(value).toLowerCase().endsWith(".gguf");
+}
+
+export function isGgufLike(value: string | undefined | null): boolean {
+ return isGgufFilename(value) || hasGgufRepoSuffix(value);
+}
diff --git a/studio/frontend/src/features/hub/lib/model-identity.ts b/studio/frontend/src/features/hub/lib/model-identity.ts
new file mode 100644
index 00000000000..488502ae287
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/model-identity.ts
@@ -0,0 +1,65 @@
+// 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 { looksLikeLocalPath } from "./local-path.ts";
+
+const WINDOWS_DRIVE_PATH_RE = /^[A-Za-z]:[\\/]/;
+const WSL_DRIVE_PATH_RE = /^\/mnt\/[A-Za-z](?:\/|$)/;
+
+function trimTrailingSeparators(path: string, minLength: number): string {
+ let end = path.length;
+ while (end > minLength && path.charCodeAt(end - 1) === 47) {
+ end -= 1;
+ }
+ return end === path.length ? path : path.slice(0, end);
+}
+
+function normalizeCaseInsensitivePath(path: string, minLength: number): string {
+ return trimTrailingSeparators(
+ path.replace(/\\/g, "/"),
+ minLength,
+ ).toLowerCase();
+}
+
+export function normalizeModelIdentity(modelId: string): string {
+ const trimmed = modelId.trim();
+ if (!looksLikeLocalPath(trimmed)) {
+ return trimmed.toLowerCase();
+ }
+ const slashPath = trimmed.replace(/\\/g, "/");
+ if (WINDOWS_DRIVE_PATH_RE.test(trimmed)) {
+ return normalizeCaseInsensitivePath(trimmed, 3);
+ }
+ if (slashPath.startsWith("//")) {
+ return normalizeCaseInsensitivePath(trimmed, 2);
+ }
+ if (WSL_DRIVE_PATH_RE.test(slashPath)) {
+ return normalizeCaseInsensitivePath(trimmed, 6);
+ }
+ return trimmed;
+}
+
+export function normalizeGgufVariantIdentity(
+ ggufVariant?: string | null,
+): string {
+ return ggufVariant?.trim().toLowerCase() ?? "";
+}
+
+export function modelIdsMatch(
+ left: string | null | undefined,
+ right: string | null | undefined,
+): boolean {
+ if (!(left && right)) {
+ return false;
+ }
+ return normalizeModelIdentity(left) === normalizeModelIdentity(right);
+}
+
+export function ggufVariantsMatch(
+ left: string | null | undefined,
+ right: string | null | undefined,
+): boolean {
+ return (
+ normalizeGgufVariantIdentity(left) === normalizeGgufVariantIdentity(right)
+ );
+}
diff --git a/studio/frontend/src/features/hub/lib/network.ts b/studio/frontend/src/features/hub/lib/network.ts
new file mode 100644
index 00000000000..549af99fbc4
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/network.ts
@@ -0,0 +1,186 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export function isBrowserOffline(): boolean {
+ return isNavigatorOffline();
+}
+
+const NETWORK_STATUS_EVENT = "unsloth-network-status";
+const REMOTE_OFFLINE_TTL_MS = 30_000;
+const HUGGING_FACE_REMOTE_ORIGINS = [
+ "https://huggingface.co",
+ "https://datasets-server.huggingface.co",
+] as const;
+const noopUnsubscribe = () => undefined;
+
+type RemoteNetworkScope = string | readonly string[];
+
+const remoteOfflineUntilByOrigin = new Map<string, number>();
+
+function isNavigatorOffline(): boolean {
+ return typeof navigator !== "undefined" && navigator.onLine === false;
+}
+
+function emitNetworkStatusChange(): void {
+ if (typeof window === "undefined") {
+ return;
+ }
+ window.dispatchEvent(new Event(NETWORK_STATUS_EVENT));
+}
+
+export function getBrowserOfflineRetryDelayMs(): number {
+ // Keyed off the empirical remote-offline TTL, not navigator.onLine, so recovery
+ // doesn't stall on platforms where navigator.onLine is stuck false.
+ return Math.max(
+ 0,
+ getRemoteOfflineUntil(HUGGING_FACE_REMOTE_ORIGINS) - Date.now(),
+ );
+}
+
+function normalizeScope(scope: RemoteNetworkScope): readonly string[] {
+ return typeof scope === "string" ? [scope] : scope;
+}
+
+function getRemoteOfflineUntil(scope: RemoteNetworkScope): number {
+ const now = Date.now();
+ let until = 0;
+ for (const origin of normalizeScope(scope)) {
+ const value = remoteOfflineUntilByOrigin.get(origin) ?? 0;
+ if (value <= now) {
+ remoteOfflineUntilByOrigin.delete(origin);
+ continue;
+ }
+ until = Math.max(until, value);
+ }
+ return until;
+}
+
+export function isRemoteNetworkOffline(
+ scope: RemoteNetworkScope = HUGGING_FACE_REMOTE_ORIGINS,
+): boolean {
+ return getRemoteOfflineUntil(scope) > Date.now();
+}
+
+export function isHuggingFaceOffline(): boolean {
+ // navigator.onLine is advisory only (false-reports offline on WSL2 / some
+ // WebKitGTK/Tauri webviews). The authoritative signal is the empirical
+ // remote-offline TTL, set when a real fetch fails and cleared on next success.
+ return isRemoteNetworkOffline(HUGGING_FACE_REMOTE_ORIGINS);
+}
+
+export function markRemoteNetworkOnline(origin?: string): void {
+ if (origin === undefined) {
+ if (remoteOfflineUntilByOrigin.size === 0) {
+ return;
+ }
+ remoteOfflineUntilByOrigin.clear();
+ emitNetworkStatusChange();
+ return;
+ }
+ if (!remoteOfflineUntilByOrigin.delete(origin)) {
+ return;
+ }
+ emitNetworkStatusChange();
+}
+
+export function markRemoteNetworkOffline(
+ originOrTtl: string | number = HUGGING_FACE_REMOTE_ORIGINS[0],
+ ttlMs = REMOTE_OFFLINE_TTL_MS,
+): void {
+ const origin =
+ typeof originOrTtl === "string"
+ ? originOrTtl
+ : HUGGING_FACE_REMOTE_ORIGINS[0];
+ const ttl = typeof originOrTtl === "number" ? originOrTtl : ttlMs;
+ const nextUntil = Date.now() + ttl;
+ if (nextUntil <= (remoteOfflineUntilByOrigin.get(origin) ?? 0)) {
+ return;
+ }
+ remoteOfflineUntilByOrigin.set(origin, nextUntil);
+ emitNetworkStatusChange();
+}
+
+export function subscribeNetworkStatus(listener: () => void): () => void {
+ if (typeof window === "undefined") {
+ return noopUnsubscribe;
+ }
+ window.addEventListener("online", listener);
+ window.addEventListener("offline", listener);
+ window.addEventListener(NETWORK_STATUS_EVENT, listener);
+ return () => {
+ window.removeEventListener("online", listener);
+ window.removeEventListener("offline", listener);
+ window.removeEventListener(NETWORK_STATUS_EVENT, listener);
+ };
+}
+
+function isAbortError(error: unknown): boolean {
+ return error instanceof DOMException && error.name === "AbortError";
+}
+
+function isNetworkFetchError(error: unknown): boolean {
+ if (isAbortError(error)) {
+ return false;
+ }
+ return error instanceof TypeError;
+}
+
+function originFromFetchInput(
+ input: Parameters<typeof fetch>[0],
+): string | null {
+ try {
+ const raw =
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url;
+ const base =
+ typeof window !== "undefined" ? window.location.href : "http://localhost";
+ return new URL(raw, base).origin;
+ } catch {
+ return null;
+ }
+}
+
+export async function fetchWithTimeout(
+ input: Parameters<typeof fetch>[0],
+ init: Parameters<typeof fetch>[1] = {},
+ timeoutMs = 15_000,
+): Promise<Response> {
+ const parentSignal = init.signal;
+ const controller = new AbortController();
+ let timedOut = false;
+ const timeout = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, timeoutMs);
+ const abortFromParent = () => controller.abort();
+
+ if (parentSignal?.aborted) {
+ abortFromParent();
+ } else {
+ parentSignal?.addEventListener("abort", abortFromParent, { once: true });
+ }
+
+ const origin = originFromFetchInput(input);
+
+ try {
+ const response = await fetch(input, { ...init, signal: controller.signal });
+ if (origin) {
+ markRemoteNetworkOnline(origin);
+ }
+ return response;
+ } catch (error) {
+ if (timedOut) {
+ throw new Error("Request timed out");
+ }
+ if (origin && isNetworkFetchError(error)) {
+ markRemoteNetworkOffline(origin);
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeout);
+ parentSignal?.removeEventListener("abort", abortFromParent);
+ }
+}
diff --git a/studio/frontend/src/features/hub/lib/provider-logos.ts b/studio/frontend/src/features/hub/lib/provider-logos.ts
new file mode 100644
index 00000000000..d271351df37
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/provider-logos.ts
@@ -0,0 +1,278 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Provider-logo registry for Unsloth re-uploads. Unsloth re-uploads upstream
+ * models (e.g. unsloth/Qwen2.5-7B is Alibaba's Qwen); we render the upstream
+ * provider's logo in place of the Unsloth profile picture.
+ *
+ * Providers are evaluated in declaration order; a provider matches if any of its
+ * `prefixes` is a prefix of the repo name (the part after "owner/"). Repo names
+ * are case-sensitive — match the publisher's exact casing.
+ */
+
+/**
+ * Logo coloring. "original" = file as-is; "mono-theme" = CSS mask in current
+ * text color (follows theme); "mono-black" = mask always pure black.
+ */
+export type LogoTreatment = "original" | "mono-theme" | "mono-black";
+
+/** Tile background. "white" keeps colored marks readable; "transparent" shows the surface. */
+export type LogoBackground = "white" | "transparent";
+
+/**
+ * Logo sizing (only for "original"; mono always pads). "contain" pads at ~75%;
+ * "cover" is full-bleed.
+ */
+export type LogoFit = "contain" | "cover";
+
+export interface ProviderLogo {
+ id: string;
+ name: string;
+ logoPath: string;
+ treatment: LogoTreatment;
+ background: LogoBackground;
+ fit?: LogoFit;
+ /**
+ * Repo-name prefixes (after `owner/`) mapping to this provider. A prefix
+ * match suffices — variants (-Instruct, -bnb-4bit, -GGUF) ride along. Match
+ * on the family stem so future minor versions are picked up automatically.
+ */
+ prefixes: readonly string[];
+}
+
+export const PROVIDER_LOGOS: readonly ProviderLogo[] = [
+ // First so Llama-3.x-Nemotron/Minitron and Mistral-NeMo beat meta-llama / mistralai.
+ {
+ id: "nvidia",
+ name: "NVIDIA",
+ logoPath: "/hub/profile/logo/nvidia.svg",
+ treatment: "original",
+ background: "white",
+ prefixes: [
+ "Llama-3.1-Nemotron-",
+ "Llama-3.3-Nemotron-",
+ "Llama-3.1-Minitron-",
+ "NVIDIA-Nemotron-",
+ "Nemotron-3-",
+ "Nemotron-4-",
+ "Nemotron-H-",
+ "Minitron-",
+ "Mistral-NeMo-",
+ "OpenReasoning-Nemotron-",
+ "OpenCodeReasoning",
+ "Cosmos-"
+ ],
+ },
+
+ // `DeepSeek-R1-Distill-*` must beat Qwen/meta-llama on the suffix family.
+ {
+ id: "deepseek-ai",
+ name: "DeepSeek",
+ logoPath: "/hub/profile/logo/deepseek.svg",
+ treatment: "original",
+ background: "white",
+ prefixes: [
+ "DeepSeek-R1-Distill-",
+ "DeepSeek-",
+ "deepseek-",
+ "deepseek-llm-",
+ "deepseek-coder-",
+ ],
+ },
+
+ {
+ id: "microsoft",
+ name: "Microsoft",
+ logoPath: "/hub/profile/logo/microsoft.svg",
+ treatment: "original",
+ background: "white",
+ prefixes: [
+ "MAI-DS-R1",
+ "NextCoder-",
+ "Phi-3-",
+ "Phi-3.5-",
+ "Phi-4",
+ "phi-1",
+ "phi-2",
+ "phi-",
+ ],
+ },
+
+ // The broad `Qwen` prefix catches Qwen1.5/2/2.5/3/future versions without explicit entries.
+ {
+ id: "qwen",
+ name: "Qwen",
+ logoPath: "/hub/profile/logo/qwen.png",
+ treatment: "original",
+ background: "white",
+ prefixes: ["Qwen", "QwQ-", "QVQ-"],
+ },
+
+ {
+ id: "moonshotai",
+ name: "Moonshot AI",
+ logoPath: "/hub/profile/logo/moonshot.jpg",
+ treatment: "original",
+ background: "transparent",
+ fit: "cover",
+ prefixes: ["Kimi-", "Moonlight-"],
+ },
+
+ // Z.ai (THUDM successor).
+ {
+ id: "zai-org",
+ name: "Z.ai",
+ logoPath: "/hub/profile/logo/zai.svg",
+ treatment: "original",
+ background: "transparent",
+ fit: "cover",
+ prefixes: ["GLM-", "glm-", "chatglm", "codegeex"],
+ },
+
+ {
+ id: "xai-org",
+ name: "xAI",
+ logoPath: "/hub/profile/logo/xai.svg",
+ treatment: "mono-black",
+ background: "white",
+ prefixes: ["grok-"],
+ },
+
+ {
+ id: "minimax",
+ name: "MiniMax AI",
+ logoPath: "/hub/profile/logo/minimax-color.png",
+ treatment: "original",
+ background: "white",
+ prefixes: ["MiniMax-"],
+ },
+
+ // SmolLM family lives under HuggingFaceTB.
+ {
+ id: "huggingface",
+ name: "Hugging Face",
+ logoPath: "/hub/profile/logo/hf.svg",
+ treatment: "original",
+ background: "white",
+ prefixes: ["SmolLM"],
+ },
+
+ {
+ id: "ibm",
+ name: "IBM",
+ logoPath: "/hub/profile/logo/ibm.png",
+ treatment: "original",
+ background: "transparent",
+ fit: "cover",
+ prefixes: ["granite-", "granitelib-"],
+ },
+
+ {
+ id: "cohere",
+ name: "Cohere Labs",
+ logoPath: "/hub/profile/logo/cohere.png",
+ treatment: "original",
+ background: "white",
+ prefixes: ["c4ai-command", "aya-"],
+ },
+
+ {
+ id: "openai",
+ name: "OpenAI",
+ logoPath: "/hub/profile/logo/openai.svg",
+ treatment: "mono-theme",
+ background: "transparent",
+ prefixes: ["gpt-oss-"],
+ },
+
+ {
+ id: "google",
+ name: "Google",
+ logoPath: "/hub/profile/logo/google.png",
+ treatment: "original",
+ background: "white",
+ prefixes: [
+ "gemma-",
+ "codegemma-",
+ "recurrentgemma-",
+ "shieldgemma-",
+ "medgemma-",
+ "functiongemma-",
+ "translategemma-",
+ "alphagenome-",
+ "t5gemma-",
+ "tipsv2-",
+ "embeddinggemma-",
+ "videoprism-",
+ "txgemma-",
+ "paligemma-",
+ "metricx-",
+ "bert-",
+ ],
+ },
+
+ // After NVIDIA so `Mistral-NeMo-` wins; generic Mistral-/Mixtral- fall through here.
+ {
+ id: "mistralai",
+ name: "Mistral AI",
+ logoPath: "/hub/profile/logo/mistral.svg",
+ treatment: "original",
+ background: "white",
+ prefixes: ["Mistral-", "Mixtral-", "Codestral-", "Pixtral-", "Devstral-", "Ministral-", "Voxtral-", "Magistral-"],
+ },
+
+ // Last among Llama-prefix providers so NVIDIA's Llama-3.x-Nemotron/Minitron match first.
+ {
+ id: "meta-llama",
+ name: "Meta",
+ logoPath: "/hub/profile/logo/meta.svg",
+ treatment: "original",
+ background: "white",
+ prefixes: [
+ "Meta-Llama-",
+ "Llama-Guard-",
+ "LlamaGuard-",
+ "CodeLlama-",
+ "Llama-",
+ "llama-",
+ "meta-"
+ ],
+ },
+];
+
+/**
+ * Resolve a repo name (after `owner/`) to its upstream provider, or null.
+ * Iterates PROVIDER_LOGOS in declaration order; first prefix match wins.
+ */
+export function matchProviderLogo(repoName: string): ProviderLogo | null {
+ if (!repoName) return null;
+ for (const provider of PROVIDER_LOGOS) {
+ if (provider.prefixes.some((prefix) => repoName.startsWith(prefix))) {
+ return provider;
+ }
+ }
+ return null;
+}
+
+// Owners whose avatars get swapped for the matched provider's logo.
+const RELABELED_OWNERS: ReadonlySet<string> = new Set(["unsloth"]);
+
+export function isProviderRelabeledOwner(
+ owner: string | null | undefined,
+): boolean {
+ if (!owner) return false;
+ return RELABELED_OWNERS.has(owner.toLowerCase());
+}
+
+/**
+ * Provider logo to render in place of the owner's profile picture, or null.
+ * Only owners in RELABELED_OWNERS are eligible.
+ */
+export function resolveOwnerProviderLogo(
+ owner: string | null | undefined,
+ repoName: string | null | undefined,
+): ProviderLogo | null {
+ if (!isProviderRelabeledOwner(owner) || !repoName) return null;
+ return matchProviderLogo(repoName);
+}
diff --git a/studio/frontend/src/features/hub/lib/search-text.ts b/studio/frontend/src/features/hub/lib/search-text.ts
new file mode 100644
index 00000000000..b6653ee1f89
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/search-text.ts
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Lowercase and strip whitespace and separators so "Llama-3.1" matches "llama 3 1". */
+export function normalizeForSearch(value: string): string {
+ return value.toLowerCase().replace(/[\s_.-]/g, "");
+}
+
+export function tokenizeQuery(query: string): string[] {
+ return query
+ .split(/\s+/)
+ .map((token) => normalizeForSearch(token))
+ .filter((token) => token.length > 0);
+}
+
+export function matchTokens(haystack: string, tokens: readonly string[]): boolean {
+ if (tokens.length === 0) return true;
+ const normalized = normalizeForSearch(haystack);
+ for (const token of tokens) {
+ if (!normalized.includes(token)) return false;
+ }
+ return true;
+}
diff --git a/studio/frontend/src/features/hub/lib/selection-resolution.ts b/studio/frontend/src/features/hub/lib/selection-resolution.ts
new file mode 100644
index 00000000000..f3c45434485
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/selection-resolution.ts
@@ -0,0 +1,145 @@
+// 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 { findCompleteHfCacheLocalRow } from "../inventory/inventory-dedupe";
+import type {
+ CachedInventoryRow,
+ DiscoverRow,
+ LocalInventoryRow,
+} from "../types";
+
+export type SelectionResolution = {
+ selectedId: string | null;
+ hiddenByFilters: boolean;
+};
+
+function idSet(rows: readonly { id: string }[]): Set<string> {
+ return new Set(rows.map((row) => row.id));
+}
+
+function idMap<T extends { id: string }>(rows: readonly T[]): Map<string, T> {
+ return new Map(rows.map((row) => [row.id, row]));
+}
+
+function resolveCachedSelection(
+ cached: CachedInventoryRow,
+ filteredCachedIds: ReadonlySet<string>,
+ filteredLocalIds: ReadonlySet<string>,
+ localRows: readonly LocalInventoryRow[],
+): SelectionResolution {
+ if (cached.partial) {
+ const completeLocal = findCompleteHfCacheLocalRow(cached, localRows);
+ if (completeLocal) {
+ return {
+ selectedId: completeLocal.id,
+ hiddenByFilters: !filteredLocalIds.has(completeLocal.id),
+ };
+ }
+ }
+ return {
+ selectedId: cached.id,
+ hiddenByFilters: !filteredCachedIds.has(cached.id),
+ };
+}
+
+function resolveDownloadedId(
+ id: string | null,
+ cachedById: ReadonlyMap<string, CachedInventoryRow>,
+ localById: ReadonlyMap<string, LocalInventoryRow>,
+ filteredCachedIds: ReadonlySet<string>,
+ filteredLocalIds: ReadonlySet<string>,
+ localRows: readonly LocalInventoryRow[],
+): SelectionResolution | null {
+ if (!id) {
+ return null;
+ }
+ const cached = cachedById.get(id);
+ if (cached) {
+ return resolveCachedSelection(
+ cached,
+ filteredCachedIds,
+ filteredLocalIds,
+ localRows,
+ );
+ }
+ if (localById.has(id)) {
+ return {
+ selectedId: id,
+ hiddenByFilters: !filteredLocalIds.has(id),
+ };
+ }
+ return null;
+}
+
+export function resolveDiscoverSelection({
+ selectedId,
+ discoverRows,
+ filteredDiscoverRows,
+ selectedSnapshotId,
+}: {
+ selectedId: string | null;
+ discoverRows: readonly DiscoverRow[];
+ filteredDiscoverRows: readonly DiscoverRow[];
+ selectedSnapshotId?: string | null;
+}): SelectionResolution {
+ const filteredIds = idSet(filteredDiscoverRows);
+ if (
+ selectedId &&
+ (discoverRows.some((row) => row.id === selectedId) ||
+ selectedSnapshotId === selectedId)
+ ) {
+ return {
+ selectedId,
+ hiddenByFilters: !filteredIds.has(selectedId),
+ };
+ }
+ return {
+ selectedId: filteredDiscoverRows[0]?.id ?? null,
+ hiddenByFilters: false,
+ };
+}
+
+export function resolveDownloadedSelection({
+ selectedId,
+ cachedRows,
+ localRows,
+ filteredCachedRows,
+ filteredLocalRows,
+}: {
+ selectedId: string | null;
+ cachedRows: readonly CachedInventoryRow[];
+ localRows: readonly LocalInventoryRow[];
+ filteredCachedRows: readonly CachedInventoryRow[];
+ filteredLocalRows: readonly LocalInventoryRow[];
+}): SelectionResolution {
+ const cachedById = idMap(cachedRows);
+ const localById = idMap(localRows);
+ const filteredCachedIds = idSet(filteredCachedRows);
+ const filteredLocalIds = idSet(filteredLocalRows);
+ return (
+ resolveDownloadedId(
+ selectedId,
+ cachedById,
+ localById,
+ filteredCachedIds,
+ filteredLocalIds,
+ localRows,
+ ) ??
+ resolveDownloadedId(
+ filteredCachedRows[0]?.id ?? null,
+ cachedById,
+ localById,
+ filteredCachedIds,
+ filteredLocalIds,
+ localRows,
+ ) ??
+ resolveDownloadedId(
+ filteredLocalRows[0]?.id ?? null,
+ cachedById,
+ localById,
+ filteredCachedIds,
+ filteredLocalIds,
+ localRows,
+ ) ?? { selectedId: null, hiddenByFilters: false }
+ );
+}
diff --git a/studio/frontend/src/features/hub/lib/token-fingerprint.ts b/studio/frontend/src/features/hub/lib/token-fingerprint.ts
new file mode 100644
index 00000000000..316ac6ea24b
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/token-fingerprint.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
+
+export function fingerprintToken(token?: string | null): string {
+ if (!token) return "anon";
+ let h1 = 0x811c9dc5;
+ let h2 = 0;
+ for (let i = 0; i < token.length; i++) {
+ const c = token.charCodeAt(i);
+ h1 = Math.imul(h1 ^ c, 0x01000193);
+ h2 = (Math.imul(h2, 33) + c) | 0;
+ }
+ return (
+ (h1 >>> 0).toString(16).padStart(8, "0") +
+ (h2 >>> 0).toString(16).padStart(8, "0")
+ );
+}
diff --git a/studio/frontend/src/features/hub/lib/unsloth-support.ts b/studio/frontend/src/features/hub/lib/unsloth-support.ts
new file mode 100644
index 00000000000..45e913b2b9c
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/unsloth-support.ts
@@ -0,0 +1,232 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+const EXCLUDED_TAGS_GPU = new Set([
+ "gptq",
+ "awq",
+ "exl2",
+ "mlx",
+ "onnx",
+ "openvino",
+ "coreml",
+ "tflite",
+ "ctranslate2",
+]);
+
+const EXCLUDED_TAGS_MLX = new Set([
+ "gptq",
+ "awq",
+ "exl2",
+ "onnx",
+ "openvino",
+ "coreml",
+ "tflite",
+ "ctranslate2",
+]);
+
+const UNSUPPORTED_PIPELINE_TAGS: ReadonlySet<string> = new Set([
+ "text-to-image",
+ "image-to-image",
+ "image-text-to-image",
+ "text-to-video",
+ "video-to-video",
+ "image-to-video",
+ "video-text-to-text",
+ "video-classification",
+ "unconditional-image-generation",
+ "text-to-3d",
+ "image-to-3d",
+ "image-segmentation",
+ "object-detection",
+ "depth-estimation",
+ "mask-generation",
+ "zero-shot-image-classification",
+ "zero-shot-object-detection",
+ "image-classification",
+ "keypoint-detection",
+ "image-feature-extraction",
+ "robotics",
+ "reinforcement-learning",
+ "graph-ml",
+ "tabular-classification",
+ "tabular-regression",
+ "time-series-forecasting",
+]);
+
+const UNSUPPORTED_LIBRARY_TAGS: ReadonlySet<string> = new Set([
+ "diffusers",
+ "stable-diffusion",
+ "stable-diffusion-xl",
+ "flux",
+ "controlnet",
+ "lora-diffusers",
+]);
+
+const FORMAT_TAG_LABEL: Record<string, string> = {
+ gptq: "GPTQ quantization",
+ awq: "AWQ quantization",
+ exl2: "EXL2 quantization",
+ mlx: "MLX-format weights",
+ onnx: "ONNX-format weights",
+ openvino: "OpenVINO-format weights",
+ coreml: "Core ML-format weights",
+ tflite: "TensorFlow Lite-format weights",
+ ctranslate2: "CTranslate2-format weights",
+};
+
+const FORMAT_ALIAS_TAGS: Record<string, string> = {
+ "auto-gptq": "gptq",
+};
+
+const FORMAT_NAME_PATTERNS: ReadonlyArray<{ key: string; pattern: RegExp }> = [
+ { key: "awq", pattern: /(?:^|[-_./])awq(?:\d+(?:bit)?)?(?:$|[-_./])/i },
+ { key: "gptq", pattern: /(?:^|[-_./])gptq(?:\d+(?:bit)?)?(?:$|[-_./])/i },
+ { key: "exl2", pattern: /(?:^|[-_./])exl2(?:$|[-_./])/i },
+ { key: "mlx", pattern: /(?:^|[-_./])mlx(?:$|[-_./])/i },
+ { key: "onnx", pattern: /(?:^|[-_./])onnx(?:$|[-_./])/i },
+ { key: "openvino", pattern: /(?:^|[-_./])openvino(?:$|[-_./])/i },
+ { key: "coreml", pattern: /(?:^|[-_./])coreml(?:$|[-_./])/i },
+ { key: "tflite", pattern: /(?:^|[-_./])tflite(?:$|[-_./])/i },
+ { key: "ctranslate2", pattern: /(?:^|[-_./])ctranslate2(?:$|[-_./])/i },
+];
+
+const SUPPORTED_QUANT_METHODS: ReadonlySet<string> = new Set([
+ "bitsandbytes",
+ "bnb",
+ "bnb_4bit",
+ "bnb_8bit",
+]);
+
+const UNSUPPORTED_QUANT_METHODS: Record<string, string> = {
+ awq: "AWQ quantization",
+ gptq: "GPTQ quantization",
+ exl2: "EXL2 quantization",
+ "compressed-tensors": "compressed-tensors quantization",
+ aqlm: "AQLM quantization",
+ eetq: "EETQ quantization",
+ hqq: "HQQ quantization",
+ fbgemm_fp8: "FBGEMM FP8 quantization",
+ finegrained_fp8: "fine-grained FP8 quantization",
+ quark: "Quark quantization",
+ vptq: "VPTQ quantization",
+ spqr: "SpQR quantization",
+ higgs: "HIGGS quantization",
+ sinq: "SINQ quantization",
+ torchao: "torchao quantization",
+ quanto: "optimum-quanto quantization",
+ auto_round: "AutoRound quantization",
+ autoround: "AutoRound quantization",
+ metal: "Metal-kernel quantization",
+ fouroversix: "Four Over Six quantization",
+ fp_quant: "FP-Quant quantization",
+};
+
+export type UnslothSupportStatus = "supported" | "unsupported";
+
+export interface UnslothSupport {
+ status: UnslothSupportStatus;
+ reason: string | null;
+}
+
+export function excludedFormatTagsForDevice(
+ deviceType?: string | null,
+): ReadonlySet<string> {
+ return deviceType?.toLowerCase() === "mac"
+ ? EXCLUDED_TAGS_MLX
+ : EXCLUDED_TAGS_GPU;
+}
+
+function normalizeQuantMethod(value: string | null | undefined): string | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.toLowerCase().trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function repoLeaf(modelId: string): string {
+ const parts = modelId.trim().split("/").filter(Boolean);
+ return parts.at(-1) ?? modelId;
+}
+
+function detectFormatKey(
+ modelId: string | null | undefined,
+ lowerTags: ReadonlySet<string>,
+): string | null {
+ for (const tag of lowerTags) {
+ if (FORMAT_TAG_LABEL[tag]) return tag;
+ const alias = FORMAT_ALIAS_TAGS[tag];
+ if (alias) return alias;
+ }
+ if (modelId) {
+ const name = repoLeaf(modelId);
+ for (const { key, pattern } of FORMAT_NAME_PATTERNS) {
+ if (pattern.test(name)) return key;
+ }
+ }
+ return null;
+}
+
+export function classifyUnslothSupport({
+ modelId,
+ pipelineTag,
+ tags,
+ libraryName,
+ deviceType,
+ quantMethod,
+}: {
+ modelId?: string | null;
+ pipelineTag?: string | null;
+ tags?: readonly string[] | null;
+ libraryName?: string | null;
+ deviceType?: string | null;
+ quantMethod?: string | null;
+}): UnslothSupport {
+ const pipeline = pipelineTag?.toLowerCase().trim() || null;
+ const lowerTags = new Set(
+ (tags ?? []).map((tag) => tag.toLowerCase().trim()).filter(Boolean),
+ );
+ const library = libraryName?.toLowerCase().trim() || null;
+ const formatTags = excludedFormatTagsForDevice(deviceType);
+ const normalizedQuant = normalizeQuantMethod(quantMethod);
+
+ if (normalizedQuant) {
+ if (SUPPORTED_QUANT_METHODS.has(normalizedQuant)) {
+ return { status: "supported", reason: null };
+ }
+ if (Object.hasOwn(UNSUPPORTED_QUANT_METHODS, normalizedQuant)) {
+ return {
+ status: "unsupported",
+ reason: `Detected ${UNSUPPORTED_QUANT_METHODS[normalizedQuant]}.`,
+ };
+ }
+ }
+
+ if (pipeline && UNSUPPORTED_PIPELINE_TAGS.has(pipeline)) {
+ return {
+ status: "unsupported",
+ reason: `Pipeline task: ${pipeline}.`,
+ };
+ }
+ for (const tag of lowerTags) {
+ if (UNSUPPORTED_LIBRARY_TAGS.has(tag)) {
+ return {
+ status: "unsupported",
+ reason: `Library: ${tag}.`,
+ };
+ }
+ }
+ if (library && UNSUPPORTED_LIBRARY_TAGS.has(library)) {
+ return {
+ status: "unsupported",
+ reason: `Library: ${library}.`,
+ };
+ }
+ const formatKey = detectFormatKey(modelId, lowerTags);
+ if (formatKey && formatTags.has(formatKey)) {
+ const label = FORMAT_TAG_LABEL[formatKey] ?? `${formatKey.toUpperCase()} weights`;
+ return {
+ status: "unsupported",
+ reason: `Detected ${label}.`,
+ };
+ }
+ return { status: "supported", reason: null };
+}
diff --git a/studio/frontend/src/features/hub/lib/view-models.ts b/studio/frontend/src/features/hub/lib/view-models.ts
new file mode 100644
index 00000000000..6fc06a6e973
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/view-models.ts
@@ -0,0 +1,189 @@
+// 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 { HfModelResult } from "@/features/hub/hooks/use-hub-model-search";
+import { resolveInventoryResource } from "@/features/hub/inventory/resource-resolver";
+import type {
+ CachedInventoryRow,
+ LocalInventoryRow,
+} from "@/features/hub/inventory/types";
+import type {
+ CapabilityFilter,
+ DiscoverRow,
+ ModelFormatFilter,
+} from "../types";
+import {
+ detectCapabilities,
+ type CapabilityKey,
+} from "./model-capabilities";
+import { ownerOf, repoOf } from "@/features/hub/lib/format";
+import { estimateSizeFromDtypes, isGgufLike } from "./hf-model-meta";
+export { matchesFormat } from "./format-filters";
+export {
+ formatLocalUpdated,
+ localSourceLabel,
+} from "@/features/hub/inventory";
+export { isGgufLike } from "./hf-model-meta";
+
+export const CAPABILITY_FILTER_OPTIONS: ReadonlyArray<{
+ value: CapabilityFilter;
+ label: string;
+}> = [
+ { value: "all", label: "All capabilities" },
+ { value: "reasoning", label: "Reasoning" },
+ { value: "code", label: "Code" },
+ { value: "vision", label: "Vision" },
+ { value: "audio", label: "Audio" },
+ { value: "tools", label: "Tools" },
+ { value: "embedding", label: "Embeddings" },
+ { value: "multilingual", label: "Multilingual" },
+];
+
+export const FORMAT_FILTER_OPTIONS: ReadonlyArray<{
+ value: ModelFormatFilter;
+ label: string;
+}> = [
+ { value: "all", label: "All formats" },
+ { value: "gguf", label: "GGUF" },
+ { value: "checkpoint", label: "Checkpoints" },
+];
+
+export function formatPipelineTag(tag: string | undefined): string | null {
+ if (!tag) return null;
+ return tag
+ .split(/[-_]/)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(" ");
+}
+
+export function formatLibrary(name: string | undefined): string | null {
+ if (!name) return null;
+ if (name === "transformers") return "Transformers";
+ return name;
+}
+
+export function buildSummary(result: HfModelResult): string {
+ const parts: string[] = [];
+ const pipeline = formatPipelineTag(result.pipelineTag);
+ if (pipeline) parts.push(pipeline);
+ if (result.totalParams) parts.push(`${compactNumber(result.totalParams)} params`);
+ if (result.isGguf) {
+ parts.push("GGUF");
+ } else {
+ const library = formatLibrary(result.libraryName);
+ if (library) parts.push(library);
+ }
+ return parts.join(" · ") || "Hugging Face model";
+}
+
+function compactNumber(value: number): string {
+ return new Intl.NumberFormat("en", {
+ notation: "compact",
+ maximumFractionDigits: value < 10 ? 1 : 0,
+ }).format(value);
+}
+
+function finiteNumber(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
+}
+
+export function toHfModelResult(raw: unknown): HfModelResult | null {
+ if (!raw || typeof raw !== "object") {
+ return null;
+ }
+
+ const model = raw as {
+ name?: string;
+ downloads?: number;
+ likes?: number;
+ task?: string;
+ pipeline_tag?: string;
+ library_name?: string;
+ updatedAt?: Date | string;
+ safetensors?: { total?: number; parameters?: Record<string, number> };
+ gguf?: { total?: number; architecture?: string };
+ tags?: string[];
+ config?: { quantization_config?: { quant_method?: string } };
+ };
+
+ if (!model.name) return null;
+
+ const isGguf =
+ Boolean(model.tags?.some((tag) => tag.toLowerCase() === "gguf")) ||
+ isGgufLike(model.name);
+ const updatedAt =
+ model.updatedAt instanceof Date
+ ? model.updatedAt.toISOString()
+ : typeof model.updatedAt === "string"
+ ? model.updatedAt
+ : undefined;
+
+ return {
+ id: model.name,
+ downloads: finiteNumber(model.downloads) ?? 0,
+ likes: finiteNumber(model.likes) ?? 0,
+ totalParams:
+ finiteNumber(model.safetensors?.total) ?? finiteNumber(model.gguf?.total),
+ estimatedSizeBytes: estimateSizeFromDtypes(model.safetensors?.parameters),
+ isGguf,
+ tags: model.tags,
+ pipelineTag: model.task ?? model.pipeline_tag,
+ updatedAt,
+ libraryName: model.library_name,
+ quantMethod: model.config?.quantization_config?.quant_method,
+ };
+}
+
+export function buildDiscoverRows(
+ results: HfModelResult[],
+ cachedRows: CachedInventoryRow[],
+ localRows: LocalInventoryRow[],
+): DiscoverRow[] {
+ return results.map((result) => {
+ const resource = resolveInventoryResource({
+ repoId: result.id,
+ cachedRows,
+ localRows,
+ formatHint: result.isGguf ? "gguf" : "non-gguf",
+ });
+ const partial = Boolean(
+ resource.cachedRow?.partial ?? resource.localRow?.partial ?? false,
+ );
+ return {
+ id: result.id,
+ owner: ownerOf(result.id),
+ repo: repoOf(result.id),
+ result,
+ isAvailableOnDevice: Boolean(resource.cachedRow || resource.localRow),
+ isPartialOnDevice: partial,
+ summary: buildSummary(result),
+ capabilities: detectCapabilities(
+ result.tags,
+ result.pipelineTag,
+ result.id,
+ ),
+ };
+ });
+}
+
+export function matchesCapability(
+ capabilities: Array<{ key: CapabilityKey }>,
+ capabilityFilter: CapabilityFilter,
+): boolean {
+ if (capabilityFilter === "all") return true;
+ return capabilities.some((capability) => capability.key === capabilityFilter);
+}
+
+const LANGUAGE_TAG_PREFIX = "language:";
+
+export function parseLanguageTags(
+ tags: readonly string[] | null | undefined,
+): string[] {
+ const langs: string[] = [];
+ for (const tag of tags ?? []) {
+ if (!tag.startsWith(LANGUAGE_TAG_PREFIX)) continue;
+ const code = tag.slice(LANGUAGE_TAG_PREFIX.length);
+ if (code && !langs.includes(code)) langs.push(code);
+ }
+ return langs;
+}
diff --git a/studio/frontend/src/features/hub/stores/external-link-confirm.ts b/studio/frontend/src/features/hub/stores/external-link-confirm.ts
new file mode 100644
index 00000000000..bcd3980362a
--- /dev/null
+++ b/studio/frontend/src/features/hub/stores/external-link-confirm.ts
@@ -0,0 +1,31 @@
+// 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 { create } from "zustand";
+
+interface ExternalLinkConfirmStore {
+ pendingUrl: string | null;
+ request: (url: string) => void;
+ dismiss: () => void;
+}
+
+export const useExternalLinkConfirm = create<ExternalLinkConfirmStore>((set) => ({
+ pendingUrl: null,
+ request: (url) => set({ pendingUrl: url }),
+ dismiss: () => set({ pendingUrl: null }),
+}));
+
+export function confirmExternalLink(url: string): boolean {
+ const trimmed = url?.trim() ?? "";
+ if (!trimmed || trimmed.startsWith("#")) return false;
+ const lower = trimmed.toLowerCase();
+ if (
+ !lower.includes("://") &&
+ !lower.startsWith("//") &&
+ !lower.startsWith("mailto:")
+ ) {
+ return false;
+ }
+ useExternalLinkConfirm.getState().request(trimmed);
+ return true;
+}
diff --git a/studio/frontend/src/features/hub/stores/hf-token-store.ts b/studio/frontend/src/features/hub/stores/hf-token-store.ts
new file mode 100644
index 00000000000..c63aa82ad45
--- /dev/null
+++ b/studio/frontend/src/features/hub/stores/hf-token-store.ts
@@ -0,0 +1,118 @@
+// 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 { create } from "zustand";
+import { bumpInventoryVersion } from "./inventory-events";
+
+const HF_TOKEN_KEY = "unsloth_hf_token";
+const HF_TOKEN_CHANGED_EVENT = "unsloth:hf-token-changed";
+const LEGACY_TRAINING_KEY = "unsloth_training_config_v1";
+let storageSyncStarted = false;
+let storageSyncListener: ((event: StorageEvent) => void) | null = null;
+let tokenChangedListener: ((event: Event) => void) | null = null;
+
+function canUseStorage(): boolean {
+ return typeof window !== "undefined";
+}
+
+function loadInitial(): string {
+ if (!canUseStorage()) return "";
+ try {
+ const direct = window.localStorage.getItem(HF_TOKEN_KEY);
+ if (direct !== null) {
+ const normalized = normalize(direct);
+ if (normalized !== direct) persist(normalized);
+ return normalized;
+ }
+ const legacy = window.localStorage.getItem(LEGACY_TRAINING_KEY);
+ if (legacy) {
+ const parsed = JSON.parse(legacy) as {
+ state?: Record<string, unknown>;
+ [key: string]: unknown;
+ };
+ const fromTraining = parsed?.state?.hfToken;
+ if (typeof fromTraining === "string" && fromTraining.length > 0) {
+ const normalized = normalize(fromTraining);
+ // Copy only: training-config-store still reads its own hfToken, so deleting it would drop that token.
+ persist(normalized);
+ return normalized;
+ }
+ }
+ } catch {
+ return "";
+ }
+ return "";
+}
+
+function persist(value: string): void {
+ if (!canUseStorage()) return;
+ try {
+ window.localStorage.setItem(HF_TOKEN_KEY, value);
+ } catch {
+ void 0;
+ }
+}
+
+function normalize(raw: string): string {
+ return raw.replace(/^[\s"']+|[\s"']+$/g, "");
+}
+
+function stopStorageSync(): void {
+ if (!canUseStorage()) return;
+ if (storageSyncListener !== null) {
+ window.removeEventListener("storage", storageSyncListener);
+ storageSyncListener = null;
+ }
+ if (tokenChangedListener !== null) {
+ window.removeEventListener(HF_TOKEN_CHANGED_EVENT, tokenChangedListener);
+ tokenChangedListener = null;
+ }
+ storageSyncStarted = false;
+}
+
+if (import.meta.hot) {
+ import.meta.hot.dispose(stopStorageSync);
+}
+
+interface HfTokenStore {
+ token: string;
+ setToken: (value: string) => void;
+ clearToken: () => void;
+}
+
+export const useHfTokenStore = create<HfTokenStore>((set) => {
+ const applyToken = (value: string, shouldPersist: boolean) => {
+ const next = normalize(value);
+ if (shouldPersist || next !== value) persist(next);
+ let changed = false;
+ set((state) => {
+ if (state.token === next) return state;
+ changed = true;
+ return { token: next };
+ });
+ if (changed) bumpInventoryVersion();
+ };
+
+ if (!storageSyncStarted && canUseStorage()) {
+ storageSyncStarted = true;
+ storageSyncListener = (event) => {
+ if (event.key !== HF_TOKEN_KEY) return;
+ applyToken(event.newValue ?? "", false);
+ };
+ window.addEventListener("storage", storageSyncListener);
+ tokenChangedListener = (event) => {
+ applyToken((event as CustomEvent<string>).detail ?? "", false);
+ };
+ window.addEventListener(HF_TOKEN_CHANGED_EVENT, tokenChangedListener);
+ }
+
+ return {
+ token: loadInitial(),
+ setToken: (value) => applyToken(value, true),
+ clearToken: () => applyToken("", true),
+ };
+});
+
+export function getHfToken(): string {
+ return useHfTokenStore.getState().token;
+}
diff --git a/studio/frontend/src/features/hub/stores/inventory-events.ts b/studio/frontend/src/features/hub/stores/inventory-events.ts
new file mode 100644
index 00000000000..c47c0407caf
--- /dev/null
+++ b/studio/frontend/src/features/hub/stores/inventory-events.ts
@@ -0,0 +1,143 @@
+// 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 { useSyncExternalStore } from "react";
+
+type Listener = () => void;
+
+const CHANNEL_NAME = "unsloth.inventory";
+const STORAGE_KEY = "unsloth.inventory.bump";
+const OUTBOUND_CHANNEL_CLOSE_DELAY_MS = 250;
+
+let _version = 0;
+const listeners = new Set<Listener>();
+const seenBumps = new Set<string>();
+const seenBumpOrder: string[] = [];
+let crossTabReady = false;
+let channel: BroadcastChannel | null = null;
+let outboundChannel: BroadcastChannel | null = null;
+let outboundCloseTimer: ReturnType<typeof setTimeout> | null = null;
+let storageHandler: ((event: StorageEvent) => void) | null = null;
+
+function emitInventoryChange(): void {
+ for (const fn of [...listeners]) fn();
+}
+
+function rememberBump(id: string): boolean {
+ if (seenBumps.has(id)) return false;
+ seenBumps.add(id);
+ seenBumpOrder.push(id);
+ while (seenBumpOrder.length > 32) {
+ const oldest = seenBumpOrder.shift();
+ if (oldest) seenBumps.delete(oldest);
+ }
+ return true;
+}
+
+function applyInventoryBump(): void {
+ _version += 1;
+ emitInventoryChange();
+}
+
+function ensureCrossTabSync(): void {
+ if (crossTabReady || typeof window === "undefined") return;
+ crossTabReady = true;
+ if (typeof BroadcastChannel !== "undefined") {
+ channel = new BroadcastChannel(CHANNEL_NAME);
+ channel.onmessage = (event) => {
+ if (typeof event.data !== "string") return;
+ if (!rememberBump(event.data)) return;
+ applyInventoryBump();
+ };
+ }
+ storageHandler = (event) => {
+ if (event.key !== STORAGE_KEY || typeof event.newValue !== "string") return;
+ if (!rememberBump(event.newValue)) return;
+ applyInventoryBump();
+ };
+ window.addEventListener("storage", storageHandler);
+ try {
+ const current = window.localStorage.getItem(STORAGE_KEY);
+ if (typeof current === "string") rememberBump(current);
+ } catch {
+ void 0;
+ }
+}
+
+function stopCrossTabSync(): void {
+ if (!crossTabReady) return;
+ channel?.close();
+ channel = null;
+ if (storageHandler && typeof window !== "undefined") {
+ window.removeEventListener("storage", storageHandler);
+ }
+ storageHandler = null;
+ crossTabReady = false;
+}
+
+function closeOutboundChannel(): void {
+ outboundCloseTimer = null;
+ outboundChannel?.close();
+ outboundChannel = null;
+}
+
+function getOutboundChannel(): BroadcastChannel | null {
+ if (typeof BroadcastChannel === "undefined") {
+ return null;
+ }
+ if (!outboundChannel) {
+ outboundChannel = new BroadcastChannel(CHANNEL_NAME);
+ }
+ if (outboundCloseTimer !== null) {
+ clearTimeout(outboundCloseTimer);
+ }
+ outboundCloseTimer = setTimeout(
+ closeOutboundChannel,
+ OUTBOUND_CHANNEL_CLOSE_DELAY_MS,
+ );
+ return outboundChannel;
+}
+
+function postInventoryBump(id: string): void {
+ const target = channel ?? getOutboundChannel();
+ target?.postMessage(id);
+ try {
+ window.localStorage.setItem(STORAGE_KEY, id);
+ } catch {
+ void 0;
+ }
+}
+
+export function getInventoryVersion(): number {
+ return _version;
+}
+
+export function bumpInventoryVersion(): void {
+ const id =
+ typeof window === "undefined"
+ ? null
+ : `${Date.now()}:${Math.random().toString(36).slice(2)}`;
+ if (id) rememberBump(id);
+ applyInventoryBump();
+ if (!id) return;
+ postInventoryBump(id);
+}
+
+export function subscribeInventory(listener: Listener): () => void {
+ listeners.add(listener);
+ ensureCrossTabSync();
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) {
+ stopCrossTabSync();
+ }
+ };
+}
+
+export function useInventoryVersion(): number {
+ return useSyncExternalStore(
+ subscribeInventory,
+ getInventoryVersion,
+ getInventoryVersion,
+ );
+}
diff --git a/studio/frontend/src/features/hub/types.ts b/studio/frontend/src/features/hub/types.ts
new file mode 100644
index 00000000000..f2aa412f649
--- /dev/null
+++ b/studio/frontend/src/features/hub/types.ts
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type {
+ BaseModelSource,
+ LocalSource,
+ ModelInventoryCapabilities,
+ ModelInventoryFormat,
+} from "@/features/hub/inventory";
+import type { HfModelResult } from "@/features/hub/hooks/use-hub-model-search";
+import type { Capability, CapabilityKey } from "./lib/model-capabilities";
+
+export type {
+ CachedInventoryRow,
+ InventoryHint,
+ InventoryRow,
+ LocalInventoryRow,
+ LocalSource,
+} from "@/features/hub/inventory";
+
+export type ModelsTab = "discover" | "downloaded";
+
+export type ResourceTypeFilter = "models" | "datasets";
+
+export type HubModelType = "text" | "vision" | "audio" | "embeddings";
+
+export type ModelFormatFilter = "all" | "gguf" | "checkpoint";
+
+export type CapabilityFilter = "all" | CapabilityKey;
+
+export interface DiscoverRow {
+ id: string;
+ owner: string;
+ repo: string;
+ result: HfModelResult;
+ isAvailableOnDevice: boolean;
+ isPartialOnDevice: boolean;
+ summary: string;
+ capabilities: Capability[];
+}
+
+export type SelectedResourceSource = "huggingface" | "hub_cache" | LocalSource;
+
+export type SelectedResourceCacheState =
+ | "remote"
+ | "cached"
+ | "local"
+ | "partial";
+
+export interface SelectedResourceRef {
+ repoId: string | null;
+ localPath: string | null;
+ source: SelectedResourceSource;
+ cacheState: SelectedResourceCacheState;
+ runId: string;
+ trainId: string;
+}
+
+export interface SelectedModelView {
+ id: string;
+ kind: "discover" | "cache" | "local";
+ resource: SelectedResourceRef;
+ displayId: string;
+ hubRepoId: string | null;
+ owner: string;
+ title: string;
+ summary: string;
+ sourceLabel: string;
+ path: string | null;
+ localSource?: LocalSource;
+ isLocal: boolean;
+ isGguf: boolean;
+ requiresVariant?: boolean;
+ modelFormat: ModelInventoryFormat | null;
+ baseModel?: string | null;
+ baseModelSource?: BaseModelSource | null;
+ baseModelHubId?: string | null;
+ baseModelSummary?: string | null;
+ adapterType?: string | null;
+ trainingMethod?: string | null;
+ isDownloaded: boolean;
+ isPartial?: boolean;
+ partialTransport?: string | null;
+ runtimeCapabilities?: ModelInventoryCapabilities;
+ capabilities: Capability[];
+ license: string | null;
+ pipelineTag?: string;
+ libraryName?: string;
+ downloads?: number;
+ likes?: number;
+ totalParams?: number;
+ estimatedSizeBytes?: number;
+ cachedBytes?: number;
+ updatedAt?: string;
+ localUpdatedAt?: number | null;
+ tags?: string[];
+ quantMethod?: string;
+}
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 83a04b60c12..45c1fabe726 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -34,6 +34,7 @@ export const en = {
newChat: "New Chat",
compare: "Compare",
search: "Search",
+ hub: "Hub",
train: "Train",
recipes: "Recipes",
export: "Export",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index f7075eb887f..3cfea1ae7a5 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -34,6 +34,7 @@ export const zhCN = {
newChat: "新聊天",
compare: "对比",
search: "搜索",
+ hub: "Hub",
train: "训练",
recipes: "配方",
export: "导出",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 68993d4a65a..521fe28190f 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -5,6 +5,7 @@
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "streamdown/styles.css";
+@import "./features/hub/hub.css";
@import "@fontsource-variable/figtree";
@import "@fontsource-variable/space-grotesk";
@import "@fontsource-variable/inter";
diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.json
index d4d706cc145..44fccaa447a 100644
--- a/studio/src-tauri/tauri.conf.json
+++ b/studio/src-tauri/tauri.conf.json
@@ -16,7 +16,7 @@
"app": {
"withGlobalTauri": true,
"security": {
- "csp": "default-src 'self'; connect-src 'self' http://localhost:* ws://localhost:* ws://127.0.0.1:* http://127.0.0.1:* https://huggingface.co https://*.huggingface.co https://datasets-server.huggingface.co; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:"
+ "csp": "default-src 'self'; connect-src 'self' http://localhost:* ws://localhost:* ws://127.0.0.1:* http://127.0.0.1:* https://huggingface.co https://*.huggingface.co https://datasets-server.huggingface.co; img-src 'self' data: blob: https:; media-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:"
},
"windows": [
{