Skip to content

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

Studio: redesign Select model dropdown to match Hub design (#6364)

Michael Han44d6727c6559
diff --git a/studio/backend/models/models.py b/studio/backend/models/models.py
index d1ef368eaec..20dea5ec128 100644
--- a/studio/backend/models/models.py
+++ b/studio/backend/models/models.py
@@ -154,6 +154,10 @@ class GgufVariantsResponse(BaseModel):
default_variant: Optional[str] = Field(
None, description = "Recommended default quantization variant"
)
+ context_length: Optional[int] = Field(
+ None,
+ description = "Native max context from GGUF metadata; set once a variant is downloaded",
+ )
class LocalModelInfo(BaseModel):
@@ -170,6 +174,11 @@ class LocalModelInfo(BaseModel):
None,
description = "HF repo id for cached models, e.g. org/model",
)
+ model_format: Optional[str] = Field(
+ None,
+ description = "Detected weights format ('gguf' when known). Lets the UI "
+ "classify scanned folders whose name lacks a -GGUF suffix.",
+ )
updated_at: Optional[float] = Field(
None,
description = "Unix timestamp of latest observed update",
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 1e567774ac0..14fb5e234c4 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -225,6 +225,29 @@ def _is_model_directory(d: Path) -> bool:
return False
+# Weight ``.bin`` files the local scanners accept (PyTorch checkpoints), as
+# opposed to companion ``.bin`` files like ``tokenizer.bin``. Mirrors the gating
+# in ``_is_weight_file`` so every weight check classifies the same files.
+_WEIGHT_BIN_PREFIXES = ("pytorch_model", "model", "adapter_model", "consolidated")
+
+
+def _is_weight_bin(name: str) -> bool:
+ low = name.lower()
+ return low.endswith(".bin") and low.startswith(_WEIGHT_BIN_PREFIXES)
+
+
+def _has_non_gguf_weights(path: Path) -> bool:
+ """True if *path* holds non-GGUF weight files (``.safetensors`` or a weight
+ ``.bin``), ignoring companion ``.bin`` files such as ``tokenizer.bin`` so a
+ GGUF-only folder is not misread as a plain checkpoint."""
+ try:
+ if any(path.glob("*.safetensors")):
+ return True
+ return any(_is_weight_bin(f.name) for f in path.glob("*.bin"))
+ except OSError:
+ return False
+
+
def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[LocalModelInfo]:
if not models_dir.exists() or not models_dir.is_dir():
return []
@@ -242,6 +265,7 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Loca
display_name = models_dir.name,
path = str(models_dir),
source = "models_dir",
+ model_format = _dir_model_format(models_dir),
updated_at = updated_at,
),
]
@@ -253,13 +277,12 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Loca
try:
if not child.is_dir():
continue
- has_model_files = (
- (child / "config.json").exists()
- or (child / "adapter_config.json").exists()
- or any(child.glob("*.safetensors"))
- or any(child.glob("*.bin"))
- or any(child.glob("*.gguf"))
- )
+ has_gguf = any(child.glob("*.gguf"))
+ has_non_gguf_weights = _has_non_gguf_weights(child)
+ has_config = (child / "config.json").exists() or (
+ child / "adapter_config.json"
+ ).exists()
+ has_model_files = has_gguf or has_non_gguf_weights or has_config
except OSError:
# Skip unreadable children rather than failing the scan.
continue
@@ -269,12 +292,17 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Loca
updated_at = child.stat().st_mtime
except OSError:
updated_at = None
+ # A folder whose only weights are .gguf is GGUF-format even when it also
+ # ships a config.json (common for HF GGUF repos); such folders often lack
+ # a -GGUF suffix, so surface the format for the UI's GGUF classification.
+ model_format = "gguf" if has_gguf and not has_non_gguf_weights else None
found.append(
LocalModelInfo(
id = str(child),
display_name = child.name,
path = str(child),
source = "models_dir",
+ model_format = model_format,
updated_at = updated_at,
),
)
@@ -294,6 +322,7 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Loca
display_name = gguf_file.stem,
path = str(gguf_file),
source = "models_dir",
+ model_format = "gguf",
updated_at = updated_at,
),
)
@@ -333,6 +362,21 @@ def _scan_hf_cache(cache_dir: Path) -> List[LocalModelInfo]:
return found
+def _dir_model_format(path: Path) -> Optional[str]:
+ """Return ``"gguf"`` for a directory whose only weights are ``.gguf`` files.
+
+ LM Studio and custom GGUF folders frequently lack a ``-GGUF`` name suffix,
+ so the UI relies on this hint to route them through the GGUF load path
+ rather than treating them as plain local checkpoints.
+ """
+ try:
+ if not any(path.glob("*.gguf")):
+ return None
+ return None if _has_non_gguf_weights(path) else "gguf"
+ except OSError:
+ return None
+
+
def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
"""Scan an LM Studio models directory for model files.
@@ -355,6 +399,7 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
display_name = lm_dir.name,
path = str(lm_dir),
source = "lmstudio",
+ model_format = _dir_model_format(lm_dir),
updated_at = updated_at,
),
]
@@ -374,6 +419,7 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
display_name = child.stem,
path = str(child),
source = "lmstudio",
+ model_format = "gguf",
updated_at = updated_at,
),
)
@@ -392,6 +438,7 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
display_name = child.name,
path = str(child),
source = "lmstudio",
+ model_format = _dir_model_format(child),
updated_at = updated_at,
),
)
@@ -420,6 +467,7 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
display_name = model_dir.name,
path = str(model_dir),
source = "lmstudio",
+ model_format = _dir_model_format(model_dir),
updated_at = updated_at,
),
)
@@ -435,6 +483,7 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:
display_name = model_dir.stem,
path = str(model_dir),
source = "lmstudio",
+ model_format = "gguf",
updated_at = updated_at,
),
)
@@ -847,13 +896,88 @@ async def remove_scan_folder_endpoint(
return {"ok": True}
+def _dir_has_downloaded_model(directory: Path, max_entries: int = 4000) -> bool:
+ """True if *directory* actually holds a downloaded model.
+
+ Recommended-folder chips should only appear once the well-known dir
+ has real weights, not just an empty LM Studio/Ollama scaffold. Two
+ layouts: a GGUF/safetensors/PyTorch-bin weight file anywhere in the
+ tree (LM Studio, plain dirs) or the Ollama content-addressable store
+ (a non-empty ``manifests/`` beside ``blobs/``, whose blobs carry no
+ extension). Weight detection mirrors the local scanner so a folder the
+ chip leads to is one the scanner would actually surface a model from.
+ Bounded by *max_entries* so a huge tree can't stall the request.
+ """
+ # Ollama layout: each manifest is JSON referencing content-addressable
+ # blobs. A manifest file alone is not enough -- a failed or pruned pull
+ # leaves the manifest behind with its model blob missing, so we resolve the
+ # ``application/vnd.ollama.image.model`` layer to an on-disk blob before
+ # counting it, mirroring _scan_ollama_dir (which only surfaces a model once
+ # its blob resolves). Otherwise the chip leads to an empty picker.
+ visited = 0
+ manifests = directory / "manifests"
+ blobs = directory / "blobs"
+ try:
+ if _safe_is_dir(manifests) and _safe_is_dir(blobs):
+ for m in manifests.rglob("*"):
+ visited += 1
+ if visited > max_entries:
+ break
+ if not m.is_file():
+ continue
+ try:
+ manifest = json.loads(m.read_text())
+ except (json.JSONDecodeError, OSError, ValueError):
+ continue
+ for layer in manifest.get("layers") or []:
+ if layer.get("mediaType") != "application/vnd.ollama.image.model":
+ continue
+ digest = layer.get("digest", "")
+ if digest and (blobs / digest.replace(":", "-")).is_file():
+ return True
+ except OSError:
+ pass
+ # Generic weights: any GGUF/safetensors in a bounded BFS that skips hidden
+ # directories (``.git``/``.cache``/venvs). ``rglob`` walks in arbitrary order
+ # and counts every entry, so a large hidden subtree could exhaust the budget
+ # before reaching real weights and falsely report "no model".
+ queue = [directory]
+ visited = 0
+ while queue:
+ current = queue.pop(0)
+ try:
+ entries = list(current.iterdir())
+ except OSError:
+ continue
+ for entry in entries:
+ visited += 1
+ if visited > max_entries:
+ return False
+ try:
+ if entry.is_dir():
+ if not entry.name.startswith("."):
+ queue.append(entry)
+ else:
+ low = entry.name.lower()
+ if low.endswith((".gguf", ".safetensors")):
+ return True
+ # PyTorch checkpoints the scanner also accepts; gate by name
+ # so tokenizer.bin and friends don't count as weights.
+ if _is_weight_bin(entry.name):
+ return True
+ except OSError:
+ continue
+ return False
+
+
@router.get("/recommended-folders")
async def get_recommended_folders(current_subject: str = Depends(get_current_subject)):
- """Return well-known model directories that exist on this machine.
+ """Return well-known model directories that hold a downloaded model.
Lightweight alternative to ``browse-folders`` for the frontend's
- one-click "Recommended" chips; returns existing paths only (HF
- cache, LM Studio, Ollama, ``~/models``, etc.).
+ one-click "Recommended" chips. Only paths that actually contain
+ weights are returned, so an empty LM Studio/Ollama scaffold no longer
+ shows up as a suggestion.
"""
from utils.paths.storage_roots import lmstudio_model_dirs
@@ -869,7 +993,11 @@ async def get_recommended_folders(current_subject: str = Depends(get_current_sub
return
if resolved in seen:
return
- if _safe_is_dir(resolved) and os.access(resolved, os.R_OK | os.X_OK):
+ if (
+ _safe_is_dir(resolved)
+ and os.access(resolved, os.R_OK | os.X_OK)
+ and _dir_has_downloaded_model(Path(resolved))
+ ):
seen.add(resolved)
folders.append(resolved)
@@ -2270,6 +2398,170 @@ async def check_embedding_model(
)
+def _read_native_context_length(repo_id: str, is_local: bool) -> Optional[int]:
+ """Native max context from a downloaded GGUF for this repo, or None.
+
+ The value is identical across quants, so reading one non-mmproj shard's
+ header is enough. Only resolves once a file is on disk. Never raises.
+ """
+ try:
+ from utils.models.gguf_metadata import read_gguf_context_length
+ if is_local:
+ roots = [Path(repo_id)]
+ else:
+ from huggingface_hub import constants as hf_constants
+
+ if not _is_valid_repo_id(repo_id):
+ return None
+ cache_dir = Path(hf_constants.HF_HUB_CACHE)
+ target = f"models--{repo_id.replace('/', '--')}".lower()
+ roots = [e for e in cache_dir.iterdir() if e.name.lower() == target]
+
+ for root in roots:
+ for f in _iter_gguf_paths(root):
+ if _is_mmproj_filename(f.name):
+ continue
+ n = read_gguf_context_length(str(f))
+ if n:
+ return n
+ except Exception:
+ pass
+ return None
+
+
+def _resolve_quant_gguf(repo_id: str, quant: str, is_local: bool) -> tuple[Optional[str], int]:
+ """Primary shard path and total weight bytes for a downloaded quant, or
+ (None, 0). Metadata lives in shard 1, so the lexicographically first file of
+ the matching quant is returned. Scoped to one snapshot to avoid summing the
+ same quant across revisions; when several snapshots hold the quant the most
+ complete one (largest total) wins so a partial revision can't shadow it.
+ Mirrors list_local_gguf_variants: quant labels are read from the snapshot-
+ relative path (so layouts like ``BF16/model.gguf`` resolve) and MTP drafter
+ files are skipped (so a ``...-Q8_0-MTP.gguf`` drafter can't be picked as the
+ Q8_0 weights). Never raises.
+ """
+ try:
+ from utils.models.model_config import (
+ _extract_quant_label,
+ _is_big_endian_gguf_path,
+ _is_mtp_drafter,
+ )
+
+ if is_local:
+ roots = [Path(repo_id)]
+ else:
+ from huggingface_hub import constants as hf_constants
+
+ if not _is_valid_repo_id(repo_id):
+ return None, 0
+ cache_dir = Path(hf_constants.HF_HUB_CACHE)
+ target = f"models--{repo_id.replace('/', '--')}".lower()
+ roots = []
+ for entry in cache_dir.iterdir():
+ if entry.name.lower() == target:
+ snaps = entry / "snapshots"
+ if snaps.is_dir():
+ roots.extend(s for s in snaps.iterdir() if s.is_dir())
+
+ want = quant.lower().replace("-", "").replace("_", "")
+ best_total = 0
+ best_first: Optional[str] = None
+ for root in roots:
+ matches: list[tuple[str, Path]] = []
+ total = 0
+ for f in _iter_gguf_paths(root):
+ if _is_mmproj_filename(f.name):
+ continue
+ try:
+ rel = f.relative_to(root).as_posix()
+ except ValueError:
+ rel = f.name
+ if _is_mtp_drafter(rel):
+ continue
+ q = _extract_quant_label(rel)
+ if _is_big_endian_gguf_path(rel, q):
+ continue
+ if q.lower().replace("-", "").replace("_", "") != want:
+ continue
+ try:
+ total += f.stat().st_size
+ except OSError:
+ continue
+ matches.append((rel, f))
+ # Prefer the most complete snapshot so a partial older revision can't
+ # shadow a newer complete one and underestimate the weight bytes.
+ if matches and total > best_total:
+ matches.sort(key = lambda m: m[0])
+ best_total = total
+ best_first = str(matches[0][1])
+ if best_first is not None:
+ return best_first, best_total
+ except Exception:
+ pass
+ return None, 0
+
+
[email protected]("/kv-cache-estimate")
+async def get_kv_cache_estimate(
+ repo_id: str = Query(..., description = "HF repo ID or local path"),
+ quant: str = Query(..., description = "Quantization label (e.g. Q4_K_M)"),
+ n_ctx: int = Query(..., ge = 1, description = "Context length to size the KV cache for"),
+ cache_type_kv: Optional[str] = Query(None, description = "KV cache dtype (e.g. q8_0)"),
+ current_subject: str = Depends(get_current_subject),
+):
+ """Estimate KV cache + weight bytes for a downloaded GGUF at n_ctx.
+
+ Powers the load dialog's "exceeds memory" warning using the same
+ architecture-aware estimator as load. Best-effort: returns nulls when the
+ metadata is unavailable so the UI simply shows no warning.
+ """
+ null = {"kv_bytes": None, "weights_bytes": None, "native_context": None}
+ try:
+ from utils.models.model_config import is_local_path
+
+ is_local = is_local_path(repo_id)
+ path, weights_bytes = _resolve_quant_gguf(repo_id, quant, is_local)
+ if not path:
+ return null
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ be = LlamaCppBackend.__new__(LlamaCppBackend)
+ for attr in (
+ "_context_length",
+ "_n_layers",
+ "_n_kv_heads",
+ "_n_heads",
+ "_embedding_length",
+ "_kv_key_length",
+ "_kv_value_length",
+ "_kv_lora_rank",
+ "_sliding_window",
+ "_sliding_window_pattern",
+ "_ssm_inner_size",
+ "_full_attention_interval",
+ "_key_length_mla",
+ "_n_kv_heads_by_layer",
+ "_kv_key_length_swa",
+ "_kv_value_length_swa",
+ "_shared_kv_layers",
+ "_nextn_predict_layers",
+ ):
+ setattr(be, attr, None)
+ be._model_identifier = "kv-estimate"
+ be._read_gguf_metadata(path)
+
+ kv = be._estimate_kv_cache_bytes(n_ctx, cache_type_kv)
+ return {
+ "kv_bytes": int(kv) if kv else None,
+ "weights_bytes": weights_bytes or None,
+ "native_context": be._context_length,
+ }
+ except Exception as e:
+ logger.debug(f"kv-cache-estimate failed for '{repo_id}' {quant}: {e}")
+ return null
+
+
@router.get("/gguf-variants", response_model = GgufVariantsResponse)
async def get_gguf_variants(
repo_id: str = Query(
@@ -2307,6 +2599,7 @@ async def get_gguf_variants(
],
has_vision = has_vision,
default_variant = default_variant,
+ context_length = _read_native_context_length(repo_id, is_local = True),
)
# Remote HuggingFace repo — query HF API.
@@ -2375,6 +2668,7 @@ async def get_gguf_variants(
],
has_vision = has_vision,
default_variant = default_variant,
+ context_length = _read_native_context_length(repo_id, is_local = False),
)
except Exception as e:
@@ -2673,6 +2967,14 @@ def _is_main_gguf_filename(name: str) -> bool:
return _is_gguf_filename(name) and not _is_mmproj_filename(name)
+def _repo_has_mmproj(repo_info) -> bool:
+ """True if the repo ships a GGUF vision adapter (mmproj), so it can
+ take image inputs. Cheap: scans already-listed file names only."""
+ return any(
+ _is_mmproj_filename(f.file_name) for revision in repo_info.revisions for f in revision.files
+ )
+
+
def _iter_gguf_paths(root: Path):
for path in root.rglob("*"):
if path.is_file() and _is_gguf_filename(path.name):
@@ -2770,6 +3072,7 @@ async def list_cached_gguf(current_subject: str = Depends(get_current_subject)):
"repo_id": repo_id,
"size_bytes": total_size,
"cache_path": str(repo_info.repo_path),
+ "has_vision": _repo_has_mmproj(repo_info),
}
# Keep the newest timestamp across duplicate caches;
# attach only when known so absent rows sort as oldest.
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 03662e7b08e..b2ead305bae 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -82,6 +82,7 @@ def test_list_cached_gguf_includes_non_suffix_repo_when_cache_contains_gguf(monk
"repo_id": "HauhauCS/Gemma-4-E4B-Uncensored-HauhauCS-Aggressive",
"size_bytes": 5_000,
"cache_path": str(repo.repo_path),
+ "has_vision": False,
}
]
@@ -103,6 +104,7 @@ def test_list_cached_gguf_matches_extension_case_insensitively(monkeypatch, tmp_
"repo_id": "Org/Model-Without-Suffix",
"size_bytes": 7_000,
"cache_path": str(repo.repo_path),
+ "has_vision": False,
}
]
@@ -197,6 +199,7 @@ def test_list_cached_gguf_keeps_largest_duplicate_repo_across_scans(monkeypatch,
"repo_id": "org/dupe",
"size_bytes": 6_000,
"cache_path": str(larger.repo_path),
+ "has_vision": False,
}
]
@@ -226,6 +229,7 @@ def test_list_cached_gguf_dedupes_shared_blobs_across_revisions(monkeypatch, tmp
"repo_id": "Org/SharedBlobRepo",
"size_bytes": 5_000,
"cache_path": str(repo.repo_path),
+ "has_vision": False,
}
]
@@ -275,6 +279,7 @@ def test_list_cached_gguf_includes_mixed_repo_with_gguf_and_safetensors(monkeypa
"repo_id": "Org/MixedRepo",
"size_bytes": 5_000,
"cache_path": str(mixed.repo_path),
+ "has_vision": False,
}
]
@@ -301,6 +306,7 @@ def test_list_cached_gguf_handles_none_size_on_disk(monkeypatch, tmp_path):
"repo_id": "Org/PartialDownload",
"size_bytes": 5_000,
"cache_path": str(partial.repo_path),
+ "has_vision": False,
}
]
@@ -336,6 +342,7 @@ def test_list_cached_gguf_skips_malformed_repo_without_wiping_response(monkeypat
"repo_id": "Org/Healthy",
"size_bytes": 5_000,
"cache_path": str(healthy.repo_path),
+ "has_vision": False,
}
]
@@ -411,6 +418,7 @@ def test_list_cached_gguf_includes_vision_repo_with_main_gguf_and_mmproj(monkeyp
"repo_id": "Org/VisionGguf",
"size_bytes": 5_000,
"cache_path": str(vision_repo.repo_path),
+ "has_vision": True,
}
]
@@ -464,6 +472,7 @@ def test_all_hf_cache_scans_survives_inaccessible_aux_cache(monkeypatch, tmp_pat
"repo_id": "Org/Active",
"size_bytes": 5_000,
"cache_path": str(tmp_path / "active"),
+ "has_vision": False,
}
]
diff --git a/studio/backend/tests/test_local_model_format.py b/studio/backend/tests/test_local_model_format.py
new file mode 100644
index 00000000000..b569163cc8e
--- /dev/null
+++ b/studio/backend/tests/test_local_model_format.py
@@ -0,0 +1,117 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for local GGUF ``model_format`` classification (PR #6364 follow-up).
+
+Suffixless GGUF folders (custom folders / LM Studio) carry no ``-GGUF`` name
+hint, so the scanners must surface ``model_format = "gguf"`` for the UI to route
+them through the GGUF load path. The rule, shared by ``_dir_model_format`` and
+``_scan_models_dir``: a directory is GGUF-format when it holds ``.gguf`` files
+and no non-GGUF weights (``.safetensors`` / ``.bin``); a stray ``config.json``
+must not disqualify it.
+
+No GPU/network: only file names and sizes are inspected.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+from pathlib import Path
+
+# Keep runnable without optional logging deps (mirrors the sibling tests).
+if "structlog" not in sys.modules:
+
+ class _DummyLogger:
+ def __getattr__(self, _name):
+ return lambda *args, **kwargs: None
+
+ sys.modules["structlog"] = types.SimpleNamespace(
+ BoundLogger = _DummyLogger,
+ get_logger = lambda *args, **kwargs: _DummyLogger(),
+ )
+
+import routes.models as models_route
+
+
+def _touch(path: Path) -> Path:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(b"\0")
+ return path
+
+
+def test_dir_model_format_gguf_only(tmp_path):
+ d = tmp_path / "model"
+ _touch(d / "model-Q4_K_M.gguf")
+ assert models_route._dir_model_format(d) == "gguf"
+
+
+def test_dir_model_format_gguf_with_config_is_still_gguf(tmp_path):
+ # A config.json alongside the .gguf must not flip it to non-GGUF.
+ d = tmp_path / "model"
+ _touch(d / "config.json")
+ _touch(d / "model-Q4_K_M.gguf")
+ assert models_route._dir_model_format(d) == "gguf"
+
+
+def test_dir_model_format_mixed_weights_is_not_gguf(tmp_path):
+ # Real safetensors weights present -> not a GGUF folder.
+ d = tmp_path / "model"
+ _touch(d / "model.safetensors")
+ _touch(d / "model-Q4_K_M.gguf")
+ assert models_route._dir_model_format(d) is None
+
+
+def test_dir_model_format_no_gguf(tmp_path):
+ d = tmp_path / "model"
+ _touch(d / "config.json")
+ _touch(d / "model.safetensors")
+ assert models_route._dir_model_format(d) is None
+
+
+def test_dir_model_format_ignores_tokenizer_bin(tmp_path):
+ # A companion tokenizer.bin is not a weight file, so a GGUF folder shipping
+ # one is still GGUF (not misread as a plain .bin checkpoint).
+ d = tmp_path / "model"
+ _touch(d / "tokenizer.bin")
+ _touch(d / "model-Q4_K_M.gguf")
+ assert models_route._dir_model_format(d) == "gguf"
+
+
+def test_dir_model_format_weight_bin_is_not_gguf(tmp_path):
+ # A real PyTorch weight .bin alongside a .gguf means mixed weights -> None.
+ d = tmp_path / "model"
+ _touch(d / "pytorch_model.bin")
+ _touch(d / "model-Q4_K_M.gguf")
+ assert models_route._dir_model_format(d) is None
+
+
+def test_scan_models_dir_classifies_gguf_with_config(tmp_path):
+ root = tmp_path / "models"
+ # GGUF repo that also ships a config.json (the regression case).
+ _touch(root / "gguf_repo" / "config.json")
+ _touch(root / "gguf_repo" / "model-Q4_K_M.gguf")
+ # A plain safetensors checkpoint stays non-GGUF.
+ _touch(root / "st_repo" / "config.json")
+ _touch(root / "st_repo" / "model.safetensors")
+ # A standalone .gguf file is GGUF.
+ _touch(root / "loose.gguf")
+
+ fmt = {Path(m.path).name: m.model_format for m in models_route._scan_models_dir(root)}
+
+ assert fmt["gguf_repo"] == "gguf"
+ assert fmt["st_repo"] is None
+ assert fmt["loose.gguf"] == "gguf"
+
+
+def test_scan_models_dir_classifies_root_gguf_with_config(tmp_path):
+ # Custom scan folders can point directly at a GGUF repo, not only at a
+ # parent directory that contains model repos.
+ root = tmp_path / "SuffixlessRepo"
+ _touch(root / "config.json")
+ _touch(root / "model-Q4_K_M.gguf")
+
+ [row] = models_route._scan_models_dir(root)
+
+ assert row.path == str(root)
+ assert row.model_format == "gguf"
diff --git a/studio/backend/tests/test_recommended_folders_has_model.py b/studio/backend/tests/test_recommended_folders_has_model.py
new file mode 100644
index 00000000000..647d5dd3dbc
--- /dev/null
+++ b/studio/backend/tests/test_recommended_folders_has_model.py
@@ -0,0 +1,166 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""
+Regression test for /recommended-folders suggesting empty scaffolds.
+
+The endpoint used to surface any well-known dir that merely existed, so a
+freshly installed LM Studio or Ollama (empty ``models`` dir) showed up as a
+"Recommended" chip with no models behind it. ``_dir_has_downloaded_model``
+now gates each candidate on real weights: a GGUF/safetensors file anywhere in
+the tree, or a non-empty Ollama ``manifests/`` beside ``blobs/``.
+
+``routes.models`` pulls the full backend dep tree, so we extract the real
+helper (and its ``_safe_is_dir`` dependency) from the source via AST and run
+the shipped code in isolation, mirroring
+``test_recommended_folders_permission.py``.
+
+Run:
+ python -m pytest studio/backend/tests/test_recommended_folders_has_model.py -v
+"""
+
+import ast
+import json
+import os
+from pathlib import Path
+
+_backend_root = Path(__file__).resolve().parent.parent
+_models_src = _backend_root / "routes" / "models.py"
+
+
+def _load_has_downloaded_model():
+ """Return the real ``_dir_has_downloaded_model`` (plus its ``_safe_is_dir``
+ and ``_is_weight_bin`` deps, and the ``_WEIGHT_BIN_PREFIXES`` constant the
+ latter reads) without importing the heavy module."""
+ tree = ast.parse(_models_src.read_text())
+ wanted = {"_safe_is_dir", "_dir_has_downloaded_model", "_is_weight_bin"}
+ body = []
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name in wanted:
+ body.append(node)
+ elif isinstance(node, ast.Assign) and any(
+ isinstance(t, ast.Name) and t.id == "_WEIGHT_BIN_PREFIXES" for t in node.targets
+ ):
+ body.append(node)
+ got = {n.name for n in body if isinstance(n, ast.FunctionDef)}
+ assert got == wanted, f"helpers missing from source: {wanted - got}"
+ module = ast.Module(body = body, type_ignores = [])
+ ns: dict = {"Path": Path, "os": os, "json": json}
+ exec(compile(module, f"<extracted {_models_src}>", "exec"), ns)
+ return ns["_dir_has_downloaded_model"]
+
+
+has_downloaded_model = _load_has_downloaded_model()
+
+
+def test_empty_scaffold_is_false(tmp_path):
+ empty = tmp_path / "lmstudio" / "models"
+ empty.mkdir(parents = True)
+ assert has_downloaded_model(empty) is False
+
+
+def test_lmstudio_gguf_is_true(tmp_path):
+ # models/publisher/repo/file.gguf (LM Studio's nested layout).
+ repo = tmp_path / "models" / "bartowski" / "Qwen3-4B-GGUF"
+ repo.mkdir(parents = True)
+ (repo / "q4.gguf").write_bytes(b"x")
+ assert has_downloaded_model(tmp_path / "models") is True
+
+
+def test_safetensors_is_true(tmp_path):
+ repo = tmp_path / "models" / "repo"
+ repo.mkdir(parents = True)
+ (repo / "model.safetensors").write_bytes(b"x")
+ assert has_downloaded_model(tmp_path / "models") is True
+
+
+def test_ollama_empty_scaffold_is_false(tmp_path):
+ models = tmp_path / "ollama" / "models"
+ (models / "manifests").mkdir(parents = True)
+ (models / "blobs").mkdir()
+ assert has_downloaded_model(models) is False
+
+
+def test_ollama_with_manifest_is_true(tmp_path):
+ models = tmp_path / "ollama" / "models"
+ manifest = models / "manifests" / "registry.ollama.ai" / "library" / "llama3"
+ manifest.mkdir(parents = True)
+ # A real manifest references its weights via an image.model layer; the
+ # referenced blob must exist on disk for the model to be loadable.
+ (manifest / "latest").write_text(
+ json.dumps(
+ {
+ "layers": [
+ {
+ "mediaType": "application/vnd.ollama.image.model",
+ "digest": "sha256:abc",
+ }
+ ]
+ }
+ )
+ )
+ (models / "blobs").mkdir()
+ (models / "blobs" / "sha256-abc").write_bytes(b"x")
+ assert has_downloaded_model(models) is True
+
+
+def test_ollama_manifest_without_blob_is_false(tmp_path):
+ # A failed/pruned pull leaves the manifest behind but its model blob is
+ # gone: the chip must not lead to an empty picker.
+ models = tmp_path / "ollama" / "models"
+ manifest = models / "manifests" / "registry.ollama.ai" / "library" / "llama3"
+ manifest.mkdir(parents = True)
+ (manifest / "latest").write_text(
+ json.dumps(
+ {
+ "layers": [
+ {
+ "mediaType": "application/vnd.ollama.image.model",
+ "digest": "sha256:missing",
+ }
+ ]
+ }
+ )
+ )
+ (models / "blobs").mkdir() # empty: the referenced blob never landed
+ assert has_downloaded_model(models) is False
+
+
+def test_non_model_files_is_false(tmp_path):
+ junk = tmp_path / "junk"
+ junk.mkdir()
+ (junk / "readme.txt").write_text("hi")
+ assert has_downloaded_model(junk) is False
+
+
+def test_pytorch_bin_weights_are_true(tmp_path):
+ # A folder whose only weights are PyTorch .bin checkpoints (which the local
+ # scanner accepts) should still earn a Recommended chip.
+ repo = tmp_path / "models" / "repo"
+ repo.mkdir(parents = True)
+ (repo / "config.json").write_text("{}")
+ (repo / "pytorch_model.bin").write_bytes(b"x")
+ assert has_downloaded_model(tmp_path / "models") is True
+
+
+def test_non_weight_bin_is_false(tmp_path):
+ # A stray .bin that is not a weight file (e.g. tokenizer.bin) must not count.
+ repo = tmp_path / "models" / "repo"
+ repo.mkdir(parents = True)
+ (repo / "tokenizer.bin").write_bytes(b"x")
+ assert has_downloaded_model(tmp_path / "models") is False
+
+
+def test_hidden_subtree_does_not_starve_the_budget(tmp_path):
+ # A real model dir that also holds a huge hidden subtree (e.g. a .git or
+ # .cache). The hidden entries must not exhaust max_entries before the walk
+ # reaches the actual weights, which would falsely report "no model".
+ models = tmp_path / "models"
+ git = models / ".git" / "objects"
+ git.mkdir(parents = True)
+ for i in range(50):
+ (git / f"obj{i}").write_bytes(b"x")
+ repo = models / "repo"
+ repo.mkdir()
+ (repo / "model.safetensors").write_bytes(b"x")
+ assert has_downloaded_model(models, max_entries = 10) is True
diff --git a/studio/backend/tests/test_resolve_quant_gguf.py b/studio/backend/tests/test_resolve_quant_gguf.py
new file mode 100644
index 00000000000..840c4d8d4c8
--- /dev/null
+++ b/studio/backend/tests/test_resolve_quant_gguf.py
@@ -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
+
+"""Tests for :func:`routes.models._resolve_quant_gguf` (PR #6364 follow-up).
+
+The /kv-cache-estimate resolver must mirror list_local_gguf_variants:
+- read the quant label from the snapshot-relative path so nested layouts like
+ ``BF16/model.gguf`` resolve (not just basenames),
+- skip MTP drafter files so a ``...-Q8_0-MTP.gguf`` drafter is never returned as
+ the Q8_0 weights, and
+- when several cache snapshots hold the quant, pick the most complete (largest
+ total) so a partial older revision can't underestimate the weight bytes.
+
+No GPU/network. The resolver only stats sizes and parses file names, so the
+GGUF files can be arbitrary bytes.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+from pathlib import Path
+
+# Keep this test runnable without optional logging deps (mirrors
+# test_cached_gguf_routes.py).
+if "structlog" not in sys.modules:
+
+ class _DummyLogger:
+ def __getattr__(self, _name):
+ return lambda *args, **kwargs: None
+
+ sys.modules["structlog"] = types.SimpleNamespace(
+ BoundLogger = _DummyLogger,
+ get_logger = lambda *args, **kwargs: _DummyLogger(),
+ )
+
+import routes.models as models_route
+
+
+def _write(path: Path, size: int) -> Path:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(b"\0" * size)
+ return path
+
+
+def test_resolves_quant_from_parent_directory_layout(tmp_path):
+ # A repo that puts the quant label in a parent dir (BF16/model.gguf).
+ root = tmp_path / "repo"
+ f = _write(root / "BF16" / "model.gguf", 1234)
+
+ path, total = models_route._resolve_quant_gguf(str(root), "BF16", is_local = True)
+
+ assert path == str(f)
+ assert total == 1234
+
+
+def test_skips_mtp_drafter_for_main_weights(tmp_path):
+ # Main Q8_0 weights next to a same-quant MTP drafter that sorts first by name.
+ root = tmp_path / "repo"
+ main = _write(root / "model-Q8_0.gguf", 100)
+ _write(root / "MTP" / "model-Q8_0-MTP.gguf", 50)
+
+ path, total = models_route._resolve_quant_gguf(str(root), "Q8_0", is_local = True)
+
+ assert path == str(main)
+ # Drafter bytes are excluded from the weight total.
+ assert total == 100
+
+
+def test_prefers_the_complete_snapshot(tmp_path, monkeypatch):
+ from huggingface_hub import constants as hf_constants
+
+ cache = tmp_path / "hub"
+ snaps = cache / "models--org--repo" / "snapshots"
+ # Partial older snapshot: one small shard.
+ _write(snaps / "aaaa" / "model-Q4_K_M.gguf", 10)
+ # Complete newer snapshot: two larger shards.
+ complete_first = _write(snaps / "bbbb" / "model-00001-of-00002-Q4_K_M.gguf", 30)
+ _write(snaps / "bbbb" / "model-00002-of-00002-Q4_K_M.gguf", 40)
+
+ monkeypatch.setattr(hf_constants, "HF_HUB_CACHE", str(cache))
+
+ path, total = models_route._resolve_quant_gguf("org/repo", "Q4_K_M", is_local = False)
+
+ # The most complete snapshot (70 bytes) wins over the partial one (10).
+ assert total == 70
+ # Shard 1 (metadata) of the complete snapshot is returned.
+ assert path == str(complete_first)
+
+
+def test_returns_none_when_quant_absent(tmp_path):
+ root = tmp_path / "repo"
+ _write(root / "model-Q4_K_M.gguf", 100)
+
+ path, total = models_route._resolve_quant_gguf(str(root), "Q8_0", is_local = True)
+
+ assert path is None
+ assert total == 0
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index 29644d04cf3..802f22e21ea 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -258,7 +258,8 @@ function TauriWrapper({ children }: { children: ReactNode }) {
return (
<>
{children}
- <DownloadManagerPanel />
+ {/* One bottom-right stack so overlays never overlap; they stack with a
+ gap, download panel anchored at the corner with banners above. */}
<div className="pointer-events-none fixed bottom-4 right-4 z-[9998] flex w-[calc(100vw-2rem)] max-w-[400px] flex-col items-stretch gap-2">
<WebUpdateBanner
positioned={false}
@@ -268,6 +269,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
positioned={false}
enabled={!WEB_UPDATE_HIDDEN_ROUTES.has(pathname)}
/>
+ <DownloadManagerPanel positioned={false} />
</div>
</>
);
@@ -285,7 +287,6 @@ function TauriWrapper({ children }: { children: ReactNode }) {
<TauriUpdateLayer isExternalServer={isExternalServer} />
<NativeIntentDrain />
{children}
- <DownloadManagerPanel />
</>
) : (
<StartupScreen
@@ -310,9 +311,13 @@ function TauriWrapper({ children }: { children: ReactNode }) {
return (
<>
{content}
- <LlamaUpdateBanner
- enabled={showApp && !HIDDEN_TITLEBAR_SIDEBAR_ROUTES.has(pathname)}
- />
+ <div className="pointer-events-none fixed bottom-4 right-4 z-[9998] flex w-[calc(100vw-2rem)] max-w-[400px] flex-col items-stretch gap-2">
+ <LlamaUpdateBanner
+ positioned={false}
+ enabled={showApp && !HIDDEN_TITLEBAR_SIDEBAR_ROUTES.has(pathname)}
+ />
+ {showApp ? <DownloadManagerPanel positioned={false} /> : null}
+ </div>
</>
);
}
@@ -326,9 +331,13 @@ function TauriWrapper({ children }: { children: ReactNode }) {
<div className="min-h-0 flex-1 overflow-hidden">
{content}
</div>
- <LlamaUpdateBanner
- enabled={showApp && !HIDDEN_TITLEBAR_SIDEBAR_ROUTES.has(pathname)}
- />
+ <div className="pointer-events-none fixed bottom-4 right-4 z-[9998] flex w-[calc(100vw-2rem)] max-w-[400px] flex-col items-stretch gap-2">
+ <LlamaUpdateBanner
+ positioned={false}
+ enabled={showApp && !HIDDEN_TITLEBAR_SIDEBAR_ROUTES.has(pathname)}
+ />
+ {showApp ? <DownloadManagerPanel positioned={false} /> : null}
+ </div>
</div>
);
}
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 0497b64882f..c6fa3e92ec7 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -68,7 +68,7 @@ import {
PowerIcon,
PencilEdit02Icon,
LayoutAlignLeftIcon,
- Setting07Icon,
+ Settings02Icon,
Sun03Icon,
TestTube01Icon,
ZapIcon,
@@ -1382,7 +1382,7 @@ export function AppSidebar() {
</div>
{/* settings cog (replaces the up/down chevron) */}
<HugeiconsIcon
- icon={Setting07Icon}
+ icon={Settings02Icon}
strokeWidth={1.5}
className="ml-auto !size-[18px] text-muted-foreground group-data-[collapsible=icon]:hidden"
/>
@@ -1398,7 +1398,7 @@ export function AppSidebar() {
<DropdownMenuItem
onSelect={() => useSettingsDialogStore.getState().openDialog()}
>
- <HugeiconsIcon icon={Setting07Icon} strokeWidth={1.75} className="size-icon" />
+ <HugeiconsIcon icon={Settings02Icon} strokeWidth={1.75} className="size-icon" />
<span>{t("shell.navigation.settings")}</span>
<DropdownMenuShortcut>⌘,</DropdownMenuShortcut>
</DropdownMenuItem>
diff --git a/studio/frontend/src/components/assistant-ui/model-selector.tsx b/studio/frontend/src/components/assistant-ui/model-selector.tsx
index d17892e1bda..8938f4dda78 100644
--- a/studio/frontend/src/components/assistant-ui/model-selector.tsx
+++ b/studio/frontend/src/components/assistant-ui/model-selector.tsx
@@ -8,24 +8,37 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
-import { InfoHint } from "@/components/ui/info-hint";
-import { Switch } from "@/components/ui/switch";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { TooltipProvider } from "@/components/ui/tooltip";
import { usePlatformStore } from "@/config/env";
import { isCustomProviderType } from "@/features/chat/external-providers";
+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { cn } from "@/lib/utils";
import {
CloudIcon,
DashboardSquare01Icon,
+ Download01Icon,
FolderSearchIcon,
RemoveCircleIcon,
Search01Icon,
+ StarIcon,
} from "@hugeicons/core-free-icons";
-import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { type KeyboardEvent, useMemo, useState } from "react";
+import { useNavigate } from "@tanstack/react-router";
+import {
+ type KeyboardEvent,
+ type ReactNode,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { Input } from "../ui/input";
-import { HubModelPicker, LoraModelPicker } from "./model-selector/pickers";
+import { HubModelPicker, hasDownloadedModels } from "./model-selector/pickers";
+import { PillTabs } from "./model-selector/pill-tabs";
+import {
+ buildSourceTabs,
+ isFineTunedSource,
+} from "./model-selector/source-tabs";
import type {
DeletedModelRef,
ExternalModelOption,
@@ -110,11 +123,6 @@ interface ModelSelectorProps {
activeGgufVariant?: string | null;
onValueChange?: (value: string, meta: ModelSelectorChangeMeta) => void;
onEject?: () => void;
- /** When provided, renders a persisted "Load on selection" toggle in the
- * popover. Off → picking a model stages it for a deferred, configured load
- * instead of loading immediately. */
- loadOnSelection?: boolean;
- onLoadOnSelectionChange?: (value: boolean) => void;
onFoldersChange?: () => void;
onPickLocalModel?: () => void | Promise<void>;
onModelsChange?: (deletedModel?: DeletedModelRef) => void;
@@ -155,8 +163,9 @@ function ModelSelectorTrigger({
className={cn(
"unsloth-model-selector-trigger flex min-w-0 items-center gap-2 transition-colors",
variant === "outline" &&
- "rounded-full border border-border/60 hover:bg-[#ececec] dark:hover:bg-[#2d2e32]",
- variant === "ghost" && "rounded-full hover:bg-[#ececec] dark:hover:bg-[#2d2e32]",
+ "rounded-full border border-border/60 hover:bg-[#ececec] dark:hover:bg-[#2d2e32]",
+ variant === "ghost" &&
+ "rounded-full hover:bg-[#ececec] dark:hover:bg-[#2d2e32]",
variant === "muted" && "rounded-full bg-muted hover:bg-muted/80",
// More left padding than right; the chevron is pulled close to the
// label (below) so the trigger reads balanced around the text.
@@ -170,7 +179,9 @@ function ModelSelectorTrigger({
<span className="size-2 shrink-0 rounded-full bg-emerald-500" />
)}
{currentModel?.icon ? (
- <span className="flex shrink-0 items-center">{currentModel.icon}</span>
+ <span className="flex shrink-0 items-center">
+ {currentModel.icon}
+ </span>
) : null}
<span className="flex min-w-0 flex-1 items-baseline">
<span className="min-w-0 flex flex-1 items-baseline truncate font-heading text-[16px] font-medium leading-tight text-black dark:text-white">
@@ -206,7 +217,52 @@ function ModelSelectorTrigger({
);
}
+type HubSection = "downloaded" | "recommended" | "custom" | "connected";
+
+// The user's most recently clicked Hub section, restored on every open so the
+// selector returns to the tab they last used.
+const HUB_SECTION_KEY = "unsloth_model_selector_section";
+// Last tab the user actually clicked, or null when none is stored yet. Only
+// On Device / Recommended persist (Connected is provider-conditional).
+function loadLastHubSection(): HubSection | null {
+ try {
+ const raw = localStorage.getItem(HUB_SECTION_KEY);
+ return raw === "downloaded" || raw === "recommended" ? raw : null;
+ } catch {
+ return null;
+ }
+}
+function saveLastHubSection(section: HubSection): void {
+ if (section !== "downloaded" && section !== "recommended") return;
+ try {
+ localStorage.setItem(HUB_SECTION_KEY, section);
+ } catch {
+ // Ignore unavailable storage.
+ }
+}
+// Default the Hub section: the last tab the user clicked; first time, On Device
+// when they have downloads, else Recommended.
+function defaultHubSection(): HubSection {
+ return (
+ loadLastHubSection() ?? (hasDownloadedModels() ? "downloaded" : "recommended")
+ );
+}
+
+const HUB_SECTION_TABS: { value: string; label: string; icon?: ReactNode }[] = [
+ {
+ value: "recommended",
+ label: "Recommended",
+ icon: <HugeiconsIcon icon={StarIcon} className="size-3.5" />,
+ },
+ {
+ value: "downloaded",
+ label: "On Device",
+ icon: <HugeiconsIcon icon={Download01Icon} className="size-3.5" />,
+ },
+];
+
function ModelSelectorContent({
+ open,
models,
loraModels,
externalModels,
@@ -215,13 +271,13 @@ function ModelSelectorContent({
onEject,
onFoldersChange,
onPickLocalModel,
+ onBrowseHub,
onModelsChange,
deleteDisabled,
- loadOnSelection,
- onLoadOnSelectionChange,
className,
dataTour,
}: {
+ open: boolean;
models: ModelOption[];
loraModels: LoraModelOption[];
externalModels: ExternalModelOption[];
@@ -230,29 +286,89 @@ function ModelSelectorContent({
onEject?: () => void;
onFoldersChange?: () => void;
onPickLocalModel?: () => void;
+ onBrowseHub?: () => void;
onModelsChange?: (deletedModel?: DeletedModelRef) => void;
deleteDisabled?: boolean;
- loadOnSelection?: boolean;
- onLoadOnSelectionChange?: (value: boolean) => void;
className?: string;
dataTour?: string;
}) {
const hasSelection = Boolean(value);
const chatOnly = usePlatformStore((s) => s.isChatOnly());
const hasExternal = externalModels.length > 0;
+ // The Fine-tuned tab is for fine-tuned models only. Local models (LM Studio,
+ // Ollama, custom folders) carry source "local" and live in the Hub tab's
+ // Downloaded / Custom sections instead.
+ const fineTunedModels = useMemo(
+ () => loraModels.filter((model) => isFineTunedSource(model.source)),
+ [loraModels],
+ );
const chatOnlyTabsDefault = useMemo(
- () => (value && externalModels.some((model) => model.id === value) ? "external" : "hub"),
+ () =>
+ value && externalModels.some((model) => model.id === value)
+ ? "external"
+ : "hub",
[externalModels, value],
);
- const studioTabsDefault = useMemo((): "hub" | "lora" | "external" => {
+ const studioTabsDefault = useMemo((): "hub" | "external" => {
if (value && externalModels.some((model) => model.id === value)) {
return "external";
}
- if (value && loraModels.some((model) => model.id === value)) {
- return "lora";
- }
return "hub";
- }, [externalModels, loraModels, value]);
+ }, [externalModels, value]);
+
+ const tabs = useMemo(() => buildSourceTabs(), []);
+ // Connected sits in the section toggle, shown only with external providers.
+ const hubSectionTabs = useMemo(
+ () =>
+ hasExternal
+ ? [
+ ...HUB_SECTION_TABS,
+ {
+ value: "connected",
+ label: "Connected",
+ icon: <HugeiconsIcon icon={CloudIcon} className="size-3.5" />,
+ },
+ ]
+ : HUB_SECTION_TABS,
+ [hasExternal],
+ );
+
+ const [activeTab, setActiveTab] = useState<string>(() =>
+ chatOnly ? chatOnlyTabsDefault : studioTabsDefault,
+ );
+ // Fall back to the first tab if the active one disappears.
+ const effectiveTab = tabs.some((tab) => tab.value === activeTab)
+ ? activeTab
+ : tabs[0].value;
+ // Open on Connected when the active model comes from a connected provider.
+ const wantsConnectedDefault =
+ (chatOnly ? chatOnlyTabsDefault : studioTabsDefault) === "external";
+ const [hubSection, setHubSection] = useState<HubSection>(() =>
+ wantsConnectedDefault ? "connected" : defaultHubSection(),
+ );
+ // Connected is only valid while external providers exist; fall back otherwise.
+ const effectiveHubSection: HubSection =
+ hubSection === "connected" && !hasExternal ? "recommended" : hubSection;
+
+ // The picker below remounts on each open, but this tab state does not, so a
+ // persisted selection that lands in lora/external after async load would
+ // reopen on Hub. Re-derive the default tab on the open edge.
+ const wasOpen = useRef(open);
+ useEffect(() => {
+ if (open && !wasOpen.current) {
+ setActiveTab(chatOnly ? chatOnlyTabsDefault : studioTabsDefault);
+ // Connected when an external model is active, else On Device when the
+ // user has downloads, else their last section.
+ setHubSection(wantsConnectedDefault ? "connected" : defaultHubSection());
+ }
+ wasOpen.current = open;
+ }, [
+ open,
+ chatOnly,
+ chatOnlyTabsDefault,
+ studioTabsDefault,
+ wantsConnectedDefault,
+ ]);
function focusActiveModelOption(root: HTMLElement): boolean {
const option =
@@ -265,9 +381,7 @@ function ModelSelectorContent({
root.querySelector<HTMLElement>(
'[role="tabpanel"]:not([hidden]) [data-model-picker-option]',
) ??
- root.querySelector<HTMLElement>(
- "[data-model-picker-option]",
- );
+ root.querySelector<HTMLElement>("[data-model-picker-option]");
if (!option) {
return false;
}
@@ -304,122 +418,101 @@ function ModelSelectorContent({
data-tour={dataTour}
onKeyDown={handlePickerEntryKeyDown}
className={cn(
- "unsloth-model-selector-menu menu-soft-surface ring-0 w-[min(440px,calc(100vw-1rem))] max-w-[calc(100vw-1rem)] min-w-0 gap-0 px-3 pt-3 pb-2",
+ "unsloth-model-selector-menu menu-soft-surface ring-0 max-w-[calc(100vw-1rem)] min-w-0 gap-0 pt-4 pb-0 pl-4",
+ // Sized so the left-packed row keeps uniform gaps and the last dropdown's
+ // right gap matches the pill's left gap (pl-4 vs pr-4).
+ hasExternal
+ ? "w-[min(614px,calc(100vw-1rem))] pr-4"
+ : "w-[min(506px,calc(100vw-1rem))] pr-2",
className,
)}
>
- {chatOnly ? (
- hasExternal ? (
- <Tabs defaultValue={chatOnlyTabsDefault} className="w-full">
- <TabsList className="mb-2 w-full">
- <TabsTrigger value="hub">Hub models</TabsTrigger>
- <TabsTrigger value="external">Connected</TabsTrigger>
- </TabsList>
- <TabsContent value="hub" className="m-0">
- <HubModelPicker models={models} value={value} onSelect={onSelect} onFoldersChange={onFoldersChange} />
- </TabsContent>
- <TabsContent value="external" className="m-0">
- <ExternalModelPicker
- externalModels={externalModels}
- value={value}
- onSelect={onSelect}
- />
- </TabsContent>
- </Tabs>
- ) : (
- <HubModelPicker models={models} value={value} onSelect={onSelect} onFoldersChange={onFoldersChange} />
- )
- ) : (
- <Tabs defaultValue={studioTabsDefault} className="w-full">
- <TabsList className="mb-2 w-full">
- <TabsTrigger value="hub">Hub models</TabsTrigger>
- <TabsTrigger value="lora">Fine-tuned</TabsTrigger>
- {hasExternal ? <TabsTrigger value="external">Connected</TabsTrigger> : null}
- </TabsList>
-
- <TabsContent value="hub" className="m-0">
- <HubModelPicker models={models} value={value} onSelect={onSelect} onFoldersChange={onFoldersChange} />
- </TabsContent>
-
- <TabsContent value="lora" className="m-0">
- <LoraModelPicker
- loraModels={loraModels}
- value={value}
- onSelect={onSelect}
- onModelsChange={onModelsChange}
- deleteDisabled={deleteDisabled}
- />
- </TabsContent>
-
- {hasExternal ? (
- <TabsContent value="external" className="m-0">
- <ExternalModelPicker
- externalModels={externalModels}
- value={value}
- onSelect={onSelect}
+ {/* Local provider so popover tooltips open instantly, including when the
+ cursor moves between icons. disableHoverableContent drops the grace
+ area between a trigger and its tooltip, so moving from one icon to the
+ next switches the tooltip at once instead of keeping the old one up. */}
+ <TooltipProvider
+ delayDuration={0}
+ skipDelayDuration={0}
+ disableHoverableContent={true}
+ >
+ {tabs.length > 1 ? (
+ <PillTabs
+ ariaLabel="Model source"
+ tabs={tabs}
+ value={effectiveTab}
+ onValueChange={setActiveTab}
+ fit={true}
+ className="mb-2"
+ />
+ ) : null}
+
+ {effectiveTab === "hub" ? (
+ <HubModelPicker
+ models={models}
+ loraModels={fineTunedModels}
+ externalModels={externalModels}
+ value={value}
+ onSelect={onSelect}
+ onFoldersChange={onFoldersChange}
+ onBrowseHub={onBrowseHub}
+ onModelsChange={onModelsChange}
+ deleteDisabled={deleteDisabled}
+ section={effectiveHubSection}
+ onEject={hasSelection && onEject ? onEject : undefined}
+ sectionToggle={
+ <PillTabs
+ ariaLabel="Hub section"
+ tabs={hubSectionTabs}
+ value={effectiveHubSection}
+ onValueChange={(next) => {
+ const section = next as HubSection;
+ setHubSection(section);
+ saveLastHubSection(section);
+ }}
+ fit={true}
/>
- </TabsContent>
- ) : null}
- </Tabs>
- )}
+ }
+ />
+ ) : null}
- {onPickLocalModel ? (
- <div className="mt-1.5 border-t border-border/70 pt-1.5">
- <button
- type="button"
- onClick={onPickLocalModel}
- className="flex w-full items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted/60"
- title="Pick a model file from disk"
- >
- <HugeiconsIcon icon={FolderSearchIcon} className="size-3.5" />
- Pick a model file from disk
- </button>
- </div>
- ) : null}
- {hasSelection && onEject ? (
- <div className="mt-1.5 border-t border-border/70 pt-1.5">
- <button
- type="button"
- onClick={onEject}
- className="flex w-full items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs text-destructive transition-colors hover:bg-destructive/10"
- title="Eject model"
- >
- <HugeiconsIcon icon={RemoveCircleIcon} className="size-3.5" />
- Eject loaded model
- </button>
- </div>
- ) : null}
- {onLoadOnSelectionChange ? (
- <div className="mt-1.5 border-t border-border/70 pt-1.5">
- <div className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-xs text-muted-foreground">
- <div className="flex min-w-0 flex-col gap-0.5">
- <div className="flex min-w-0 items-center gap-1.5">
- <span>Load on selection</span>
- <InfoHint>
- <div className="space-y-1">
- <div>
- <span className="font-medium">On:</span> load the model
- immediately after selection.
- </div>
- <div>
- <span className="font-medium">Off:</span> configure options
- first, then click Load model.
- </div>
- </div>
- </InfoHint>
- </div>
- <span className="text-[10px] leading-none text-muted-foreground/70">
- Local GGUF models only
- </span>
- </div>
- <Switch
- className="panel-switch shrink-0"
- checked={loadOnSelection ?? true}
- onCheckedChange={onLoadOnSelectionChange}
- />
+ {effectiveTab === "external" ? (
+ <ExternalModelPicker
+ externalModels={externalModels}
+ value={value}
+ onSelect={onSelect}
+ />
+ ) : null}
+
+ {onPickLocalModel ? (
+ <div className="mt-1.5 border-t border-border/70 pt-1.5">
+ <button
+ type="button"
+ onClick={onPickLocalModel}
+ className="flex w-full items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted/60"
+ title="Pick a model file from disk"
+ >
+ <HugeiconsIcon icon={FolderSearchIcon} className="size-3.5" />
+ Pick a model file from disk
+ </button>
</div>
- </div>
- ) : null}
+ ) : null}
+ {/* Hub renders Eject inline as the last list row; other tabs keep the
+ footer button. */}
+ {effectiveTab !== "hub" && hasSelection && onEject ? (
+ <div className="mt-1.5 pt-1.5">
+ <button
+ type="button"
+ onClick={onEject}
+ className="flex w-full items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs text-destructive transition-colors hover:bg-destructive/10"
+ title="Eject model"
+ >
+ <HugeiconsIcon icon={RemoveCircleIcon} className="size-3.5" />
+ Eject loaded model
+ </button>
+ </div>
+ ) : null}
+ </TooltipProvider>
</PopoverContent>
);
}
@@ -437,8 +530,6 @@ export function ModelSelector({
onPickLocalModel,
onModelsChange,
deleteDisabled,
- loadOnSelection,
- onLoadOnSelectionChange,
variant = "outline",
size = "default",
className,
@@ -452,6 +543,7 @@ export function ModelSelector({
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
const open = controlledOpen ?? uncontrolledOpen;
const setOpen = onOpenChange ?? setUncontrolledOpen;
+ const navigate = useNavigate();
const [uncontrolled, setUncontrolled] = useState(defaultValue ?? "");
const selected = value ?? uncontrolled;
@@ -511,7 +603,9 @@ export function ModelSelector({
const found = optionById.get(selected);
if (activeGgufVariant) {
const desc = `GGUF · ${activeGgufVariant}`;
- return found ? { ...found, description: desc } : { id: selected, name: selected, description: desc };
+ return found
+ ? { ...found, description: desc }
+ : { id: selected, name: selected, description: desc };
}
return found ?? { id: selected, name: selected };
}, [selected, optionById, activeGgufVariant]);
@@ -535,6 +629,11 @@ export function ModelSelector({
void onPickLocalModel?.();
}
+ function handleBrowseHub() {
+ setOpen(false);
+ void navigate({ to: "/hub", search: { tab: "discover" } });
+ }
+
return (
<Popover open={open} onOpenChange={setOpen}>
<ModelSelectorTrigger
@@ -547,6 +646,7 @@ export function ModelSelector({
dataTour={triggerDataTour}
/>
<ModelSelectorContent
+ open={open}
models={models}
loraModels={loraModels}
externalModels={externalModels}
@@ -555,10 +655,9 @@ export function ModelSelector({
onEject={onEject ? handleEject : undefined}
onFoldersChange={onFoldersChange}
onPickLocalModel={onPickLocalModel ? handlePickLocalModel : undefined}
+ onBrowseHub={handleBrowseHub}
onModelsChange={onModelsChange}
deleteDisabled={deleteDisabled}
- loadOnSelection={loadOnSelection}
- onLoadOnSelectionChange={onLoadOnSelectionChange}
className={contentClassName}
dataTour={contentDataTour}
/>
@@ -627,7 +726,7 @@ function ExternalModelPicker({
className="h-9 pl-8"
/>
</div>
- <div className="max-h-64 overflow-y-auto">
+ <div className="-mr-1.5 max-h-72 overflow-y-auto pr-1.5">
<div className="space-y-2 p-1">
{grouped.length === 0 ? (
<div className="px-2.5 py-2 text-xs leading-relaxed text-muted-foreground">
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/folder-browser.tsx b/studio/frontend/src/components/assistant-ui/model-selector/folder-browser.tsx
index 3cb80ca2e1e..6311e15bfe2 100644
--- a/studio/frontend/src/components/assistant-ui/model-selector/folder-browser.tsx
+++ b/studio/frontend/src/components/assistant-ui/model-selector/folder-browser.tsx
@@ -3,6 +3,8 @@
"use client";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogClose,
@@ -35,7 +37,8 @@ function splitBreadcrumb(path: string): { label: string; value: string }[] {
// Detect path style BEFORE normalizing: on POSIX, `\` is a valid filename
// char, so blindly rewriting `\` -> `/` mangles names like `my\backup` into
// 404ing breadcrumbs. Only Windows-style paths (drive letter, or UNC) convert.
- const isWindowsDrive = /^[A-Za-z]:[\\/]/.test(path) || /^[A-Za-z]:$/.test(path);
+ const isWindowsDrive =
+ /^[A-Za-z]:[\\/]/.test(path) || /^[A-Za-z]:$/.test(path);
const isUnc = /^\\\\/.test(path);
const isWindows = isWindowsDrive || isUnc;
const normalized = isWindows ? path.replace(/\\/g, "/") : path;
@@ -149,18 +152,16 @@ export function FolderBrowser({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
- className="max-w-md p-0 gap-0"
+ className="corner-squircle dialog-soft-surface sm:max-w-md p-0 gap-0 [&_[data-slot=dialog-close]]:top-4"
overlayClassName="bg-black/20 backdrop-blur-none"
data-testid="folder-browser-dialog"
>
- <DialogHeader className="px-4 pt-4 pb-2">
- <DialogTitle className="text-sm font-medium">
- Browse for folder
- </DialogTitle>
+ <DialogHeader className="px-6 pt-6 pb-2">
+ <DialogTitle>Select folder to detect models</DialogTitle>
</DialogHeader>
{/* Breadcrumb */}
- <div className="flex flex-wrap items-center gap-0.5 border-t border-border/50 px-4 py-2 font-mono text-[11px] text-muted-foreground">
+ <div className="flex flex-wrap items-center gap-0.5 border-t border-border/50 px-6 py-2 font-mono text-[11px] text-muted-foreground">
{crumbs.length === 0 ? (
<span className="text-muted-foreground/60">(loading…)</span>
) : (
@@ -168,7 +169,7 @@ export function FolderBrowser({
<span key={c.value} className="flex items-center gap-0.5">
<button
type="button"
- className="rounded px-1 py-0.5 hover:bg-accent hover:text-foreground"
+ className="rounded px-1 py-0.5 hover:bg-muted hover:text-foreground"
onClick={() => navigate(c.value, showHidden)}
disabled={loading}
>
@@ -184,14 +185,14 @@ export function FolderBrowser({
{/* Suggestions (quick-pick chips) */}
{data?.suggestions && data.suggestions.length > 0 && (
- <div className="flex flex-wrap gap-1 border-t border-border/50 px-4 py-2">
+ <div className="flex flex-wrap gap-1 border-t border-border/50 px-6 py-2">
{data.suggestions.map((s) => (
<button
key={s}
type="button"
onClick={() => navigate(s, showHidden)}
disabled={loading}
- className="rounded-full border border-border/50 px-2 py-0.5 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
+ className="rounded-full border border-border/50 px-2 py-0.5 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40"
title={s}
>
{s.length > 36 ? `…${s.slice(-33)}` : s}
@@ -200,25 +201,33 @@ export function FolderBrowser({
</div>
)}
- {/* Entry list */}
+ {/* Entry list. Keep the list mounted while a refetch is in flight (e.g.
+ toggling Show hidden) and just dim it, so the dialog doesn't collapse and
+ flash. The full-height spinner only shows on the first load, when there
+ is no data yet. */}
<div className="max-h-64 min-h-24 overflow-y-auto border-t border-border/50">
{error && (
- <div className="px-4 py-3 text-xs text-destructive">{error}</div>
+ <div className="px-6 py-3 text-xs text-destructive">{error}</div>
)}
- {!error && loading && (
- <div className="flex items-center gap-2 px-4 py-3">
+ {!error && !data && loading && (
+ <div className="flex items-center gap-2 px-6 py-3">
<Spinner className="size-3 text-muted-foreground" />
<span className="text-xs text-muted-foreground">Loading…</span>
</div>
)}
- {!error && !loading && data && (
- <>
+ {!error && data && (
+ <div
+ className={cn(
+ "transition-opacity duration-150",
+ loading && "pointer-events-none opacity-50",
+ )}
+ >
{/* Up row */}
{data.parent !== null && (
<button
type="button"
onClick={() => navigate(data.parent ?? undefined, showHidden)}
- className="flex w-full items-center gap-2 px-4 py-1.5 text-left text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ className="flex w-full items-center gap-2 px-6 py-1.5 text-left text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<HugeiconsIcon
icon={ArrowUp02Icon}
@@ -227,18 +236,22 @@ export function FolderBrowser({
<span className="font-mono">..</span>
</button>
)}
- {data.entries.length === 0 && !(data.model_files_here && data.model_files_here > 0) && (
- <div className="px-4 py-3 text-xs text-muted-foreground/60">
- (empty directory)
- </div>
- )}
- {data.model_files_here !== undefined && data.model_files_here > 0 && (
- <div className="border-t border-border/30 px-4 py-1.5 text-[10px] text-foreground/70">
- {data.model_files_here} model file{data.model_files_here === 1 ? "" : "s"} in this folder. Click "Use this folder" to scan it.
- </div>
- )}
+ {data.entries.length === 0 &&
+ !(data.model_files_here && data.model_files_here > 0) && (
+ <div className="px-6 py-3 text-xs text-muted-foreground/60">
+ (empty directory)
+ </div>
+ )}
+ {data.model_files_here !== undefined &&
+ data.model_files_here > 0 && (
+ <div className="border-t border-border/30 px-6 py-1.5 text-[10px] text-foreground/70">
+ {data.model_files_here} model file
+ {data.model_files_here === 1 ? "" : "s"} in this folder.
+ Click "Use this folder" to scan it.
+ </div>
+ )}
{data.truncated === true && (
- <div className="border-t border-border/30 px-4 py-1.5 text-[10px] text-muted-foreground/70">
+ <div className="border-t border-border/30 px-6 py-1.5 text-[10px] text-muted-foreground/70">
Showing first {data.entries.length} entries. Narrow the path
to see more.
</div>
@@ -252,7 +265,7 @@ export function FolderBrowser({
navigate(`${data.current}${sep}${e.name}`, showHidden);
}}
className={cn(
- "flex w-full items-center gap-2 px-4 py-1.5 text-left text-xs transition-colors hover:bg-accent hover:text-foreground",
+ "flex w-full items-center gap-2 px-6 py-1.5 text-left text-xs transition-colors hover:bg-muted hover:text-foreground",
e.hidden && "text-muted-foreground/60",
)}
>
@@ -273,42 +286,41 @@ export function FolderBrowser({
)}
</button>
))}
- </>
+ </div>
)}
</div>
{/* Footer */}
- <DialogFooter className="flex items-center justify-between gap-2 border-t border-border/50 px-4 py-2">
- <label className="flex cursor-pointer items-center gap-1.5 text-[10px] text-muted-foreground">
- <input
- type="checkbox"
+ <DialogFooter className="flex items-center justify-between gap-2 border-t border-border/50 px-6 py-3">
+ <label
+ htmlFor="folder-browser-show-hidden"
+ className="flex cursor-pointer items-center gap-2 text-xs text-muted-foreground"
+ >
+ <Checkbox
+ id="folder-browser-show-hidden"
+ className="rounded-full"
checked={showHidden}
- onChange={(e) => {
- const next = e.target.checked;
+ onCheckedChange={(checked) => {
+ const next = checked === true;
setShowHidden(next);
navigate(path, next);
}}
- className="size-3"
/>
Show hidden
</label>
<div className="flex gap-2">
<DialogClose asChild={true}>
- <button
- type="button"
- className="h-7 rounded border border-border/50 px-2.5 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
- >
+ <Button type="button" variant="ghost">
Cancel
- </button>
+ </Button>
</DialogClose>
- <button
+ <Button
type="button"
onClick={handleConfirm}
disabled={!path || loading || !!error}
- className="h-7 rounded bg-foreground px-2.5 text-[11px] font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-40"
>
Use this folder
- </button>
+ </Button>
</div>
</DialogFooter>
</DialogContent>
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/model-capabilities.ts b/studio/frontend/src/components/assistant-ui/model-selector/model-capabilities.ts
new file mode 100644
index 00000000000..62ecac831b5
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/model-selector/model-capabilities.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
+
+// Pure helpers that infer what a model can do (vision / reasoning / audio) from
+// its HF tags + pipeline tag, falling back to repo-name keywords. No React/DOM
+// deps so they stay easy to test.
+
+export interface ModelCapabilities {
+ vision: boolean;
+ reasoning: boolean;
+ audio: boolean;
+}
+
+// Authoritative HF pipeline tags / tags for each capability.
+const VISION_TAGS = new Set([
+ "image-text-to-text",
+ "image-to-text",
+ "visual-question-answering",
+ "video-text-to-text",
+ "any-to-any",
+ "multimodal",
+ "vision",
+]);
+const AUDIO_TAGS = new Set([
+ "automatic-speech-recognition",
+ "audio-text-to-text",
+ "text-to-speech",
+ "text-to-audio",
+ "audio-to-audio",
+ "audio-classification",
+]);
+const REASONING_TAGS = new Set(["reasoning"]);
+
+// Repo-name fallbacks, bounded so we never read a token out of a longer word.
+const SEP = "(?:^|[-_/. ])";
+const END = "(?=$|[-_/. ])";
+const VISION_NAME_RE = new RegExp(
+ `${SEP}(?:vl|llava|pixtral|moondream|smolvlm|internvl|cogvlm|idefics|paligemma|vision)${END}`,
+ "i",
+);
+const REASONING_NAME_RE = new RegExp(
+ `${SEP}(?:r1|qwq|thinking|reason(?:ing|er)?|magistral|o1|marco)${END}`,
+ "i",
+);
+const AUDIO_NAME_RE = new RegExp(
+ `${SEP}(?:whisper|tts|parakeet|parler|musicgen|bark|orpheus|csm|voice|speech|audio)${END}`,
+ "i",
+);
+
+function hasAny(tagSet: Set<string>, wanted: Set<string>): boolean {
+ for (const tag of wanted) if (tagSet.has(tag)) return true;
+ return false;
+}
+
+/** Infer capabilities from HF tags + pipeline tag, then repo-name keywords. */
+export function detectCapabilities(opts: {
+ id: string;
+ tags?: readonly string[];
+ pipelineTag?: string;
+}): ModelCapabilities {
+ const { id, tags, pipelineTag } = opts;
+ const tagSet = new Set((tags ?? []).map((t) => t.toLowerCase()));
+ if (pipelineTag) tagSet.add(pipelineTag.toLowerCase());
+ return {
+ vision: hasAny(tagSet, VISION_TAGS) || VISION_NAME_RE.test(id),
+ reasoning: hasAny(tagSet, REASONING_TAGS) || REASONING_NAME_RE.test(id),
+ audio: hasAny(tagSet, AUDIO_TAGS) || AUDIO_NAME_RE.test(id),
+ };
+}
+
+/** True when at least one capability is present (worth rendering a badge). */
+export function hasAnyCapability(caps: ModelCapabilities): boolean {
+ return caps.vision || caps.reasoning || caps.audio;
+}
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/model-load-settings-action.tsx b/studio/frontend/src/components/assistant-ui/model-selector/model-load-settings-action.tsx
new file mode 100644
index 00000000000..58510762d4c
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/model-selector/model-load-settings-action.tsx
@@ -0,0 +1,59 @@
+// 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 { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import { cn } from "@/lib/utils";
+import { Settings02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+
+/** Gear button on a downloaded quant row. Stages the model into the Run
+ * settings sidebar (always, regardless of the Load-on-selection toggle) so the
+ * user can set load options, then click Load model. */
+export function ModelLoadSettingsAction({
+ ariaLabel,
+ repoId,
+ quant,
+ maxContext,
+}: {
+ ariaLabel: string;
+ repoId: string;
+ quant: string;
+ maxContext?: number | null;
+}) {
+ return (
+ <Tooltip delayDuration={0}>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ useChatRuntimeStore.getState().stageModel({
+ id: repoId,
+ ggufVariant: quant,
+ isDownloaded: true,
+ contextLength: maxContext ?? null,
+ });
+ }}
+ aria-label={ariaLabel}
+ className={cn(
+ "shrink-0 rounded-md p-1 text-muted-foreground/60 transition-colors hover:bg-muted hover:text-foreground",
+ )}
+ >
+ <HugeiconsIcon
+ icon={Settings02Icon}
+ strokeWidth={1.75}
+ className="size-3"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="tooltip-compact">
+ Configure run settings before loading model
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/model-usage.ts b/studio/frontend/src/components/assistant-ui/model-selector/model-usage.ts
new file mode 100644
index 00000000000..dbcd4b9a1b8
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/model-selector/model-usage.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
+
+// Tracks when each model was last loaded so the "Recent" sort can order by usage
+// (distinct from "Downloaded", which orders by the file's download date). Kept in
+// localStorage; ids are lowercased to match how the picker compares them.
+
+import { useEffect, useState } from "react";
+
+export type ModelLoadTimes = Record<string, number>;
+
+const STORAGE_KEY = "unsloth.model-load-times.v1";
+
+function readLoadTimes(): ModelLoadTimes {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ return raw ? (JSON.parse(raw) as ModelLoadTimes) : {};
+ } catch {
+ return {};
+ }
+}
+
+/** Stamp a model as loaded now and return the updated map. */
+export function recordModelLoaded(id: string): ModelLoadTimes {
+ const next = { ...readLoadTimes(), [id.toLowerCase()]: Date.now() };
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
+ } catch {
+ // ignore quota / disabled storage
+ }
+ return next;
+}
+
+/** Epoch ms the model was last loaded, or -1 if never. */
+export function loadedAt(times: ModelLoadTimes, id: string): number {
+ return times[id.toLowerCase()] ?? -1;
+}
+
+/** Load times, restamping whenever the active model changes. */
+export function useModelLoadTimes(currentValue?: string): ModelLoadTimes {
+ const [times, setTimes] = useState<ModelLoadTimes>(() => readLoadTimes());
+ useEffect(() => {
+ if (currentValue) setTimes(recordModelLoaded(currentValue));
+ }, [currentValue]);
+ return times;
+}
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx b/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx
index c08619d611c..46b6fe2e63f 100644
--- a/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx
+++ b/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx
@@ -9,6 +9,7 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { usePlatformStore } from "@/config/env";
+import { ApiProviderLogo } from "@/features/chat/api-provider-logo";
import {
type ScanFolderInfo,
addScanFolder,
@@ -27,35 +28,83 @@ import type {
CachedModelRepo,
LocalModelInfo,
} from "@/features/chat/api/chat-api";
+import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
import type { GgufVariantDetail } from "@/features/chat/types/api";
+import { DotTag } from "@/features/hub/catalog/dot-tag";
import {
- useDebouncedValue,
- useGpuInfo,
- useHfModelSearch,
- useInfiniteScroll,
- useRecommendedModelVram,
-} from "@/hooks";
+ type HubOption,
+ HubOptionMenu,
+} from "@/features/hub/catalog/hub-option-menu";
+import { TrainIcon } from "@/features/hub/components/train-icon";
+import { useHubInfiniteScroll } from "@/features/hub/hooks/use-hub-infinite-scroll";
+import {
+ type HfModelResult,
+ type HfSortKey,
+ useHubModelSearch,
+} from "@/features/hub/hooks/use-hub-model-search";
+import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
+import { isHiddenModelId } from "@/features/hub/lib/hidden-models";
+import { classifyUnslothSupport } from "@/features/hub/lib/unsloth-support";
+import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";
+import { useDebouncedValue, useGpuInfo } from "@/hooks";
import { extractParamLabel } from "@/lib/model-size";
+import { toast } from "@/lib/toast";
import { cn, formatCompact } from "@/lib/utils";
import type { VramFitStatus } from "@/lib/vram";
import { checkVramFit, estimateLoadingVram } from "@/lib/vram";
-import { Add01Icon, Cancel01Icon, Download01Icon, Folder02Icon, Search01Icon, StarIcon } from "@hugeicons/core-free-icons";
+import {
+ Add01Icon,
+ AudioWave01Icon,
+ Cancel01Icon,
+ DashboardCircleIcon,
+ Download01Icon,
+ Flag01Icon,
+ Folder02Icon,
+ RemoveCircleIcon,
+ Search01Icon,
+ ViewIcon,
+} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { FolderBrowser } from "./folder-browser";
-import { ModelDeleteAction } from "./model-delete-action";
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react";
import {
+ type Dispatch,
type KeyboardEvent,
type ReactNode,
+ type SetStateAction,
useCallback,
useEffect,
useId,
useMemo,
+ useRef,
useState,
} from "react";
-import { toast } from "@/lib/toast";
+import { FolderBrowser } from "./folder-browser";
+import {
+ type ModelCapabilities,
+ detectCapabilities,
+ hasAnyCapability,
+} from "./model-capabilities";
+import { ModelDeleteAction } from "./model-delete-action";
+import { ModelLoadSettingsAction } from "./model-load-settings-action";
+import {
+ type ModelLoadTimes,
+ loadedAt,
+ useModelLoadTimes,
+} from "./model-usage";
+import {
+ type FormatFilter,
+ estimateQuantBytes,
+ fitsDevice,
+ isMlxId,
+ isMobileVariant,
+ isRecommendableFormat,
+ matchesFormatFilter,
+ paramsFromId,
+} from "./recommended-fit";
+import { parseMetaTokens, splitRepoLabel } from "./row-meta";
import type {
DeletedModelRef,
+ ExternalModelOption,
LoraModelOption,
ModelOption,
ModelSelectorChangeMeta,
@@ -65,17 +114,9 @@ function dedupe(values: string[]): string[] {
return [...new Set(values.filter(Boolean))];
}
-/** Newest-first by `last_modified` (epoch s), repo_id tie-break. Copies the
- * input; treats a missing field as oldest for older-backend compatibility. */
-function sortByDownloadRecency<T extends { repo_id: string; last_modified?: number }>(
- rows: T[],
-): T[] {
- return [...rows].sort((a, b) => {
- const at = a.last_modified ?? -1;
- const bt = b.last_modified ?? -1;
- if (at !== bt) return bt - at;
- return a.repo_id.localeCompare(b.repo_id);
- });
+/** Repos published by Unsloth; the rest group under the "Other models" section. */
+function isUnslothRepoId(repoId: string): boolean {
+ return repoId.toLowerCase().startsWith("unsloth/");
}
/** Lowercase and strip separators for fuzzy search. */
@@ -92,7 +133,9 @@ function makeModelOptionChildrenId(optionKey: string): string {
}
function focusFirstChildOption(optionKey: string): boolean {
- const childList = document.getElementById(makeModelOptionChildrenId(optionKey));
+ const childList = document.getElementById(
+ makeModelOptionChildrenId(optionKey),
+ );
const option = childList?.querySelector<HTMLElement>(
"[data-model-picker-option]",
);
@@ -240,31 +283,49 @@ function useRovingModelList({
function ListLabel({
children,
icon,
+ action,
collapsed,
onToggle,
+ divider,
}: {
children: ReactNode;
icon?: ReactNode;
+ action?: ReactNode;
collapsed?: boolean;
onToggle?: () => void;
+ /** Draw a divider line above, evenly spaced, to separate it from the section
+ * above (omit on the first section). */
+ divider?: boolean;
}) {
return (
- <div className="flex items-center justify-between gap-1 px-2.5 py-1.5">
+ <div
+ className={cn(
+ "flex items-center justify-between gap-1 px-2.5 pb-1",
+ divider ? "mt-3 border-t border-border/50 pt-3" : "pt-3",
+ )}
+ >
<span className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
{icon}
{children}
</span>
- {onToggle && (
- <button
- type="button"
- onClick={onToggle}
- aria-label={collapsed ? "Expand section" : "Collapse section"}
- className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
- >
- {collapsed
- ? <ChevronRightIcon className="size-3" />
- : <ChevronDownIcon className="size-3" />}
- </button>
+ {(action || onToggle) && (
+ <div className="flex items-center gap-0.5">
+ {action}
+ {onToggle && (
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-label={collapsed ? "Expand section" : "Collapse section"}
+ className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
+ >
+ {collapsed ? (
+ <ChevronRightIcon className="size-3" />
+ ) : (
+ <ChevronDownIcon className="size-3" />
+ )}
+ </button>
+ )}
+ </div>
)}
</div>
);
@@ -291,6 +352,29 @@ function formatBytes(bytes: number): string {
return `${value.toFixed(value < 10 ? 1 : 0)} ${units[i]}`;
}
+// Small icon badges for what a model can do (vision / reasoning / audio).
+// Vision and reasoning badges were dropped to keep rows uncluttered.
+const CAPABILITY_BADGES = [
+ { key: "audio" as const, icon: AudioWave01Icon, title: "Audio" },
+];
+
+function CapabilityIcons({ caps }: { caps: ModelCapabilities }) {
+ return (
+ <>
+ {CAPABILITY_BADGES.filter((b) => caps[b.key]).map((b) => (
+ <span
+ key={b.key}
+ title={b.title}
+ aria-label={b.title}
+ className="flex size-[18px] shrink-0 items-center justify-center rounded-md border border-border/60 text-muted-foreground"
+ >
+ <HugeiconsIcon icon={b.icon} className="size-3" strokeWidth={1.8} />
+ </span>
+ ))}
+ </>
+ );
+}
+
function ModelRow({
label,
meta,
@@ -302,6 +386,11 @@ function ModelRow({
tooltipText,
optionProps,
onArrowDownIntoChildren,
+ capabilities,
+ hideOwner,
+ downloaded,
+ showVision,
+ className,
}: {
label: string;
meta?: string | null;
@@ -313,6 +402,15 @@ function ModelRow({
tooltipText?: ReactNode;
optionProps?: ModelRowOptionProps;
onArrowDownIntoChildren?: () => boolean;
+ /** Capability override (HF rows have tags); falls back to name detection. */
+ capabilities?: ModelCapabilities;
+ /** Hide the "owner/" prefix (e.g. Recommended, where all are unsloth). */
+ hideOwner?: boolean;
+ /** Mark a row already on disk (shown in Recommended instead of being hidden). */
+ downloaded?: boolean;
+ /** Show a Vision badge on the name (On Device, read from GGUF metadata). */
+ showVision?: boolean;
+ className?: string;
}) {
const exceeds = vramStatus === "exceeds";
const showVramTooltip =
@@ -326,6 +424,14 @@ function ModelRow({
: `~${vramEst}GB VRAM`
: null;
+ const { owner, name } = splitRepoLabel(label);
+ const parsed = parseMetaTokens(meta);
+ // Param chip from meta, else derived from the name so GGUF rows show it too.
+ const paramLabel = parsed.param ?? extractParamLabel(name) ?? null;
+ // Use the passed-in capabilities (tag-aware) or infer from the repo name.
+ const caps = capabilities ?? detectCapabilities({ id: label });
+ const showCaps = hasAnyCapability(caps);
+
const content = (
<button
type="button"
@@ -339,28 +445,94 @@ function ModelRow({
}}
onClick={onClick}
className={cn(
- "flex w-full items-center gap-2 rounded-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-[#ececec] focus-visible:bg-[#ececec] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45 dark:hover:bg-[#3a3d44] dark:focus-visible:bg-[#3a3d44]",
- selected && "bg-[#ececec] dark:bg-[#3a3d44]",
+ "flex w-full items-center gap-2 rounded-full px-2 py-1.5 text-left text-sm transition-colors hover:bg-[#ececec] focus-visible:bg-[#ececec] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45 dark:hover:bg-[var(--sidebar-accent)] dark:focus-visible:bg-[var(--sidebar-accent)]",
+ selected && "bg-[#ececec] dark:bg-[var(--sidebar-accent)]",
+ className,
)}
>
- <span
- className={cn(
- "block min-w-0 flex-1 truncate",
- exceeds && "!text-gray-500 dark:!text-gray-400",
- )}
- >
- {label}
+ <span className="flex min-w-0 flex-1 items-baseline">
+ {owner && !hideOwner ? (
+ <span className="inline-flex min-w-0 max-w-[45%] shrink items-baseline text-[13px] text-muted-foreground/90">
+ <span className="truncate">{owner}</span>
+ <span className="shrink-0 text-muted-foreground/45">/</span>
+ </span>
+ ) : null}
+ <span className="min-w-0 flex-1 truncate">{name}</span>
</span>
- <span className="ml-auto flex items-center gap-1.5 shrink-0">
+ <span className="ml-auto flex shrink-0 items-center gap-1.5">
+ {showCaps && <CapabilityIcons caps={caps} />}
+ {showVision && (
+ <Tooltip delayDuration={0}>
+ <TooltipTrigger asChild={true}>
+ <span
+ aria-label="Vision"
+ className="flex h-[18px] shrink-0 items-center justify-center rounded-md border border-border/60 px-1.5 text-indigo-700 dark:text-indigo-300"
+ >
+ <HugeiconsIcon
+ icon={ViewIcon}
+ className="size-3"
+ strokeWidth={1.8}
+ />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="tooltip-compact">
+ This model can process image inputs
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {selected && (
+ <DotTag
+ tone="success"
+ label="Loaded"
+ className="h-[18px] gap-1 rounded-md px-1.5"
+ dotClassName="size-[5px]"
+ />
+ )}
+ {downloaded && !selected && (
+ <span
+ title="Already downloaded"
+ aria-label="Already downloaded"
+ className="flex h-[18px] shrink-0 items-center justify-center rounded-md border border-border/60 px-1.5 text-muted-foreground"
+ >
+ <HugeiconsIcon
+ icon={Download01Icon}
+ className="size-3"
+ strokeWidth={1.8}
+ />
+ </span>
+ )}
{vramStatus === "exceeds" && (
- <span className="text-[9px] font-medium !text-red-700 !bg-red-50 dark:!text-red-400 dark:!bg-red-950 px-1.5 py-0.5 rounded">OOM</span>
+ <span className="text-[9px] font-medium !text-red-700 !bg-red-50 dark:!text-red-300 dark:!bg-red-500/15 px-1.5 py-0.5 rounded">
+ OOM
+ </span>
)}
{vramStatus === "tight" && (
<span className="text-[9px] font-medium !text-amber-400">TIGHT</span>
)}
- {meta ? (
- <span className="text-[10px] text-muted-foreground">{meta}</span>
+ {paramLabel ? (
+ <span className="rounded-md border border-border/60 px-1.5 py-px text-[10px] font-medium text-muted-foreground tabular-nums">
+ {paramLabel}
+ </span>
+ ) : null}
+ {parsed.texts.map((text) => (
+ <span key={text} className="text-[10px] text-muted-foreground">
+ {text}
+ </span>
+ ))}
+ {parsed.size !== undefined ? (
+ <span className="text-[10px] text-muted-foreground tabular-nums">
+ {parsed.size}
+ </span>
) : null}
+ {parsed.formats.map((f) => (
+ <DotTag
+ key={f.label}
+ tone={f.tone}
+ label={f.label}
+ className="h-[18px] gap-[3px] rounded-md px-1.5"
+ dotClassName="size-[5px]"
+ />
+ ))}
</span>
</button>
);
@@ -412,6 +584,8 @@ function GgufVariantExpander({
renderDeleteVariantDescription,
getDeleteVariantSuccessMessage,
deleteDisabled = false,
+ onDevice = false,
+ onHasVision,
}: {
repoId: string;
onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
@@ -426,10 +600,17 @@ function GgufVariantExpander({
renderDeleteVariantDescription?: (quant: string) => ReactNode;
getDeleteVariantSuccessMessage?: (quant: string) => string;
deleteDisabled?: boolean;
+ /** On Device rows honor the Show all quantizations setting; Recommended and
+ * other browse lists always show every quant. */
+ onDevice?: boolean;
+ /** Report GGUF vision support up so the parent row can badge it. */
+ onHasVision?: (hasVision: boolean) => void;
}) {
const [variants, setVariants] = useState<GgufVariantDetail[] | null>(null);
const [defaultVariant, setDefaultVariant] = useState<string | null>(null);
const [hasVision, setHasVision] = useState(false);
+ // Native max context (GGUF metadata); only set once a variant is downloaded.
+ const [nativeContext, setNativeContext] = useState<number | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -444,6 +625,8 @@ function GgufVariantExpander({
setVariants(res.variants);
setDefaultVariant(res.default_variant);
setHasVision(res.has_vision);
+ onHasVision?.(res.has_vision);
+ setNativeContext(res.context_length ?? null);
})
.catch((err) => {
if (canceled) return;
@@ -467,15 +650,22 @@ function GgufVariantExpander({
const handleVariantClick = useCallback(
(quant: string, downloaded?: boolean, sizeBytes?: number) => {
+ // Only seed the staged context for picks whose weights are already on
+ // disk. The staging effect short-circuits on a known contextLength
+ // (pendingHasContext) before starting the download, so attaching it to an
+ // undownloaded quant from a partially cached repo would skip the download
+ // entirely (and, with Load on selection, never load).
+ const isAvailable = isLocalPath || downloaded === true;
onSelect(repoId, {
source: sourceOverride ?? (isLocalPath ? "local" : "hub"),
isLora: false,
ggufVariant: quant,
isDownloaded: isLocalPath ? true : downloaded,
expectedBytes: sizeBytes,
+ contextLength: isAvailable ? nativeContext : undefined,
});
},
- [repoId, isLocalPath, onSelect, sourceOverride],
+ [repoId, isLocalPath, onSelect, sourceOverride, nativeContext],
);
// GGUF fit classification matching llama-server's _select_gpus logic:
@@ -487,19 +677,24 @@ function GgufVariantExpander({
const getGgufFit = useCallback(
(sizeBytes: number): "fits" | "tight" | "oom" => {
- if (!gpuGb || gpuGb <= 0) return "fits";
+ // No device budget at all (no GPU and no known system RAM): can't
+ // classify, so don't scare the user with OOM badges.
+ if (totalBudgetGb <= 0) return "fits";
const gb = sizeBytes / 1024 ** 3;
if (gb <= 0 || gb <= gpuBudgetGb) return "fits";
+ // No-GPU / unified-memory hosts (Mac) have only the RAM budget, so the
+ // tier collapses to fit-or-oom against system RAM rather than GPU+offload.
+ if (gpuBudgetGb <= 0) return gb <= totalBudgetGb ? "fits" : "oom";
if (gb <= totalBudgetGb) return "tight";
return "oom";
},
- [gpuGb, gpuBudgetGb, totalBudgetGb],
+ [gpuBudgetGb, totalBudgetGb],
);
// If the recommended variant is OOM, pick the largest fitting one;
// if all are OOM, recommend the smallest.
const effectiveRecommended = useMemo(() => {
- if (!variants || !gpuGb || gpuGb <= 0) return defaultVariant;
+ if (!variants || totalBudgetGb <= 0) return defaultVariant;
const defaultV = variants.find((v) => v.quant === defaultVariant);
if (defaultV && getGgufFit(defaultV.size_bytes) !== "oom")
return defaultVariant;
@@ -512,7 +707,7 @@ function GgufVariantExpander({
// All OOM -- recommend smallest (most likely to partially run)
const sorted = [...variants].sort((a, b) => a.size_bytes - b.size_bytes);
return sorted[0].quant;
- }, [variants, defaultVariant, gpuGb, getGgufFit]);
+ }, [variants, defaultVariant, totalBudgetGb, getGgufFit]);
const sortedVariants = useMemo(() => {
if (!variants) return variants;
@@ -542,12 +737,24 @@ function GgufVariantExpander({
});
}, [variants, effectiveRecommended, getGgufFit]);
+ // On Device only: when Show all quantizations is off, list quants already on
+ // disk. Recommended and other browse lists always show every quant.
+ const showAllQuantizations = useChatRuntimeStore(
+ (s) => s.showAllQuantizations,
+ );
+ const displayVariants = useMemo(() => {
+ if (!sortedVariants) return sortedVariants;
+ return showAllQuantizations || !onDevice
+ ? sortedVariants
+ : sortedVariants.filter((v) => v.downloaded);
+ }, [sortedVariants, showAllQuantizations, onDevice]);
+
const variantOptionKeys = useMemo(
() =>
- (sortedVariants ?? []).map((variant) =>
+ (displayVariants ?? []).map((variant) =>
makeModelOptionKey("gguf-variant", `${repoId}:${variant.filename}`),
),
- [repoId, sortedVariants],
+ [repoId, displayVariants],
);
const variantList = useRovingModelList({
label: `${repoId} quantizations`,
@@ -569,7 +776,7 @@ function GgufVariantExpander({
return <div className="px-5 py-2 text-xs text-destructive">{error}</div>;
}
- if (!sortedVariants || sortedVariants.length === 0) {
+ if (!displayVariants || displayVariants.length === 0) {
return (
<div className="px-5 py-2 text-xs text-muted-foreground">
No GGUF variants found.
@@ -587,15 +794,26 @@ function GgufVariantExpander({
}
className="pl-4 border-l-2 border-accent/50 ml-3 my-1"
>
- <div className="px-2 py-1 flex items-center gap-1.5">
- <span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
- Quantizations
- </span>
- {hasVision && (
- <span className="text-[9px] font-medium text-blue-400">Vision</span>
- )}
- </div>
- {sortedVariants.map((v) => {
+ {/* On Device shows the model name above, so the Quantizations heading is
+ redundant; its Vision badge is relayed to the name instead. */}
+ {!onDevice && (
+ <div className="px-2 py-1 flex items-center gap-1.5">
+ <span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
+ Quantizations
+ </span>
+ {hasVision && (
+ <span className="flex items-center gap-0.5 text-[9px] font-medium text-indigo-700 dark:text-indigo-300">
+ <HugeiconsIcon
+ icon={ViewIcon}
+ className="size-3"
+ strokeWidth={1.8}
+ />
+ Vision
+ </span>
+ )}
+ </div>
+ )}
+ {displayVariants.map((v) => {
const fit = getGgufFit(v.size_bytes);
const oom = fit === "oom";
const tight = fit === "tight";
@@ -610,11 +828,15 @@ function GgufVariantExpander({
handleVariantClick(v.quant, v.downloaded, v.size_bytes)
}
className={cn(
- "flex min-w-0 flex-1 items-center justify-between gap-2 rounded-full px-3 py-1 text-left text-sm transition-colors hover:bg-[#ececec] focus-visible:bg-[#ececec] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45 dark:hover:bg-[#3a3d44] dark:focus-visible:bg-[#3a3d44]",
+ "flex min-w-0 flex-1 items-center justify-between gap-2 rounded-full px-2 py-1 text-left text-sm transition-colors hover:bg-[#ececec] focus-visible:bg-[#ececec] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/45 dark:hover:bg-[var(--sidebar-accent)] dark:focus-visible:bg-[var(--sidebar-accent)]",
)}
>
<span className="min-w-0 flex-1 truncate font-mono text-xs">
- <span className={cn(oom && "!text-gray-500 dark:!text-gray-400")}>{v.quant}</span>
+ <span
+ className={cn(oom && "!text-gray-500 dark:!text-gray-400")}
+ >
+ {v.quant}
+ </span>
{v.downloaded ? (
<span className="ml-1.5 text-[9px] font-sans font-medium text-green-400">
downloaded
@@ -627,7 +849,7 @@ function GgufVariantExpander({
</span>
<span className="flex items-center gap-1.5 shrink-0">
{oom && (
- <span className="text-[9px] font-medium !text-red-700 !bg-red-50 dark:!text-red-400 dark:!bg-red-950 px-1.5 py-0.5 rounded">
+ <span className="text-[9px] font-medium !text-red-700 !bg-red-50 dark:!text-red-300 dark:!bg-red-500/15 px-1.5 py-0.5 rounded">
OOM
</span>
)}
@@ -641,6 +863,14 @@ function GgufVariantExpander({
</span>
</span>
</button>
+ {v.downloaded && (
+ <ModelLoadSettingsAction
+ ariaLabel={`Inference settings for ${repoId} ${v.quant}`}
+ repoId={repoId}
+ quant={v.quant}
+ maxContext={nativeContext}
+ />
+ )}
{v.downloaded && onDeleteVariant && (
<ModelDeleteAction
ariaLabel={`Delete ${repoId} ${v.quant}`}
@@ -687,9 +917,23 @@ function isGgufRepo(id: string, hintedIsGguf?: boolean): boolean {
let _cachedGgufCache: CachedGgufRepo[] = [];
let _cachedModelsCache: CachedModelRepo[] = [];
let _lmStudioCache: LocalModelInfo[] = [];
+let _localDirCache: LocalModelInfo[] = [];
let _customFolderCache: LocalModelInfo[] = [];
let _scanFoldersCache: ScanFolderInfo[] = [];
+/** True when any on-device model (downloaded GGUF, cached repo, LM Studio, or
+ * custom-folder model) is known. Reads the module caches, which persist across
+ * popover mounts, so the selector can default to the On Device tab. */
+export function hasDownloadedModels(): boolean {
+ return (
+ _cachedGgufCache.length > 0 ||
+ _cachedModelsCache.length > 0 ||
+ _lmStudioCache.length > 0 ||
+ _localDirCache.length > 0 ||
+ _customFolderCache.length > 0
+ );
+}
+
/** Sort LM Studio models with unsloth publisher first. */
function sortLmStudio(models: LocalModelInfo[]): LocalModelInfo[] {
return [...models].sort((a, b) => {
@@ -711,22 +955,213 @@ function canDeleteLoraModel(model: LoraModelOption): boolean {
// ── Hub Model Picker ──────────────────────────────────────────
+// Recommended section sort. "recommended" = newly created unsloth GGUF/MLX that
+// fit the device; the rest are plain HF sort keys over all unsloth models.
+type RecommendedSortKey = "recommended" | "trendingScore" | "lastModified";
+
+const RECOMMENDED_SORT_OPTIONS: HubOption<RecommendedSortKey>[] = [
+ { value: "recommended", label: "Recommended" },
+ { value: "trendingScore", label: "Trending" },
+ { value: "lastModified", label: "Recent" },
+];
+
+// Sort for the On Device / Custom (local) lists. "recent" = last loaded;
+// "downloaded" = file download date.
+type LocalSortKey = "recent" | "downloaded" | "size" | "name";
+
+const LOCAL_SORT_OPTIONS: HubOption<LocalSortKey>[] = [
+ { value: "recent", label: "Recent" },
+ { value: "size", label: "Size" },
+ { value: "name", label: "Name" },
+ { value: "downloaded", label: "Downloaded" },
+];
+
+// Format filter dropdown for the Unsloth listing. Plain labels are reused in
+// the empty-state copy below.
+const FORMAT_FILTER_LABELS: Record<FormatFilter, string> = {
+ all: "All",
+ gguf: "GGUF",
+ mlx: "MLX",
+ safetensors: "Safetensors",
+};
+
+// Dot colors match the row format tags: gguf blue, mlx amber, safetensors pink.
+const FORMAT_FILTER_DOTS: Partial<Record<FormatFilter, string>> = {
+ gguf: "bg-format-gguf",
+ mlx: "bg-format-mlx",
+ safetensors: "bg-format-checkpoint",
+};
+
+const FORMAT_FILTER_OPTIONS: HubOption<FormatFilter>[] = (
+ Object.keys(FORMAT_FILTER_LABELS) as FormatFilter[]
+).map((value) => {
+ const dot = FORMAT_FILTER_DOTS[value];
+ return {
+ value,
+ label: dot ? (
+ <span className="flex items-center gap-2">
+ <span
+ className={cn("inline-block size-1.5 shrink-0 rounded-full", dot)}
+ />
+ {FORMAT_FILTER_LABELS[value]}
+ </span>
+ ) : (
+ FORMAT_FILTER_LABELS[value]
+ ),
+ };
+});
+
+/** Sort cached repos: by last-loaded, download date, size desc, or name. */
+function sortCachedRepos<
+ T extends { repo_id: string; size_bytes: number; last_modified?: number },
+>(rows: T[], key: LocalSortKey, loadTimes: ModelLoadTimes): T[] {
+ const byDate = (a: T, b: T) =>
+ (b.last_modified ?? -1) - (a.last_modified ?? -1) ||
+ a.repo_id.localeCompare(b.repo_id);
+ return [...rows].sort((a, b) => {
+ if (key === "name") return a.repo_id.localeCompare(b.repo_id);
+ if (key === "size") {
+ return b.size_bytes - a.size_bytes || a.repo_id.localeCompare(b.repo_id);
+ }
+ if (key === "recent") {
+ const d = loadedAt(loadTimes, b.repo_id) - loadedAt(loadTimes, a.repo_id);
+ return d !== 0 ? d : byDate(a, b);
+ }
+ return byDate(a, b); // "downloaded"
+ });
+}
+
+/** Sort local-provider models. They carry no size, so "size" falls back to name. */
+function sortLocalModels(
+ rows: LocalModelInfo[],
+ key: LocalSortKey,
+ loadTimes: ModelLoadTimes,
+): LocalModelInfo[] {
+ const name = (m: LocalModelInfo) => m.model_id ?? m.display_name ?? m.id;
+ const byDate = (a: LocalModelInfo, b: LocalModelInfo) =>
+ (b.updated_at ?? -1) - (a.updated_at ?? -1) ||
+ name(a).localeCompare(name(b));
+ return [...rows].sort((a, b) => {
+ if (key === "recent") {
+ const d = loadedAt(loadTimes, a.id) - loadedAt(loadTimes, b.id);
+ return d !== 0 ? -d : byDate(a, b);
+ }
+ if (key === "downloaded") return byDate(a, b);
+ return name(a).localeCompare(name(b)); // "size" (no size) and "name"
+ });
+}
+
+/** GGUF detection for a local model by backend format hint, name, or file path. */
+function localModelIsGguf(m: LocalModelInfo): boolean {
+ return (
+ m.model_format === "gguf" ||
+ isGgufRepo(m.id) ||
+ isGgufRepo(m.display_name) ||
+ m.path.toLowerCase().endsWith(".gguf")
+ );
+}
+
+/** Whether a local model is an MLX build (name hint). MLX runs on Mac only, so
+ * callers gate visibility on the host being a Mac. */
+function localModelIsMlx(m: LocalModelInfo): boolean {
+ return (
+ isMlxId(m.id) || isMlxId(m.display_name) || isMlxId(m.model_id ?? "")
+ );
+}
+
+/** Whether a local model matches the format toggle (GGUF detected by name/path). */
+function localModelMatchesFormat(
+ m: LocalModelInfo,
+ filter: FormatFilter,
+): boolean {
+ return matchesFormatFilter(
+ m.model_id ?? m.display_name ?? m.id,
+ localModelIsGguf(m),
+ filter,
+ );
+}
+
export function HubModelPicker({
models,
+ loraModels = [],
+ externalModels = [],
value,
onSelect,
onFoldersChange,
+ onBrowseHub,
+ onModelsChange,
+ deleteDisabled = false,
+ section = "downloaded",
+ sectionToggle,
+ onEject,
}: {
models: ModelOption[];
+ /** Fine-tuned models, shown as a section in the On Device view. */
+ loraModels?: LoraModelOption[];
+ /** Connected provider models, shown in the Connected section. */
+ externalModels?: ExternalModelOption[];
value?: string;
onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
onFoldersChange?: () => void;
+ /** Open the full Hub page to browse more models. */
+ onBrowseHub?: () => void;
+ onModelsChange?: (deletedModel?: DeletedModelRef) => void;
+ deleteDisabled?: boolean;
+ /** Section shown when not searching. Search spans all sections. */
+ section?: "downloaded" | "recommended" | "custom" | "connected";
+ /** Section toggle rendered under the search bar. */
+ sectionToggle?: ReactNode;
+ /** Eject the loaded model. Rendered as the last list row when set. */
+ onEject?: () => void;
}) {
const gpu = useGpuInfo();
+ // Last-loaded timestamps power the "Recent" sort (vs "Downloaded" = file date).
+ const loadTimes = useModelLoadTimes(value);
+ // Fade the list's top edge once scrolled, and its bottom edge while more
+ // rows sit below the fold.
+ const [listScrolled, setListScrolled] = useState(false);
+ const [listMoreBelow, setListMoreBelow] = useState(false);
const [query, setQuery] = useState("");
const debouncedQuery = useDebouncedValue(query);
- const { results, isLoading, isLoadingMore, fetchMore } =
- useHfModelSearch(debouncedQuery);
+ // Shared Hub search stack (the same hooks the Hub page uses) so the picker
+ // and Hub run one implementation. Scoped to unsloth like the old listing.
+ const online = useOnlineStatus();
+ const accessToken = useHfTokenStore((s) => s.token) || undefined;
+ // Recommended section: a live unsloth listing sorted by the dropdown. The
+ // same sort drives the search results so the dropdown works while searching.
+ const [recommendedSort, setRecommendedSort] =
+ useState<RecommendedSortKey>("trendingScore");
+ // "recommended" surfaces the most recently created Unsloth repos.
+ const recommendedSortBy: HfSortKey =
+ recommendedSort === "recommended" ? "createdAt" : recommendedSort;
+ const {
+ results,
+ isLoading,
+ isLoadingMore,
+ fetchMore,
+ scannedCount,
+ hasMore,
+ } = useHubModelSearch(debouncedQuery, {
+ ownerScope: "unsloth",
+ sortBy: recommendedSortBy,
+ sortDirection: "desc",
+ pinUnslothFirst: true,
+ keepUnsupportedTags: true,
+ accessToken,
+ // Only the Recommended section renders Hub results (On Device / Connected
+ // use local data), so keep the Hub hooks idle on the other tabs to avoid
+ // needless requests/spinner and to preserve offline-local behavior.
+ enabled: online && section === "recommended",
+ });
+ const recommendedSearch = useHubModelSearch("", {
+ ownerScope: "unsloth",
+ sortBy: recommendedSortBy,
+ sortDirection: "desc",
+ pinUnslothFirst: true,
+ keepUnsupportedTags: true,
+ accessToken,
+ enabled: online && section === "recommended",
+ });
// Lowercased repo ids confirmed GGUF by the store or HF search.
// Absence means "no hint" -> hasGgufSuffix is the fallback (don't
@@ -739,13 +1174,15 @@ export function HubModelPicker({
}
return ids;
}, [models]);
+ // Both listings contribute GGUF hints so a tag-only GGUF (no "-GGUF" suffix)
+ // in Recommended still expands variants instead of loading as a checkpoint.
const resultGgufIds = useMemo(() => {
const ids = new Set<string>();
- for (const result of results) {
+ for (const result of [...results, ...recommendedSearch.results]) {
if (result.isGguf) ids.add(result.id.toLowerCase());
}
return ids;
- }, [results]);
+ }, [results, recommendedSearch.results]);
const isKnownGgufRepo = useCallback(
(id: string): boolean => {
const key = id.toLowerCase();
@@ -756,10 +1193,97 @@ export function HubModelPicker({
// Track which GGUF repo is expanded for variant selection
const [expandedGguf, setExpandedGguf] = useState<string | null>(null);
+ // GGUF vision support per repo, reported by the expander once it has read the
+ // metadata, so On Device rows can show a Vision badge on the name.
+ const [visionByRepo, setVisionByRepo] = useState<Record<string, boolean>>({});
+ const reportVision = useCallback((repoId: string, hasVision: boolean) => {
+ setVisionByRepo((prev) =>
+ prev[repoId] === hasVision ? prev : { ...prev, [repoId]: hasVision },
+ );
+ }, []);
+ // When on, On Device GGUF repos show their quantizations without a click.
+ const expandQuantizations = useChatRuntimeStore((s) => s.expandQuantizations);
+ // Repos the user clicked to collapse while expand-by-default is on. Kept in
+ // memory only, so it resets on reload (and when the setting is toggled).
+ const [collapsedGguf, setCollapsedGguf] = useState<Set<string>>(
+ () => new Set(),
+ );
+ useEffect(() => {
+ setCollapsedGguf(new Set());
+ }, [expandQuantizations]);
+ const isGgufExpanded = useCallback(
+ (id: string) =>
+ expandQuantizations ? !collapsedGguf.has(id) : expandedGguf === id,
+ [expandQuantizations, collapsedGguf, expandedGguf],
+ );
+ // Toggle a repo's quantizations: flip the collapse set when expand-by-default
+ // is on, otherwise drive the single-open expandedGguf state.
+ const toggleGgufExpanded = useCallback(
+ (id: string) => {
+ if (expandQuantizations) {
+ setCollapsedGguf((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ } else {
+ setExpandedGguf((prev) => (prev === id ? null : id));
+ }
+ },
+ [expandQuantizations],
+ );
const [downloadedCollapsed, setDownloadedCollapsed] = useState(false);
+ const [otherModelsCollapsed, setOtherModelsCollapsed] = useState(false);
const [customFoldersCollapsed, setCustomFoldersCollapsed] = useState(false);
- const [recommendedCollapsed, setRecommendedCollapsed] = useState(false);
+ const [fineTunedCollapsed, setFineTunedCollapsed] = useState(false);
+ const [lmStudioCollapsed, setLmStudioCollapsed] = useState(false);
+ const [localDirCollapsed, setLocalDirCollapsed] = useState(false);
+ // The Fine-tuned section header; the train icon on the Unsloth header scrolls
+ // here so users can jump to their trained models.
+ const fineTunedSectionRef = useRef<HTMLDivElement>(null);
+ const scrollToFineTuned = useCallback(() => {
+ setFineTunedCollapsed(false);
+ // Two frames so the expand renders before we scroll the section to the top
+ // of the list.
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ fineTunedSectionRef.current?.scrollIntoView({
+ behavior: "smooth",
+ block: "start",
+ });
+ });
+ });
+ }, []);
+ // The Other models header; the directions icon on the Unsloth header scrolls
+ // here.
+ const otherModelsSectionRef = useRef<HTMLDivElement>(null);
+ const scrollToOtherModels = useCallback(() => {
+ setOtherModelsCollapsed(false);
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ otherModelsSectionRef.current?.scrollIntoView({
+ behavior: "smooth",
+ block: "start",
+ });
+ });
+ });
+ }, []);
+ // The Custom Folders header; the folder icon on the Unsloth header scrolls
+ // here instead of opening the browse popup.
+ const customFolderSectionRef = useRef<HTMLDivElement>(null);
+ const scrollToCustomFolders = useCallback(() => {
+ setCustomFoldersCollapsed(false);
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ customFolderSectionRef.current?.scrollIntoView({
+ behavior: "smooth",
+ block: "start",
+ });
+ });
+ });
+ }, []);
// Cached (downloaded) repos -- module-level cache avoids flashing an
// empty "Downloaded" section when the popover re-mounts.
@@ -774,11 +1298,16 @@ export function HubModelPicker({
// LM Studio local models -- module-level cache, same pattern as above.
const [lmStudioModels, setLmStudioModels] =
useState<LocalModelInfo[]>(_lmStudioCache);
+ // Models found under the local models directory (./models), so they stay
+ // selectable on the On Device tab after leaving the Fine-tuned tab.
+ const [localDirModels, setLocalDirModels] =
+ useState<LocalModelInfo[]>(_localDirCache);
const [customFolderModels, setCustomFolderModels] =
useState<LocalModelInfo[]>(_customFolderCache);
// Custom scan folders management
- const [scanFolders, setScanFolders] = useState<ScanFolderInfo[]>(_scanFoldersCache);
+ const [scanFolders, setScanFolders] =
+ useState<ScanFolderInfo[]>(_scanFoldersCache);
const [folderInput, setFolderInput] = useState("");
const [folderError, setFolderError] = useState<string | null>(null);
const [showFolderInput, setShowFolderInput] = useState(false);
@@ -794,6 +1323,9 @@ export function HubModelPicker({
);
_lmStudioCache = lm;
setLmStudioModels(lm);
+ const ld = res.models.filter((m) => m.source === "models_dir");
+ _localDirCache = ld;
+ setLocalDirModels(ld);
const cf = res.models.filter((m) => m.source === "custom");
_customFolderCache = cf;
setCustomFolderModels(cf);
@@ -810,58 +1342,72 @@ export function HubModelPicker({
.catch(() => {});
}, []);
- const handleAddFolder = useCallback(async (overridePath?: string) => {
- // Explicit path lets the folder browser submit in the same tick it
- // calls `setFolderInput`; reading `folderInput` would race the update.
- const raw = overridePath !== undefined ? overridePath : folderInput;
- const trimmed = raw.trim();
- if (!trimmed || folderLoading) return;
- setFolderError(null);
- setFolderLoading(true);
- // From the folder browser's one-click "Use this folder": the typed-
- // input panel is closed, so the inline folderError is invisible.
- // Surface failures (denylisted path, sandbox 403, etc.) via toast.
- const fromBrowser = overridePath !== undefined;
- try {
- const created = await addScanFolder(trimmed);
- // Backend returns the existing row for duplicates, so dedupe.
- const next = _scanFoldersCache.some((f) => f.id === created.id || f.path === created.path)
- ? _scanFoldersCache
- : [..._scanFoldersCache, created];
- _scanFoldersCache = next;
- setScanFolders(next);
- setFolderInput("");
- setShowFolderInput(false);
- refreshLocalModelsList();
- onFoldersChange?.();
- // Background reconciliation with the server
- void refreshScanFolders();
- } catch (e) {
- const message = e instanceof Error ? e.message : "Failed to add folder";
- setFolderError(message);
- if (fromBrowser) {
- toast.error("Couldn't add folder", { description: message });
+ const handleAddFolder = useCallback(
+ async (overridePath?: string) => {
+ // Explicit path lets the folder browser submit in the same tick it
+ // calls `setFolderInput`; reading `folderInput` would race the update.
+ const raw = overridePath !== undefined ? overridePath : folderInput;
+ const trimmed = raw.trim();
+ if (!trimmed || folderLoading) return;
+ setFolderError(null);
+ setFolderLoading(true);
+ // From the folder browser's one-click "Use this folder": the typed-
+ // input panel is closed, so the inline folderError is invisible.
+ // Surface failures (denylisted path, sandbox 403, etc.) via toast.
+ const fromBrowser = overridePath !== undefined;
+ try {
+ const created = await addScanFolder(trimmed);
+ // Backend returns the existing row for duplicates, so dedupe.
+ const next = _scanFoldersCache.some(
+ (f) => f.id === created.id || f.path === created.path,
+ )
+ ? _scanFoldersCache
+ : [..._scanFoldersCache, created];
+ _scanFoldersCache = next;
+ setScanFolders(next);
+ setFolderInput("");
+ setShowFolderInput(false);
+ refreshLocalModelsList();
+ onFoldersChange?.();
+ // Background reconciliation with the server
+ void refreshScanFolders();
+ } catch (e) {
+ const message = e instanceof Error ? e.message : "Failed to add folder";
+ setFolderError(message);
+ if (fromBrowser) {
+ toast.error("Couldn't add folder", { description: message });
+ }
+ } finally {
+ setFolderLoading(false);
}
- } finally {
- setFolderLoading(false);
- }
- }, [folderInput, folderLoading, refreshScanFolders, refreshLocalModelsList, onFoldersChange]);
-
- const handleRemoveFolder = useCallback(async (id: number) => {
- try {
- await removeScanFolder(id);
- // Optimistic: drop it immediately.
- const next = _scanFoldersCache.filter((f) => f.id !== id);
- _scanFoldersCache = next;
- setScanFolders(next);
- refreshScanFolders();
- refreshLocalModelsList();
- onFoldersChange?.();
- } catch (e) {
- toast.error(e instanceof Error ? e.message : "Failed to remove folder");
- refreshScanFolders();
- }
- }, [refreshScanFolders, refreshLocalModelsList, onFoldersChange]);
+ },
+ [
+ folderInput,
+ folderLoading,
+ refreshScanFolders,
+ refreshLocalModelsList,
+ onFoldersChange,
+ ],
+ );
+
+ const handleRemoveFolder = useCallback(
+ async (id: number) => {
+ try {
+ await removeScanFolder(id);
+ // Optimistic: drop it immediately.
+ const next = _scanFoldersCache.filter((f) => f.id !== id);
+ _scanFoldersCache = next;
+ setScanFolders(next);
+ refreshScanFolders();
+ refreshLocalModelsList();
+ onFoldersChange?.();
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : "Failed to remove folder");
+ refreshScanFolders();
+ }
+ },
+ [refreshScanFolders, refreshLocalModelsList, onFoldersChange],
+ );
const refreshCachedLists = useCallback(() => {
listCachedGguf()
@@ -921,11 +1467,33 @@ export function HubModelPicker({
}, [cachedGguf, cachedModels]);
const chatOnly = usePlatformStore((s) => s.isChatOnly());
+ const deviceType = usePlatformStore((s) => s.deviceType);
+ const isMac = deviceType === "mac";
+
+ // Drop models Studio can't run for chat (diffusion / image / video / etc.)
+ // using the Hub's classifier on the tags the listing already carries.
+ const isChatSupported = useCallback(
+ (r: HfModelResult) =>
+ classifyUnslothSupport({
+ modelId: r.id,
+ pipelineTag: r.pipelineTag,
+ tags: r.tags,
+ libraryName: r.libraryName,
+ quantMethod: r.quantMethod,
+ deviceType,
+ }).status !== "unsupported",
+ [deviceType],
+ );
const recommendedIds = useMemo(() => {
const all = dedupe([...models.map((model) => model.id), value ?? ""])
+ .filter((id) => !isHiddenModelId(id))
.filter((id) => !downloadedSet.has(id.toLowerCase()))
- .filter((id) => !chatOnly || isKnownGgufRepo(id))
+ // Chat-only keeps runnable formats: GGUF anywhere, plus MLX/safetensors
+ // on Mac (matches the empty Recommended view so search stays consistent).
+ .filter(
+ (id) => !chatOnly || isRecommendableFormat(id, isKnownGgufRepo(id), isMac),
+ )
.filter((id) => !/-FP8[-.]|FP8-Dynamic/i.test(id));
// Sort: GGUFs first, then hub models
const gguf: string[] = [];
@@ -935,121 +1503,378 @@ export function HubModelPicker({
else hub.push(id);
}
return [...gguf, ...hub];
- }, [models, value, downloadedSet, chatOnly, isKnownGgufRepo]);
+ }, [models, value, downloadedSet, chatOnly, isKnownGgufRepo, isMac]);
- // Infinite scroll paging for the recommended section
- const [recommendedPage, setRecommendedPage] = useState(1);
- // Reset page when the underlying list changes
- useEffect(() => {
- setRecommendedPage(1);
- }, [models, chatOnly]);
-
- const visibleRecommendedIds = useMemo(() => {
- const hubStartIndex = recommendedIds.findIndex((id) => !isKnownGgufRepo(id));
- const allGguf =
- hubStartIndex === -1
- ? recommendedIds
- : recommendedIds.slice(0, hubStartIndex);
- const allHub =
- hubStartIndex === -1 ? [] : recommendedIds.slice(hubStartIndex);
- // Interleave in chunks of 4: [4 gguf, 4 hub, 4 gguf, 4 hub, ...]
- const result: string[] = [];
- for (let p = 0; p < recommendedPage; p++) {
- result.push(...allGguf.slice(p * 4, (p + 1) * 4));
- result.push(...allHub.slice(p * 4, (p + 1) * 4));
- }
- return result;
- }, [recommendedIds, recommendedPage, isKnownGgufRepo]);
+ const showHfSection = debouncedQuery.trim().length > 0;
- const hasMoreRecommended =
- visibleRecommendedIds.length < recommendedIds.length;
+ // Independent sort for each local section's inline dropdown.
+ const [downloadedSort, setDownloadedSort] = useState<LocalSortKey>("recent");
+ const [customSort, setCustomSort] = useState<LocalSortKey>("recent");
+ // Format filter toggle for the Unsloth listing.
+ const [formatFilter, setFormatFilter] = useState<FormatFilter>("all");
+
+ // Recommended suggests GGUF anywhere; on Mac also MLX and safetensors. The
+ // "recommended" sort also drops models too big for the device. Already-
+ // downloaded models stay visible (badged), never hidden.
+ const recommendedRows = useMemo(() => {
+ // Never list mobile-targeted builds in the Unsloth section.
+ let rows = recommendedSearch.results
+ .filter((r) => !isHiddenModelId(r.id))
+ .filter((r) => !isMobileVariant(r.id));
+ // Drop models Studio can't run for chat (diffusion / image / video / etc.).
+ rows = rows.filter(isChatSupported);
+ // With no explicit format, show the device-recommended formats (GGUF, plus
+ // MLX on Mac). When the user picks a format, honor it instead so Safetensors
+ // is not dropped by the recommendation default.
+ rows =
+ formatFilter === "all"
+ ? rows.filter((r) => isRecommendableFormat(r.id, r.isGguf, isMac))
+ : rows.filter((r) => matchesFormatFilter(r.id, r.isGguf, formatFilter));
+ if (recommendedSort !== "recommended") return rows;
+ return rows.filter((r) => {
+ // Downloaded models always show, regardless of device fit.
+ if (downloadedSet.has(r.id.toLowerCase())) return true;
+ // Unified-memory hosts (Mac / no discrete GPU) still report system RAM,
+ // so fall back to that budget instead of skipping the fit check entirely.
+ const hasDeviceBudget =
+ gpu.memoryTotalGb > 0 || gpu.systemRamAvailableGb > 0;
+ if (!hasDeviceBudget) return true;
+ // GGUF/MLX repos rarely expose safetensors metadata, so fall back to the
+ // GGUF param count, then the repo name, for a size estimate. Anything we
+ // still cannot size is hidden (requireKnown) so over-budget models like a
+ // 1T GGUF don't slip into Recommended.
+ const params = r.totalParams ?? paramsFromId(r.id);
+ const sizeBytes =
+ r.estimatedSizeBytes ??
+ (params ? estimateQuantBytes(params) : undefined);
+ return fitsDevice({
+ sizeBytes,
+ gpuGb: gpu.memoryTotalGb,
+ systemRamGb: gpu.systemRamAvailableGb,
+ requireKnown: true,
+ });
+ });
+ }, [
+ recommendedSearch.results,
+ downloadedSet,
+ recommendedSort,
+ formatFilter,
+ isMac,
+ gpu,
+ isChatSupported,
+ ]);
- const showHfSection = debouncedQuery.trim().length > 0;
+ // Per-row meta + VRAM badge from the recommended listing's own metadata.
+ const recommendedMeta = useMemo(() => {
+ const map = new Map<
+ string,
+ { meta: string | null; status: VramFitStatus | null; est: number }
+ >();
+ for (const r of recommendedSearch.results) {
+ const isG = isKnownGgufRepo(r.id);
+ // GGUF param count comes from the repo name or the GGUF metadata, so even
+ // repos with no "<n>B" token (Kimi, MiniMax) show a param chip.
+ const ggufParams = r.totalParams ?? paramsFromId(r.id);
+ const meta = isG
+ ? [
+ ggufParams ? formatCompact(ggufParams) : null,
+ "GGUF",
+ r.estimatedSizeBytes ? formatBytes(r.estimatedSizeBytes) : null,
+ ]
+ .filter(Boolean)
+ .join(" · ")
+ : [
+ r.totalParams
+ ? formatCompact(r.totalParams)
+ : extractParamLabel(r.id),
+ // MLX and safetensors get a format pill like GGUF.
+ isMlxId(r.id) ? "MLX" : "Safetensors",
+ r.estimatedSizeBytes ? formatBytes(r.estimatedSizeBytes) : null,
+ ]
+ .filter(Boolean)
+ .join(" · ") || null;
+ if (isG) {
+ // GGUF fit is size-based: flag OOM when even the smallest quant we can
+ // size exceeds the device budget. Repos we cannot size show no badge.
+ const params = ggufParams;
+ const sizeBytes =
+ r.estimatedSizeBytes ??
+ (params ? estimateQuantBytes(params) : undefined);
+ const hasDeviceBudget =
+ gpu.memoryTotalGb > 0 || gpu.systemRamAvailableGb > 0;
+ const exceeds =
+ hasDeviceBudget &&
+ sizeBytes != null &&
+ !fitsDevice({
+ sizeBytes,
+ gpuGb: gpu.memoryTotalGb,
+ systemRamGb: gpu.systemRamAvailableGb,
+ });
+ map.set(r.id, {
+ meta,
+ status: exceeds ? "exceeds" : null,
+ est: sizeBytes ? Math.round(sizeBytes / 1024 ** 3) : 0,
+ });
+ continue;
+ }
+ const est = r.totalParams
+ ? estimateLoadingVram(r.totalParams, "qlora")
+ : 0;
+ const status =
+ est > 0 && gpu.available ? checkVramFit(est, gpu.memoryTotalGb) : null;
+ map.set(r.id, { meta, status, est });
+ }
+ return map;
+ }, [recommendedSearch.results, isKnownGgufRepo, gpu]);
+
+ // Tag-accurate capabilities keyed by repo id, pooled from both HF listings.
+ // Rows look it up by id and fall back to name detection when absent.
+ const capsById = useMemo(() => {
+ const map = new Map<string, ModelCapabilities>();
+ for (const r of [...results, ...recommendedSearch.results]) {
+ if (map.has(r.id)) continue;
+ map.set(
+ r.id,
+ detectCapabilities({
+ id: r.id,
+ tags: r.tags,
+ pipelineTag: r.pipelineTag,
+ }),
+ );
+ }
+ return map;
+ }, [results, recommendedSearch.results]);
- // Newest-first (also covers older backends without `last_modified`).
+ // Ordered by the On Device dropdown (recent/download date/size/name).
const sortedCachedGguf = useMemo(
- () => sortByDownloadRecency(cachedGguf),
- [cachedGguf],
+ () => sortCachedRepos(cachedGguf, downloadedSort, loadTimes),
+ [cachedGguf, downloadedSort, loadTimes],
);
const sortedCachedModels = useMemo(
- () => sortByDownloadRecency(cachedModels),
- [cachedModels],
+ () => sortCachedRepos(cachedModels, downloadedSort, loadTimes),
+ [cachedModels, downloadedSort, loadTimes],
+ );
+ // Each local section's search is scoped to its own models (matched by name).
+ const localQuery = normalizeForSearch(debouncedQuery.trim());
+ const matchesLocalQuery = (m: LocalModelInfo) =>
+ !localQuery ||
+ normalizeForSearch(
+ `${m.model_id ?? ""} ${m.display_name} ${m.id}`,
+ ).includes(localQuery);
+ const sortedLmStudio = useMemo(
+ () =>
+ sortLocalModels(
+ lmStudioModels.filter(
+ (m) =>
+ localModelMatchesFormat(m, formatFilter) && matchesLocalQuery(m),
+ ),
+ downloadedSort,
+ loadTimes,
+ ),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [lmStudioModels, downloadedSort, formatFilter, loadTimes, localQuery],
+ );
+ // Local ./models entries. Chat-only Studio runs GGUF (any host) and MLX (Mac
+ // only), so raw checkpoints there are hidden (mirrors the cached non-GGUF
+ // rule). An MLX build a Mac user dropped in ./models stays selectable.
+ const sortedLocalDir = useMemo(
+ () =>
+ sortLocalModels(
+ localDirModels.filter(
+ (m) =>
+ (!chatOnly ||
+ localModelIsGguf(m) ||
+ (isMac && localModelIsMlx(m))) &&
+ localModelMatchesFormat(m, formatFilter) &&
+ matchesLocalQuery(m),
+ ),
+ downloadedSort,
+ loadTimes,
+ ),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [
+ localDirModels,
+ downloadedSort,
+ formatFilter,
+ isMac,
+ loadTimes,
+ localQuery,
+ chatOnly,
+ ],
+ );
+ const sortedCustomFolderModels = useMemo(
+ () =>
+ sortLocalModels(
+ customFolderModels.filter(
+ (m) =>
+ localModelMatchesFormat(m, formatFilter) && matchesLocalQuery(m),
+ ),
+ customSort,
+ loadTimes,
+ ),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [customFolderModels, customSort, formatFilter, loadTimes, localQuery],
);
+ // Fine-tuned models for the On Device "Fine-tuned" section: flat, query-
+ // filtered, newest first.
+ const fineTunedRows = useMemo(() => {
+ const needle = normalizeForSearch(debouncedQuery.trim());
+ return loraModels
+ .filter((m) => {
+ const text = normalizeForSearch(
+ `${m.name} ${m.baseModel ?? ""} ${m.id}`,
+ );
+ return !needle || text.includes(needle);
+ })
+ .slice()
+ .sort((a, b) => {
+ const aTime = a.updatedAt ?? -1;
+ const bTime = b.updatedAt ?? -1;
+ if (aTime !== bTime) return bTime - aTime;
+ return a.name.localeCompare(b.name);
+ });
+ }, [loraModels, debouncedQuery]);
+
// While searching, filter Downloaded by the query instead of hiding it, so a
// downloaded model the user is searching for stays visible.
const visibleCachedGguf = useMemo(() => {
- if (!showHfSection) return sortedCachedGguf;
+ if (!showHfSection)
+ return sortedCachedGguf.filter((c) =>
+ matchesFormatFilter(c.repo_id, true, formatFilter),
+ );
const q = normalizeForSearch(debouncedQuery.trim());
- return sortedCachedGguf.filter((c) => normalizeForSearch(c.repo_id).includes(q));
- }, [sortedCachedGguf, showHfSection, debouncedQuery]);
+ // Keep the format filter active while searching so the dropdown stays
+ // consistent with the no-query branch (Safetensors selected shouldn't show
+ // GGUF downloads just because the user typed).
+ return sortedCachedGguf.filter(
+ (c) =>
+ matchesFormatFilter(c.repo_id, true, formatFilter) &&
+ normalizeForSearch(c.repo_id).includes(q),
+ );
+ }, [sortedCachedGguf, showHfSection, debouncedQuery, formatFilter]);
const visibleCachedModels = useMemo(() => {
- if (!showHfSection) return sortedCachedModels;
+ if (!showHfSection)
+ return sortedCachedModels.filter((c) =>
+ matchesFormatFilter(c.repo_id, false, formatFilter),
+ );
const q = normalizeForSearch(debouncedQuery.trim());
- return sortedCachedModels.filter((c) => normalizeForSearch(c.repo_id).includes(q));
- }, [sortedCachedModels, showHfSection, debouncedQuery]);
+ return sortedCachedModels.filter(
+ (c) =>
+ matchesFormatFilter(c.repo_id, false, formatFilter) &&
+ normalizeForSearch(c.repo_id).includes(q),
+ );
+ }, [sortedCachedModels, showHfSection, debouncedQuery, formatFilter]);
// Non-GGUF cached rows are not shown in chat-only mode, so the empty-state
// logic must use this (not visibleCachedModels) or the picker can go blank.
const visibleCachedModelRows = chatOnly ? [] : visibleCachedModels;
+ // Split downloaded models so non-Unsloth repos get their own "Other models"
+ // section above Fine-tuned.
+ const unslothCachedGguf = useMemo(
+ () => visibleCachedGguf.filter((c) => isUnslothRepoId(c.repo_id)),
+ [visibleCachedGguf],
+ );
+ const otherCachedGguf = useMemo(
+ () => visibleCachedGguf.filter((c) => !isUnslothRepoId(c.repo_id)),
+ [visibleCachedGguf],
+ );
+ const unslothCachedModelRows = useMemo(
+ () => visibleCachedModelRows.filter((c) => isUnslothRepoId(c.repo_id)),
+ [visibleCachedModelRows],
+ );
+ const otherCachedModelRows = useMemo(
+ () => visibleCachedModelRows.filter((c) => !isUnslothRepoId(c.repo_id)),
+ [visibleCachedModelRows],
+ );
+
// Recommended models that match the current search query
const filteredRecommendedIds = useMemo(() => {
if (!showHfSection) return [];
const q = normalizeForSearch(debouncedQuery.trim());
- return recommendedIds.filter((id) => normalizeForSearch(id).includes(q));
- }, [showHfSection, debouncedQuery, recommendedIds]);
-
- // VRAM info for visible models plus any surfaced by a search query, so
- // filtered recommended models also show VRAM badges. Skip GGUF repos:
- // no safetensors metadata, and the render layer shows a "GGUF" badge.
- const idsForVram = useMemo(() => {
- const ids = showHfSection
- ? [...new Set([...visibleRecommendedIds, ...filteredRecommendedIds])]
- : visibleRecommendedIds;
- return ids.filter((id) => !isKnownGgufRepo(id));
- }, [visibleRecommendedIds, showHfSection, filteredRecommendedIds, isKnownGgufRepo]);
- const { paramCountById: recommendedParamCountById } =
- useRecommendedModelVram(idsForVram);
+ return recommendedIds
+ .filter((id) => normalizeForSearch(id).includes(q))
+ .filter((id) =>
+ matchesFormatFilter(id, isKnownGgufRepo(id), formatFilter),
+ );
+ }, [
+ showHfSection,
+ debouncedQuery,
+ recommendedIds,
+ formatFilter,
+ isKnownGgufRepo,
+ ]);
+
+ // Param counts come straight off the unsloth listings the picker already
+ // loaded, so no extra per-id fetch is needed for the VRAM badges.
+ const recommendedParamCountById = useMemo(() => {
+ const map = new Map<string, number>();
+ for (const r of [...results, ...recommendedSearch.results]) {
+ if (r.totalParams) map.set(r.id, r.totalParams);
+ }
+ return map;
+ }, [results, recommendedSearch.results]);
const recommendedSet = useMemo(
- () =>
- new Set(showHfSection ? filteredRecommendedIds : visibleRecommendedIds),
- [showHfSection, filteredRecommendedIds, visibleRecommendedIds],
+ () => new Set(filteredRecommendedIds),
+ [filteredRecommendedIds],
);
const hfIds = useMemo(() => {
- if (!showHfSection) return [];
+ // Only the Unsloth tab searches the HF listing, and only Unsloth models.
+ if (!showHfSection || section !== "recommended") return [];
return results
+ .filter(isChatSupported)
.map((result) => result.id)
+ .filter((id) => !isHiddenModelId(id))
+ .filter((id) => id.toLowerCase().startsWith("unsloth/"))
.filter((id) => !recommendedSet.has(id))
- // Shown under Downloaded (kept visible while searching); no duplicate.
- .filter((id) => !downloadedSet.has(id.toLowerCase()))
- .filter((id) => !chatOnly || isKnownGgufRepo(id))
- .filter((id) => !/-FP8[-.]|FP8-Dynamic/i.test(id));
- }, [recommendedSet, downloadedSet, results, showHfSection, chatOnly, isKnownGgufRepo]);
+ // Chat-only keeps runnable formats: GGUF anywhere, plus MLX/safetensors
+ // on Mac (matches the empty Recommended view so search stays consistent).
+ .filter(
+ (id) => !chatOnly || isRecommendableFormat(id, isKnownGgufRepo(id), isMac),
+ )
+ .filter((id) => !/-FP8[-.]|FP8-Dynamic/i.test(id))
+ .filter((id) =>
+ matchesFormatFilter(id, isKnownGgufRepo(id), formatFilter),
+ );
+ }, [
+ recommendedSet,
+ results,
+ showHfSection,
+ section,
+ chatOnly,
+ isKnownGgufRepo,
+ isChatSupported,
+ formatFilter,
+ isMac,
+ ]);
const hubOptionKeys = useMemo(() => {
const keys: string[] = [];
+ // Downloaded (Unsloth) rows (query-filtered) on the On Device tab only.
if (
+ section === "downloaded" &&
cachedReady &&
!downloadedCollapsed &&
- (visibleCachedGguf.length > 0 || visibleCachedModelRows.length > 0)
+ (unslothCachedGguf.length > 0 || unslothCachedModelRows.length > 0)
) {
keys.push(
- ...visibleCachedGguf.map((model) =>
+ ...unslothCachedGguf.map((model) =>
makeModelOptionKey("downloaded-gguf", model.repo_id),
),
);
keys.push(
- ...visibleCachedModelRows.map((model) =>
+ ...unslothCachedModelRows.map((model) =>
makeModelOptionKey("downloaded-model", model.repo_id),
),
);
}
- if (showHfSection) {
+ // Unsloth-tab search keys (curated matches + HF unsloth results).
+ if (showHfSection && section === "recommended") {
keys.push(
...filteredRecommendedIds.map((id) =>
makeModelOptionKey("search-recommended", id),
@@ -1059,45 +1884,84 @@ export function HubModelPicker({
return keys;
}
- if (chatOnly) {
+ // Other (non-Unsloth) downloaded rows sit just above Fine-tuned.
+ if (
+ section === "downloaded" &&
+ cachedReady &&
+ !otherModelsCollapsed &&
+ (otherCachedGguf.length > 0 || otherCachedModelRows.length > 0)
+ ) {
keys.push(
- ...lmStudioModels.map((model) =>
- makeModelOptionKey("lm-studio", model.id),
+ ...otherCachedGguf.map((model) =>
+ makeModelOptionKey("downloaded-gguf", model.repo_id),
+ ),
+ );
+ keys.push(
+ ...otherCachedModelRows.map((model) =>
+ makeModelOptionKey("downloaded-model", model.repo_id),
),
);
}
- if (!customFoldersCollapsed) {
+ // Fine-tuned models sit below downloaded, above custom folders.
+ if (section === "downloaded" && !fineTunedCollapsed) {
+ keys.push(...fineTunedRows.map((m) => makeModelOptionKey("lora", m.id)));
+ }
+
+ // Custom folders sit right below the downloaded models on On Device.
+ if (section === "downloaded" && !customFoldersCollapsed) {
keys.push(
- ...customFolderModels.map((model) =>
+ ...sortedCustomFolderModels.map((model) =>
makeModelOptionKey("custom-folder", model.id),
),
);
}
- if (cachedReady && !recommendedCollapsed) {
+ if (section === "downloaded" && !lmStudioCollapsed) {
+ keys.push(
+ ...sortedLmStudio.map((model) =>
+ makeModelOptionKey("lm-studio", model.id),
+ ),
+ );
+ }
+
+ if (section === "downloaded" && !localDirCollapsed) {
keys.push(
- ...visibleRecommendedIds.map((id) =>
- makeModelOptionKey("recommended", id),
+ ...sortedLocalDir.map((model) =>
+ makeModelOptionKey("local-dir", model.id),
),
);
}
+ if (section === "recommended") {
+ keys.push(
+ ...recommendedRows.map((r) => makeModelOptionKey("recommended", r.id)),
+ );
+ }
+
return keys;
}, [
cachedReady,
chatOnly,
- customFolderModels,
+ sortedCustomFolderModels,
customFoldersCollapsed,
downloadedCollapsed,
+ fineTunedRows,
+ fineTunedCollapsed,
filteredRecommendedIds,
hfIds,
- lmStudioModels,
- recommendedCollapsed,
+ sortedLmStudio,
+ lmStudioCollapsed,
+ recommendedRows,
+ section,
showHfSection,
- visibleCachedGguf,
- visibleCachedModelRows,
- visibleRecommendedIds,
+ sortedLocalDir,
+ localDirCollapsed,
+ unslothCachedGguf,
+ unslothCachedModelRows,
+ otherCachedGguf,
+ otherCachedModelRows,
+ otherModelsCollapsed,
]);
const selectedHubOptionKey = useMemo(
@@ -1153,9 +2017,10 @@ export function HubModelPicker({
string,
{ est: number; status: VramFitStatus | null; detail: string | null }
>();
- const ids = showHfSection ? filteredRecommendedIds : visibleRecommendedIds;
- for (const id of ids) {
- const totalParams = recommendedParamCountById.get(id);
+ for (const id of filteredRecommendedIds) {
+ // GGUF fit is size-based and badged elsewhere; skip the qlora estimate.
+ if (isKnownGgufRepo(id)) continue;
+ const totalParams = recommendedParamCountById.get(id) ?? paramsFromId(id);
if (totalParams) {
const est = estimateLoadingVram(totalParams, "qlora");
const status = gpu.available
@@ -1166,47 +2031,66 @@ export function HubModelPicker({
}
}
return map;
- }, [
- showHfSection,
- filteredRecommendedIds,
- visibleRecommendedIds,
- recommendedParamCountById,
- gpu,
- ]);
+ }, [filteredRecommendedIds, recommendedParamCountById, isKnownGgufRepo, gpu]);
- const { scrollRef, sentinelRef } = useInfiniteScroll(
+ const { scrollRef, sentinelRef } = useHubInfiniteScroll(
fetchMore,
- results.length,
+ scannedCount,
+ {
+ enabled: online && hasMore,
+ isFetching: isLoading || isLoadingMore,
+ resultCount: results.length,
+ resetKey: debouncedQuery,
+ },
);
- // Sentinel + IntersectionObserver for recommended infinite scroll.
- // Disconnect after each fire so it doesn't loop during re-render; the
- // effect re-creates it next page. Callback ref detects mount/unmount.
+ // Recompute the top/bottom edge fades from the scroll position.
+ const updateListFades = useCallback((el: HTMLDivElement) => {
+ const scrolled = el.scrollTop > 0;
+ setListScrolled((prev) => (prev === scrolled ? prev : scrolled));
+ const moreBelow = el.scrollHeight - el.scrollTop - el.clientHeight > 1;
+ setListMoreBelow((prev) => (prev === moreBelow ? prev : moreBelow));
+ }, []);
+
+ // Keep the fades in sync when rows are added, removed, or filtered.
+ useEffect(() => {
+ const el = scrollRef.current;
+ if (!el) return;
+ updateListFades(el);
+ const observer = new ResizeObserver(() => updateListFades(el));
+ observer.observe(el);
+ if (el.firstElementChild) observer.observe(el.firstElementChild);
+ return () => observer.disconnect();
+ }, [scrollRef, updateListFades]);
+
+ // Sentinel + IntersectionObserver for recommended infinite scroll. Re-running
+ // on each loaded page (results length) re-attaches the observer so a heavily
+ // filtered list keeps paging until the viewport fills or the listing ends;
+ // fetchMore is a no-op while a page is in flight. Callback ref tracks mount.
const [recommendedSentinel, setRecommendedSentinel] =
useState<HTMLDivElement | null>(null);
const recommendedSentinelRef = useCallback((node: HTMLDivElement | null) => {
setRecommendedSentinel(node);
}, []);
useEffect(() => {
- if (!recommendedSentinel || !hasMoreRecommended) return;
+ if (!recommendedSentinel || !recommendedSearch.hasMore) return;
const root = scrollRef.current;
if (!root) return;
const obs = new IntersectionObserver(
([e]) => {
- if (e.isIntersecting) {
- obs.disconnect();
- setRecommendedPage((p) => p + 1);
- }
+ if (e.isIntersecting) recommendedSearch.fetchMore();
},
{ threshold: 0, root },
);
- // Small delay so layout settles after the previous page render.
- const timer = setTimeout(() => obs.observe(recommendedSentinel), 100);
- return () => {
- clearTimeout(timer);
- obs.disconnect();
- };
- }, [recommendedSentinel, hasMoreRecommended, recommendedPage, scrollRef]);
+ obs.observe(recommendedSentinel);
+ return () => obs.disconnect();
+ }, [
+ recommendedSentinel,
+ recommendedSearch.hasMore,
+ recommendedSearch.fetchMore,
+ recommendedSearch.results.length,
+ scrollRef,
+ ]);
/** Handle clicking a model row — GGUF repos expand, others load directly. */
const handleModelClick = useCallback(
@@ -1215,961 +2099,1468 @@ export function HubModelPicker({
// Toggle GGUF variant expander
setExpandedGguf((prev) => (prev === id ? null : id));
} else {
- onSelect(id, { source: "hub", isLora: false });
+ // Cached repos load now; uncached ones download via the Hub manager.
+ onSelect(id, {
+ source: "hub",
+ isLora: false,
+ isDownloaded: downloadedSet.has(id.toLowerCase()),
+ });
}
},
- [onSelect, isKnownGgufRepo],
+ [onSelect, isKnownGgufRepo, downloadedSet],
);
- return (
- <div className="space-y-2">
- <div className="relative">
- <HugeiconsIcon
- icon={Search01Icon}
- className="pointer-events-none absolute left-2.5 top-2.5 size-4 text-muted-foreground"
- />
- <Input
- value={query}
- onChange={(event) => setQuery(event.target.value)}
- placeholder="Search models"
- data-model-picker-search-input={true}
- className="h-9 border-[#f2f2f2] dark:border-input pl-8 pr-8"
- />
- {isLoading && (
- <Spinner className="pointer-events-none absolute right-2.5 top-2.5 size-4 text-muted-foreground" />
+ // On Device owns the downloaded and custom-folder models; the Unsloth tab
+ // searches the HF listing (below). Both filter locally by the query.
+ const showDownloaded = section === "downloaded";
+ const showCustom = section === "downloaded";
+ const showRecommendedSection = !showHfSection && section === "recommended";
+ const downloadedEmpty =
+ visibleCachedGguf.length === 0 &&
+ visibleCachedModelRows.length === 0 &&
+ sortedLmStudio.length === 0 &&
+ sortedLocalDir.length === 0 &&
+ // Fine-tuned models are on-device too: don't show the empty state above a
+ // non-empty Fine-tuned section.
+ fineTunedRows.length === 0;
+
+ // Sort dropdown shown inline to the right of the section toggle. Options
+ // depend on the tab and stay visible while searching so results can be
+ // sorted. Fixed width matching the Search Hub button so it and the format
+ // dropdown always line up; text-xs matches that button too. The trigger label
+ // clips (no ellipsis) when long; the open menu expands to show it in full.
+ const sortTriggerClassName =
+ "w-[110px] shrink-0 justify-between pr-2.5 !border-0 text-xs [&>span]:!text-clip";
+ // Tighter menu like the Projects activity Select: less left/top padding and
+ // text-xs to match the trigger. Keep the option's right padding so the
+ // selected-item checkmark never overlaps the label.
+ const sortMenuContentClassName =
+ "!p-1 !rounded-[14px] [&_[role=option]]:!pl-2 [&_[role=option]]:!py-1.5 [&_[role=option]]:!text-xs [&_[role=option]]:!rounded-[10px]";
+ const sectionSortDropdown =
+ section === "recommended" ? (
+ <HubOptionMenu
+ value={recommendedSort}
+ options={RECOMMENDED_SORT_OPTIONS}
+ onValueChange={setRecommendedSort}
+ ariaLabel="Sort Unsloth models"
+ align="end"
+ className={sortTriggerClassName}
+ contentClassName={sortMenuContentClassName}
+ />
+ ) : section === "downloaded" ? (
+ <HubOptionMenu
+ value={downloadedSort}
+ options={LOCAL_SORT_OPTIONS}
+ onValueChange={setDownloadedSort}
+ ariaLabel="Sort downloaded models"
+ align="end"
+ className={sortTriggerClassName}
+ contentClassName={sortMenuContentClassName}
+ />
+ ) : (
+ <HubOptionMenu
+ value={customSort}
+ options={LOCAL_SORT_OPTIONS}
+ onValueChange={setCustomSort}
+ ariaLabel="Sort custom models"
+ align="end"
+ className={sortTriggerClassName}
+ contentClassName={sortMenuContentClassName}
+ />
+ );
+
+ // Connected models grouped by provider, filtered by the shared search query.
+ const connectedGroups = useMemo(() => {
+ const needle = normalizeForSearch(debouncedQuery.trim());
+ const byProvider = new Map<
+ string,
+ {
+ providerId: string;
+ providerName: string;
+ providerType: string;
+ models: ExternalModelOption[];
+ }
+ >();
+ for (const model of externalModels) {
+ const text = normalizeForSearch(
+ `${model.name} ${model.providerName} ${model.id}`,
+ );
+ if (needle && !text.includes(needle)) continue;
+ const prev = byProvider.get(model.providerId);
+ if (prev) {
+ prev.models.push(model);
+ } else {
+ byProvider.set(model.providerId, {
+ providerId: model.providerId,
+ providerName: model.providerName,
+ providerType: model.providerType,
+ models: [model],
+ });
+ }
+ }
+ return [...byProvider.values()]
+ .map((group) => ({
+ ...group,
+ models: group.models.sort((a, b) => a.name.localeCompare(b.name)),
+ }))
+ .sort((a, b) => a.providerName.localeCompare(b.providerName));
+ }, [externalModels, debouncedQuery]);
+ const showConnected = section === "connected";
+ // The Connected layout uses a wider box, so it drops the search inset to keep
+ // Search Hub on the last dropdown's edge while the right gap matches the left.
+ const hasConnected = externalModels.length > 0;
+ // The Other models section and its shortcut only show with non-Unsloth downloads.
+ const hasOtherModels =
+ otherCachedGguf.length > 0 || otherCachedModelRows.length > 0;
+
+ const downloadedRowButtonClassName =
+ "bg-transparent pr-1 hover:bg-transparent focus-visible:bg-transparent dark:bg-transparent dark:hover:bg-transparent dark:focus-visible:bg-transparent";
+ const downloadedRowShellClassName = (selected: boolean) =>
+ cn(
+ "group flex items-center rounded-full transition-colors hover:bg-[#ececec] focus-within:bg-[#ececec] dark:hover:bg-[var(--sidebar-accent)] dark:focus-within:bg-[var(--sidebar-accent)]",
+ selected && "bg-[#ececec] dark:bg-[var(--sidebar-accent)]",
+ );
+
+ // Shared row renderers so Downloaded (Unsloth) and Other models render alike.
+ const renderDownloadedGgufRow = (c: (typeof visibleCachedGguf)[number]) => {
+ const optionKey = makeModelOptionKey("downloaded-gguf", c.repo_id);
+ const isSelected = value === c.repo_id;
+ return (
+ <div key={c.repo_id}>
+ <div className={downloadedRowShellClassName(isSelected)}>
+ <div className="min-w-0 flex-1">
+ <ModelRow
+ label={c.repo_id}
+ meta="GGUF"
+ showVision={c.has_vision ?? visionByRepo[c.repo_id]}
+ selected={isSelected}
+ optionProps={hubModelList.getOptionProps(optionKey, isSelected)}
+ onClick={() => toggleGgufExpanded(c.repo_id)}
+ onArrowDownIntoChildren={
+ isGgufExpanded(c.repo_id)
+ ? () => focusFirstChildOption(optionKey)
+ : undefined
+ }
+ vramStatus={null}
+ className={downloadedRowButtonClassName}
+ />
+ </div>
+ <span aria-hidden="true" className="mr-1 h-6 w-[26px] shrink-0" />
+ </div>
+ {isGgufExpanded(c.repo_id) && (
+ <GgufVariantExpander
+ repoId={c.repo_id}
+ onDevice={true}
+ onHasVision={(v) => reportVision(c.repo_id, v)}
+ onSelect={onSelect}
+ parentOptionKey={optionKey}
+ onNavigatePastStart={() => hubModelList.focusOption(optionKey)}
+ onNavigatePastEnd={() => hubModelList.moveFocus(optionKey, "next")}
+ gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
+ systemRamGb={gpu.systemRamAvailableGb || undefined}
+ onDeleteVariant={async (quant) => {
+ await deleteCachedModel(c.repo_id, quant);
+ refreshCachedLists();
+ }}
+ />
)}
</div>
-
+ );
+ };
+ const renderDownloadedModelRow = (
+ c: (typeof visibleCachedModelRows)[number],
+ ) => {
+ const optionKey = makeModelOptionKey("downloaded-model", c.repo_id);
+ const isSelected = value === c.repo_id;
+ return (
<div
- ref={scrollRef}
- className="max-h-64 overflow-y-auto"
- {...hubModelList.listboxProps}
+ key={c.repo_id}
+ className={downloadedRowShellClassName(isSelected)}
>
- <div className="py-1">
- {/* First-load spinner only when nothing cached is shown yet. */}
- {!cachedReady &&
- !showHfSection &&
- visibleCachedGguf.length === 0 &&
- visibleCachedModelRows.length === 0 ? (
- <div className="flex items-center gap-2 px-5 py-3">
- <Spinner className="size-3 text-muted-foreground" />
- <span className="text-xs text-muted-foreground">
- Loading models…
- </span>
- </div>
- ) : null}
-
- {/* Downloaded stays visible (filtered) while searching. */}
- {visibleCachedGguf.length > 0 || visibleCachedModelRows.length > 0 ? (
+ <div className="min-w-0 flex-1">
+ <ModelRow
+ label={c.repo_id}
+ meta={`${isMlxId(c.repo_id) ? "MLX" : "Safetensors"} · ${formatBytes(
+ c.size_bytes,
+ )}`}
+ selected={isSelected}
+ optionProps={hubModelList.getOptionProps(
+ optionKey,
+ isSelected,
+ )}
+ onClick={() =>
+ onSelect(c.repo_id, {
+ source: "hub",
+ isLora: false,
+ isDownloaded: true,
+ })
+ }
+ vramStatus={null}
+ className={downloadedRowButtonClassName}
+ />
+ </div>
+ <ModelDeleteAction
+ ariaLabel={`Delete ${c.repo_id}`}
+ title="Delete cached model?"
+ description={
<>
- <ListLabel
- icon={<HugeiconsIcon icon={Download01Icon} className="size-3" />}
- collapsed={downloadedCollapsed}
- onToggle={() => setDownloadedCollapsed((v) => !v)}
- >Downloaded</ListLabel>
- {!downloadedCollapsed &&
- visibleCachedGguf.map((c) => {
- const optionKey = makeModelOptionKey("downloaded-gguf", c.repo_id);
- return (
- <div key={c.repo_id}>
- <ModelRow
- label={c.repo_id}
- meta={`GGUF · ${formatBytes(c.size_bytes)}`}
- selected={value === c.repo_id}
- optionProps={hubModelList.getOptionProps(
- optionKey,
- value === c.repo_id,
- )}
- onClick={() =>
- setExpandedGguf((prev) =>
- prev === c.repo_id ? null : c.repo_id,
- )
- }
- onArrowDownIntoChildren={
- expandedGguf === c.repo_id
- ? () => {
- const focused = focusFirstChildOption(optionKey);
- return focused;
- }
- : undefined
- }
- vramStatus={null}
- />
- {expandedGguf === c.repo_id && (
- <GgufVariantExpander
- repoId={c.repo_id}
- onSelect={onSelect}
- parentOptionKey={optionKey}
- onNavigatePastStart={() =>
- hubModelList.focusOption(optionKey)
- }
- onNavigatePastEnd={() =>
- hubModelList.moveFocus(optionKey, "next")
- }
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- systemRamGb={
- gpu.available ? gpu.systemRamAvailableGb : undefined
- }
- onDeleteVariant={async (quant) => {
- await deleteCachedModel(c.repo_id, quant);
- refreshCachedLists();
- }}
- />
- )}
- </div>
- );
- })}
- {!downloadedCollapsed &&
- visibleCachedModelRows.map((c) => {
- const optionKey = makeModelOptionKey("downloaded-model", c.repo_id);
- return (
- <div key={c.repo_id} className="flex items-center gap-0.5">
- <div className="min-w-0 flex-1">
- <ModelRow
- label={c.repo_id}
- meta={formatBytes(c.size_bytes)}
- selected={value === c.repo_id}
- optionProps={hubModelList.getOptionProps(
- optionKey,
- value === c.repo_id,
- )}
- onClick={() =>
- onSelect(c.repo_id, {
- source: "hub",
- isLora: false,
- isDownloaded: true,
- })
- }
- vramStatus={null}
- />
- </div>
- <ModelDeleteAction
- ariaLabel={`Delete ${c.repo_id}`}
- title="Delete cached model?"
- description={
- <>
- This will remove{" "}
- <span className="font-medium text-foreground">
- {c.repo_id}
- </span>{" "}
- from disk. You can re-download it later.
- </>
- }
- successMessage={`Deleted ${c.repo_id}`}
- onConfirm={() => deleteCachedModel(c.repo_id)}
- onDeleted={refreshCachedLists}
- />
- </div>
- );
- })}
+ This will remove{" "}
+ <span className="font-medium text-foreground">{c.repo_id}</span>{" "}
+ from disk. You can re-download it later.
</>
- ) : null}
+ }
+ successMessage={`Deleted ${c.repo_id}`}
+ buttonClassName="mr-1"
+ onConfirm={() => deleteCachedModel(c.repo_id)}
+ onDeleted={refreshCachedLists}
+ />
+ </div>
+ );
+ };
- {!showHfSection && chatOnly && lmStudioModels.length > 0 ? (
- <>
- <ListLabel>LM Studio</ListLabel>
- {lmStudioModels.map((m) => {
- const isGgufFile = m.path.toLowerCase().endsWith(".gguf");
- const isGguf = isGgufRepo(m.id) || isGgufRepo(m.display_name);
- const optionKey = makeModelOptionKey("lm-studio", m.id);
- return (
- <div key={m.id}>
- <ModelRow
- label={m.model_id ?? m.display_name}
- meta={isGguf || isGgufFile ? "GGUF" : "Local"}
- selected={value === m.id}
- optionProps={hubModelList.getOptionProps(
- optionKey,
- value === m.id,
- )}
- onClick={() => {
- if (isGguf) {
- setExpandedGguf((prev) =>
- prev === m.id ? null : m.id,
- );
- } else {
- onSelect(m.id, {
- source: "local",
- isLora: false,
- isDownloaded: true,
- isGguf: isGgufFile,
- });
- }
- }}
- onArrowDownIntoChildren={
- expandedGguf === m.id
- ? () => {
- const focused = focusFirstChildOption(optionKey);
- return focused;
- }
- : undefined
- }
- vramStatus={null}
+ return (
+ <div className="relative space-y-2">
+ {/* A small right inset shortens the search bar so Search Hub lands on the
+ last dropdown's right edge (none on the wider Connected box). */}
+ <div
+ className={cn(
+ "flex items-center gap-2 pb-1",
+ hasConnected ? "pr-0" : "pr-2",
+ )}
+ >
+ <div className="relative flex-1">
+ <HugeiconsIcon
+ icon={Search01Icon}
+ className="pointer-events-none absolute left-2.5 top-2.5 size-4 text-muted-foreground"
+ />
+ <Input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder="Search models"
+ data-model-picker-search-input={true}
+ className="field-soft h-9 border-0 pl-8 pr-8"
+ />
+ {isLoading && (
+ <Spinner className="pointer-events-none absolute right-2.5 top-2.5 size-4 text-muted-foreground" />
+ )}
+ </div>
+ {onBrowseHub ? (
+ <button
+ type="button"
+ onClick={onBrowseHub}
+ aria-label="Search more models on the Hub"
+ className="hub-tab-toggle-pill flex h-9 w-[110px] shrink-0 items-center justify-center gap-[5px] rounded-full border-0 text-xs text-foreground transition-colors"
+ >
+ <HugeiconsIcon icon={DashboardCircleIcon} className="size-4" />
+ Search Hub
+ </button>
+ ) : null}
+ </div>
+
+ {/* Section tabs then the format and sort dropdowns, packed left with one
+ uniform gap between every control. The box is sized so the last
+ dropdown still lands on Search Hub's edge. Dropdowns hide on Connected. */}
+ <div className="flex items-center gap-2">
+ {sectionToggle}
+ {showConnected ? null : (
+ <div className="flex items-center gap-2">
+ <HubOptionMenu
+ value={formatFilter}
+ options={FORMAT_FILTER_OPTIONS}
+ onValueChange={setFormatFilter}
+ ariaLabel="Filter by format"
+ align="end"
+ className={sortTriggerClassName}
+ contentClassName={sortMenuContentClassName}
+ />
+ {sectionSortDropdown}
+ </div>
+ )}
+ </div>
+
+ <div
+ ref={scrollRef}
+ onScroll={(e) => updateListFades(e.currentTarget)}
+ className={cn(
+ // List sits within the menu padding so left and right gaps match.
+ // Height tracks the content up to the cap, so short lists do not
+ // leave white space. scroll-py + symmetric px keep the focus ring off
+ // the overflow clip edges during keyboard nav.
+ "model-list-scroll max-h-[21rem] overflow-y-auto scroll-py-1.5 px-0.5 mr-1",
+ listScrolled && "is-scrolled",
+ listMoreBelow && "is-bottom-faded",
+ )}
+ {...hubModelList.listboxProps}
+ >
+ {/* Clear space for the floating Eject pill when scrolled to the end, so
+ its gap above the last row matches its gap below (applies to every
+ section, including Recommended). */}
+ <div
+ className={cn(
+ "pr-0",
+ // On Device pulls the heading block tight to the controls; Recommended
+ // keeps a little more top room above its first row.
+ showDownloaded ? "pt-0" : "pt-[4px]",
+ onEject ? "pb-[60px]" : "pb-4",
+ )}
+ >
+ {showConnected ? (
+ connectedGroups.length === 0 ? (
+ <div className="px-2.5 py-2 text-xs leading-relaxed text-muted-foreground">
+ {externalModels.length === 0
+ ? "No models from your connections. Set up in Settings then Connections."
+ : "No models match your search."}
+ </div>
+ ) : (
+ connectedGroups.map((group) => (
+ <div key={group.providerId}>
+ <div className="flex items-center gap-2 px-2.5 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
+ <ApiProviderLogo
+ providerType={group.providerType}
+ className="size-3.5"
+ title={group.providerName}
/>
- {expandedGguf === m.id && (
- <GgufVariantExpander
- repoId={m.id}
- onSelect={onSelect}
- parentOptionKey={optionKey}
- onNavigatePastStart={() =>
- hubModelList.focusOption(optionKey)
- }
- onNavigatePastEnd={() =>
- hubModelList.moveFocus(optionKey, "next")
- }
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- systemRamGb={
- gpu.available ? gpu.systemRamAvailableGb : undefined
- }
- />
- )}
+ <span className="min-w-0 truncate">
+ {group.providerName}
+ </span>
</div>
- );
- })}
- </>
- ) : null}
-
- {!showHfSection ? (
+ {group.models.map((model) => (
+ <button
+ key={model.id}
+ type="button"
+ onClick={() =>
+ onSelect(model.id, {
+ source: "external",
+ isLora: false,
+ })
+ }
+ className={cn(
+ "flex w-full items-center rounded-md px-2.5 py-1.5 text-left text-sm transition-colors hover:bg-[#ececec] dark:hover:bg-[var(--sidebar-accent)]",
+ value === model.id &&
+ "bg-[#ececec] dark:bg-[var(--sidebar-accent)]",
+ )}
+ >
+ <span className="min-w-0 truncate">{model.name}</span>
+ </button>
+ ))}
+ </div>
+ ))
+ )
+ ) : (
<>
- <div className="flex items-center gap-1 px-2.5 py-1.5">
- <span className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
- <HugeiconsIcon icon={Folder02Icon} className="size-3" />
- Custom Folders
- </span>
- <div className="flex items-center gap-0.5">
- <button
- type="button"
- aria-label={showFolderInput ? "Cancel adding folder" : "Add scan folder by path"}
- title={showFolderInput ? "Cancel" : "Add by typing a path"}
- onClick={() => {
- setShowFolderInput((open) => {
- if (open) { setFolderInput(""); setFolderError(null); }
- return !open;
- });
- }}
- className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
- >
- <HugeiconsIcon icon={showFolderInput ? Cancel01Icon : Add01Icon} className="size-3" />
- </button>
- <button
- type="button"
- aria-label="Browse for a folder on the server"
- title="Browse folders on the server"
- onClick={() => setShowFolderBrowser(true)}
- className="shrink-0 rounded p-0.5 text-muted-foreground/60 transition-colors hover:text-foreground"
- >
- <HugeiconsIcon icon={Search01Icon} className="size-2.5" />
- </button>
+ {/* First-load spinner only when nothing cached is shown yet. */}
+ {showDownloaded &&
+ !cachedReady &&
+ !showHfSection &&
+ downloadedEmpty ? (
+ <div className="flex items-center gap-2 px-5 py-3">
+ <Spinner className="size-3 text-muted-foreground" />
+ <span className="text-xs text-muted-foreground">
+ Loading models…
+ </span>
</div>
- <div className="ml-auto">
- <button
- type="button"
- aria-label={customFoldersCollapsed ? "Expand custom folders" : "Collapse custom folders"}
- title={customFoldersCollapsed ? "Expand" : "Collapse"}
- onClick={() => setCustomFoldersCollapsed((v) => !v)}
- className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
- >
- {customFoldersCollapsed
- ? <ChevronRightIcon className="size-3" />
- : <ChevronDownIcon className="size-3" />}
- </button>
+ ) : null}
+
+ {/* Empty On Device: a search miss vs nothing downloaded yet. Hidden
+ when custom folders below still have matches. */}
+ {showDownloaded &&
+ cachedReady &&
+ downloadedEmpty &&
+ sortedCustomFolderModels.length === 0 ? (
+ <div className="px-2.5 py-2 text-xs text-muted-foreground">
+ {showHfSection
+ ? "No matching models on device."
+ : formatFilter === "all"
+ ? "No downloaded models yet. Search above or pick Recommended."
+ : `No downloaded ${FORMAT_FILTER_LABELS[formatFilter]} models yet.`}
</div>
- </div>
+ ) : null}
- {/* Folder paths */}
- {!customFoldersCollapsed && scanFolders.map((f) => (
- <div
- key={f.id}
- className="group flex items-center gap-1.5 px-2.5 py-0.5"
- >
- <HugeiconsIcon icon={Folder02Icon} className="size-3 shrink-0 text-muted-foreground/40" />
- <span
- className="min-w-0 flex-1 truncate font-mono text-[10px] text-muted-foreground/70"
- title={f.path}
+ {/* Downloaded (Unsloth) stays visible (filtered) while searching. */}
+ {showDownloaded &&
+ (unslothCachedGguf.length > 0 ||
+ unslothCachedModelRows.length > 0) ? (
+ <>
+ <ListLabel
+ collapsed={downloadedCollapsed}
+ onToggle={() => setDownloadedCollapsed((v) => !v)}
+ action={
+ <>
+ {hasOtherModels ? (
+ <Tooltip delayDuration={0}>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ onClick={scrollToOtherModels}
+ aria-label="Go to other models"
+ className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={Flag01Icon}
+ className="size-3"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ className="tooltip-compact"
+ >
+ Other non-Unsloth models
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ <Tooltip delayDuration={0}>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ onClick={scrollToFineTuned}
+ aria-label="Go to fine-tuned models"
+ className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={TrainIcon}
+ className="size-3"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ className="tooltip-compact"
+ >
+ Go to fine-tuned models
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip delayDuration={0}>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ onClick={scrollToCustomFolders}
+ aria-label="Go to custom folders"
+ className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={Folder02Icon}
+ className="size-3"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ className="tooltip-compact"
+ >
+ Go to custom folders
+ </TooltipContent>
+ </Tooltip>
+ </>
+ }
>
- {f.path}
- </span>
- <button
- type="button"
- onClick={() => handleRemoveFolder(f.id)}
- aria-label={`Remove folder ${f.path}`}
- className="shrink-0 rounded p-1 text-foreground/70 transition-colors hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive"
+ {/* When other providers (LM Studio/Ollama) also show here, name
+ this group "Unsloth" so the two are easy to tell apart. */}
+ {sortedLmStudio.length > 0 ? "Unsloth" : "Downloaded"}
+ </ListLabel>
+ {!downloadedCollapsed &&
+ unslothCachedGguf.map(renderDownloadedGgufRow)}
+ {!downloadedCollapsed &&
+ unslothCachedModelRows.map(renderDownloadedModelRow)}
+ </>
+ ) : null}
+
+ {/* Other models: non-Unsloth downloads, grouped just above
+ Fine-tuned. Shown only when such models exist. */}
+ {showDownloaded && hasOtherModels ? (
+ <div ref={otherModelsSectionRef}>
+ <ListLabel
+ divider={true}
+ icon={
+ <HugeiconsIcon icon={Flag01Icon} className="size-3.5" />
+ }
+ collapsed={otherModelsCollapsed}
+ onToggle={() => setOtherModelsCollapsed((v) => !v)}
>
- <HugeiconsIcon icon={Cancel01Icon} className="size-3" />
- </button>
+ Other models
+ </ListLabel>
+ {!otherModelsCollapsed &&
+ otherCachedGguf.map(renderDownloadedGgufRow)}
+ {!otherModelsCollapsed &&
+ otherCachedModelRows.map(renderDownloadedModelRow)}
</div>
- ))}
-
- {/* Recommended folders */}
- {!customFoldersCollapsed && (() => {
- const registered = new Set(scanFolders.map((f) => f.path));
- const unregistered = recommendedFolders.filter((p) => !registered.has(p));
- if (unregistered.length === 0) return null;
- return (
- <div className="flex flex-wrap gap-1 px-2.5 pb-0.5">
- {unregistered.map((p) => (
+ ) : null}
+
+ {/* Fine-tuned models: a section above Custom Folders. Always shown on
+ On Device so the train shortcut always has a target, with an empty
+ state when none exist. */}
+ {section === "downloaded" ? (
+ <>
+ <div
+ ref={fineTunedSectionRef}
+ className="mt-3 flex items-center gap-1 border-t border-border/50 px-2.5 pb-1 pt-3"
+ >
+ <span className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
+ <HugeiconsIcon icon={TrainIcon} className="size-3.5" />
+ Fine-tuned
+ </span>
+ <div className="ml-auto">
<button
- key={p}
type="button"
- onClick={() => void handleAddFolder(p)}
- disabled={folderLoading}
- title={`Add ${p}`}
- className="rounded-full border border-dashed border-border/50 px-2 py-0.5 font-mono text-[10px] text-muted-foreground/70 transition-colors hover:border-foreground/30 hover:bg-accent hover:text-foreground disabled:opacity-40"
+ aria-label={
+ fineTunedCollapsed
+ ? "Expand fine-tuned models"
+ : "Collapse fine-tuned models"
+ }
+ title={fineTunedCollapsed ? "Expand" : "Collapse"}
+ onClick={() => setFineTunedCollapsed((v) => !v)}
+ className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
>
- <span className="text-[11px] font-semibold">+</span> {p.length > 30 ? `...${p.slice(-27)}` : p}
+ {fineTunedCollapsed ? (
+ <ChevronRightIcon className="size-3" />
+ ) : (
+ <ChevronDownIcon className="size-3" />
+ )}
</button>
- ))}
+ </div>
</div>
- );
- })()}
-
- {/* Add folder input */}
- {!customFoldersCollapsed && showFolderInput && (
- <div className="px-2.5 pb-1 pt-0.5">
- <div className="flex items-center gap-1">
- <HugeiconsIcon icon={Folder02Icon} className="size-3 shrink-0 text-muted-foreground/40" />
- <input
- value={folderInput}
- onChange={(e) => { setFolderInput(e.target.value); setFolderError(null); }}
- onKeyDown={(e) => {
- if (e.key === "Enter") { e.preventDefault(); handleAddFolder(); }
- if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); setShowFolderInput(false); setFolderInput(""); setFolderError(null); }
- }}
- placeholder="/path/to/models"
- className="h-6 min-w-0 flex-1 rounded border border-border/50 bg-transparent px-1.5 font-mono text-[10px] text-foreground outline-none placeholder:text-muted-foreground/40 focus:border-foreground/20"
- disabled={folderLoading}
- autoFocus={true}
+ {!fineTunedCollapsed && fineTunedRows.length > 0 && (
+ <FineTunedRows
+ adapters={fineTunedRows}
+ value={value}
+ onSelect={onSelect}
+ onModelsChange={onModelsChange}
+ deleteDisabled={deleteDisabled}
+ loraModelList={hubModelList}
+ expandedGguf={expandedGguf}
+ setExpandedGguf={setExpandedGguf}
+ gpu={gpu}
/>
+ )}
+ </>
+ ) : null}
+
+ {showCustom ? (
+ <>
+ <div
+ ref={customFolderSectionRef}
+ className="mt-3 flex items-center gap-1 border-t border-border/50 px-2.5 pb-1 pt-3"
+ >
<button
type="button"
onClick={() => setShowFolderBrowser(true)}
- disabled={folderLoading}
- aria-label="Browse for folder"
title="Browse folders on the server"
- className="flex h-6 shrink-0 items-center justify-center rounded border border-border/50 px-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
+ className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:text-foreground"
>
- <HugeiconsIcon icon={Search01Icon} className="size-3" />
+ <HugeiconsIcon icon={Folder02Icon} className="size-3.5" />
+ Custom Folders
</button>
- <button
- type="button"
- onClick={() => { void handleAddFolder(); }}
- disabled={folderLoading || !folderInput.trim()}
- className="h-6 shrink-0 rounded border border-border/50 px-1.5 text-[10px] text-muted-foreground transition-colors hover:bg-accent disabled:opacity-40"
- >
- Add
- </button>
- </div>
- {folderError && (
- <p className="px-0.5 pt-0.5 text-[10px] text-destructive">{folderError}</p>
- )}
- </div>
- )}
-
- <FolderBrowser
- open={showFolderBrowser}
- onOpenChange={setShowFolderBrowser}
- initialPath={folderInput.trim() || undefined}
- onSelect={(picked) => {
- setFolderInput(picked);
- setFolderError(null);
- // Pass the path explicitly: `folderInput` state hasn't
- // flushed yet when "Use this folder" submits.
- void handleAddFolder(picked);
- }}
- />
-
-
- {/* Models from custom folders */}
- {!customFoldersCollapsed && customFolderModels.map((m) => {
- const isGgufFile = m.path.toLowerCase().endsWith(".gguf");
- const isGguf =
- isGgufFile ||
- isGgufRepo(m.id) ||
- isGgufRepo(m.display_name);
- // Single .gguf files (e.g. Ollama blobs) load directly;
- // GGUF repos/directories expand to pick a variant.
- const isDirectGguf = isGgufFile;
- const optionKey = makeModelOptionKey("custom-folder", m.id);
- return (
- <div key={m.id}>
- <ModelRow
- label={m.model_id ?? m.display_name}
- meta={isGguf ? "GGUF" : "Local"}
- selected={value === m.id}
- optionProps={hubModelList.getOptionProps(
- optionKey,
- value === m.id,
- )}
- onClick={() => {
- if (isDirectGguf) {
- onSelect(m.id, {
- source: "local",
- isLora: false,
- isDownloaded: true,
- isGguf: true,
- });
- } else if (isGguf) {
- setExpandedGguf((prev) =>
- prev === m.id ? null : m.id,
- );
- } else {
- onSelect(m.id, {
- source: "local",
- isLora: false,
- isDownloaded: true,
- });
- }
- }}
- onArrowDownIntoChildren={
- expandedGguf === m.id
- ? () => {
- const focused = focusFirstChildOption(optionKey);
- return focused;
- }
- : undefined
- }
- vramStatus={null}
- />
- {expandedGguf === m.id && (
- <GgufVariantExpander
- repoId={m.id}
- onSelect={onSelect}
- parentOptionKey={optionKey}
- onNavigatePastStart={() =>
- hubModelList.focusOption(optionKey)
- }
- onNavigatePastEnd={() =>
- hubModelList.moveFocus(optionKey, "next")
- }
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- systemRamGb={
- gpu.available ? gpu.systemRamAvailableGb : undefined
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ aria-label={
+ showFolderInput
+ ? "Cancel adding folder"
+ : "Add scan folder by path"
}
- />
- )}
- </div>
- );
- })}
- </>
- ) : null}
-
- {!showHfSection && cachedReady ? (
- <>
- <ListLabel
- icon={<HugeiconsIcon icon={StarIcon} className="size-3" />}
- collapsed={recommendedCollapsed}
- onToggle={() => setRecommendedCollapsed((v) => !v)}
- >Recommended</ListLabel>
- {recommendedCollapsed ? null : visibleRecommendedIds.length === 0 ? (
- <div className="px-2.5 py-2 text-xs text-muted-foreground">
- No default models.
- </div>
- ) : (
- visibleRecommendedIds.map((id) => {
- const vram = recommendedVramMap.get(id);
- const optionKey = makeModelOptionKey("recommended", id);
- return (
- <div key={id}>
- <ModelRow
- label={id}
- meta={
- isKnownGgufRepo(id)
- ? "GGUF"
- : (vram?.detail ?? extractParamLabel(id))
+ title={
+ showFolderInput ? "Cancel" : "Add by typing a path"
}
- selected={value === id}
- optionProps={hubModelList.getOptionProps(
- optionKey,
- value === id,
- )}
onClick={() => {
- if (isKnownGgufRepo(id)) {
- setExpandedGguf((prev) => (prev === id ? null : id));
- } else {
- handleModelClick(id);
- }
+ setShowFolderInput((open) => {
+ if (open) {
+ setFolderInput("");
+ setFolderError(null);
+ }
+ return !open;
+ });
}}
- vramStatus={
- isKnownGgufRepo(id) ? null : (vram?.status ?? null)
- }
- vramEst={isKnownGgufRepo(id) ? undefined : vram?.est}
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- onArrowDownIntoChildren={
- expandedGguf === id
- ? () => {
- const focused = focusFirstChildOption(optionKey);
- return focused;
- }
- : undefined
- }
- />
- {expandedGguf === id && (
- <GgufVariantExpander
- repoId={id}
- onSelect={onSelect}
- parentOptionKey={optionKey}
- onNavigatePastStart={() =>
- hubModelList.focusOption(optionKey)
- }
- onNavigatePastEnd={() =>
- hubModelList.moveFocus(optionKey, "next")
- }
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- systemRamGb={
- gpu.available ? gpu.systemRamAvailableGb : undefined
- }
+ className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={showFolderInput ? Cancel01Icon : Add01Icon}
+ className="size-3"
/>
- )}
+ </button>
+ <button
+ type="button"
+ aria-label="Browse for a folder on the server"
+ title="Browse folders on the server"
+ onClick={() => setShowFolderBrowser(true)}
+ className="shrink-0 rounded p-0.5 text-muted-foreground/60 transition-colors hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={Search01Icon}
+ className="size-2.5"
+ />
+ </button>
</div>
- );
- })
- )}
- {!recommendedCollapsed && hasMoreRecommended && (
- <>
- <div ref={recommendedSentinelRef} className="h-px" />
- <div className="flex items-center justify-center py-2">
- <Spinner className="size-3.5 text-muted-foreground" />
- </div>
- </>
- )}
- </>
- ) : null}
-
- {showHfSection && filteredRecommendedIds.length > 0 ? (
- <>
- <ListLabel icon={<HugeiconsIcon icon={StarIcon} className="size-3" />}>Recommended</ListLabel>
- {filteredRecommendedIds.map((id) => {
- const vram = recommendedVramMap.get(id);
- const optionKey = makeModelOptionKey("search-recommended", id);
- return (
- <div key={id}>
- <ModelRow
- label={id}
- meta={
- isKnownGgufRepo(id)
- ? "GGUF"
- : (vram?.detail ?? extractParamLabel(id))
- }
- selected={value === id}
- optionProps={hubModelList.getOptionProps(
- optionKey,
- value === id,
- )}
- onClick={() => {
- if (isKnownGgufRepo(id)) {
- setExpandedGguf((prev) => (prev === id ? null : id));
- } else {
- handleModelClick(id);
- }
- }}
- vramStatus={
- isKnownGgufRepo(id) ? null : (vram?.status ?? null)
- }
- vramEst={isKnownGgufRepo(id) ? undefined : vram?.est}
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- onArrowDownIntoChildren={
- expandedGguf === id
- ? () => {
- const focused = focusFirstChildOption(optionKey);
- return focused;
- }
- : undefined
- }
- />
- {expandedGguf === id && (
- <GgufVariantExpander
- repoId={id}
- onSelect={onSelect}
- parentOptionKey={optionKey}
- onNavigatePastStart={() =>
- hubModelList.focusOption(optionKey)
- }
- onNavigatePastEnd={() =>
- hubModelList.moveFocus(optionKey, "next")
- }
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- systemRamGb={
- gpu.available ? gpu.systemRamAvailableGb : undefined
+ <div className="ml-auto">
+ <button
+ type="button"
+ aria-label={
+ customFoldersCollapsed
+ ? "Expand custom folders"
+ : "Collapse custom folders"
}
- />
- )}
+ title={customFoldersCollapsed ? "Expand" : "Collapse"}
+ onClick={() => setCustomFoldersCollapsed((v) => !v)}
+ className="shrink-0 rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground"
+ >
+ {customFoldersCollapsed ? (
+ <ChevronRightIcon className="size-3" />
+ ) : (
+ <ChevronDownIcon className="size-3" />
+ )}
+ </button>
+ </div>
</div>
- );
- })}
- </>
- ) : null}
- {showHfSection ? (
- <>
- {(hfIds.length > 0 || isLoading) && (
- <ListLabel>Hugging Face</ListLabel>
- )}
- {hfIds.length === 0 && !isLoading ? (
- filteredRecommendedIds.length === 0 &&
- visibleCachedGguf.length === 0 &&
- visibleCachedModelRows.length === 0 ? (
- <div className="px-2.5 py-2 text-xs text-muted-foreground">
- No matching models.
- </div>
- ) : null
- ) : (
- hfIds.map((id) => {
- const vram = vramMap.get(id);
- const isSearchGguf = isKnownGgufRepo(id);
- const optionKey = makeModelOptionKey("search-hf", id);
- return (
- <div key={id}>
- <ModelRow
- label={id}
- meta={
- isSearchGguf
- ? "GGUF"
- : (metricsById.get(id) ?? extractParamLabel(id))
- }
- selected={value === id}
- optionProps={hubModelList.getOptionProps(
- optionKey,
- value === id,
- )}
- onClick={() => {
- if (isSearchGguf) {
- setExpandedGguf((prev) => (prev === id ? null : id));
- } else {
- handleModelClick(id);
- }
- }}
- vramStatus={
- isSearchGguf ? null : (vram?.status ?? null)
- }
- vramEst={isSearchGguf ? undefined : vram?.est}
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- onArrowDownIntoChildren={
- expandedGguf === id
- ? () => {
- const focused = focusFirstChildOption(optionKey);
- return focused;
- }
- : undefined
- }
- />
- {expandedGguf === id && (
- <GgufVariantExpander
- repoId={id}
- onSelect={onSelect}
- parentOptionKey={optionKey}
- onNavigatePastStart={() =>
- hubModelList.focusOption(optionKey)
- }
- onNavigatePastEnd={() =>
- hubModelList.moveFocus(optionKey, "next")
- }
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- systemRamGb={
- gpu.available ? gpu.systemRamAvailableGb : undefined
- }
+ {/* Folder paths */}
+ {!customFoldersCollapsed &&
+ scanFolders.map((f) => (
+ <div
+ key={f.id}
+ className="group flex items-center gap-1.5 px-2.5 py-0.5"
+ >
+ <HugeiconsIcon
+ icon={Folder02Icon}
+ className="size-3 shrink-0 text-muted-foreground/40"
+ />
+ <span
+ className="min-w-0 flex-1 truncate font-mono text-[10px] text-muted-foreground/70"
+ title={f.path}
+ >
+ {f.path}
+ </span>
+ <button
+ type="button"
+ onClick={() => handleRemoveFolder(f.id)}
+ aria-label={`Remove folder ${f.path}`}
+ className="shrink-0 rounded p-1 text-foreground/70 transition-colors hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive"
+ >
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ className="size-3"
+ />
+ </button>
+ </div>
+ ))}
+
+ {/* Recommended folders */}
+ {!customFoldersCollapsed &&
+ (() => {
+ const registered = new Set(
+ scanFolders.map((f) => f.path),
+ );
+ const unregistered = recommendedFolders.filter(
+ (p) => !registered.has(p),
+ );
+ if (unregistered.length === 0) return null;
+ return (
+ <div className="flex flex-wrap gap-1 px-2.5 pb-0.5">
+ {unregistered.map((p) => (
+ <button
+ key={p}
+ type="button"
+ onClick={() => void handleAddFolder(p)}
+ disabled={folderLoading}
+ title={`Add ${p}`}
+ className="rounded-full border border-dashed border-border/50 px-2 py-0.5 font-mono text-[10px] text-muted-foreground/70 transition-colors hover:border-foreground/30 hover:bg-accent hover:text-foreground disabled:opacity-40"
+ >
+ <span className="text-[11px] font-semibold">
+ +
+ </span>{" "}
+ {p.length > 30 ? `...${p.slice(-27)}` : p}
+ </button>
+ ))}
+ </div>
+ );
+ })()}
+
+ {/* Add folder input */}
+ {!customFoldersCollapsed && showFolderInput && (
+ <div className="px-2.5 pb-1 pt-0.5">
+ <div className="flex items-center gap-1">
+ <HugeiconsIcon
+ icon={Folder02Icon}
+ className="size-3 shrink-0 text-muted-foreground/40"
/>
+ <input
+ value={folderInput}
+ onChange={(e) => {
+ setFolderInput(e.target.value);
+ setFolderError(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleAddFolder();
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ e.stopPropagation();
+ setShowFolderInput(false);
+ setFolderInput("");
+ setFolderError(null);
+ }
+ }}
+ placeholder="/path/to/models"
+ className="h-6 min-w-0 flex-1 rounded border border-border/50 bg-transparent px-1.5 font-mono text-[10px] text-foreground outline-none placeholder:text-muted-foreground/40 focus:border-foreground/20"
+ disabled={folderLoading}
+ autoFocus={true}
+ />
+ <button
+ type="button"
+ onClick={() => setShowFolderBrowser(true)}
+ disabled={folderLoading}
+ aria-label="Browse for folder"
+ title="Browse folders on the server"
+ className="flex h-6 shrink-0 items-center justify-center rounded border border-border/50 px-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
+ >
+ <HugeiconsIcon
+ icon={Search01Icon}
+ className="size-3"
+ />
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ void handleAddFolder();
+ }}
+ disabled={folderLoading || !folderInput.trim()}
+ className="h-6 shrink-0 rounded border border-border/50 px-1.5 text-[10px] text-muted-foreground transition-colors hover:bg-accent disabled:opacity-40"
+ >
+ Add
+ </button>
+ </div>
+ {folderError && (
+ <p className="px-0.5 pt-0.5 text-[10px] text-destructive">
+ {folderError}
+ </p>
)}
</div>
- );
- })
- )}
- <div ref={sentinelRef} className="h-px" />
- {isLoadingMore ? (
- <div className="flex items-center justify-center py-2">
- <Spinner className="size-3.5 text-muted-foreground" />
- </div>
- ) : null}
- </>
- ) : null}
- </div>
- </div>
-
- </div>
- );
-}
-
-export function LoraModelPicker({
- loraModels,
- value,
- onSelect,
- onModelsChange,
- deleteDisabled = false,
-}: {
- loraModels: LoraModelOption[];
- value?: string;
- onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
- onModelsChange?: (deletedModel?: DeletedModelRef) => void;
- deleteDisabled?: boolean;
-}) {
- const [query, setQuery] = useState("");
- const [expandedGguf, setExpandedGguf] = useState<string | null>(null);
- const gpu = useGpuInfo();
-
- const normalized = useMemo(
- () =>
- loraModels
- .map((model) => ({
- ...model,
- baseModel:
- model.baseModel || model.description || "Unknown base model",
- }))
- .sort((a, b) => {
- const baseCmp = a.baseModel.localeCompare(b.baseModel);
- if (baseCmp !== 0) return baseCmp;
- // Prioritize unsloth publisher within LM Studio group
- if (a.baseModel === "LM Studio" && b.baseModel === "LM Studio") {
- const aUnsloth = a.name.startsWith("unsloth/") ? 0 : 1;
- const bUnsloth = b.name.startsWith("unsloth/") ? 0 : 1;
- if (aUnsloth !== bUnsloth) return aUnsloth - bUnsloth;
- }
- const aTime = a.updatedAt ?? -1;
- const bTime = b.updatedAt ?? -1;
- if (aTime !== bTime) return bTime - aTime;
- return a.name.localeCompare(b.name);
- }),
- [loraModels],
- );
-
- const grouped = useMemo(() => {
- const needle = normalizeForSearch(query.trim());
- const out = new Map<string, LoraModelOption[]>();
-
- for (const model of normalized) {
- const searchText = normalizeForSearch(
- `${model.name} ${model.baseModel} ${model.id}`,
- );
- if (needle && !searchText.includes(needle)) continue;
-
- const key = model.baseModel || "Unknown base model";
- const prev = out.get(key) ?? [];
- prev.push(model);
- out.set(key, prev);
- }
-
- return [...out.entries()].sort((a, b) => {
- const aLatest = Math.max(...a[1].map((model) => model.updatedAt ?? -1));
- const bLatest = Math.max(...b[1].map((model) => model.updatedAt ?? -1));
- if (aLatest !== bLatest) return bLatest - aLatest;
- return a[0].localeCompare(b[0]);
- });
- }, [normalized, query]);
-
- const loraOptionKeys = useMemo(
- () =>
- grouped.flatMap(([, adapters]) =>
- adapters.map((adapter) => makeModelOptionKey("lora", adapter.id)),
- ),
- [grouped],
- );
- const selectedLoraOptionKey = useMemo(
- () =>
- value
- ? loraOptionKeys.find((optionKey) => optionKey.endsWith(`::${value}`))
- : undefined,
- [loraOptionKeys, value],
- );
- const loraModelList = useRovingModelList({
- label: "Fine-tuned models",
- optionKeys: loraOptionKeys,
- selectedOptionKey: selectedLoraOptionKey,
- });
-
- return (
- <div className="space-y-2">
- <div className="relative">
- <HugeiconsIcon
- icon={Search01Icon}
- className="pointer-events-none absolute left-2.5 top-2.5 size-4 text-muted-foreground"
- />
- <Input
- value={query}
- onChange={(event) => setQuery(event.target.value)}
- placeholder="Search trained models"
- data-model-picker-search-input={true}
- className="h-9 border-[#f2f2f2] dark:border-input pl-8"
- />
- </div>
+ )}
- <div className="max-h-64 overflow-y-auto" {...loraModelList.listboxProps}>
- <div className="py-1">
- {grouped.length === 0 ? (
- <div className="px-2.5 py-2 text-xs text-muted-foreground">
- No trained models found.
- </div>
- ) : (
- grouped.map(([baseModel, adapters], index) => (
- <div key={baseModel}>
- {index > 0 ? <div className="my-1" /> : null}
- <ListLabel>{baseModel}</ListLabel>
- {adapters.map((adapter) => {
- const isLocal = adapter.source === "local";
- const isTraining = adapter.source === "training";
- const isExported = adapter.source === "exported";
- const isMerged = adapter.exportType === "merged";
- const isGguf = adapter.exportType === "gguf";
- const isExportedGguf = isExported && isGguf;
- const canDelete = canDeleteLoraModel(adapter);
- const isTrainingFull = isTraining && isMerged;
- const isLocalGgufDir =
- isLocal &&
- (isGgufRepo(adapter.id) || isGgufRepo(adapter.name));
- const optionKey = makeModelOptionKey("lora", adapter.id);
- const tag = isLocal
- ? isLocalGgufDir
- ? "GGUF"
- : "Local"
- : isGguf
- ? "GGUF"
- : isTrainingFull
- ? "Full"
- : isExported
- ? isMerged
- ? "Merged"
- : "LoRA"
- : "LoRA";
- const meta = isLocal
- ? isLocalGgufDir
- ? "GGUF"
- : "Local"
- : isTrainingFull
- ? "Full finetune"
- : isExported
- ? `${tag} · Exported`
- : tag;
- return (
- <div key={adapter.id}>
- <div className="flex items-center gap-0.5">
- <div className="min-w-0 flex-1">
+ <FolderBrowser
+ open={showFolderBrowser}
+ onOpenChange={setShowFolderBrowser}
+ initialPath={folderInput.trim() || undefined}
+ onSelect={(picked) => {
+ setFolderInput(picked);
+ setFolderError(null);
+ // Pass the path explicitly: `folderInput` state hasn't
+ // flushed yet when "Use this folder" submits.
+ void handleAddFolder(picked);
+ }}
+ />
+
+ {/* Models from custom folders */}
+ {!customFoldersCollapsed &&
+ sortedCustomFolderModels.map((m) => {
+ const isGgufFile = m.path.toLowerCase().endsWith(".gguf");
+ // Honor the backend model_format hint (suffixless GGUF
+ // folders) in addition to name/path so the row classifies
+ // and loads through the same GGUF path as the filter.
+ const isGguf = localModelIsGguf(m);
+ // Single .gguf files (e.g. Ollama blobs) load directly;
+ // GGUF repos/directories expand to pick a variant.
+ const isDirectGguf = isGgufFile;
+ const optionKey = makeModelOptionKey(
+ "custom-folder",
+ m.id,
+ );
+ return (
+ <div key={m.id}>
<ModelRow
- label={adapter.name}
- meta={meta}
- selected={value === adapter.id}
- optionProps={loraModelList.getOptionProps(
+ label={m.model_id ?? m.display_name}
+ meta={isGguf ? "GGUF" : "Local"}
+ selected={value === m.id}
+ optionProps={hubModelList.getOptionProps(
optionKey,
- value === adapter.id,
+ value === m.id,
)}
onClick={() => {
- if (isLocalGgufDir || isExportedGguf) {
- setExpandedGguf((prev) =>
- prev === adapter.id ? null : adapter.id,
- );
+ if (isDirectGguf) {
+ onSelect(m.id, {
+ source: "local",
+ isLora: false,
+ isDownloaded: true,
+ // Mark GGUF so "Load on selection = off" stages
+ // through Run settings (matches LM Studio path).
+ isGguf: true,
+ });
+ } else if (isGguf) {
+ toggleGgufExpanded(m.id);
} else {
- onSelect(adapter.id, {
- source: isLocal
- ? "local"
- : isExported
- ? "exported"
- : "lora",
- isLora: !isLocal && !isMerged && !isGguf,
+ onSelect(m.id, {
+ source: "local",
+ isLora: false,
isDownloaded: true,
});
}
}}
- tooltipText={
- <>
- <span className="block break-words">
- {adapter.name}
- </span>
- <span className="block mt-1 text-[10px] text-muted-foreground break-all">
- {adapter.id}
- </span>
- </>
+ onArrowDownIntoChildren={
+ isGgufExpanded(m.id)
+ ? () => {
+ const focused =
+ focusFirstChildOption(optionKey);
+ return focused;
+ }
+ : undefined
}
+ vramStatus={null}
+ />
+ {isGgufExpanded(m.id) && (
+ <GgufVariantExpander
+ repoId={m.id}
+ onDevice={true}
+ onSelect={onSelect}
+ parentOptionKey={optionKey}
+ onNavigatePastStart={() =>
+ hubModelList.focusOption(optionKey)
+ }
+ onNavigatePastEnd={() =>
+ hubModelList.moveFocus(optionKey, "next")
+ }
+ gpuGb={
+ gpu.available ? gpu.memoryTotalGb : undefined
+ }
+ systemRamGb={gpu.systemRamAvailableGb || undefined}
+ />
+ )}
+ </div>
+ );
+ })}
+ {!customFoldersCollapsed &&
+ showHfSection &&
+ sortedCustomFolderModels.length === 0 ? (
+ <div className="px-2.5 py-2 text-xs text-muted-foreground">
+ No matching models in custom folders.
+ </div>
+ ) : null}
+ </>
+ ) : null}
+
+ {section === "downloaded" && sortedLmStudio.length > 0 ? (
+ <>
+ <ListLabel
+ divider={true}
+ collapsed={lmStudioCollapsed}
+ onToggle={() => setLmStudioCollapsed((v) => !v)}
+ >
+ LM Studio
+ </ListLabel>
+ {!lmStudioCollapsed &&
+ sortedLmStudio.map((m) => {
+ const isGgufFile = m.path.toLowerCase().endsWith(".gguf");
+ // LM Studio dirs are GGUF but rarely carry a -GGUF suffix;
+ // use the shared helper (model_format hint) so the row,
+ // filter, and load path agree.
+ const isGguf = localModelIsGguf(m);
+ const optionKey = makeModelOptionKey("lm-studio", m.id);
+ return (
+ <div key={m.id}>
+ <ModelRow
+ label={m.model_id ?? m.display_name}
+ meta={isGguf ? "GGUF" : "Local"}
+ selected={value === m.id}
+ optionProps={hubModelList.getOptionProps(
+ optionKey,
+ value === m.id,
+ )}
+ onClick={() => {
+ if (isGgufFile) {
+ onSelect(m.id, {
+ source: "local",
+ isLora: false,
+ isDownloaded: true,
+ isGguf: true,
+ });
+ } else if (isGguf) {
+ toggleGgufExpanded(m.id);
+ } else {
+ onSelect(m.id, {
+ source: "local",
+ isLora: false,
+ isDownloaded: true,
+ });
+ }
+ }}
onArrowDownIntoChildren={
- expandedGguf === adapter.id
+ !isGgufFile && isGgufExpanded(m.id)
? () => {
- const focused = focusFirstChildOption(optionKey);
+ const focused =
+ focusFirstChildOption(optionKey);
return focused;
}
: undefined
}
+ vramStatus={null}
/>
+ {!isGgufFile && isGgufExpanded(m.id) && (
+ <GgufVariantExpander
+ repoId={m.id}
+ onDevice={true}
+ onSelect={onSelect}
+ parentOptionKey={optionKey}
+ onNavigatePastStart={() =>
+ hubModelList.focusOption(optionKey)
+ }
+ onNavigatePastEnd={() =>
+ hubModelList.moveFocus(optionKey, "next")
+ }
+ gpuGb={
+ gpu.available ? gpu.memoryTotalGb : undefined
+ }
+ systemRamGb={gpu.systemRamAvailableGb || undefined}
+ />
+ )}
</div>
- {canDelete && (
- <ModelDeleteAction
- ariaLabel={`Delete ${adapter.name}`}
- title="Delete fine-tuned model?"
- description={
- <>
- This will remove{" "}
- <span className="font-medium text-foreground">
- {adapter.name}
- </span>{" "}
- from disk. This cannot be undone.
- </>
+ );
+ })}
+ </>
+ ) : null}
+
+ {section === "downloaded" && sortedLocalDir.length > 0 ? (
+ <>
+ <ListLabel
+ divider={true}
+ collapsed={localDirCollapsed}
+ onToggle={() => setLocalDirCollapsed((v) => !v)}
+ >
+ Local models
+ </ListLabel>
+ {!localDirCollapsed &&
+ sortedLocalDir.map((m) => {
+ // A loose ./models/*.gguf file loads directly; a GGUF repo
+ // directory expands to pick a variant. The backend's local
+ // variant scanner returns nothing for a config-less loose
+ // file, so expanding it would dead-end at "No GGUF variants".
+ const isGgufFile = m.path.toLowerCase().endsWith(".gguf");
+ const isGguf = localModelIsGguf(m);
+ const optionKey = makeModelOptionKey("local-dir", m.id);
+ return (
+ <div key={m.id}>
+ <ModelRow
+ label={m.model_id ?? m.display_name}
+ meta={isGguf ? "GGUF" : "Local"}
+ selected={value === m.id}
+ optionProps={hubModelList.getOptionProps(
+ optionKey,
+ value === m.id,
+ )}
+ onClick={() => {
+ if (isGgufFile) {
+ onSelect(m.id, {
+ source: "local",
+ isLora: false,
+ isDownloaded: true,
+ isGguf: true,
+ });
+ } else if (isGguf) {
+ toggleGgufExpanded(m.id);
+ } else {
+ onSelect(m.id, {
+ source: "local",
+ isLora: false,
+ isDownloaded: true,
+ });
+ }
+ }}
+ onArrowDownIntoChildren={
+ !isGgufFile && isGgufExpanded(m.id)
+ ? () => focusFirstChildOption(optionKey)
+ : undefined
}
- successMessage={`Deleted ${adapter.name}`}
- disabled={deleteDisabled}
- onConfirm={() =>
- deleteFineTunedModel({
- modelPath: adapter.id,
- source: isExported ? "exported" : "training",
- exportType: adapter.exportType,
- })
+ vramStatus={null}
+ />
+ {!isGgufFile && isGgufExpanded(m.id) && (
+ <GgufVariantExpander
+ repoId={m.id}
+ onDevice={true}
+ onSelect={onSelect}
+ parentOptionKey={optionKey}
+ onNavigatePastStart={() =>
+ hubModelList.focusOption(optionKey)
+ }
+ onNavigatePastEnd={() =>
+ hubModelList.moveFocus(optionKey, "next")
+ }
+ gpuGb={
+ gpu.available ? gpu.memoryTotalGb : undefined
+ }
+ systemRamGb={gpu.systemRamAvailableGb || undefined}
+ />
+ )}
+ </div>
+ );
+ })}
+ </>
+ ) : null}
+
+ {showRecommendedSection ? (
+ <>
+ {recommendedSearch.isLoading &&
+ recommendedRows.length === 0 ? (
+ <div className="flex items-center gap-2 px-5 py-3">
+ <Spinner className="size-3 text-muted-foreground" />
+ <span className="text-xs text-muted-foreground">
+ Loading models…
+ </span>
+ </div>
+ ) : recommendedRows.length === 0 ? (
+ <div className="px-2.5 py-2 text-xs text-muted-foreground">
+ No models found.
+ </div>
+ ) : (
+ recommendedRows.map((r) => {
+ const id = r.id;
+ const info = recommendedMeta.get(id);
+ const isG = isKnownGgufRepo(id);
+ const optionKey = makeModelOptionKey("recommended", id);
+ return (
+ <div key={id}>
+ <ModelRow
+ label={id}
+ hideOwner={true}
+ downloaded={downloadedSet.has(id.toLowerCase())}
+ capabilities={capsById.get(id)}
+ meta={
+ info?.meta ??
+ (isG ? "GGUF" : extractParamLabel(id))
}
- onDeleted={() =>
- onModelsChange?.({ id: adapter.id })
+ selected={value === id}
+ optionProps={hubModelList.getOptionProps(
+ optionKey,
+ value === id,
+ )}
+ onClick={() => {
+ if (isG) {
+ setExpandedGguf((prev) =>
+ prev === id ? null : id,
+ );
+ } else {
+ handleModelClick(id);
+ }
+ }}
+ vramStatus={info?.status ?? null}
+ vramEst={info?.est}
+ gpuGb={
+ gpu.available ? gpu.memoryTotalGb : undefined
+ }
+ onArrowDownIntoChildren={
+ expandedGguf === id
+ ? () => focusFirstChildOption(optionKey)
+ : undefined
}
/>
- )}
+ {expandedGguf === id && (
+ <GgufVariantExpander
+ repoId={id}
+ onSelect={onSelect}
+ parentOptionKey={optionKey}
+ onNavigatePastStart={() =>
+ hubModelList.focusOption(optionKey)
+ }
+ onNavigatePastEnd={() =>
+ hubModelList.moveFocus(optionKey, "next")
+ }
+ gpuGb={
+ gpu.available ? gpu.memoryTotalGb : undefined
+ }
+ systemRamGb={gpu.systemRamAvailableGb || undefined}
+ onDeleteVariant={async (quant) => {
+ await deleteCachedModel(id, quant);
+ refreshCachedLists();
+ }}
+ />
+ )}
+ </div>
+ );
+ })
+ )}
+ {recommendedSearch.hasMore && (
+ <>
+ <div ref={recommendedSentinelRef} className="h-px" />
+ <div className="flex items-center justify-center py-2">
+ <Spinner className="size-3.5 text-muted-foreground" />
</div>
- {expandedGguf === adapter.id && (
- <GgufVariantExpander
- repoId={adapter.id}
- onSelect={onSelect}
- parentOptionKey={optionKey}
- onNavigatePastStart={() =>
- loraModelList.focusOption(optionKey)
- }
- onNavigatePastEnd={() =>
- loraModelList.moveFocus(optionKey, "next")
- }
- gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
- systemRamGb={
- gpu.available ? gpu.systemRamAvailableGb : undefined
+ </>
+ )}
+ </>
+ ) : null}
+
+ {showHfSection &&
+ section === "recommended" &&
+ filteredRecommendedIds.length > 0 ? (
+ <>
+ {filteredRecommendedIds.map((id) => {
+ const vram = recommendedVramMap.get(id);
+ const optionKey = makeModelOptionKey(
+ "search-recommended",
+ id,
+ );
+ return (
+ <div key={id}>
+ <ModelRow
+ label={id}
+ capabilities={capsById.get(id)}
+ meta={
+ isKnownGgufRepo(id)
+ ? "GGUF"
+ : (vram?.detail ?? extractParamLabel(id))
}
- sourceOverride={isExportedGguf ? "exported" : undefined}
- deleteVariantTitle="Delete exported GGUF variant?"
- renderDeleteVariantDescription={(quant) => (
- <>
- This will remove{" "}
- <span className="font-medium text-foreground">
- {adapter.name} ({quant})
- </span>{" "}
- from disk. This cannot be undone.
- </>
+ selected={value === id}
+ optionProps={hubModelList.getOptionProps(
+ optionKey,
+ value === id,
)}
- getDeleteVariantSuccessMessage={(quant) =>
- `Deleted ${adapter.name} ${quant}`
+ onClick={() => {
+ if (isKnownGgufRepo(id)) {
+ setExpandedGguf((prev) =>
+ prev === id ? null : id,
+ );
+ } else {
+ handleModelClick(id);
+ }
+ }}
+ vramStatus={
+ isKnownGgufRepo(id) ? null : (vram?.status ?? null)
}
- deleteDisabled={deleteDisabled}
- onDeleteVariant={
- isExportedGguf
- ? async (quant) => {
- await deleteFineTunedModel({
- modelPath: adapter.id,
- source: "exported",
- exportType: "gguf",
- ggufVariant: quant,
- });
- onModelsChange?.({
- id: adapter.id,
- ggufVariant: quant,
- });
+ vramEst={isKnownGgufRepo(id) ? undefined : vram?.est}
+ gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
+ onArrowDownIntoChildren={
+ expandedGguf === id
+ ? () => {
+ const focused =
+ focusFirstChildOption(optionKey);
+ return focused;
}
: undefined
}
/>
- )}
+ {expandedGguf === id && (
+ <GgufVariantExpander
+ repoId={id}
+ onSelect={onSelect}
+ parentOptionKey={optionKey}
+ onNavigatePastStart={() =>
+ hubModelList.focusOption(optionKey)
+ }
+ onNavigatePastEnd={() =>
+ hubModelList.moveFocus(optionKey, "next")
+ }
+ gpuGb={
+ gpu.available ? gpu.memoryTotalGb : undefined
+ }
+ systemRamGb={gpu.systemRamAvailableGb || undefined}
+ onDeleteVariant={async (quant) => {
+ await deleteCachedModel(id, quant);
+ refreshCachedLists();
+ }}
+ />
+ )}
+ </div>
+ );
+ })}
+ </>
+ ) : null}
+
+ {showHfSection && section === "recommended" ? (
+ <>
+ {hfIds.length === 0 && !isLoading ? (
+ filteredRecommendedIds.length === 0 ? (
+ <div className="px-2.5 py-2 text-xs text-muted-foreground">
+ No matching Unsloth models.
+ </div>
+ ) : null
+ ) : (
+ hfIds.map((id) => {
+ const vram = vramMap.get(id);
+ const isSearchGguf = isKnownGgufRepo(id);
+ const optionKey = makeModelOptionKey("search-hf", id);
+ return (
+ <div key={id}>
+ <ModelRow
+ label={id}
+ capabilities={capsById.get(id)}
+ meta={
+ isSearchGguf
+ ? "GGUF"
+ : [
+ metricsById.get(id) ??
+ extractParamLabel(id),
+ isMlxId(id) ? "MLX" : "Safetensors",
+ ]
+ .filter(Boolean)
+ .join(" · ")
+ }
+ selected={value === id}
+ optionProps={hubModelList.getOptionProps(
+ optionKey,
+ value === id,
+ )}
+ onClick={() => {
+ if (isSearchGguf) {
+ setExpandedGguf((prev) =>
+ prev === id ? null : id,
+ );
+ } else {
+ handleModelClick(id);
+ }
+ }}
+ vramStatus={
+ isSearchGguf ? null : (vram?.status ?? null)
+ }
+ vramEst={isSearchGguf ? undefined : vram?.est}
+ gpuGb={
+ gpu.available ? gpu.memoryTotalGb : undefined
+ }
+ onArrowDownIntoChildren={
+ expandedGguf === id
+ ? () => {
+ const focused =
+ focusFirstChildOption(optionKey);
+ return focused;
+ }
+ : undefined
+ }
+ />
+ {expandedGguf === id && (
+ <GgufVariantExpander
+ repoId={id}
+ onSelect={onSelect}
+ parentOptionKey={optionKey}
+ onNavigatePastStart={() =>
+ hubModelList.focusOption(optionKey)
+ }
+ onNavigatePastEnd={() =>
+ hubModelList.moveFocus(optionKey, "next")
+ }
+ gpuGb={
+ gpu.available ? gpu.memoryTotalGb : undefined
+ }
+ systemRamGb={gpu.systemRamAvailableGb || undefined}
+ onDeleteVariant={async (quant) => {
+ await deleteCachedModel(id, quant);
+ refreshCachedLists();
+ }}
+ />
+ )}
+ </div>
+ );
+ })
+ )}
+ <div ref={sentinelRef} className="h-px" />
+ {isLoadingMore ? (
+ <div className="flex items-center justify-center py-2">
+ <Spinner className="size-3.5 text-muted-foreground" />
</div>
- );
- })}
- </div>
- ))
+ ) : null}
+ </>
+ ) : null}
+ </>
)}
</div>
</div>
-
+ {/* Floating eject pill: overlaid on the list bottom, outside the scroll
+ so the edge fade never touches it. Only the pill catches clicks. */}
+ {onEject ? (
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-end pr-3.5 pb-5">
+ <button
+ type="button"
+ onClick={onEject}
+ className="pointer-events-auto inline-flex items-center justify-center gap-2 rounded-md bg-popover px-3 py-2 text-[13px] text-destructive shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] transition-colors hover:bg-[color-mix(in_srgb,var(--destructive)_12%,var(--popover))] dark:bg-[color-mix(in_srgb,var(--foreground)_10%,var(--sidebar))] dark:shadow-none dark:hover:bg-[color-mix(in_srgb,var(--destructive)_22%,var(--sidebar))]"
+ title="Eject model"
+ >
+ <HugeiconsIcon icon={RemoveCircleIcon} className="size-3.5" />
+ Eject model
+ </button>
+ </div>
+ ) : null}
</div>
);
}
+
+/** Fine-tuned model rows for the On Device tab's Fine-tuned section. Plugs into
+ * that section's roving list and shared GGUF-expand state. */
+function FineTunedRows({
+ adapters,
+ value,
+ onSelect,
+ onModelsChange,
+ deleteDisabled = false,
+ loraModelList,
+ expandedGguf,
+ setExpandedGguf,
+ gpu,
+}: {
+ adapters: LoraModelOption[];
+ value?: string;
+ onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
+ onModelsChange?: (deletedModel?: DeletedModelRef) => void;
+ deleteDisabled?: boolean;
+ loraModelList: ReturnType<typeof useRovingModelList>;
+ expandedGguf: string | null;
+ setExpandedGguf: Dispatch<SetStateAction<string | null>>;
+ gpu: {
+ available: boolean;
+ memoryTotalGb: number;
+ systemRamAvailableGb: number;
+ };
+}) {
+ return (
+ <>
+ {adapters.map((adapter) => {
+ const isLocal = adapter.source === "local";
+ const isTraining = adapter.source === "training";
+ const isExported = adapter.source === "exported";
+ const isMerged = adapter.exportType === "merged";
+ const isGguf = adapter.exportType === "gguf";
+ const isExportedGguf = isExported && isGguf;
+ const canDelete = canDeleteLoraModel(adapter);
+ const isTrainingFull = isTraining && isMerged;
+ const isLocalGgufDir =
+ isLocal && (isGgufRepo(adapter.id) || isGgufRepo(adapter.name));
+ const optionKey = makeModelOptionKey("lora", adapter.id);
+ const tag = isLocal
+ ? isLocalGgufDir
+ ? "GGUF"
+ : "Local"
+ : isGguf
+ ? "GGUF"
+ : isTrainingFull
+ ? "Full"
+ : isExported
+ ? isMerged
+ ? "Merged"
+ : "LoRA"
+ : "LoRA";
+ const meta = isLocal
+ ? isLocalGgufDir
+ ? "GGUF"
+ : "Local"
+ : isTrainingFull
+ ? "Full finetune"
+ : isExported
+ ? `${tag} · Exported`
+ : tag;
+ return (
+ <div key={adapter.id}>
+ <div className="flex items-center gap-0.5">
+ <div className="min-w-0 flex-1">
+ <ModelRow
+ label={adapter.name}
+ meta={meta}
+ selected={value === adapter.id}
+ optionProps={loraModelList.getOptionProps(
+ optionKey,
+ value === adapter.id,
+ )}
+ onClick={() => {
+ if (isLocalGgufDir || isExportedGguf) {
+ setExpandedGguf((prev) =>
+ prev === adapter.id ? null : adapter.id,
+ );
+ } else {
+ onSelect(adapter.id, {
+ source: isLocal
+ ? "local"
+ : isExported
+ ? "exported"
+ : "lora",
+ isLora: !isLocal && !isMerged && !isGguf,
+ isDownloaded: true,
+ });
+ }
+ }}
+ tooltipText={
+ <>
+ <span className="block break-words">{adapter.name}</span>
+ <span className="block mt-1 text-[10px] text-muted-foreground break-all">
+ {adapter.id}
+ </span>
+ </>
+ }
+ onArrowDownIntoChildren={
+ expandedGguf === adapter.id
+ ? () => {
+ const focused = focusFirstChildOption(optionKey);
+ return focused;
+ }
+ : undefined
+ }
+ />
+ </div>
+ {canDelete && (
+ <ModelDeleteAction
+ ariaLabel={`Delete ${adapter.name}`}
+ title="Delete fine-tuned model?"
+ description={
+ <>
+ This will remove{" "}
+ <span className="font-medium text-foreground">
+ {adapter.name}
+ </span>{" "}
+ from disk. This cannot be undone.
+ </>
+ }
+ successMessage={`Deleted ${adapter.name}`}
+ disabled={deleteDisabled}
+ onConfirm={() =>
+ deleteFineTunedModel({
+ modelPath: adapter.id,
+ source: isExported ? "exported" : "training",
+ exportType: adapter.exportType,
+ })
+ }
+ onDeleted={() => onModelsChange?.({ id: adapter.id })}
+ />
+ )}
+ </div>
+ {expandedGguf === adapter.id && (
+ <GgufVariantExpander
+ repoId={adapter.id}
+ onSelect={onSelect}
+ parentOptionKey={optionKey}
+ onNavigatePastStart={() => loraModelList.focusOption(optionKey)}
+ onNavigatePastEnd={() =>
+ loraModelList.moveFocus(optionKey, "next")
+ }
+ gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}
+ systemRamGb={gpu.systemRamAvailableGb || undefined}
+ sourceOverride={isExportedGguf ? "exported" : undefined}
+ deleteVariantTitle="Delete exported GGUF variant?"
+ renderDeleteVariantDescription={(quant) => (
+ <>
+ This will remove{" "}
+ <span className="font-medium text-foreground">
+ {adapter.name} ({quant})
+ </span>{" "}
+ from disk. This cannot be undone.
+ </>
+ )}
+ getDeleteVariantSuccessMessage={(quant) =>
+ `Deleted ${adapter.name} ${quant}`
+ }
+ deleteDisabled={deleteDisabled}
+ onDeleteVariant={
+ isExportedGguf
+ ? async (quant) => {
+ await deleteFineTunedModel({
+ modelPath: adapter.id,
+ source: "exported",
+ exportType: "gguf",
+ ggufVariant: quant,
+ });
+ onModelsChange?.({
+ id: adapter.id,
+ ggufVariant: quant,
+ });
+ }
+ : undefined
+ }
+ />
+ )}
+ </div>
+ );
+ })}
+ </>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/pill-tabs.tsx b/studio/frontend/src/components/assistant-ui/model-selector/pill-tabs.tsx
new file mode 100644
index 00000000000..e6da8a7b74d
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/model-selector/pill-tabs.tsx
@@ -0,0 +1,104 @@
+// 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 type { ReactNode } from "react";
+
+export interface PillTab {
+ value: string;
+ label: string;
+ icon?: ReactNode;
+}
+
+/** Segmented pill toggle reusing the Hub's .hub-tab-toggle styling (extended in
+ * hub.css to also match .unsloth-model-selector-menu). Keeps tab roles for
+ * keyboard nav. */
+export function PillTabs({
+ tabs,
+ value,
+ onValueChange,
+ ariaLabel,
+ className,
+ compact = false,
+ fit = false,
+}: {
+ tabs: PillTab[];
+ value: string;
+ onValueChange: (value: string) => void;
+ ariaLabel: string;
+ className?: string;
+ compact?: boolean;
+ /** Size each tab to its label instead of equal widths. The active tab carries
+ * the pill background directly (the toggle never animates). */
+ fit?: boolean;
+}) {
+ const activeIndex = Math.max(
+ 0,
+ tabs.findIndex((tab) => tab.value === value),
+ );
+ return (
+ <div
+ role="tablist"
+ aria-label={ariaLabel}
+ className={cn(
+ "hub-menu-trigger hub-tab-toggle relative inline-flex items-center rounded-full",
+ compact ? "h-7" : "h-9",
+ // Don't stretch to fill a flex-column parent (the popover) in fit mode,
+ // and never compress so the last tab keeps its padding.
+ fit && "w-fit max-w-full shrink-0 self-start",
+ className,
+ )}
+ >
+ {!fit && (
+ <span
+ aria-hidden="true"
+ style={{
+ width: `${100 / tabs.length}%`,
+ transform: `translateX(${activeIndex * 100}%)`,
+ }}
+ className="hub-tab-toggle-pill pointer-events-none absolute inset-y-0 left-0 rounded-full transition-transform duration-200 ease-out"
+ />
+ )}
+ {tabs.map((tab, index) => (
+ <button
+ key={tab.value}
+ type="button"
+ role="tab"
+ aria-selected={value === tab.value}
+ // Roving tabindex: only the active tab is in the tab order; Arrow
+ // Left/Right move between tabs (WAI-ARIA tablist pattern). ArrowDown
+ // is left to bubble so the picker's "enter the list" handler still runs.
+ tabIndex={value === tab.value ? 0 : -1}
+ onKeyDown={(e) => {
+ if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;
+ e.preventDefault();
+ const next =
+ (index + (e.key === "ArrowRight" ? 1 : -1) + tabs.length) %
+ tabs.length;
+ onValueChange(tabs[next].value);
+ e.currentTarget.parentElement
+ ?.querySelectorAll<HTMLElement>('button[role="tab"]')
+ [next]?.focus();
+ }}
+ onClick={() => onValueChange(tab.value)}
+ className={cn(
+ "relative z-10 inline-flex items-center justify-center gap-1.5 rounded-full transition-colors",
+ fit ? "shrink-0" : "min-w-0 flex-1",
+ compact ? "h-7 px-2.5 text-[11px]" : "h-9 px-3 text-[12.5px]",
+ value === tab.value
+ ? "text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ // The active tab carries the pill; pin its hover bg so an
+ // already-selected tab shows no hover change.
+ fit &&
+ value === tab.value &&
+ "hub-tab-toggle-pill hover:!bg-[var(--background)] dark:hover:!bg-[color-mix(in_srgb,var(--foreground)_10%,transparent)]",
+ )}
+ >
+ {tab.icon}
+ {tab.label}
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/recommended-fit.ts b/studio/frontend/src/components/assistant-ui/model-selector/recommended-fit.ts
new file mode 100644
index 00000000000..24f0edc7848
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/model-selector/recommended-fit.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Pure helpers for the Recommended list: which formats to surface and whether a
+// model fits the device. No React/DOM deps so they are easy to test.
+
+const GGUF_SUFFIX_RE = /-GGUF(?:$|-)/i;
+const MLX_RE = /-MLX(?:$|-)/i;
+
+export function isGgufId(id: string, hintedIsGguf?: boolean): boolean {
+ return Boolean(hintedIsGguf) || GGUF_SUFFIX_RE.test(id);
+}
+
+export function isMlxId(id: string): boolean {
+ return MLX_RE.test(id);
+}
+
+// "mobile" build token (e.g. "gemma-4-E4B-it-qat-mobile-GGUF"); bounded so it
+// never matches inside a longer word.
+const MOBILE_RE = /(?:^|[-_/. ])mobile(?:$|[-_/. ])/i;
+
+/** A mobile-targeted build, which we keep out of the Recommended list. */
+export function isMobileVariant(id: string): boolean {
+ return MOBILE_RE.test(id);
+}
+
+/** Recommended only surfaces ready-to-run local formats (GGUF / MLX). */
+export function isRunnableRecommendedFormat(
+ id: string,
+ hintedIsGguf?: boolean,
+): boolean {
+ return isGgufId(id, hintedIsGguf) || isMlxId(id);
+}
+
+/** What Recommended is allowed to suggest: GGUF anywhere; on Mac also MLX and
+ * safetensors (both now run locally there). GPU keeps GGUF-only recommendations. */
+export function isRecommendableFormat(
+ id: string,
+ hintedIsGguf: boolean | undefined,
+ isMac: boolean,
+): boolean {
+ if (isGgufId(id, hintedIsGguf)) return true;
+ return isMac;
+}
+
+/** Format filter for the listing toggle. "safetensors" means anything that is
+ * neither GGUF nor MLX. */
+export type FormatFilter = "all" | "gguf" | "mlx" | "safetensors";
+
+export function matchesFormatFilter(
+ id: string,
+ hintedIsGguf: boolean | undefined,
+ filter: FormatFilter,
+): boolean {
+ switch (filter) {
+ case "gguf":
+ return isGgufId(id, hintedIsGguf);
+ case "mlx":
+ return isMlxId(id);
+ case "safetensors":
+ return !isGgufId(id, hintedIsGguf) && !isMlxId(id);
+ default:
+ return true;
+ }
+}
+
+// First "<n>B" token in a repo id, e.g. "Qwen3-4B-GGUF" -> 4, "gpt-oss-20b" ->
+// 20, "Qwen3-30B-A3B" -> 30 (MoE total), "gemma-4-E4B" -> 4 (effective-param
+// "E" series). The digits must be bounded by a separator so we never read "16"
+// from "bf16" or the "2" in "Kimi-K2".
+const PARAM_RE = /(?:^|[-_/. ])[eE]?(\d+(?:\.\d+)?)\s*[bB](?=$|[-_./ ])/;
+
+/** Parameter count (absolute, e.g. 4e9) parsed from a repo id, or undefined
+ * when the id has no size token (so callers can treat the size as unknown). */
+export function paramsFromId(id: string): number | undefined {
+ const match = PARAM_RE.exec(id);
+ if (!match) return undefined;
+ const billions = parseFloat(match[1]);
+ return Number.isFinite(billions) && billions > 0 ? billions * 1e9 : undefined;
+}
+
+// Smallest practical GGUF/MLX quant (~Q2_K, low-bit). The fit check asks whether
+// a model can run at all, so it uses this rather than a default 4-bit size; a
+// user with a smaller device can still pick a low-bit variant.
+const MIN_QUANT_BYTES_PER_PARAM = 0.4;
+
+/** Rough on-disk bytes for the smallest practical quant of `params` weights. */
+export function estimateQuantBytes(params: number): number {
+ return params * MIN_QUANT_BYTES_PER_PARAM;
+}
+
+/** A model fits when its on-disk size (or a precomputed VRAM estimate) is within
+ * the device budget (0.7*GPU + 0.7*RAM). Unknown device means we cannot tell, so
+ * treat it as fitting. Unknown size normally fits too, but Recommended passes
+ * `requireKnown` so a model we cannot size (e.g. a huge GGUF with no metadata or
+ * size token) is hidden rather than wrongly shown. */
+export function fitsDevice(opts: {
+ sizeBytes?: number;
+ estimatedVramGb?: number;
+ gpuGb?: number;
+ systemRamGb?: number;
+ requireKnown?: boolean;
+}): boolean {
+ const { sizeBytes, estimatedVramGb, gpuGb, systemRamGb, requireKnown } = opts;
+ // Unified-memory hosts (Mac / no discrete GPU) report system RAM but no GPU,
+ // so the budget must include RAM. Only an entirely unknown budget fits freely.
+ const budgetGb = Math.max(0, gpuGb ?? 0) * 0.7 + Math.max(0, systemRamGb ?? 0) * 0.7;
+ if (budgetGb <= 0) return true;
+ if (sizeBytes && sizeBytes > 0) {
+ return sizeBytes / 1024 ** 3 <= budgetGb;
+ }
+ if (estimatedVramGb && estimatedVramGb > 0) {
+ return estimatedVramGb <= budgetGb;
+ }
+ return requireKnown ? false : true;
+}
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/remembered-load-settings.ts b/studio/frontend/src/components/assistant-ui/model-selector/remembered-load-settings.ts
new file mode 100644
index 00000000000..85e088ffb2d
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/model-selector/remembered-load-settings.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Per-model pre-load inference settings, persisted in localStorage so the load
+// dialog can offer "Remember settings for <model>".
+
+const KEY = "unsloth_load_settings";
+
+export interface RememberedLoadSettings {
+ contextLength: number | null;
+ kvCacheDtype: string | null;
+ speculativeType: string | null;
+ specDraftNMax: number | null;
+ tensorParallel: boolean;
+}
+
+function readAll(): Record<string, RememberedLoadSettings> {
+ try {
+ return JSON.parse(localStorage.getItem(KEY) ?? "{}");
+ } catch {
+ return {};
+ }
+}
+
+function writeAll(all: Record<string, RememberedLoadSettings>) {
+ try {
+ localStorage.setItem(KEY, JSON.stringify(all));
+ } catch {
+ // Ignore quota / unavailable storage.
+ }
+}
+
+export function loadRememberedLoadSettings(
+ modelId: string,
+): RememberedLoadSettings | null {
+ return readAll()[modelId] ?? null;
+}
+
+export function saveRememberedLoadSettings(
+ modelId: string,
+ settings: RememberedLoadSettings,
+) {
+ const all = readAll();
+ all[modelId] = settings;
+ writeAll(all);
+}
+
+export function clearRememberedLoadSettings(modelId: string) {
+ const all = readAll();
+ if (modelId in all) {
+ delete all[modelId];
+ writeAll(all);
+ }
+}
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/row-meta.ts b/studio/frontend/src/components/assistant-ui/model-selector/row-meta.ts
new file mode 100644
index 00000000000..15a93285cb8
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/model-selector/row-meta.ts
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Pure helpers for model-row presentation: owner/name split, format pills,
+// param chip, tabular size. No React/DOM deps so they stay easy to test.
+
+export type FormatTone = "gguf" | "mlx" | "checkpoint" | "adapter";
+
+// Format keyword to DotTag tone. Looked up by full token and by first word,
+// so "Full finetune" resolves via "full".
+export const FORMAT_TONE: Record<string, FormatTone> = {
+ gguf: "gguf",
+ mlx: "mlx",
+ local: "checkpoint",
+ safetensors: "checkpoint",
+ checkpoint: "checkpoint",
+ lora: "adapter",
+ merged: "adapter",
+ adapter: "adapter",
+ exported: "adapter",
+ full: "adapter",
+};
+
+/** Split "owner/name" on the last slash. No slash means name only. */
+export function splitRepoLabel(label: string): {
+ owner: string | null;
+ name: string;
+} {
+ const slash = label.lastIndexOf("/");
+ if (slash <= 0 || slash === label.length - 1) {
+ return { owner: null, name: label };
+ }
+ return { owner: label.slice(0, slash), name: label.slice(slash + 1) };
+}
+
+export type MetaToken =
+ | { kind: "format"; label: string; tone: FormatTone }
+ | { kind: "size"; label: string }
+ | { kind: "param"; label: string }
+ | { kind: "text"; label: string };
+
+const META_SIZE_RE = /(?:KB|MB|GB|TB)\b/i;
+const META_APPROX_RE = /^~/;
+const META_PARAM_RE = /^\d+(?:\.\d+)?B$/i;
+const META_WHITESPACE_RE = /\s+/;
+
+/** Classify a meta token: size (has KB/MB/GB/TB or leading "~"), param (bare
+ * "<n>B" like "4B"), format keyword, or plain text. */
+export function classifyMetaToken(raw: string): MetaToken | null {
+ const t = raw.trim();
+ if (!t) return null;
+ if (META_SIZE_RE.test(t) || META_APPROX_RE.test(t)) {
+ return { kind: "size", label: t };
+ }
+ if (META_PARAM_RE.test(t)) {
+ return { kind: "param", label: t.toUpperCase() };
+ }
+ const lower = t.toLowerCase();
+ const tone =
+ FORMAT_TONE[lower] ?? FORMAT_TONE[lower.split(META_WHITESPACE_RE)[0]];
+ if (tone) {
+ return { kind: "format", label: t, tone };
+ }
+ return { kind: "text", label: t };
+}
+
+/** Parse the dot-separated meta string into structured tokens. */
+export function parseMetaTokens(meta?: string | null): {
+ formats: { label: string; tone: FormatTone }[];
+ param?: string;
+ size?: string;
+ texts: string[];
+} {
+ const formats: { label: string; tone: FormatTone }[] = [];
+ const texts: string[] = [];
+ let param: string | undefined;
+ let size: string | undefined;
+ if (!meta) return { formats, texts };
+ for (const part of meta.split("·")) {
+ const token = classifyMetaToken(part);
+ if (!token) continue;
+ if (token.kind === "format") {
+ formats.push({ label: token.label, tone: token.tone });
+ } else if (token.kind === "size") {
+ size ??= token.label;
+ } else if (token.kind === "param") {
+ param ??= token.label;
+ } else {
+ texts.push(token.label);
+ }
+ }
+ return { formats, param, size, texts };
+}
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/source-tabs.ts b/studio/frontend/src/components/assistant-ui/model-selector/source-tabs.ts
new file mode 100644
index 00000000000..8330dbca2ec
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/model-selector/source-tabs.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
+
+// Pure rules for the source toggle (Hub models / Fine-tuned / Connected).
+
+export type SourceTab = { value: string; label: string };
+
+/** Local models (LM Studio, Ollama, custom folders) are not fine-tuned; they
+ * live in the Hub tab's Downloaded / Custom sections. */
+export function isFineTunedSource(source?: string): boolean {
+ return source !== "local";
+}
+
+/** Build the source tabs. Fine-tuned and Connected models live as sections in
+ * the Hub tab's toggle, so Hub is the only source and its strip stays hidden. */
+export function buildSourceTabs(): SourceTab[] {
+ return [{ value: "hub", label: "Hub models" }];
+}
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/types.ts b/studio/frontend/src/components/assistant-ui/model-selector/types.ts
index 6a86e4f7ed6..6a865152677 100644
--- a/studio/frontend/src/components/assistant-ui/model-selector/types.ts
+++ b/studio/frontend/src/components/assistant-ui/model-selector/types.ts
@@ -31,6 +31,8 @@ export interface ModelSelectorChangeMeta {
ggufVariant?: string;
isDownloaded?: boolean;
expectedBytes?: number;
+ /** Native GGUF context, threaded so a staged pick can seed the slider. */
+ contextLength?: number | null;
/** Direct local .gguf file picked without a variant (custom folder / LM
* Studio). Marks it as a GGUF source for the deferred-load staging flow. */
isGguf?: boolean;
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 5003072903e..589fae5fe9a 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -12,8 +12,8 @@ import type {
} from "../types";
import type {
ApiMonitorEntry,
- AudioGenerationResponse,
ApiMonitorResponse,
+ AudioGenerationResponse,
GgufVariantsResponse,
InferenceStatusResponse,
ListLorasResponse,
@@ -200,6 +200,9 @@ export interface CachedGgufRepo {
/** Epoch seconds of the newest downloaded quant; sorts Downloaded
* newest-first. Optional for older-backend compatibility. */
last_modified?: number;
+ /** True when the repo ships an mmproj adapter (image inputs). Optional for
+ * older-backend compatibility. */
+ has_vision?: boolean;
}
export async function getGgufDownloadProgress(
@@ -278,6 +281,9 @@ export interface LocalModelInfo {
path: string;
source: "models_dir" | "hf_cache" | "lmstudio" | "custom";
model_id?: string | null;
+ // Backend-detected weights format ("gguf" when known), so the UI can
+ // classify scanned folders whose name lacks a -GGUF suffix.
+ model_format?: string | null;
updated_at?: number | null;
}
@@ -777,6 +783,34 @@ export async function listGgufVariants(
return parseJsonOrThrow<GgufVariantsResponse>(response);
}
+export interface KvCacheEstimate {
+ kv_bytes: number | null;
+ weights_bytes: number | null;
+ native_context: number | null;
+}
+
+/** Estimate KV cache + weight bytes for a downloaded quant at a context length,
+ * for the load dialog's memory warning. */
+export async function estimateKvCache(
+ repoId: string,
+ quant: string,
+ nCtx: number,
+ cacheTypeKv?: string | null,
+ signal?: AbortSignal,
+): Promise<KvCacheEstimate> {
+ const params = new URLSearchParams({
+ repo_id: repoId,
+ quant,
+ n_ctx: String(nCtx),
+ });
+ if (cacheTypeKv) params.set("cache_type_kv", cacheTypeKv);
+ const response = await authFetch(
+ `/api/models/kv-cache-estimate?${params}`,
+ signal ? { signal } : undefined,
+ );
+ return parseJsonOrThrow<KvCacheEstimate>(response);
+}
+
function parseSseEvent(rawEvent: string): string[] {
const dataLines: string[] = [];
for (const line of rawEvent.split(/\r?\n/)) {
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 83452c2ea82..4816e1d5157 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -9,6 +9,7 @@ import {
ModelSelector,
} from "@/components/assistant-ui/model-selector";
import { ProjectComposer, Thread } from "@/components/assistant-ui/thread";
+import { CopyableErrorChip } from "@/components/ui/copyable-error-chip";
import {
ResizableHandle,
ResizablePanel,
@@ -16,18 +17,20 @@ import {
} from "@/components/ui/resizable";
import { useSidebar } from "@/components/ui/sidebar";
import { Tooltip, TooltipContent } from "@/components/ui/tooltip";
-import { ProjectSourcesPanel } from "@/features/rag/components/project-sources-panel";
+import { useLatestRef } from "@/features/hub/hooks/use-latest-ref";
import {
+ type NativeIntent,
NativeModelChip,
NativeModelDropOverlay,
- type NativeIntent,
useChooseNativeModel,
useNativeIntentStore,
useNativeModelDrop,
useNativePathLeasesSupported,
} from "@/features/native-intents";
+import { ProjectSourcesPanel } from "@/features/rag/components/project-sources-panel";
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { isTauri } from "@/lib/api-base";
+import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import {
BubbleChatTemporaryIcon,
@@ -37,7 +40,6 @@ import {
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate } from "@tanstack/react-router";
import { Tooltip as TooltipPrimitive } from "radix-ui";
-import type { PanelImperativeHandle } from "react-resizable-panels";
import {
type CSSProperties,
type ReactElement,
@@ -48,10 +50,16 @@ import {
useRef,
useState,
} from "react";
-import { toast } from "@/lib/toast";
+import type { PanelImperativeHandle } from "react-resizable-panels";
import { listLocalModels } from "./api/chat-api";
+import { ArtifactSurface } from "./artifacts/artifact-surface";
+import {
+ clearAutoOpenedArtifacts,
+ useChatArtifactsStore,
+ useSelectedChatArtifact,
+} from "./artifacts/store";
+import type { ChatArtifact, ChatArtifactSurface } from "./artifacts/types";
import { ChatSettingsPanel } from "./chat-settings-sheet";
-import { CopyableErrorChip } from "@/components/ui/copyable-error-chip";
import { ContextUsageBar } from "./components/context-usage-bar";
import { ModelLoadInlineStatus } from "./components/model-load-status";
import { ProjectSwitcher } from "./components/project-switcher";
@@ -63,12 +71,11 @@ import {
import { useChatModelRuntime } from "./hooks/use-chat-model-runtime";
import type { SelectedModelInput } from "./hooks/use-chat-model-runtime";
import { useChatProjects } from "./hooks/use-chat-projects";
-import { useStagedModelPreparation } from "./hooks/use-staged-model-preparation";
-import { useLatestRef } from "@/features/hub/hooks/use-latest-ref";
import {
type SidebarItem,
useChatSidebarItems,
} from "./hooks/use-chat-sidebar-items";
+import { useStagedModelPreparation } from "./hooks/use-staged-model-preparation";
import {
clearTrainingCompareHandoff,
getTrainingCompareHandoff,
@@ -101,19 +108,15 @@ import {
CHAT_TOOLS_ENABLED_KEY,
CHAT_WEB_FETCH_TOOLS_ENABLED_KEY,
hasGgufSource,
+ isDownloadableHubRepo,
loadOptionalBool,
+ pendingSelectionMatches,
useChatRuntimeStore,
} from "./stores/chat-runtime-store";
+import type { PendingModelSelection } from "./stores/chat-runtime-store";
import { useChatPreferencesStore } from "./stores/chat-preferences-store";
import { useExternalProvidersStore } from "./stores/external-providers-store";
import { buildChatTourSteps } from "./tour";
-import { ArtifactSurface } from "./artifacts/artifact-surface";
-import {
- clearAutoOpenedArtifacts,
- useChatArtifactsStore,
- useSelectedChatArtifact,
-} from "./artifacts/store";
-import type { ChatArtifact, ChatArtifactSurface } from "./artifacts/types";
import type { ChatView, MessageRecord } from "./types";
import {
getStoredChatThread,
@@ -912,7 +915,9 @@ function ProjectLanding({
},
] as const;
}
- const messages = await listStoredChatMessages(item.id).catch(() => []);
+ const messages = await listStoredChatMessages(item.id).catch(
+ () => [],
+ );
const firstUserMessage =
messages.find((message) => message.role === "user") ?? messages[0];
return [
@@ -1002,41 +1007,41 @@ function ProjectLanding({
{projectTab === "sources" ? (
<ProjectSourcesPanel projectId={projectId} />
) : (
- <div className="mt-8 flex flex-col gap-1">
- {items.map((item) => {
- const preview = previews[item.id];
- return (
- <button
- key={`${item.type}:${item.id}`}
- type="button"
- onClick={() => {
- navigate({
- to: "/chat",
- search:
- item.type === "single"
- ? { thread: item.id, project: projectId }
- : { compare: item.id, project: projectId },
- });
- }}
- className="group flex min-h-[58px] w-full items-center gap-4 rounded-full px-4 py-2 text-left transition-colors hover:bg-nav-surface-hover"
- >
- <div className="min-w-0 flex-1">
- <div className="truncate text-[15px] font-semibold leading-5 text-foreground">
- {item.title}
- </div>
- {preview?.snippet ? (
- <div className="mt-0.5 truncate text-[14px] leading-5 text-muted-foreground">
- {preview.snippet}
+ <div className="mt-8 flex flex-col gap-1">
+ {items.map((item) => {
+ const preview = previews[item.id];
+ return (
+ <button
+ key={`${item.type}:${item.id}`}
+ type="button"
+ onClick={() => {
+ navigate({
+ to: "/chat",
+ search:
+ item.type === "single"
+ ? { thread: item.id, project: projectId }
+ : { compare: item.id, project: projectId },
+ });
+ }}
+ className="group flex min-h-[58px] w-full items-center gap-4 rounded-full px-4 py-2 text-left transition-colors hover:bg-nav-surface-hover"
+ >
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[15px] font-semibold leading-5 text-foreground">
+ {item.title}
</div>
- ) : null}
- </div>
- <span className="shrink-0 text-[14px] text-muted-foreground">
- {preview?.date ?? formatProjectChatDate(item.createdAt)}
- </span>
- </button>
- );
- })}
- </div>
+ {preview?.snippet ? (
+ <div className="mt-0.5 truncate text-[14px] leading-5 text-muted-foreground">
+ {preview.snippet}
+ </div>
+ ) : null}
+ </div>
+ <span className="shrink-0 text-[14px] text-muted-foreground">
+ {preview?.date ?? formatProjectChatDate(item.createdAt)}
+ </span>
+ </button>
+ );
+ })}
+ </div>
)}
</div>
</div>
@@ -1073,11 +1078,16 @@ export function ChatPage({
const settingsOpen = useChatRuntimeStore((s) => s.settingsPanelOpen);
const setSettingsOpen = useChatRuntimeStore((s) => s.setSettingsPanelOpen);
- const loadOnSelection = useChatRuntimeStore((s) => s.loadOnSelection);
- const setLoadOnSelection = useChatRuntimeStore((s) => s.setLoadOnSelection);
// Deferred-load staging: downloads a staged GGUF (if needed) and reads its
// header context so the sheet can show the context slider before the load.
- const stagedDownload = useStagedModelPreparation();
+ // autoLoad picks instead load the cached file as soon as the download ends;
+ // selectModel is defined below, so the load runs through a ref.
+ const autoLoadStagedRef = useRef<
+ ((pending: PendingModelSelection) => void) | null
+ >(null);
+ const stagedDownload = useStagedModelPreparation({
+ onAutoLoad: (pending) => autoLoadStagedRef.current?.(pending),
+ });
// Abandon a staged pick: the store action cancels its in-flight download and
// reverts the edited knobs, so nothing lingers after the user walks away.
const abandonStaged = useCallback(() => {
@@ -1255,6 +1265,28 @@ export function ChatPage({
refreshRef.current = refresh;
selectModelRef.current = selectModel;
}, [refresh, selectModel]);
+ // Load a cached autoLoad pick once its download finishes. The sheet was never
+ // opened, so on a load failure just drop the orphaned staged knobs.
+ autoLoadStagedRef.current = (pending) => {
+ void selectModel({
+ ...pending,
+ isDownloaded: true,
+ forceReload: true,
+ keepSpeculative: false,
+ throwOnError: true,
+ }).catch(() => {
+ const store = useChatRuntimeStore.getState();
+ // selectModel only clears pendingSelection on success, so a failed
+ // auto-load leaves our staged pick (and its edited load knobs) behind.
+ // Abandon it when it is still the active stage; otherwise just revert the
+ // settings if the stage was already cleared by something else.
+ if (pendingSelectionMatches(store.pendingSelection, pending)) {
+ store.abandonStagedModel();
+ } else if (!store.pendingSelection) {
+ store.resetModelSettingsToLoaded();
+ }
+ });
+ };
const isExternalModel = useMemo(
() => isExternalModelId(inferenceParams.checkpoint),
[inferenceParams.checkpoint],
@@ -1449,7 +1481,9 @@ export function ChatPage({
}
if (search.thread) {
- const thread = await getStoredChatThread(search.thread).catch(() => null);
+ const thread = await getStoredChatThread(search.thread).catch(
+ () => null,
+ );
if (!canceled) {
const projectId = thread?.projectId ?? null;
setCurrentProjectId(projectId);
@@ -1596,11 +1630,16 @@ export function ChatPage({
const stageOrLoad = useCallback(
async (selection: SelectedModelInput) => {
const store = useChatRuntimeStore.getState();
- // Only GGUF picks have pre-load options worth staging. Non-GGUF models
- // (and the toggle-on case) load immediately, so e.g. a trust_remote_code
- // approval surfaces through the normal load path.
- if (store.loadOnSelection || !hasGgufSource(selection)) {
- // Abandon any staged GGUF first so its edited knobs (e.g. a custom
+ // An un-cached HF repo (GGUF variant or a full non-GGUF snapshot) downloads
+ // through the manager first (global indicator), then auto-loads. Everything
+ // else -- cached picks, local/native files, LoRA, external -- loads now.
+ const wantManagerDownload =
+ isDownloadableHubRepo(selection) && !selection.isDownloaded;
+ if (
+ (!hasGgufSource(selection) && !wantManagerDownload) ||
+ (store.loadOnSelection && selection.isDownloaded)
+ ) {
+ // Abandon any staged pick first so its edited knobs (e.g. a custom
// context length) don't leak into this immediate load -- resolveLoad
// reads customContextLength before checking the target is GGUF.
abandonStaged();
@@ -1616,7 +1655,8 @@ export function ChatPage({
return;
}
// Tear down any existing staged pick first so its in-flight download is
- // cancelled, not left running after we rebind to the new pick.
+ // cancelled, not left running after we rebind to the new pick. With the
+ // toggle on, autoLoad downloads silently then loads; off stages for the sheet.
abandonStaged();
store.stageModel({
id: selection.id,
@@ -1626,6 +1666,8 @@ export function ChatPage({
expectedBytes: selection.expectedBytes,
nativePathToken: selection.nativePathToken,
isGguf: selection.isGguf,
+ isHubRepo: wantManagerDownload || undefined,
+ autoLoad: store.loadOnSelection,
});
},
[abandonStaged, selectModel],
@@ -1719,8 +1761,7 @@ export function ChatPage({
selectedProvider?.providerType,
selectedExternal?.modelId,
{
- isReasoningProvider:
- selectedProvider?.isReasoningModel === true,
+ isReasoningProvider: selectedProvider?.isReasoningModel === true,
baseUrl: selectedProvider?.baseUrl ?? null,
},
);
@@ -1878,6 +1919,7 @@ export function ChatPage({
}
const selection = {
id: value,
+ source: meta?.source,
isLora: meta?.isLora,
ggufVariant: meta?.ggufVariant,
isDownloaded: meta?.isDownloaded,
@@ -1977,8 +2019,7 @@ export function ChatPage({
if (!usage) return;
const store = useChatRuntimeStore.getState();
const activeCheckpoint = store.params.checkpoint;
- const usageModelId =
- (usage as { modelId?: unknown }).modelId;
+ const usageModelId = (usage as { modelId?: unknown }).modelId;
// Scope by modelId when present; reject if no active checkpoint
// (model-scoped usage can't be attributed to "nothing").
if (typeof usageModelId === "string" && usageModelId) {
@@ -2262,7 +2303,7 @@ export function ChatPage({
beneath it, instead of a hard cut. */}
{view.mode !== "compare" && (
<div
- aria-hidden
+ aria-hidden={true}
className="pointer-events-none absolute left-0 right-[10px] top-[48px] z-20 h-6 bg-gradient-to-b from-background to-transparent"
/>
)}
@@ -2284,8 +2325,6 @@ export function ChatPage({
activeGgufVariant={activeGgufVariant}
onValueChange={handleCheckpointChange}
onEject={handleEject}
- loadOnSelection={loadOnSelection}
- onLoadOnSelectionChange={setLoadOnSelection}
onFoldersChange={refreshLocalModels}
onPickLocalModel={isTauri ? chooseNativeModel : undefined}
onModelsChange={refreshModelLists}
@@ -2313,7 +2352,7 @@ export function ChatPage({
/>
{currentProject && activeThreadId ? (
<>
- <span className="shrink-0" aria-hidden>
+ <span className="shrink-0" aria-hidden={true}>
/
</span>
<span className="min-w-0 truncate">
@@ -2555,7 +2594,8 @@ export function ChatPage({
stagedDownloadFraction={stagedDownload.progress?.fraction ?? null}
onCancelStagedDownload={() =>
stagedDownload.cancelDownload(
- useChatRuntimeStore.getState().pendingSelection?.ggufVariant ?? null,
+ useChatRuntimeStore.getState().pendingSelection?.ggufVariant ??
+ null,
)
}
/>
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 77d7cf4c6db..bd315e19d48 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -17,6 +17,12 @@ import {
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ clearRememberedLoadSettings,
+ loadRememberedLoadSettings,
+ saveRememberedLoadSettings,
+} from "@/components/assistant-ui/model-selector/remembered-load-settings";
import {
Dialog,
DialogContent,
@@ -520,9 +526,13 @@ export function ChatSettingsPanel({
})();
const isLoadedGguf =
useChatRuntimeStore((s) => s.activeGgufVariant) != null;
- const isGguf = isLoadedGguf || pendingIsGguf;
- // A staged pick is always a local GGUF, so show its Model section (and the
- // Load button) even when the currently active model is external.
+ // While a pick is staged the sheet configures *that* model, so its GGUF-ness
+ // (not the currently loaded model's) decides whether the GGUF-only controls
+ // show. Otherwise a staged non-GGUF Hub repo would inherit the loaded GGUF's
+ // context/KV/speculative controls.
+ const isGguf = pendingSelection != null ? pendingIsGguf : isLoadedGguf;
+ // The Model section (and Load button) shows for any staged pick, even when the
+ // currently active model is external.
const hasModelContent =
pendingSelection != null ||
(!isExternalModel && (isGguf || Boolean(params.checkpoint)));
@@ -599,6 +609,29 @@ export function ChatSettingsPanel({
// pendingSelection, so the slider can use the staged model's real ceiling
// without reading the loaded model's `ggufContextLength`.
const stagedContextLength = pendingSelection?.contextLength ?? null;
+ // "Remember settings next time" tick for a staged model. Seeds the store from
+ // the saved per-model settings on stage, so the sheet opens with what was used
+ // last time; the tick reflects whether a saved entry exists.
+ const [remember, setRemember] = useState(false);
+ const pendingId = pendingSelection?.id ?? null;
+ useEffect(() => {
+ if (!pendingId) return;
+ const saved = loadRememberedLoadSettings(pendingId);
+ setRemember(saved != null);
+ if (!saved) return;
+ setCustomContextLength(saved.contextLength);
+ setKvCacheDtype(saved.kvCacheDtype);
+ setSpeculativeType(saved.speculativeType ?? "auto");
+ setSpecDraftNMax(saved.specDraftNMax);
+ setTensorParallel(saved.tensorParallel);
+ }, [
+ pendingId,
+ setCustomContextLength,
+ setKvCacheDtype,
+ setSpeculativeType,
+ setSpecDraftNMax,
+ setTensorParallel,
+ ]);
// While staging, the sheet reflects the STAGED model, so its header context
// takes precedence over the loaded model's (which may differ or be larger).
const baseContext = pendingIsGguf ? stagedContextLength : ggufContextLength;
@@ -1148,34 +1181,61 @@ export function ChatSettingsPanel({
staged (deferred load), Load/Cancel takes its place: there's
nothing loaded to "apply" against yet. */}
{pendingSelection ? (
- <div className="flex flex-col gap-2">
+ <div className="flex flex-col gap-4">
{stagedDownloading && (
<p className="text-[11px] text-muted-foreground">
Downloading…{" "}
{Math.round((stagedDownloadFraction ?? 0) * 100)}%
</p>
)}
+ <label className="flex cursor-pointer items-center gap-2 pb-1.5 text-[12px] text-muted-foreground">
+ <Checkbox
+ className="size-3.5 rounded-full [&_[data-slot=checkbox-indicator]_svg]:size-2.5"
+ checked={remember}
+ onCheckedChange={(v) => setRemember(v === true)}
+ />
+ Remember settings next time
+ </label>
{stagedLoading ? (
// Mid-load: nothing to load or abandon until it settles, so disable.
<Button
type="button"
disabled
size="sm"
- className="h-7 w-fit px-3 text-[12px] font-medium tracking-nav bg-primary/92 text-primary-foreground hover:bg-primary"
+ className="h-9 w-full rounded-full text-[13px] font-medium tracking-nav bg-primary text-primary-foreground hover:bg-primary/90"
>
<Spinner className="size-3.5" />
Loading…
</Button>
) : (
- <div className="flex flex-wrap gap-1.5">
+ <div className="grid grid-cols-2 gap-3">
<Button
type="button"
- onClick={() => onLoadPendingModel?.()}
+ onClick={() => {
+ // Persist (or clear) this model's load knobs before loading.
+ // Save the explicit context override only (null = auto), so
+ // restoring never forces the native context into an OOM.
+ const pid = pendingSelection?.id;
+ if (pid) {
+ if (remember) {
+ saveRememberedLoadSettings(pid, {
+ contextLength: customContextLength,
+ kvCacheDtype,
+ speculativeType,
+ specDraftNMax,
+ tensorParallel,
+ });
+ } else {
+ clearRememberedLoadSettings(pid);
+ }
+ }
+ onLoadPendingModel?.();
+ }}
// Disabled while a different model is mid-load: selectModel
// refuses a concurrent load, so the click could only toast.
disabled={stagedDownloading || loadingModel != null}
size="sm"
- className="h-7 px-3 text-[12px] font-medium tracking-nav bg-primary/92 text-primary-foreground hover:bg-primary"
+ className="h-9 w-full rounded-full text-[13px] font-medium tracking-nav bg-primary text-primary-foreground hover:bg-primary/90"
>
{loadingModel != null ? "Another model loading…" : "Load model"}
</Button>
@@ -1189,7 +1249,7 @@ export function ChatSettingsPanel({
if (stagedDownloading) onCancelStagedDownload?.();
abandonStagedModel();
}}
- className="h-7 px-3 text-[12px] font-medium tracking-nav text-muted-foreground"
+ className="h-9 w-full rounded-full text-[13px] font-medium tracking-nav text-muted-foreground"
>
Cancel
</Button>
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index bbf106400c1..e23d1b0b33b 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -25,6 +25,7 @@ import {
} from "../api/chat-api";
import { formatEta, formatRate } from "../utils/format-transfer";
import {
+ isLocalModelPath,
pendingSelectionMatches,
readPersistedSpeculativeType,
resolveToolsEnabledOnLoad,
@@ -57,6 +58,11 @@ export type SelectedModelInput = {
id: string;
isLora?: boolean;
ggufVariant?: string;
+ /** Where the pick came from (e.g. "hub", "local", "external"). Used to decide
+ * whether an uncached repo should download via the Hub manager. */
+ source?: string;
+ /** Uncached non-GGUF HF repo staged for a snapshot download (variant null). */
+ isHubRepo?: boolean;
loadingDescription?: string;
isDownloaded?: boolean;
expectedBytes?: number;
@@ -484,8 +490,7 @@ export function useChatModelRuntime() {
: undefined;
const previousIsLora =
previousModel?.isLora ?? (previousLora?.exportType === "lora");
- // Covers Unix absolute (/), relative (./ ../), tilde (~/), Windows drive (C:\), UNC (\\server)
- const isLocal = /^(\/|\.{1,2}[\\/]|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(modelId);
+ const isLocal = isLocalModelPath(modelId);
const isCachedLora = isLora && isLocal;
const loadingDescription = [
currentCheckpoint ? "Switching models." : null,
diff --git a/studio/frontend/src/features/chat/hooks/use-staged-model-preparation.ts b/studio/frontend/src/features/chat/hooks/use-staged-model-preparation.ts
index b11f496aa51..d8076c720b8 100644
--- a/studio/frontend/src/features/chat/hooks/use-staged-model-preparation.ts
+++ b/studio/frontend/src/features/chat/hooks/use-staged-model-preparation.ts
@@ -3,9 +3,9 @@
import { useCallback, useEffect } from "react";
-import { useLatestRef } from "@/features/hub/hooks/use-latest-ref";
import { useRepoDownload } from "@/features/hub/download-manager/use-repo-download";
import type { DownloadJob } from "@/features/hub/download-manager/use-repo-download";
+import { useLatestRef } from "@/features/hub/hooks/use-latest-ref";
import { fetchGgufContextLength } from "../api/chat-api";
import {
@@ -13,6 +13,7 @@ import {
pendingSelectionMatches,
useChatRuntimeStore,
} from "../stores/chat-runtime-store";
+import type { PendingModelSelection } from "../stores/chat-runtime-store";
/**
* Drives the deferred ("Load on selection" off) staging flow for a GGUF:
@@ -23,7 +24,10 @@ import {
* the loaded model's `ggufContextLength`). Returns the live download job so the
* sheet can render progress / cancel. Mount once on the chat page.
*/
-export function useStagedModelPreparation(): DownloadJob {
+export function useStagedModelPreparation(opts?: {
+ /** Load the cached file once an autoLoad pick's download completes. */
+ onAutoLoad?: (pending: PendingModelSelection) => void;
+}): DownloadJob {
const pendingId = useChatRuntimeStore((s) => s.pendingSelection?.id ?? null);
const pendingVariant = useChatRuntimeStore(
(s) => s.pendingSelection?.ggufVariant ?? null,
@@ -35,6 +39,10 @@ export function useStagedModelPreparation(): DownloadJob {
const pendingIsGguf = useChatRuntimeStore((s) =>
isPendingGguf(s.pendingSelection),
);
+ // Non-GGUF HF repos download a full snapshot (variant null) but have no header.
+ const pendingIsHubRepo = useChatRuntimeStore(
+ (s) => s.pendingSelection?.isHubRepo ?? false,
+ );
const pendingDownloaded = useChatRuntimeStore(
(s) => s.pendingSelection?.isDownloaded ?? false,
);
@@ -42,6 +50,19 @@ export function useStagedModelPreparation(): DownloadJob {
(s) => s.pendingSelection?.contextLength != null,
);
const setPendingSelection = useChatRuntimeStore((s) => s.setPendingSelection);
+ const onAutoLoadRef = useLatestRef(opts?.onAutoLoad);
+
+ // A failed or cancelled autoLoad download has no sheet to retry from, so drop
+ // the staged pick rather than leave it waiting on a load that won't come.
+ const handleAutoLoadAbort = useCallback((variant: string | null) => {
+ const latest = useChatRuntimeStore.getState().pendingSelection;
+ if (
+ latest?.autoLoad &&
+ (latest.ggufVariant ?? null) === (variant ?? null)
+ ) {
+ useChatRuntimeStore.getState().abandonStagedModel();
+ }
+ }, []);
const fetchContextMetadata = useCallback(async () => {
const current = useChatRuntimeStore.getState().pendingSelection;
@@ -76,9 +97,21 @@ export function useStagedModelPreparation(): DownloadJob {
// inert until something is staged.
repoId: pendingId ?? "__staged_idle__",
activeVariant: pendingVariant,
- onComplete: () => {
+ onComplete: (variant) => {
+ // autoLoad picks load the cached file now; staged picks read the header so
+ // the sheet's context slider can show before a manual load.
+ const latest = useChatRuntimeStore.getState().pendingSelection;
+ if (
+ latest?.autoLoad &&
+ (latest.ggufVariant ?? null) === (variant ?? null)
+ ) {
+ onAutoLoadRef.current?.(latest);
+ return;
+ }
void fetchContextMetadata();
},
+ onError: handleAutoLoadAbort,
+ onCancelled: handleAutoLoadAbort,
});
// job.requestStartDownload's identity changes per render; hold it in a ref so
@@ -87,9 +120,18 @@ export function useStagedModelPreparation(): DownloadJob {
const fetchMetadataRef = useLatestRef(fetchContextMetadata);
useEffect(() => {
- if (!pendingId || !pendingIsGguf || pendingHasContext) return;
+ // GGUF picks (header worth reading) and uncached non-GGUF hub repos (full
+ // snapshot, no header) both run here; everything else is loaded directly.
+ if (
+ !pendingId ||
+ (!pendingIsGguf && !pendingIsHubRepo) ||
+ pendingHasContext
+ ) {
+ return;
+ }
// Native files and already-downloaded HF files are local: read the header
- // now. Otherwise download first; onComplete then reads it.
+ // now. Otherwise download first (a GGUF variant, or a null-variant snapshot
+ // for a hub repo); onComplete then reads the header or auto-loads.
if (pendingNativeToken || pendingDownloaded) {
void fetchMetadataRef.current();
} else {
@@ -102,6 +144,7 @@ export function useStagedModelPreparation(): DownloadJob {
pendingVariant,
pendingNativeToken,
pendingIsGguf,
+ pendingIsHubRepo,
pendingDownloaded,
pendingHasContext,
startDownloadRef,
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index 9b7ca08c1b5..9386650fee1 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -175,6 +175,9 @@ export function applyActiveModelStatusToStore(
status.chat_template === undefined
? prevState.defaultChatTemplate
: status.chat_template;
+ // While a load is in flight, performLoad owns the load params. Seeding them
+ // from a stale poll here would clobber the values the load dialog just set.
+ const seedLoadParams = !prevState.modelLoading;
useChatRuntimeStore.setState({
supportsReasoning,
@@ -199,22 +202,26 @@ export function applyActiveModelStatusToStore(
loadedIsMultimodal: isMultimodalResponse(status),
loadedIsDiffusion: status.is_diffusion ?? false,
specFallbackReason: status.spec_fallback_reason ?? null,
- ...(prevState.loadedSpeculativeType === null && {
- speculativeType: currentSpecType,
- loadedSpeculativeType: currentSpecType,
- }),
- ...(status.spec_draft_n_max !== undefined &&
+ ...(seedLoadParams &&
+ prevState.loadedSpeculativeType === null && {
+ speculativeType: currentSpecType,
+ loadedSpeculativeType: currentSpecType,
+ }),
+ ...(seedLoadParams &&
+ status.spec_draft_n_max !== undefined &&
prevState.loadedSpecDraftNMax === null &&
prevState.specDraftNMax === null && {
specDraftNMax: status.spec_draft_n_max ?? null,
loadedSpecDraftNMax: status.spec_draft_n_max ?? null,
}),
- ...(status.cache_type_kv !== undefined &&
+ ...(seedLoadParams &&
+ status.cache_type_kv !== undefined &&
prevState.loadedKvCacheDtype === null && {
kvCacheDtype: status.cache_type_kv,
loadedKvCacheDtype: status.cache_type_kv,
}),
- ...(status.tensor_parallel !== undefined &&
+ ...(seedLoadParams &&
+ status.tensor_parallel !== undefined &&
prevState.loadedTensorParallel === null && {
tensorParallel: status.tensor_parallel,
loadedTensorParallel: status.tensor_parallel,
diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsx
index 87fe9b66eca..1651b496269 100644
--- a/studio/frontend/src/features/chat/projects-page.tsx
+++ b/studio/frontend/src/features/chat/projects-page.tsx
@@ -302,13 +302,13 @@ export function ProjectsPage() {
<DropdownMenuSubContent className="w-52">
{EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
<DropdownMenuItem key={`ap-m-${fmt}`} onSelect={() => void handleBulkProjectExport("projects", fmt, true)}>
- {label} — combined
+ {label} (combined)
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
{EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
<DropdownMenuItem key={`ap-s-${fmt}`} onSelect={() => void handleBulkProjectExport("projects", fmt, false)}>
- {label} — per chat
+ {label} (per chat)
</DropdownMenuItem>
))}
</DropdownMenuSubContent>
@@ -318,13 +318,13 @@ export function ProjectsPage() {
<DropdownMenuSubContent className="w-52">
{EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
<DropdownMenuItem key={`all-m-${fmt}`} onSelect={() => void handleBulkProjectExport("all", fmt, true)}>
- {label} — combined
+ {label} (combined)
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
{EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
<DropdownMenuItem key={`all-s-${fmt}`} onSelect={() => void handleBulkProjectExport("all", fmt, false)}>
- {label} — per chat
+ {label} (per chat)
</DropdownMenuItem>
))}
</DropdownMenuSubContent>
@@ -586,7 +586,8 @@ export function ProjectsPage() {
<DialogTitle>Import chats</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
- <span className="font-medium text-foreground">{importFile?.name}</span> — choose where to import:
+ Choose where to import{" "}
+ <span className="font-medium text-foreground">{importFile?.name}</span>:
</p>
<Select
value={importTargetId ?? "__recents__"}
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 2ec741b1bfe..4cca3dc2e3d 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -1,27 +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 { cancelStagedModelDownload } from "@/features/hub";
import { toast } from "@/lib/toast";
import { create } from "zustand";
-import { cancelStagedModelDownload } from "@/features/hub";
+import { isExternalModelId, parseExternalModelId } from "../external-providers";
import {
type ChatPresetSource,
type Preset,
getPresetSource,
} from "../presets/preset-policy";
+import { getExternalMaxOutputTokens } from "../provider-capabilities";
import {
type ChatLoraSummary,
type ChatModelSummary,
DEFAULT_INFERENCE_PARAMS,
type InferenceParams,
} from "../types/runtime";
-import { isExternalModelId, parseExternalModelId } from "../external-providers";
-import { getExternalMaxOutputTokens } from "../provider-capabilities";
-import { useExternalProvidersStore } from "./external-providers-store";
import {
loadChatSettingsWithLegacyImport,
savePersistedChatSettingsPatch,
} from "../utils/chat-settings-storage";
+import { useExternalProvidersStore } from "./external-providers-store";
const HF_TOKEN_KEY = "unsloth_hf_token";
const HF_TOKEN_CHANGED_EVENT = "unsloth:hf-token-changed";
@@ -37,6 +37,10 @@ export const CHAT_ALLOW_ARTIFACT_NETWORK_ACCESS_KEY =
export const CHAT_MCP_ENABLED_KEY = "unsloth_chat_mcp_enabled";
export const CHAT_CONFIRM_TOOL_CALLS_KEY = "unsloth_chat_confirm_tool_calls";
export const CHAT_LOAD_ON_SELECTION_KEY = "unsloth_chat_load_on_selection";
+export const CHAT_EXPAND_QUANTIZATIONS_KEY =
+ "unsloth_chat_expand_quantizations";
+export const CHAT_SHOW_ALL_QUANTIZATIONS_KEY =
+ "unsloth_chat_show_all_quantizations";
export const CHAT_BYPASS_PERMISSIONS_KEY = "unsloth_chat_bypass_permissions";
export const CHAT_WEB_FETCH_TOOLS_ENABLED_KEY =
"unsloth_chat_web_fetch_tools_enabled";
@@ -53,9 +57,7 @@ export const CHAT_SPECULATIVE_TYPE_KEY = "unsloth_chat_speculative_type";
// choice would silently no-op on models without an MTP head. Unknown -> auto.
const PERSISTED_SPEC_MODES = new Set(["auto", "ngram", "off"]);
-export type RagSource =
- | { type: "thread" }
- | { type: "kb"; kbId: string };
+export type RagSource = { type: "thread" } | { type: "kb"; kbId: string };
export type RagMode = "hybrid" | "lexical" | "dense";
@@ -120,7 +122,11 @@ function loadRagTopK(): number {
function loadRagNumber(
key: string,
fallback: number,
- { min, max, integer = false }: { min: number; max: number; integer?: boolean },
+ {
+ min,
+ max,
+ integer = false,
+ }: { min: number; max: number; integer?: boolean },
): number {
if (typeof window === "undefined") return fallback;
try {
@@ -360,7 +366,10 @@ export function normalizeSpeculativeType(
}
if (s === "mtp+ngram") return "mtp+ngram";
// Comma-chained legacy values (e.g. from older backend echoes).
- const parts = s.split(",").map((p) => p.trim()).filter(Boolean);
+ const parts = s
+ .split(",")
+ .map((p) => p.trim())
+ .filter(Boolean);
const hasMtp = parts.some((p) => p === "mtp" || p === "draft-mtp");
const hasNgram = parts.some(
(p) => p === "ngram" || p === "ngram-mod" || p === "ngram-simple",
@@ -411,7 +420,9 @@ export function saveSpeculativeType(value: string | null): void {
function notifyHfTokenChanged(value: string): void {
if (!canUseStorage()) return;
try {
- window.dispatchEvent(new CustomEvent(HF_TOKEN_CHANGED_EVENT, { detail: value }));
+ window.dispatchEvent(
+ new CustomEvent(HF_TOKEN_CHANGED_EVENT, { detail: value }),
+ );
} catch {
// ignore
}
@@ -435,6 +446,12 @@ export type PendingModelSelection = {
* Scoped here (not the shared `ggufContextLength`) so a staged model's
* metadata never pollutes the currently-loaded model's context display. */
contextLength?: number | null;
+ /** "Load on selection" on + un-cached GGUF: download via the manager (global
+ * indicator) without opening the sheet, then load once the download finishes. */
+ autoLoad?: boolean;
+ /** Uncached non-GGUF HF repo: download the full snapshot via the manager
+ * (variant null) the same way GGUF picks download a variant. */
+ isHubRepo?: boolean;
};
/** A pick is a GGUF (HF variant, native file, or a direct local .gguf) and so
@@ -449,6 +466,33 @@ export function hasGgufSource(x: {
);
}
+/** A local-disk model id: Unix absolute (/), relative (./ ../), tilde (~/),
+ * Windows drive (C:\) or UNC (\\server). Shared so the loader and the
+ * hub-repo predicate classify ids identically. */
+export function isLocalModelPath(id: string): boolean {
+ return /^(\/|\.{1,2}[\\/]|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(id);
+}
+
+/** An uncached HF hub repo we can download as a full snapshot (non-GGUF
+ * safetensors / MLX). Excludes GGUF sources, local paths, native files, LoRA,
+ * and external provider models so none are mis-routed into a snapshot. */
+export function isDownloadableHubRepo(x: {
+ id: string;
+ source?: string;
+ isLora?: boolean;
+ ggufVariant?: string;
+ nativePathToken?: string;
+ isGguf?: boolean;
+}): boolean {
+ return (
+ x.source === "hub" &&
+ !hasGgufSource(x) &&
+ x.isLora !== true &&
+ x.nativePathToken == null &&
+ !isLocalModelPath(x.id)
+ );
+}
+
export function isPendingGguf(pending: PendingModelSelection | null): boolean {
return pending != null && hasGgufSource(pending);
}
@@ -609,6 +653,11 @@ type ChatRuntimeStore = {
* `pendingSelection` (and opens settings) instead of loading immediately,
* so load settings can be set before the single load. */
loadOnSelection: boolean;
+ /** Persisted: expand every On Device GGUF repo's quantizations by default
+ * instead of waiting for a click. */
+ expandQuantizations: boolean;
+ /** Persisted: show non-downloaded quantizations too, not just downloaded. */
+ showAllQuantizations: boolean;
/** A local model picked while `loadOnSelection` is off: staged, not loaded.
* The settings sheet shows its load knobs and a Load button. */
pendingSelection: PendingModelSelection | null;
@@ -723,6 +772,8 @@ type ChatRuntimeStore = {
resetModelSettingsToLoaded: () => void;
setTensorParallel: (value: boolean) => void;
setLoadOnSelection: (value: boolean) => void;
+ setExpandQuantizations: (value: boolean) => void;
+ setShowAllQuantizations: (value: boolean) => void;
setPendingSelection: (selection: PendingModelSelection | null) => void;
/** Stage a pick for a deferred load: revert knobs to the loaded baseline,
* record the selection, and open the settings sheet. */
@@ -1035,6 +1086,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
tensorParallel: false,
loadedTensorParallel: null,
loadOnSelection: loadBool(CHAT_LOAD_ON_SELECTION_KEY, true),
+ expandQuantizations: loadBool(CHAT_EXPAND_QUANTIZATIONS_KEY, false),
+ showAllQuantizations: loadBool(CHAT_SHOW_ALL_QUANTIZATIONS_KEY, true),
pendingSelection: null,
loadedIsMultimodal: false,
loadedIsDiffusion: false,
@@ -1176,7 +1229,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// render gate would otherwise show old counters until the next completion.
const checkpointChanged = state.params.checkpoint !== modelId;
const pendingToClear =
- checkpointChanged && state.params.checkpoint ? state.pendingSelection : null;
+ checkpointChanged && state.params.checkpoint
+ ? state.pendingSelection
+ : null;
if (pendingToClear) {
cancelStagedModelDownload(pendingToClear);
}
@@ -1476,6 +1531,14 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
saveBool(CHAT_LOAD_ON_SELECTION_KEY, loadOnSelection);
set({ loadOnSelection });
},
+ setExpandQuantizations: (expandQuantizations) => {
+ saveBool(CHAT_EXPAND_QUANTIZATIONS_KEY, expandQuantizations);
+ set({ expandQuantizations });
+ },
+ setShowAllQuantizations: (showAllQuantizations) => {
+ saveBool(CHAT_SHOW_ALL_QUANTIZATIONS_KEY, showAllQuantizations);
+ set({ showAllQuantizations });
+ },
setPendingSelection: (pendingSelection) => set({ pendingSelection }),
stageModel: (selection) => {
// Refuse staging mid-load: post-load cleanup would silently drop the queued
@@ -1493,7 +1556,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
return {
...loadedBaselineSettings(s),
pendingSelection: selection,
- settingsPanelOpen: true,
+ // autoLoad downloads silently and loads on completion, so keep the sheet shut.
+ settingsPanelOpen: !selection.autoLoad,
// Speculative starts from the standing default, not the loaded model's
// mode, so a fresh pick doesn't inherit (and then carry, via the staged
// Load's keepSpeculative) a forced MTP mode onto a model that may lack it.
@@ -1537,7 +1601,7 @@ export function resolveSpeculativeSettingsForLoad({
const state = useChatRuntimeStore.getState();
const speculativeType = usePersistedPreference
? readPersistedSpeculativeType()
- : state.speculativeType ?? readPersistedSpeculativeType();
+ : (state.speculativeType ?? readPersistedSpeculativeType());
return {
speculativeType,
specDraftNMax:
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index d9b69a1ef6b..b8391e31e74 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -92,6 +92,8 @@ export interface GgufVariantsResponse {
variants: GgufVariantDetail[];
has_vision: boolean;
default_variant: string | null;
+ /** Native max context from GGUF metadata; present once a variant is downloaded. */
+ context_length?: number | null;
}
export function isMultimodalResponse(
diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsx
index f4ce169bbe2..64123bc2f5d 100644
--- a/studio/frontend/src/features/export/export-page.tsx
+++ b/studio/frontend/src/features/export/export-page.tsx
@@ -37,12 +37,9 @@ import {
type LocalModelInfo,
useTrainingConfigStore,
} from "@/features/training";
+import { useHubModelSearch } from "@/features/hub/hooks/use-hub-model-search";
import { confirmRemoteCodeIfNeeded } from "@/features/security";
-import {
- useDebouncedValue,
- useHfModelSearch,
- useHfTokenValidation,
-} from "@/hooks";
+import { useDebouncedValue, useHfTokenValidation } from "@/hooks";
import {
AlertCircleIcon,
ArrowDown01Icon,
@@ -285,9 +282,12 @@ export function ExportPage() {
results: hfResults,
isLoading: isLoadingHfModels,
error: hfSearchError,
- } = useHfModelSearch(debouncedModelQuery, {
+ } = useHubModelSearch(debouncedModelQuery, {
accessToken: debouncedHfToken || undefined,
excludeGguf: true,
+ // Curated unsloth listing by default, but a typed query searches the whole
+ // Hub (unsloth floated first) so non-unsloth base models stay selectable.
+ ownerScope: debouncedModelQuery.trim() ? "all" : "unsloth",
});
const { error: tokenValidationError, isChecking: isCheckingToken } =
useHfTokenValidation(hfToken);
diff --git a/studio/frontend/src/features/hub/catalog/dot-tag.tsx b/studio/frontend/src/features/hub/catalog/dot-tag.tsx
index 8e6c9f97fcb..9452a201d41 100644
--- a/studio/frontend/src/features/hub/catalog/dot-tag.tsx
+++ b/studio/frontend/src/features/hub/catalog/dot-tag.tsx
@@ -8,6 +8,7 @@ type DotTagTone =
| "warning"
| "danger"
| "gguf"
+ | "mlx"
| "checkpoint"
| "adapter";
@@ -16,6 +17,7 @@ const TONE_CLASS: Record<DotTagTone, string> = {
warning: "bg-status-warning",
danger: "bg-status-danger",
gguf: "bg-format-gguf",
+ mlx: "bg-format-mlx",
checkpoint: "bg-format-checkpoint",
adapter: "bg-format-adapter",
};
@@ -24,10 +26,12 @@ export function DotTag({
tone,
label,
className,
+ dotClassName,
}: {
tone: DotTagTone;
label: string;
className?: string;
+ dotClassName?: string;
}) {
return (
<span
@@ -38,7 +42,11 @@ export function DotTag({
>
<span
aria-hidden="true"
- className={cn("inline-block size-1.5 shrink-0 rounded-full", TONE_CLASS[tone])}
+ className={cn(
+ "inline-block size-1.5 shrink-0 rounded-full",
+ TONE_CLASS[tone],
+ dotClassName,
+ )}
/>
{label}
</span>
diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
index ea3f158aa6f..d089835c3d3 100644
--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
@@ -144,7 +144,9 @@ function QuantBadge({
<span
className={cn(
CHIP_BASE,
- "gap-1.5 cursor-help",
+ // `shrink` overrides CHIP_BASE's shrink-0 so a long file-path quant
+ // label can shrink and truncate instead of overflowing the row.
+ "min-w-0 max-w-full shrink gap-1.5 cursor-help",
active ? CHIP_ACTIVE : CHIP_DEFAULT,
)}
>
@@ -155,12 +157,12 @@ function QuantBadge({
className={cn("size-3.5 shrink-0", meta.iconClassName)}
/>
)}
- <span>{quant}</span>
+ <span className="min-w-0 truncate">{quant}</span>
</span>
) : (
<span
className={cn(
- "inline-flex cursor-help items-center gap-1.5 text-[12.5px] font-medium tracking-tight tabular-nums",
+ "inline-flex min-w-0 max-w-full shrink 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",
)}
>
@@ -171,7 +173,7 @@ function QuantBadge({
className={cn("size-3.5 shrink-0", meta.iconClassName)}
/>
)}
- <span>{quant}</span>
+ <span className="min-w-0 truncate">{quant}</span>
</span>
);
if (!showFit || tooltipMode === "none") return inner;
@@ -680,7 +682,7 @@ export function GgufDownloadCard({
Select quantization
</span>
)}
- <span className="ml-auto flex items-center gap-1.5 text-[12px] text-muted-foreground">
+ <span className="ml-auto flex shrink-0 items-center gap-1.5 text-[12px] text-muted-foreground">
{selected?.downloaded && (
<DotTag
tone="success"
diff --git a/studio/frontend/src/features/hub/catalog/hub-detail-view.tsx b/studio/frontend/src/features/hub/catalog/hub-detail-view.tsx
index 460dba96131..d733049ec33 100644
--- a/studio/frontend/src/features/hub/catalog/hub-detail-view.tsx
+++ b/studio/frontend/src/features/hub/catalog/hub-detail-view.tsx
@@ -45,8 +45,16 @@ export function HubDetailView({
<div
ref={scrollRef}
data-hub-scroll="true"
- // Right margin nudges the scrollbar in from the pane's edge.
- className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto [overflow-anchor:none] mr-2 [scrollbar-gutter:stable] [scrollbar-width:thin]"
+ // Mirror the catalog's gutter strategy so the centered column lines up
+ // with the top bar: the full overlay reserves an equal both-edges gutter
+ // to stay symmetric; split pins a narrow pane so it nudges the scrollbar
+ // in from the edge with a right gutter only.
+ className={cn(
+ "min-h-0 flex-1 overflow-x-hidden overflow-y-auto [overflow-anchor:none] [scrollbar-width:thin]",
+ compact
+ ? "mr-2 [scrollbar-gutter:stable]"
+ : "[scrollbar-gutter:stable_both-edges]",
+ )}
>
<div
className={cn(
diff --git a/studio/frontend/src/features/hub/catalog/hub-option-menu.tsx b/studio/frontend/src/features/hub/catalog/hub-option-menu.tsx
index ed83e46b364..7895a892545 100644
--- a/studio/frontend/src/features/hub/catalog/hub-option-menu.tsx
+++ b/studio/frontend/src/features/hub/catalog/hub-option-menu.tsx
@@ -214,7 +214,9 @@ export function HubOptionMenu<T extends string>({
}}
onPointerEnter={() => activateIndex(index)}
className={cn(
- "relative flex w-full min-w-0 cursor-pointer select-none items-center rounded-[12px] py-2 pr-8 pl-3 text-left text-sm leading-snug outline-none transition-colors",
+ // 14px menu radius minus the 4px padding, so the hover nests
+ // cleanly into the dropdown's corners.
+ "relative flex w-full min-w-0 cursor-pointer select-none items-center rounded-[10px] 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">
diff --git a/studio/frontend/src/features/hub/catalog/models-toolbar.tsx b/studio/frontend/src/features/hub/catalog/models-toolbar.tsx
index 7c9071daad7..c8adfb54f5b 100644
--- a/studio/frontend/src/features/hub/catalog/models-toolbar.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-toolbar.tsx
@@ -47,11 +47,11 @@ const SORT_OPTIONS: ReadonlyArray<{
value: HfSortKey;
label: string;
}> = [
+ { value: "createdAt", label: "Newest" },
{ value: "trendingScore", label: "Trending" },
- { value: "likes", label: "Most likes" },
{ value: "downloads", label: "Most downloads" },
{ value: "lastModified", label: "Recently updated" },
- { value: "createdAt", label: "Newest" },
+ { value: "likes", label: "Most likes" },
];
export const ModelsToolbar = memo(function ModelsToolbar({
diff --git a/studio/frontend/src/features/hub/catalog/owner-avatar.tsx b/studio/frontend/src/features/hub/catalog/owner-avatar.tsx
index 852c09ab5f2..82a1f150d25 100644
--- a/studio/frontend/src/features/hub/catalog/owner-avatar.tsx
+++ b/studio/frontend/src/features/hub/catalog/owner-avatar.tsx
@@ -19,6 +19,24 @@ const SIZES: Record<AvatarSize, string> = {
lg: "size-12 rounded-[15px] text-[16px]",
};
+// Unsloth's own uploads (no upstream provider match) show the bundled Unsloth
+// brand avatar instead of a colored-initial tile, so they read as Unsloth even
+// in virtualized rows that never fetch the HF profile picture.
+const UNSLOTH_OWNER_LOGO: ProviderLogo = {
+ id: "unsloth",
+ name: "Unsloth",
+ logoPath: "/circle-logo-small.png",
+ treatment: "original",
+ background: "transparent",
+ fit: "cover",
+ // Used directly for the unsloth owner, never via prefix matching.
+ prefixes: [],
+};
+
+function isUnslothOwner(owner: string): boolean {
+ return owner.trim().toLowerCase() === "unsloth";
+}
+
const AVATAR_IMAGE_RETRY_BASE_MS = 60_000;
const AVATAR_IMAGE_RETRY_MAX_MS = 30 * 60_000;
@@ -68,6 +86,15 @@ export function OwnerAvatar({
/>
);
}
+ if (isUnslothOwner(owner)) {
+ return (
+ <ProviderLogoTile
+ provider={UNSLOTH_OWNER_LOGO}
+ size={size}
+ className={className}
+ />
+ );
+ }
return (
<DefaultAvatar
owner={owner}
@@ -87,6 +114,9 @@ export function useAvatarImageUrl(
if (provider) {
return provider.treatment === "original" ? provider.logoPath : null;
}
+ if (isUnslothOwner(owner)) {
+ return UNSLOTH_OWNER_LOGO.logoPath;
+ }
return remoteUrl;
}
diff --git a/studio/frontend/src/features/hub/catalog/owner-scope-toggle.tsx b/studio/frontend/src/features/hub/catalog/owner-scope-toggle.tsx
index 17c3f2ba342..fed8568f99c 100644
--- a/studio/frontend/src/features/hub/catalog/owner-scope-toggle.tsx
+++ b/studio/frontend/src/features/hub/catalog/owner-scope-toggle.tsx
@@ -28,7 +28,8 @@ export function OwnerScopeToggle({
onValueChange={onChange}
ariaLabel="Publisher scope"
align="end"
- className="h-8 text-[11.5px]"
+ // Extra gap so the chevron sits a touch further from the label.
+ className="h-8 gap-1.5 text-[11.5px]"
/>
);
}
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
index 023cc50947b..948b0c098d2 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx
@@ -106,7 +106,7 @@ function DownloadRow({ jobKey }: { jobKey: string }) {
job.state === "cancelled" ||
job.state === "error";
return (
- <li className="flex flex-col gap-1.5 px-3 py-2.5">
+ <li className="flex flex-col gap-1.5 py-2.5 pl-4 pr-3">
<div className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-foreground">
{job.repoId}
@@ -173,7 +173,9 @@ function DownloadRow({ jobKey }: { jobKey: string }) {
);
}
-export function DownloadManagerPanel() {
+export function DownloadManagerPanel({
+ positioned = true,
+}: { positioned?: boolean } = {}) {
const pathname = useRouterState({ select: (s) => s.location.pathname });
const enabled = canUseDownloadManager(pathname);
const [collapsed, setCollapsed] = useState(false);
@@ -195,7 +197,14 @@ export function DownloadManagerPanel() {
: "Downloads";
return (
- <div className="pointer-events-none fixed bottom-4 right-4 z-50">
+ <div
+ className={cn(
+ // Standalone: anchor bottom-right. In a shared stack (positioned=false)
+ // flow as a right-aligned row so overlays stack instead of overlapping.
+ "pointer-events-none",
+ positioned ? "fixed bottom-4 right-4 z-50" : "flex justify-end",
+ )}
+ >
{collapsed ? (
<Tooltip>
<TooltipTrigger asChild={true}>
@@ -221,7 +230,7 @@ export function DownloadManagerPanel() {
</Tooltip>
) : (
<div className="hub-download-panel pointer-events-auto w-[min(400px,calc(100vw-2rem))] overflow-hidden">
- <div className="flex items-center gap-2 border-b border-foreground/[0.07] px-3 py-2">
+ <div className="flex items-center gap-2 border-b border-foreground/[0.07] py-2 pl-4 pr-3">
<span className="min-w-0 flex-1 truncate text-[12.5px] font-semibold text-foreground">
{headerLabel}
</span>
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
index 647c9adb5ee..4e7be09f2c7 100644
--- a/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts
+++ b/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts
@@ -1,14 +1,9 @@
// 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 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,
@@ -16,33 +11,44 @@ import {
useMemo,
useState,
} from "react";
-import { pullBatch, useHubPaginatedSearch } from "./use-hub-paginated-search";
-import { usePlatformStore } from "@/config/env";
+import {
+ type CachedResult,
+ cachedModelInfo,
+ primeCacheFromListing,
+} from "../lib/hf-cache";
import { EMBEDDING_TAGS, estimateSizeFromDtypes } from "../lib/hf-model-meta";
import { detectBaseModel } from "../lib/model-capabilities";
import { isGgufLike } from "../lib/model-identifiers";
+import { fetchWithTimeout } from "../lib/network";
import {
- classifyUnslothSupport,
- excludedFormatTagsForDevice,
type UnslothSupport,
type UnslothSupportStatus,
+ classifyUnslothSupport,
+ excludedFormatTagsForDevice,
} from "../lib/unsloth-support";
+import { pullBatch, useHubPaginatedSearch } from "./use-hub-paginated-search";
-const ALL_FIELDS: (
- | "safetensors"
- | "tags"
- | "library_name"
- | "config"
- | "createdAt"
- | "downloadsAllTime"
-)[] = [
+// "gguf" is not in the @huggingface/hub expandable-key type, but the listing
+// supports expand=gguf (see withGgufExpand) and listModels' pick() copies any
+// requested field through at runtime. Request it here so GGUF repos whose id
+// has no "<n>B" token (Kimi, MiniMax, GLM) still populate m.gguf.total for the
+// param chip / OOM badge. The cast bridges that single library type gap.
+const ALL_FIELDS = [
"safetensors",
"tags",
"library_name",
"config",
"createdAt",
"downloadsAllTime",
-];
+ "gguf",
+] as unknown as (
+ | "safetensors"
+ | "tags"
+ | "library_name"
+ | "config"
+ | "createdAt"
+ | "downloadsAllTime"
+)[];
export { classifyUnslothSupport };
export type { UnslothSupport, UnslothSupportStatus };
@@ -115,10 +121,28 @@ export interface HfModelResult {
const DESC_ONLY_SORTS = new Set<HfSortKey>(["trendingScore"]);
const HF_SEARCH_TIMEOUT_MS = 15_000;
+// The HF listModels lib doesn't whitelist gguf metadata, but the listing
+// supports it. Append expand=gguf so GGUF repos report a param count (used for
+// the size / OOM badge) even when the name has no "<n>B" token (Kimi, MiniMax,
+// GLM). Shared by every fetch path so the badge is consistent.
+function withGgufExpand(input: Parameters<typeof fetch>[0]): string {
+ const rawUrl =
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url;
+ const url = new URL(rawUrl);
+ if (!url.searchParams.getAll("expand").includes("gguf")) {
+ url.searchParams.append("expand", "gguf");
+ }
+ return url.toString();
+}
+
function makeHfFetch(signal?: AbortSignal): typeof fetch {
return (input, init) =>
fetchWithTimeout(
- input,
+ withGgufExpand(input),
signal ? { ...init, signal } : init,
HF_SEARCH_TIMEOUT_MS,
);
@@ -149,7 +173,7 @@ function makeSortFetch(
url.searchParams.set("direction", effectiveDir === "asc" ? "1" : "-1");
return fetchWithTimeout(
- url,
+ withGgufExpand(url),
signal ? { ...init, signal } : init,
HF_SEARCH_TIMEOUT_MS,
);
@@ -450,7 +474,9 @@ function createChannelIterator(
additionalFields: ALL_FIELDS,
fetch: makeSortFetch(opts.sortBy, opts.sortDirection, opts.signal),
sort: opts.sortBy,
- ...(opts.accessToken ? { credentials: { accessToken: opts.accessToken } } : {}),
+ ...(opts.accessToken
+ ? { credentials: { accessToken: opts.accessToken } }
+ : {}),
}) as AsyncGenerator<unknown>;
}
@@ -564,7 +590,11 @@ export async function fetchChannelFirstPage(
yield model;
}
}
- const { items, done, scanned } = await pullBatch(primed(), mapModel, pageSize);
+ const { items, done, scanned } = await pullBatch(
+ primed(),
+ mapModel,
+ pageSize,
+ );
return { results: items, scanned, done };
}
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
index de78ce7438e..943aca5e9a4 100644
--- a/studio/frontend/src/features/hub/hub-page.tsx
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -65,6 +65,7 @@ import {
SECTION_TO_CHANNEL,
findChannel,
} from "./lib/channels";
+import { isHiddenModelId } from "./lib/hidden-models";
import { inventoryRowMatches, tokenizeQuery } from "./lib/inventory-search";
import {
buildDiscoverRows,
@@ -576,9 +577,10 @@ export function ModelsPage() {
const effectiveSort: HfSortKey =
isFeedMode && liveListChannel ? liveListChannel.sort : sortBy;
const effectiveDirection: HfSortDirection = isFeedMode ? "desc" : direction;
- // Feed mode uses the live channel format so it does not hide non-matching rows.
- const effectiveDiscoverFormat: ModelFormatFilter =
- isFeedMode && liveListChannel ? liveListChannel.format : deferredFormatFilter;
+ // The format dropdown always filters the visible list, including the feed's
+ // "Latest" list, so the default (GGUF) hides fp8/safetensors and picking a
+ // format actually changes the rows.
+ const effectiveDiscoverFormat: ModelFormatFilter = deferredFormatFilter;
const listChannel = useMemo<HfModelSearchChannel | null>(() => {
if (!liveListChannel) return null;
@@ -683,6 +685,7 @@ export function ModelsPage() {
if (isDatasetMode) return discoverRows;
return discoverRows.filter(
(row) =>
+ !isHiddenModelId(row.id) &&
matchesFormat(detectResultFormat(row.result), effectiveDiscoverFormat) &&
matchesCapability(row.capabilities, deferredCapabilityFilter) &&
(!activeChannel?.finetunableOnly || isUnslothFinetunable(row.result)),
@@ -710,7 +713,9 @@ export function ModelsPage() {
hubFeed.trending.results,
effectiveCachedRows,
effectiveLocalRows,
- ).filter((row) => matchesFormat(row.result.isGguf, "gguf")),
+ )
+ .filter((row) => !isHiddenModelId(row.id))
+ .filter((row) => matchesFormat(row.result.isGguf, "gguf")),
[hubFeed.trending.results, modelDiscoveryInventorySignature],
);
const feedRows = useMemo(() => {
diff --git a/studio/frontend/src/features/hub/hub.css b/studio/frontend/src/features/hub/hub.css
index 8fc3cc6a07f..947dd8cb349 100644
--- a/studio/frontend/src/features/hub/hub.css
+++ b/studio/frontend/src/features/hub/hub.css
@@ -697,12 +697,20 @@
box-shadow: 0 2px 8px -2px rgba(0, 0, 0, 0.16);
}
+ html:not(.dark) .hub-tab-toggle-pill:hover {
+ background-color: #f3f3f3;
+ }
+
html.dark .hub-tab-toggle-pill {
background-color: color-mix(in srgb, var(--foreground) 10%, transparent);
border: 0;
box-shadow: none;
}
+ html.dark .hub-tab-toggle-pill:hover {
+ background-color: color-mix(in srgb, var(--foreground) 18%, transparent);
+ }
+
html:not(.dark) .hub-page .catalog-row {
background-color: transparent;
border-color: transparent;
diff --git a/studio/frontend/src/features/hub/lib/channels.ts b/studio/frontend/src/features/hub/lib/channels.ts
index 4106820c4d3..944a42362e6 100644
--- a/studio/frontend/src/features/hub/lib/channels.ts
+++ b/studio/frontend/src/features/hub/lib/channels.ts
@@ -48,7 +48,9 @@ export const CHANNEL_PRESETS: readonly ChannelPreset[] = [
hint: "Freshly released models from the Unsloth channel.",
owner: "unsloth",
format: "all",
- sort: "lastModified",
+ // Newest by creation date so the feed shows freshly released models, not
+ // ones merely re-touched (lastModified).
+ sort: "createdAt",
},
{
id: "unsloth-safetensors",
diff --git a/studio/frontend/src/features/hub/lib/hidden-models.ts b/studio/frontend/src/features/hub/lib/hidden-models.ts
new file mode 100644
index 00000000000..2dbe2579470
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/hidden-models.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
+
+// Infra models hidden from every browse/preview list (Hub discover and the chat
+// model selector). Mirrors the backend `_is_hidden_model`: the RAG embedding
+// model and the llama.cpp validation probe are not usable chat models. Per-repo
+// file/download views are NOT filtered, so a reinstall still shows the model as
+// already downloaded.
+const HIDDEN_NEEDLES = [
+ "bge-small-en-v1.5", // RAG embedder: unsloth/bge-small-en-v1.5[-GGUF]
+ "ggml-org/models", // llama.cpp validation probe repo
+ "stories260k.gguf", // probe filename (carries .gguf so it stays specific)
+];
+
+/** True if any id/path is a hidden infra model. */
+export function isHiddenModelId(
+ ...values: (string | null | undefined)[]
+): boolean {
+ return values.some((v) => {
+ if (!v) return false;
+ const lower = v.toLowerCase();
+ return HIDDEN_NEEDLES.some((needle) => lower.includes(needle));
+ });
+}
diff --git a/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx b/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx
index 415b84a7ed7..6404ddd40fd 100644
--- a/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx
+++ b/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx
@@ -35,12 +35,9 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
-import {
- useDebouncedValue,
- useHfDatasetSearch,
- useHfTokenValidation,
- useInfiniteScroll,
-} from "@/hooks";
+import { useDebouncedValue, useHfTokenValidation } from "@/hooks";
+import { useHubDatasetSearch } from "@/features/hub/hooks/use-hub-dataset-search";
+import { useHubInfiniteScroll } from "@/features/hub/hooks/use-hub-infinite-scroll";
import { cn } from "@/lib/utils";
import {
HfDatasetSubsetSplitSelectors,
@@ -117,8 +114,9 @@ export function DatasetStep() {
isLoading,
isLoadingMore,
fetchMore,
+ scannedCount,
error: hfSearchError,
- } = useHfDatasetSearch(debouncedQuery, {
+ } = useHubDatasetSearch(debouncedQuery, {
modelType,
accessToken: hfToken || undefined,
});
@@ -129,10 +127,11 @@ export function DatasetStep() {
const resultIds = useMemo(() => hfResults.map((r) => r.id), [hfResults]);
const comboboxAnchorRef = useRef<HTMLDivElement>(null);
- const { scrollRef, sentinelRef } = useInfiniteScroll(
- fetchMore,
- hfResults.length,
- );
+ const { scrollRef, sentinelRef } = useHubInfiniteScroll(fetchMore, scannedCount, {
+ isFetching: isLoading || isLoadingMore,
+ resultCount: hfResults.length,
+ resetKey: debouncedQuery,
+ });
const handleFileUpload = () => {
setUploadedFile("my_dataset.jsonl");
diff --git a/studio/frontend/src/features/onboarding/components/steps/model-selection-step.tsx b/studio/frontend/src/features/onboarding/components/steps/model-selection-step.tsx
index f42b83d14ad..a5ce25dd328 100644
--- a/studio/frontend/src/features/onboarding/components/steps/model-selection-step.tsx
+++ b/studio/frontend/src/features/onboarding/components/steps/model-selection-step.tsx
@@ -37,10 +37,10 @@ import { MODEL_TYPE_TO_HF_TASK, PRIORITY_TRAINING_MODELS, applyPriorityOrdering
import {
useDebouncedValue,
useGpuInfo,
- useHfModelSearch,
useHfTokenValidation,
- useInfiniteScroll,
} from "@/hooks";
+import { useHubModelSearch } from "@/features/hub/hooks/use-hub-model-search";
+import { useHubInfiniteScroll } from "@/features/hub/hooks/use-hub-infinite-scroll";
import { extractParamLabel } from "@/lib/model-size";
import { formatCompact } from "@/lib/utils";
import {
@@ -93,12 +93,16 @@ export function ModelSelectionStep() {
isLoading,
isLoadingMore,
fetchMore,
+ scannedCount,
error: hfSearchError,
- } = useHfModelSearch(debouncedQuery, {
+ } = useHubModelSearch(debouncedQuery, {
task,
accessToken: debouncedHfToken || undefined,
excludeGguf: true,
priorityIds: PRIORITY_TRAINING_MODELS,
+ // Curated unsloth listing by default, but a typed query searches the whole
+ // Hub (unsloth floated first) so non-unsloth base models stay selectable.
+ ownerScope: debouncedQuery.trim() ? "all" : "unsloth",
});
const { error: tokenValidationError, isChecking: isCheckingToken } =
@@ -128,10 +132,11 @@ export function ModelSelectionStep() {
}, [hfResults, gpu, trainingMethod]);
const comboboxAnchorRef = useRef<HTMLDivElement>(null);
- const { scrollRef, sentinelRef } = useInfiniteScroll(
- fetchMore,
- hfResults.length,
- );
+ const { scrollRef, sentinelRef } = useHubInfiniteScroll(fetchMore, scannedCount, {
+ isFetching: isLoading || isLoadingMore,
+ resultCount: hfResults.length,
+ resetKey: debouncedQuery,
+ });
useEffect(() => {
ensureModelDefaultsLoaded();
diff --git a/studio/frontend/src/features/recipe-studio/components/shared/hf-dataset-combobox.tsx b/studio/frontend/src/features/recipe-studio/components/shared/hf-dataset-combobox.tsx
index b02033320ba..c8ae67ad9bc 100644
--- a/studio/frontend/src/features/recipe-studio/components/shared/hf-dataset-combobox.tsx
+++ b/studio/frontend/src/features/recipe-studio/components/shared/hf-dataset-combobox.tsx
@@ -10,7 +10,8 @@ import {
ComboboxList,
} from "@/components/ui/combobox";
import { Spinner } from "@/components/ui/spinner";
-import { useDebouncedValue, useHfDatasetSearch } from "@/hooks";
+import { useDebouncedValue } from "@/hooks";
+import { useHubDatasetSearch } from "@/features/hub/hooks/use-hub-dataset-search";
import { type ReactElement, useEffect, useMemo, useRef, useState } from "react";
type HfDatasetComboboxProps = {
@@ -39,7 +40,7 @@ export function HfDatasetCombobox({
setInputValue(value);
}, [value]);
- const { results, isLoading, error } = useHfDatasetSearch(debouncedQuery, {
+ const { results, isLoading, error } = useHubDatasetSearch(debouncedQuery, {
accessToken,
});
diff --git a/studio/frontend/src/features/settings/components/settings-row.tsx b/studio/frontend/src/features/settings/components/settings-row.tsx
index afb535bc648..3c049d2f998 100644
--- a/studio/frontend/src/features/settings/components/settings-row.tsx
+++ b/studio/frontend/src/features/settings/components/settings-row.tsx
@@ -11,23 +11,32 @@ export function SettingsRow({
children,
destructive,
className,
+ alignTop,
}: {
label: string;
- description?: string;
+ description?: ReactNode;
icon?: ReactNode;
children?: ReactNode;
destructive?: boolean;
className?: string;
+ /** Top-align the control instead of centering it, for tall descriptions. */
+ alignTop?: boolean;
}) {
return (
<div
className={cn(
- "flex items-center justify-between gap-6 py-3",
+ "flex justify-between gap-6 py-3",
+ alignTop ? "items-start" : "items-center",
destructive && "border-t border-border/60 mt-2 pt-4",
className,
)}
>
- <div className="flex min-w-0 items-center gap-2.5">
+ <div
+ className={cn(
+ "flex min-w-0 gap-2.5",
+ alignTop ? "items-start" : "items-center",
+ )}
+ >
{icon ? (
<span className="flex shrink-0 items-center text-foreground">
{icon}
@@ -42,7 +51,18 @@ export function SettingsRow({
) : null}
</div>
</div>
- {children ? <div className="flex shrink-0 items-center">{children}</div> : null}
+ {children ? (
+ <div
+ className={cn(
+ "flex shrink-0",
+ // Drop the control past the label row so it lines up with the first
+ // description line instead of the label.
+ alignTop ? "items-start pt-[21px]" : "items-center",
+ )}
+ >
+ {children}
+ </div>
+ ) : null}
</div>
);
}
diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsx
index 4255dc1c930..0ee0dd0a7cb 100644
--- a/studio/frontend/src/features/settings/settings-dialog.tsx
+++ b/studio/frontend/src/features/settings/settings-dialog.tsx
@@ -7,7 +7,7 @@ import {
DialogDescription,
DialogTitle,
} from "@/components/ui/dialog";
-import { useT, type TranslationKey } from "@/i18n";
+import { type TranslationKey, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import {
Cancel01Icon,
@@ -23,8 +23,8 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { motion, useReducedMotion } from "motion/react";
import { useEffect, useRef } from "react";
import {
- useSettingsDialogStore,
type SettingsTab,
+ useSettingsDialogStore,
} from "./stores/settings-dialog-store";
import { AboutTab } from "./tabs/about-tab";
import { ApiKeysTab } from "./tabs/api-keys-tab";
@@ -49,12 +49,16 @@ const TABS: TabDef[] = [
labelKey: "settings.tabs.appearance",
icon: PaintBrush02Icon,
},
- { id: "chat", labelKey: "settings.tabs.chat", icon: Message01Icon },
+ {
+ id: "chat",
+ labelKey: "settings.tabs.chat",
+ icon: Message01Icon,
+ badgeKey: "common.new",
+ },
{
id: "api-keys",
labelKey: "settings.tabs.apiKeys",
icon: Globe02Icon,
- badgeKey: "common.new",
},
{
id: "connections",
@@ -134,7 +138,9 @@ export function SettingsDialog() {
"max-sm:h-dvh max-sm:w-dvw max-sm:!max-w-none max-sm:rounded-none",
)}
>
- <DialogTitle className="sr-only">{t("settings.dialog.title")}</DialogTitle>
+ <DialogTitle className="sr-only">
+ {t("settings.dialog.title")}
+ </DialogTitle>
<DialogDescription className="sr-only">
{t("settings.dialog.description")}
</DialogDescription>
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index 262b23e67d9..b26b09e022b 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -2,8 +2,6 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { Button } from "@/components/ui/button";
-import { Switch } from "@/components/ui/switch";
-import { toast } from "@/lib/toast";
import {
Dialog,
DialogContent,
@@ -22,19 +20,21 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { Switch } from "@/components/ui/switch";
import {
EXPORT_FORMATS_LIST,
+ type PlusMenuItemId,
bulkExportConversationsByScope,
clearAllChats,
countAllChats,
downloadChatExport,
importConversationsFromFile,
- useChatRuntimeStore,
useChatPreferencesStore,
- type PlusMenuItemId,
+ useChatRuntimeStore,
usePlusMenuPrefsStore,
} from "@/features/chat";
import { useT } from "@/i18n";
+import { toast } from "@/lib/toast";
import {
Bookmark02Icon,
Delete02Icon,
@@ -43,6 +43,7 @@ import {
Folder01Icon,
McpServerIcon,
PencilRulerIcon,
+ Settings02Icon,
ShieldBanIcon,
Upload01Icon,
} from "@hugeicons/core-free-icons";
@@ -50,99 +51,102 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { Columns2Icon, PlusIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
+import { ArchivedChatsDialog } from "../components/archived-chats-dialog";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
-import { ArchivedChatsDialog } from "../components/archived-chats-dialog";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
// Adjustable "+" menu items shown in settings, in display order. Icons mirror
// the ones used in the composer + menu itself.
const PLUS_MENU_ICON_CLASS = "size-[18px]";
-const PLUS_MENU_SETTINGS: { id: PlusMenuItemId; label: string; icon: ReactNode }[] =
- [
- {
- id: "chatWithFiles",
- label: "Chat with Files",
- icon: (
- <HugeiconsIcon
- icon={FileDatabaseIcon}
- strokeWidth={2}
- className={PLUS_MENU_ICON_CLASS}
- />
- ),
- },
- {
- id: "mcp",
- label: "MCP",
- icon: (
- <HugeiconsIcon
- icon={McpServerIcon}
- strokeWidth={2}
- className={PLUS_MENU_ICON_CLASS}
- />
- ),
- },
- {
- id: "savedPrompts",
- label: "Saved prompts",
- icon: (
- <HugeiconsIcon
- icon={Bookmark02Icon}
- strokeWidth={2}
- className={PLUS_MENU_ICON_CLASS}
- />
- ),
- },
- {
- id: "compareChat",
- label: "Compare chat",
- icon: <Columns2Icon className={PLUS_MENU_ICON_CLASS} />,
- },
- {
- id: "exportChat",
- label: "Export chat",
- icon: (
- <HugeiconsIcon
- icon={Download01Icon}
- strokeWidth={2}
- className={PLUS_MENU_ICON_CLASS}
- />
- ),
- },
- {
- id: "canvas",
- label: "Canvas",
- icon: (
- <HugeiconsIcon
- icon={PencilRulerIcon}
- strokeWidth={2}
- className={PLUS_MENU_ICON_CLASS}
- />
- ),
- },
- {
- id: "projects",
- label: "Projects",
- icon: (
- <HugeiconsIcon
- icon={Folder01Icon}
- strokeWidth={2}
- className={PLUS_MENU_ICON_CLASS}
- />
- ),
- },
- {
- id: "bypassPermissions",
- label: "Bypass permissions",
- icon: (
- <HugeiconsIcon
- icon={ShieldBanIcon}
- strokeWidth={2}
- className={PLUS_MENU_ICON_CLASS}
- />
- ),
- },
- ];
+const PLUS_MENU_SETTINGS: {
+ id: PlusMenuItemId;
+ label: string;
+ icon: ReactNode;
+}[] = [
+ {
+ id: "chatWithFiles",
+ label: "Chat with Files (RAG)",
+ icon: (
+ <HugeiconsIcon
+ icon={FileDatabaseIcon}
+ strokeWidth={2}
+ className={PLUS_MENU_ICON_CLASS}
+ />
+ ),
+ },
+ {
+ id: "mcp",
+ label: "MCP",
+ icon: (
+ <HugeiconsIcon
+ icon={McpServerIcon}
+ strokeWidth={2}
+ className={PLUS_MENU_ICON_CLASS}
+ />
+ ),
+ },
+ {
+ id: "savedPrompts",
+ label: "Saved prompts",
+ icon: (
+ <HugeiconsIcon
+ icon={Bookmark02Icon}
+ strokeWidth={2}
+ className={PLUS_MENU_ICON_CLASS}
+ />
+ ),
+ },
+ {
+ id: "compareChat",
+ label: "Compare chat",
+ icon: <Columns2Icon className={PLUS_MENU_ICON_CLASS} />,
+ },
+ {
+ id: "exportChat",
+ label: "Export chat",
+ icon: (
+ <HugeiconsIcon
+ icon={Download01Icon}
+ strokeWidth={2}
+ className={PLUS_MENU_ICON_CLASS}
+ />
+ ),
+ },
+ {
+ id: "canvas",
+ label: "Canvas",
+ icon: (
+ <HugeiconsIcon
+ icon={PencilRulerIcon}
+ strokeWidth={2}
+ className={PLUS_MENU_ICON_CLASS}
+ />
+ ),
+ },
+ {
+ id: "projects",
+ label: "Projects",
+ icon: (
+ <HugeiconsIcon
+ icon={Folder01Icon}
+ strokeWidth={2}
+ className={PLUS_MENU_ICON_CLASS}
+ />
+ ),
+ },
+ {
+ id: "bypassPermissions",
+ label: "Bypass permissions",
+ icon: (
+ <HugeiconsIcon
+ icon={ShieldBanIcon}
+ strokeWidth={2}
+ className={PLUS_MENU_ICON_CLASS}
+ />
+ ),
+ },
+];
export function ChatTab() {
const t = useT();
@@ -181,6 +185,22 @@ export function ChatTab() {
const hydratePersistedSettings = useChatRuntimeStore(
(state) => state.hydratePersistedSettings,
);
+ const loadOnSelection = useChatRuntimeStore((state) => state.loadOnSelection);
+ const setLoadOnSelection = useChatRuntimeStore(
+ (state) => state.setLoadOnSelection,
+ );
+ const expandQuantizations = useChatRuntimeStore(
+ (state) => state.expandQuantizations,
+ );
+ const setExpandQuantizations = useChatRuntimeStore(
+ (state) => state.setExpandQuantizations,
+ );
+ const showAllQuantizations = useChatRuntimeStore(
+ (state) => state.showAllQuantizations,
+ );
+ const setShowAllQuantizations = useChatRuntimeStore(
+ (state) => state.setShowAllQuantizations,
+ );
const confirmDeleteChats = useChatPreferencesStore(
(state) => state.confirmDeleteChats,
);
@@ -295,16 +315,83 @@ export function ChatTab() {
</p>
</header>
+ <SettingsSection title="Select model settings">
+ <SettingsRow
+ label="Load on selection"
+ alignTop={true}
+ description={
+ <span>
+ On: Unsloth auto-picks the best settings and loads it.
+ <br />
+ Off: opens Run settings to customize, then load.
+ <br />
+ The gear always opens Run settings:{" "}
+ <span className="ml-2 inline-flex items-center gap-3 align-middle">
+ <span className="font-mono text-xs text-foreground">
+ Q4_K_M
+ </span>
+ <span className="text-[9px] font-medium text-green-400">
+ downloaded
+ </span>
+ <span className="text-[10px] text-muted-foreground">16 GB</span>
+ <span className="inline-flex size-4 items-center justify-center rounded bg-black/[0.06] dark:bg-white/[0.08]">
+ <HugeiconsIcon
+ icon={Settings02Icon}
+ strokeWidth={1.75}
+ className="size-2.5 text-muted-foreground/80"
+ />
+ </span>
+ </span>
+ </span>
+ }
+ >
+ <Switch
+ checked={loadOnSelection}
+ onCheckedChange={setLoadOnSelection}
+ />
+ </SettingsRow>
+ <SettingsRow
+ label="Expand quantizations"
+ description={
+ <span>
+ On: On Device GGUF models show their quantizations right away.
+ <br />
+ Off: click a model to view its quantizations.
+ </span>
+ }
+ >
+ <Switch
+ checked={expandQuantizations}
+ onCheckedChange={setExpandQuantizations}
+ />
+ </SettingsRow>
+ <SettingsRow
+ label="Show all quantizations"
+ description={
+ <span>
+ On: list every On Device quantization, including not downloaded.
+ <br />
+ Off: show only downloaded quantizations.
+ </span>
+ }
+ >
+ <Switch
+ checked={showAllQuantizations}
+ onCheckedChange={setShowAllQuantizations}
+ />
+ </SettingsRow>
+ </SettingsSection>
+
<SettingsSection
title="Chat menu"
description={
<>
- Choose which items are pinned in chat's{" "}
+ Pin items to chat's{" "}
<PlusIcon
aria-label="+"
className="inline size-3.5 align-[-2px] stroke-[2px]"
/>{" "}
- side menu. Unpinned items move into “More”.
+ side menu. Others move into “More”.
</>
}
>
@@ -477,7 +564,7 @@ export function ChatTab() {
</SettingsRow>
<SettingsRow
- destructive
+ destructive={true}
// divide-y already draws the row separator; drop the extra border.
className="border-t-0 mt-0 pt-3"
label={t("settings.chat.clearAllChats")}
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index 0ecd6af189e..975eeb69f4f 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -24,25 +24,25 @@ import {
setShowLlamaUpdateBanner,
useShowLlamaUpdateBanner,
} from "@/hooks/use-llama-update-pref";
+import { LOCALE_STORAGE_KEY, useT } from "@/i18n";
+import { useNavigate, useRouterState } from "@tanstack/react-router";
+import { Eye, EyeOff } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
import {
+ type HelperPrecacheSettings,
loadHelperPrecacheSettings,
updateHelperPrecacheSettings,
- type HelperPrecacheSettings,
} from "../api/helper-precache";
import {
DEFAULT_UPLOAD_LIMIT_MB,
+ type UploadLimitSettings,
loadUploadLimitSettings,
updateUploadLimitSettings,
- type UploadLimitSettings,
} from "../api/upload-limit";
-import { useSettingsDialogStore } from "../stores/settings-dialog-store";
-import { LOCALE_STORAGE_KEY, useT } from "@/i18n";
-import { useNavigate, useRouterState } from "@tanstack/react-router";
-import { useEffect, useRef, useState } from "react";
-import { Eye, EyeOff } from "lucide-react";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
import { StudioVersionSection } from "../components/studio-version-section";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
// Keys cleared by "Reset all local preferences".
// NEVER include auth/session keys here — clearing them would log the user out
@@ -66,6 +66,11 @@ const PREFS_KEYS: string[] = [
"unsloth_chat_inference_params",
"unsloth_chat_collapsible_state",
"unsloth_chat_preferences",
+ "unsloth_load_settings",
+ // Model selector settings ("Select model settings" group)
+ "unsloth_chat_load_on_selection",
+ "unsloth_chat_expand_quantizations",
+ "unsloth_chat_show_all_quantizations",
// Chat presets
"unsloth_chat_custom_presets",
"unsloth_chat_active_preset",
@@ -108,7 +113,7 @@ export function GeneralTab() {
pathname: s.location.pathname,
search:
"searchStr" in s.location
- ? (s.location as { searchStr?: string }).searchStr ?? ""
+ ? ((s.location as { searchStr?: string }).searchStr ?? "")
: typeof window !== "undefined"
? window.location.search
: "",
@@ -176,7 +181,9 @@ export function GeneralTab() {
.catch((error) => {
if (cancelled) return;
setUploadLimitError(
- error instanceof Error ? error.message : "Failed to load upload limit.",
+ error instanceof Error
+ ? error.message
+ : "Failed to load upload limit.",
);
});
return () => {
@@ -324,7 +331,11 @@ export function GeneralTab() {
}
tabIndex={-1}
>
- {showToken ? <EyeOff className="size-3.5" /> : <Eye className="size-3.5" />}
+ {showToken ? (
+ <EyeOff className="size-3.5" />
+ ) : (
+ <Eye className="size-3.5" />
+ )}
</button>
</div>
</SettingsRow>
@@ -366,7 +377,19 @@ export function GeneralTab() {
</SettingsRow>
</SettingsSection>
- <StudioVersionSection />
+ <SettingsSection title={t("settings.general.notifications.sectionTitle")}>
+ <SettingsRow
+ label={t("settings.general.notifications.showLlamaUpdates")}
+ description={t(
+ "settings.general.notifications.showLlamaUpdatesDescription",
+ )}
+ >
+ <Switch
+ checked={showLlamaUpdates}
+ onCheckedChange={setShowLlamaUpdateBanner}
+ />
+ </SettingsRow>
+ </SettingsSection>
<SettingsSection title={t("settings.general.helperLlm.sectionTitle")}>
<SettingsRow
@@ -398,20 +421,6 @@ export function GeneralTab() {
</SettingsRow>
</SettingsSection>
- <SettingsSection title={t("settings.general.notifications.sectionTitle")}>
- <SettingsRow
- label={t("settings.general.notifications.showLlamaUpdates")}
- description={t(
- "settings.general.notifications.showLlamaUpdatesDescription",
- )}
- >
- <Switch
- checked={showLlamaUpdates}
- onCheckedChange={setShowLlamaUpdateBanner}
- />
- </SettingsRow>
- </SettingsSection>
-
<SettingsSection title={t("settings.general.uploads.sectionTitle")}>
<SettingsRow
label={t("settings.general.uploads.maxUploadSize")}
@@ -444,9 +453,7 @@ export function GeneralTab() {
disabled={isSavingUploadLimit}
onClick={() => void saveUploadLimit()}
>
- {isSavingUploadLimit
- ? t("common.saving")
- : t("common.save")}
+ {isSavingUploadLimit ? t("common.saving") : t("common.save")}
</Button>
</div>
{uploadLimitError ? (
@@ -479,9 +486,11 @@ export function GeneralTab() {
</SettingsSection>
)}
- <SettingsSection title={t("settings.general.resetPreferences.sectionTitle")}>
+ <SettingsSection
+ title={t("settings.general.resetPreferences.sectionTitle")}
+ >
<SettingsRow
- destructive
+ destructive={true}
label={t("settings.general.resetPreferences.label")}
description={t("settings.general.resetPreferences.description")}
>
diff --git a/studio/frontend/src/features/studio/sections/dataset-section.tsx b/studio/frontend/src/features/studio/sections/dataset-section.tsx
index 38dbc8742b8..32f7990d075 100644
--- a/studio/frontend/src/features/studio/sections/dataset-section.tsx
+++ b/studio/frontend/src/features/studio/sections/dataset-section.tsx
@@ -33,12 +33,9 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
-import {
- useDebouncedValue,
- useHfDatasetSearch,
- useHfTokenValidation,
- useInfiniteScroll,
-} from "@/hooks";
+import { useDebouncedValue, useHfTokenValidation } from "@/hooks";
+import { useHubDatasetSearch } from "@/features/hub/hooks/use-hub-dataset-search";
+import { useHubInfiniteScroll } from "@/features/hub/hooks/use-hub-infinite-scroll";
import {
HfDatasetSubsetSplitSelectors,
listLocalDatasets,
@@ -311,8 +308,9 @@ export function DatasetSection() {
isLoading,
isLoadingMore,
fetchMore,
+ scannedCount,
error: hfSearchError,
- } = useHfDatasetSearch(pickerTab === "huggingface" ? debouncedQuery : "", {
+ } = useHubDatasetSearch(pickerTab === "huggingface" ? debouncedQuery : "", {
modelType: effectiveModelType,
accessToken: hfToken || undefined,
enabled: pickerTab === "huggingface",
@@ -421,10 +419,12 @@ export function DatasetSection() {
const comboboxAnchorRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const evalFileInputRef = useRef<HTMLInputElement>(null);
- const { scrollRef, sentinelRef } = useInfiniteScroll(
- fetchMore,
- hfResults.length,
- );
+ const { scrollRef, sentinelRef } = useHubInfiniteScroll(fetchMore, scannedCount, {
+ enabled: pickerTab === "huggingface",
+ isFetching: isLoading || isLoadingMore,
+ resultCount: hfResults.length,
+ resetKey: debouncedQuery,
+ });
const [isUploading, setIsUploading] = useState(false);
const [isDatasetDragOver, setIsDatasetDragOver] = useState(false);
diff --git a/studio/frontend/src/features/studio/sections/model-section.tsx b/studio/frontend/src/features/studio/sections/model-section.tsx
index e37620cc0a0..c8f36b397cc 100644
--- a/studio/frontend/src/features/studio/sections/model-section.tsx
+++ b/studio/frontend/src/features/studio/sections/model-section.tsx
@@ -41,10 +41,10 @@ import {
import {
useDebouncedValue,
useGpuInfo,
- useHfModelSearch,
useHfTokenValidation,
- useInfiniteScroll,
} from "@/hooks";
+import { useHubModelSearch } from "@/features/hub/hooks/use-hub-model-search";
+import { useHubInfiniteScroll } from "@/features/hub/hooks/use-hub-infinite-scroll";
import { extractParamLabel } from "@/lib/model-size";
import { formatCompact } from "@/lib/utils";
import {
@@ -168,12 +168,16 @@ export function ModelSection() {
isLoading,
isLoadingMore,
fetchMore,
+ scannedCount,
error: hfSearchError,
- } = useHfModelSearch(debouncedQuery, {
+ } = useHubModelSearch(debouncedQuery, {
task,
accessToken: debouncedHfToken || undefined,
excludeGguf: true,
priorityIds: PRIORITY_TRAINING_MODELS,
+ // Curated unsloth listing by default, but a typed query searches the whole
+ // Hub (unsloth floated first) so non-unsloth base models stay selectable.
+ ownerScope: debouncedQuery.trim() ? "all" : "unsloth",
});
const { error: tokenValidationError, isChecking: isCheckingToken } =
@@ -255,10 +259,11 @@ export function ModelSection() {
const comboboxAnchorRef = useRef<HTMLDivElement>(null);
const localComboboxAnchorRef = useRef<HTMLDivElement>(null);
- const { scrollRef, sentinelRef } = useInfiniteScroll(
- fetchMore,
- hfResults.length,
- );
+ const { scrollRef, sentinelRef } = useHubInfiniteScroll(fetchMore, scannedCount, {
+ isFetching: isLoading || isLoadingMore,
+ resultCount: hfResults.length,
+ resetKey: debouncedQuery,
+ });
return (
<div data-tour="studio-model" className="w-full min-w-0">
diff --git a/studio/frontend/src/hooks/index.ts b/studio/frontend/src/hooks/index.ts
index cfbd8e51156..d5c923d57d5 100644
--- a/studio/frontend/src/hooks/index.ts
+++ b/studio/frontend/src/hooks/index.ts
@@ -5,11 +5,7 @@ export { useDebouncedValue } from "./use-debounced-value";
export { useGpuInfo } from "./use-gpu-info";
export { useGpuUtilization } from "./use-gpu-utilization";
export { useHardwareInfo } from "./use-hardware-info";
-export { useHfModelSearch } from "./use-hf-model-search";
-export { useRecommendedModelVram } from "./use-recommended-model-vram";
-export { useHfDatasetSearch } from "./use-hf-dataset-search";
export { useHfDatasetSplits } from "./use-hf-dataset-splits";
export { useHfTokenValidation } from "./use-hf-token-validation";
-export { useInfiniteScroll } from "./use-infinite-scroll";
export { useTauriBackend } from "./use-tauri-backend";
export { useCollapseScrollLock } from "./use-collapse-scroll-lock";
diff --git a/studio/frontend/src/hooks/use-gpu-info.ts b/studio/frontend/src/hooks/use-gpu-info.ts
index c7a2852067e..eb4d89abd8b 100644
--- a/studio/frontend/src/hooks/use-gpu-info.ts
+++ b/studio/frontend/src/hooks/use-gpu-info.ts
@@ -31,15 +31,22 @@ async function fetchGpuOnce(): Promise<GpuInfo> {
const res = await authFetch("/api/system");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
+ const ramAvailableGb = data?.memory?.available_gb ?? 0;
const gpuData = data?.gpu;
- if (!gpuData?.available || !gpuData.devices?.length) return DEFAULT_GPU;
+ if (!gpuData?.available || !gpuData.devices?.length) {
+ // No discrete GPU (e.g. Mac): still surface system RAM so memory math
+ // (unified memory) has a budget to work with.
+ const info: GpuInfo = { ...DEFAULT_GPU, systemRamAvailableGb: ramAvailableGb };
+ cachedGpu = info;
+ return info;
+ }
const devices = gpuData.devices as Array<{ name?: string; memory_total_gb?: number }>;
const totalGb = devices.reduce((sum, d) => sum + (d.memory_total_gb ?? 0), 0);
const info: GpuInfo = {
available: true,
name: devices[0]?.name ?? "Unknown",
memoryTotalGb: totalGb,
- systemRamAvailableGb: data?.memory?.available_gb ?? 0,
+ systemRamAvailableGb: ramAvailableGb,
};
cachedGpu = info;
return info;
diff --git a/studio/frontend/src/hooks/use-hf-dataset-search.ts b/studio/frontend/src/hooks/use-hf-dataset-search.ts
deleted file mode 100644
index f8863f328fc..00000000000
--- a/studio/frontend/src/hooks/use-hf-dataset-search.ts
+++ /dev/null
@@ -1,398 +0,0 @@
-// 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 { listDatasets } from "@huggingface/hub";
-import { useCallback, useMemo } from "react";
-import type { ModelType } from "@/types/training";
-import { useHfPaginatedSearch } from "./use-hf-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,
- likes: ds.likes,
- totalExamples: extractTotalExamples(card),
- sizeCategory: card?.size_categories?.[0],
- taskCategories,
- plainTags,
- };
-}
-
-function withTrendingSort(
- input: Parameters<typeof fetch>[0],
- init?: Parameters<typeof fetch>[1],
-): ReturnType<typeof fetch> {
- 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", "trendingScore");
- }
- if (!url.searchParams.has("direction")) {
- url.searchParams.set("direction", "-1");
- }
-
- return fetch(url, init);
-}
-
-type DatasetRelevance = "incompatible" | "neutral" | "boosted";
-
-const BOOSTED_TASK_CATEGORIES: Record<ModelType, 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<ModelType, 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<ModelType, 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: ModelType,
-): 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. Adapts them to the shared result shape used
- // by downstream combobox/ranking code without extra HF requests.
- return {
- id,
- downloads: 0,
- likes: 0,
- taskCategories: [],
- plainTags: [],
- };
-}
-
-export function useHfDatasetSearch(
- query: string,
- options?: { modelType?: ModelType | null; accessToken?: string; enabled?: boolean },
-) {
- const { modelType, accessToken, enabled = true } = options ?? {};
- const hasQuery = query.trim().length > 0;
- const useCuratedOnly = !hasQuery && !!modelType;
- const createIter = useCallback(
- () => {
- // Use curated defaults for typed model flows only.
- if (useCuratedOnly) {
- return (async function* empty() {})() as AsyncGenerator<unknown>;
- }
- return listDatasets({
- search: hasQuery ? { query } : {},
- additionalFields: ["cardData", "tags"],
- fetch: withTrendingSort,
- ...(accessToken ? { credentials: { accessToken } } : {}),
- }) as AsyncGenerator<unknown>;
- },
- [useCuratedOnly, hasQuery, query, accessToken],
- );
-
- const search = useHfPaginatedSearch(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/hooks/use-hf-model-search.ts b/studio/frontend/src/hooks/use-hf-model-search.ts
deleted file mode 100644
index ba52b654b8b..00000000000
--- a/studio/frontend/src/hooks/use-hf-model-search.ts
+++ /dev/null
@@ -1,348 +0,0 @@
-// 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 { useCallback, useMemo } from "react";
-import { useHfPaginatedSearch } from "./use-hf-paginated-search";
-import { usePlatformStore } from "@/config/env";
-
-export interface HfModelResult {
- id: string;
- downloads: number;
- likes: number;
- totalParams?: number;
- estimatedSizeBytes?: number;
- isGguf: boolean;
-}
-
-/** Tags to exclude on GPU (CUDA/ROCm) — MLX models won't load on GPU. */
-const EXCLUDED_TAGS_GPU = new Set([
- "gptq",
- "awq",
- "exl2",
- "mlx",
- "onnx",
- "openvino",
- "coreml",
- "tflite",
- "ctranslate2",
-]);
-
-/** Tags to exclude on MLX (Mac) — GPU-only quant formats won't load on MLX. */
-const EXCLUDED_TAGS_MLX = new Set([
- "gptq",
- "awq",
- "exl2",
- "onnx",
- "openvino",
- "coreml",
- "tflite",
- "ctranslate2",
-]);
-
-// Embedding / sentence-transformer models ship onnx/openvino as extra
-// export formats, so the tag check above must not exclude them.
-const EMBEDDING_TAGS = new Set([
- "sentence-transformers",
- "feature-extraction",
-]);
-
-function withPopularitySort(
- input: Parameters<typeof fetch>[0],
- init?: Parameters<typeof fetch>[1],
-): ReturnType<typeof fetch> {
- 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", "downloads");
- }
- if (!url.searchParams.has("direction")) {
- url.searchParams.set("direction", "-1");
- }
-
- return fetch(url, init);
-}
-
-/** Bytes per parameter for each dtype. */
-const DTYPE_BYTES: Record<string, number> = {
- F64: 8, F32: 4, F16: 2, BF16: 2,
- I64: 8, I32: 4, I16: 2, I8: 1, U8: 1,
- // Quantized types (4-bit)
- NF4: 0.5, FP4: 0.5, INT4: 0.5, GPTQ: 0.5,
-};
-
-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 bpp = DTYPE_BYTES[dtype.toUpperCase()] ?? 2; // default BF16
- total += count * bpp;
- }
- return total > 0 ? total : undefined;
-}
-
-function makeMapModel(excludeGguf: boolean, excludedTags: Set<string>) {
- return (raw: unknown): HfModelResult | null => {
- const m = raw as {
- name: string;
- downloads: number;
- likes: number;
- safetensors?: { total: number; parameters?: Record<string, number> };
- tags?: string[];
- };
- const isEmbedding = m.tags?.some((t) => EMBEDDING_TAGS.has(t));
- if (!isEmbedding && m.tags?.some((t) => excludedTags.has(t))) {
- return null;
- }
- const isGguf =
- Boolean(m.tags?.some((tag) => tag.toLowerCase() === "gguf")) ||
- /-GGUF(?:$|-)/i.test(m.name);
- if (excludeGguf && isGguf) {
- return null;
- }
- return {
- id: m.name,
- downloads: m.downloads,
- likes: m.likes,
- totalParams: m.safetensors?.total,
- estimatedSizeBytes: estimateSizeFromDtypes(m.safetensors?.parameters),
- isGguf,
- };
- };
-}
-
-/** Number of unsloth results to pull up-front before yielding general results. */
-const UNSLOTH_PREFETCH = 20;
-/** Fewer unsloth results before the pinned model when a publisher is searched. */
-const UNSLOTH_PINNED_PREFETCH = 4;
-/** Matches a valid "owner/repo" identifier (exactly two non-empty segments). */
-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 without
- * re-fetching. 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);
- }
-}
-
-/**
- * Creates a merged async generator that yields unsloth-owned models first,
- * then general results (with deduplication).
- */
-async function* mergedModelIterator(
- query: string,
- task?: PipelineType,
- accessToken?: string,
- pinnedId?: string,
-): AsyncGenerator<unknown> {
- const common = {
- additionalFields: ["safetensors", "tags"] as ("safetensors" | "tags")[],
- fetch: withPopularitySort,
- ...(accessToken ? { credentials: { accessToken } } : {}),
- };
-
- // Fire both iterators immediately (parallel network requests on first pull)
- const unslothIter = listModels({
- search: { query, owner: "unsloth", ...(task ? { task } : {}) },
- ...common,
- });
- const generalIter = listModels({
- search: { query, ...(task ? { task } : {}) },
- ...common,
- });
-
- // 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: ["safetensors", "tags"],
- ...(accessToken ? { credentials: { accessToken } } : {}),
- }).catch(() => null)
- : null;
-
- const limit = pinnedId ? UNSLOTH_PINNED_PREFETCH : UNSLOTH_PREFETCH;
-
- // Phase 1: pull & yield 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: yield the pinned (original publisher) model before general results
- if (pinnedId && !seen.has(pinnedId) && pinnedPromise) {
- const pinned = await pinnedPromise;
- if (pinned) {
- // Record both the raw input and HF's canonical name so phase 2 dedupe
- // works across casing (e.g. "OpenAI/..." vs HF's "openai/...").
- seen.add(pinnedId);
- const canonicalName = (pinned as { name?: string }).name;
- if (canonicalName && canonicalName !== pinnedId) {
- seen.add(canonicalName);
- }
- yield pinned;
- }
- }
-
- // Phase 2: yield 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;
- }
-}
-
-/**
- * Creates an async generator that yields priority models (fetched individually
- * via modelInfo for full metadata), then the general unsloth listing.
- */
-async function* priorityThenListingIterator(
- priorityIds: readonly string[],
- task?: PipelineType,
- accessToken?: string,
-): AsyncGenerator<unknown> {
- const common = {
- additionalFields: ["safetensors", "tags"] as ("safetensors" | "tags")[],
- fetch: withPopularitySort,
- ...(accessToken ? { credentials: { accessToken } } : {}),
- };
-
- // Phase 1: fetch priority models in parallel via modelInfo
- const seen = new Set<string>();
- const settled = await Promise.allSettled(
- priorityIds.map((id) =>
- cachedModelInfo({
- name: id,
- additionalFields: ["safetensors", "tags"],
- ...(accessToken ? { credentials: { accessToken } } : {}),
- }),
- ),
- );
- for (const result of settled) {
- if (result.status === "fulfilled") {
- const m = result.value as { name?: string; pipeline_tag?: string };
- // Skip models that don't match the task filter.
- if (task && m.pipeline_tag && m.pipeline_tag !== task) continue;
- if (m.name) seen.add(m.name);
- yield result.value;
- }
- }
-
- // Phase 2: yield general unsloth listing, skipping already-seen
- const generalIter = listModels({
- search: { owner: "unsloth", ...(task ? { task } : {}) },
- ...common,
- });
- 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 function useHfModelSearch(
- query: string,
- options?: {
- task?: PipelineType;
- accessToken?: string;
- excludeGguf?: boolean;
- priorityIds?: readonly string[];
- },
-) {
- const { task, accessToken, excludeGguf = false, priorityIds } = options ?? {};
-
- // Detect the publisher once, shared by the iterator factory and the
- // secondary sort gate (avoids duplicating the regex + logic).
- 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(
- () => {
- if (!trimmed) {
- // No query: priority models first (full metadata), then general unsloth.
- if (priorityIds && priorityIds.length > 0) {
- return priorityThenListingIterator(priorityIds, task, accessToken) as AsyncGenerator<unknown>;
- }
- return listModels({
- search: { owner: "unsloth", ...(task ? { task } : {}) },
- additionalFields: ["safetensors", "tags"],
- fetch: withPopularitySort,
- ...(accessToken ? { credentials: { accessToken } } : {}),
- }) as AsyncGenerator<unknown>;
- }
- // Typed query: disable the task filter so explicitly searched models
- // appear even with wrong/missing HF task metadata. For a valid
- // "owner/repo" query, strip the org prefix so unsloth variants
- // surface, then pin the original publisher model after a small batch.
- // unsloth-owned queries are left as-is for the full prefetch + sort.
- return mergedModelIterator(searchQuery, undefined, accessToken, pinnedId) as AsyncGenerator<unknown>;
- },
- [trimmed, searchQuery, pinnedId, task, accessToken, priorityIds],
- );
-
- const deviceType = usePlatformStore((s) => s.deviceType);
- const excludedTags = deviceType === "mac" ? EXCLUDED_TAGS_MLX : EXCLUDED_TAGS_GPU;
- const mapModel = useMemo(() => makeMapModel(excludeGguf, excludedTags), [excludeGguf, excludedTags]);
- const search = useHfPaginatedSearch(createIter, mapModel);
-
- // Secondary sort: unsloth models always float to the top. Skip for a
- // specific non-unsloth publisher query (e.g. "openai/gpt-oss-20b") --
- // the iterator already handles pinned ordering there.
- const results = useMemo(
- () =>
- isPublisherQuery
- ? search.results
- : [...search.results].sort((a, b) => {
- const aFirst = a.id.startsWith("unsloth/") ? 0 : 1;
- const bFirst = b.id.startsWith("unsloth/") ? 0 : 1;
- return aFirst - bFirst;
- }),
- [search.results, isPublisherQuery],
- );
-
- return { ...search, results };
-}
diff --git a/studio/frontend/src/hooks/use-hf-paginated-search.ts b/studio/frontend/src/hooks/use-hf-paginated-search.ts
deleted file mode 100644
index a2ffbad5418..00000000000
--- a/studio/frontend/src/hooks/use-hf-paginated-search.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-// 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[];
- isLoading: boolean;
- isLoadingMore: boolean;
- hasMore: boolean;
- error: string | null;
-}
-
-const INITIAL: HfPaginatedState<never> = {
- results: [],
- isLoading: false,
- isLoadingMore: false,
- hasMore: false,
- error: null,
-};
-const BATCH = 20;
-
-async function pullBatch<T>(
- iter: AsyncGenerator<unknown>,
- mapItem: (raw: unknown) => T | null,
- size: number,
-) {
- const items: T[] = [];
- while (items.length < size) {
- const result = await iter.next();
- if (result.done) {
- return { items, done: true };
- }
- const mapped = mapItem(result.value);
- if (mapped !== null) {
- items.push(mapped);
- }
- }
- return { items, done: false };
-}
-
-export function useHfPaginatedSearch<T>(
- createIter: () => AsyncGenerator<unknown>,
- mapItem: (raw: unknown) => T | null,
- options?: { enabled?: boolean },
-): HfPaginatedState<T> & { fetchMore: () => void } {
- const enabled = options?.enabled ?? true;
- const [state, setState] = useState<HfPaginatedState<T>>(
- INITIAL as HfPaginatedState<T>,
- );
- const stateRef = useRef(state);
- useEffect(() => {
- stateRef.current = state;
- }, [state]);
-
- const iterRef = useRef<AsyncGenerator<unknown> | null>(null);
- const versionRef = useRef(0);
-
- useEffect(() => {
- const v = ++versionRef.current;
- iterRef.current = null;
-
- if (!enabled) {
- setState(INITIAL as HfPaginatedState<T>);
- return;
- }
-
- setState({
- ...(INITIAL as HfPaginatedState<T>),
- isLoading: true,
- });
-
- const iter = createIter();
- iterRef.current = iter;
-
- pullBatch(iter, mapItem, BATCH)
- .then(({ items, done }) => {
- if (versionRef.current !== v) {
- return;
- }
- setState({
- results: items,
- isLoading: false,
- isLoadingMore: false,
- hasMore: !done,
- error: null,
- });
- })
- .catch((err) => {
- if (versionRef.current !== v) {
- return;
- }
- setState({
- results: [],
- isLoading: false,
- isLoadingMore: false,
- hasMore: false,
- error: err instanceof Error ? err.message : "Search failed",
- });
- });
- }, [createIter, mapItem, enabled]);
-
- const fetchMore = useCallback(() => {
- const iter = iterRef.current;
- const { isLoading, isLoadingMore, hasMore } = stateRef.current;
- if (!iter || isLoading || isLoadingMore || !hasMore) {
- return;
- }
-
- const v = versionRef.current;
- setState((prev) => ({ ...prev, isLoadingMore: true }));
-
- pullBatch(iter, mapItem, BATCH)
- .then(({ items, done }) => {
- if (versionRef.current !== v) {
- return;
- }
- setState((prev) => ({
- ...prev,
- results: [...prev.results, ...items],
- isLoadingMore: false,
- hasMore: !done,
- }));
- })
- .catch(() => {
- if (versionRef.current !== v) {
- return;
- }
- setState((prev) => ({ ...prev, isLoadingMore: false, hasMore: false }));
- });
- }, [mapItem]);
-
- return { ...state, fetchMore };
-}
diff --git a/studio/frontend/src/hooks/use-infinite-scroll.ts b/studio/frontend/src/hooks/use-infinite-scroll.ts
deleted file mode 100644
index db8dc334909..00000000000
--- a/studio/frontend/src/hooks/use-infinite-scroll.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-// 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, useRef } from "react";
-
-export function useInfiniteScroll(fetchMore: () => void, _itemCount: number) {
- const scrollRef = useRef<HTMLDivElement>(null);
- const sentinelRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- const el = sentinelRef.current;
- if (!el) {
- return;
- }
- const obs = new IntersectionObserver(
- ([e]) => {
- if (e.isIntersecting) {
- fetchMore();
- }
- },
- { threshold: 0, root: scrollRef.current },
- );
- obs.observe(el);
- return () => obs.disconnect();
- }, [fetchMore]);
-
- return { scrollRef, sentinelRef };
-}
diff --git a/studio/frontend/src/hooks/use-recommended-model-vram.ts b/studio/frontend/src/hooks/use-recommended-model-vram.ts
deleted file mode 100644
index 39d58fe6005..00000000000
--- a/studio/frontend/src/hooks/use-recommended-model-vram.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-// 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 { cachedModelInfo } from "@/lib/hf-cache";
-import { useEffect, useState } from "react";
-
-/**
- * Fetches Hugging Face model info (safetensors total param count) for a list of
- * model IDs. Used to show VRAM fit (FIT / TIGHT / OOM) for recommended/default
- * models in the chat model dropdown.
- */
-export function useRecommendedModelVram(ids: string[]) {
- const [paramCountById, setParamCountById] = useState<Map<string, number>>(
- new Map(),
- );
- const [isLoading, setIsLoading] = useState(false);
-
- const stableKey = [...ids].filter(Boolean).sort().join(",");
-
- useEffect(() => {
- const stableIds = stableKey ? stableKey.split(",") : [];
- if (stableIds.length === 0) {
- setParamCountById(new Map());
- setIsLoading(false);
- return;
- }
- let canceled = false;
- void (async () => {
- setIsLoading(true);
- const next = new Map<string, number>();
- await Promise.all(
- stableIds.map(async (id) => {
- if (canceled) {
- return;
- }
- try {
- const info = await cachedModelInfo({
- name: id,
- additionalFields: ["safetensors"],
- });
- const total = info.safetensors?.total;
- if (typeof total === "number" && total > 0) {
- next.set(id, total);
- }
- } catch {
- // Model not on HF or no safetensors; skip
- }
- }),
- );
- if (!canceled) {
- // Merge with previous state so VRAM badges for already-visible models
- // persist while newly-visible models are still loading.
- setParamCountById((prev) => new Map([...prev, ...next]));
- setIsLoading(false);
- }
- })();
- return () => {
- canceled = true;
- };
- }, [stableKey]);
-
- return { paramCountById, isLoading };
-}
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 68590ae7ae0..214767bec0c 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -123,7 +123,7 @@ export const en = {
sectionTitle: "Notifications",
showLlamaUpdates: "llama.cpp update notifications",
showLlamaUpdatesDescription:
- "Notify when a newer llama.cpp build is available. Turn off if you only train.",
+ "Notify when a newer llama.cpp build is available to run new models. Turn off if you only train.",
},
gettingStarted: "Getting started",
startOnboarding: "Start onboarding",
@@ -133,8 +133,7 @@ export const en = {
uploads: {
sectionTitle: "Uploads",
maxUploadSize: "Training dataset upload cap",
- maxUploadSizeDescription:
- "Default is {defaultSize} MB.",
+ maxUploadSizeDescription: "Default is {defaultSize} MB.",
},
storage: {
sectionTitle: "Storage",
@@ -222,8 +221,7 @@ export const en = {
},
data: "Data",
exportHistory: "Export chat history",
- exportHistoryDescription:
- "Download all chats and messages as JSON.",
+ exportHistoryDescription: "Download all chats and messages as JSON.",
exportAction: "Export",
exportingAction: "Exporting...",
exportConversations: "Export Recents and Projects",
@@ -283,8 +281,7 @@ export const en = {
},
apiKeys: {
title: "API",
- description:
- "Access Unsloth via the OpenAI-compatible API.",
+ description: "Access Unsloth via the OpenAI-compatible API.",
readDocs: "Read the API docs",
noAccess: "No API access yet.",
newBadge: "New",
@@ -340,8 +337,7 @@ export const en = {
},
about: {
title: "About",
- description:
- "Docs, release notes, feedback, and build info.",
+ description: "Docs, release notes, feedback, and build info.",
studioVersion: "Unsloth Version",
packageVersion: "Package Version",
llamaCppVersion: "llama.cpp Version",
@@ -360,8 +356,7 @@ export const en = {
sectionTitle: "License",
studioLabel: "Unsloth Studio",
studioLicense: "AGPL-3.0",
- studioDescription:
- "Open source under the GNU AGPL v3.0.",
+ studioDescription: "Open source under the GNU AGPL v3.0.",
libraryLabel: "Unsloth Core",
libraryLicense: "Apache-2.0",
libraryDescription: "Licensed under Apache 2.0.",
@@ -385,7 +380,8 @@ export const en = {
installCommandWindows: "Windows install command",
localInstallDetected:
"Local install detected. Update from your original checkout to avoid replacing it with PyPI.",
- pullThenUpdate: "Pull the latest changes, then run the local installer:",
+ pullThenUpdate:
+ "Pull the latest changes, then run the local installer:",
gitPullCommand: "git pull command",
localInstallerCommand: "local installer command",
sourceInstallDetected:
@@ -545,7 +541,8 @@ export const en = {
subset: "Subset",
s3: {
title: "S3 Configuration",
- description: "Load .parquet, .json, .jsonl, or .csv datasets from Amazon S3",
+ description:
+ "Load .parquet, .json, .jsonl, or .csv datasets from Amazon S3",
bucket: "Bucket Name",
bucketPlaceholder: "my-training-data-bucket",
region: "AWS Region",
@@ -558,12 +555,14 @@ export const en = {
secretAccessKey: "Secret Access Key",
secretAccessKeyPlaceholder: "Your AWS secret access key",
useIamRole: "Use IAM Role",
- useIamRoleTooltip: "Use IAM role credentials instead of access keys (recommended for EC2/SageMaker)",
+ useIamRoleTooltip:
+ "Use IAM role credentials instead of access keys (recommended for EC2/SageMaker)",
testConnection: "Test Connection",
connectionSuccess: "Successfully connected to S3 bucket",
connectionFailed: "Failed to connect to S3 bucket",
comingSoon: "S3 integration coming soon",
- comingSoonDescription: "S3 dataset loading requires boto3. This feature is under development.",
+ comingSoonDescription:
+ "S3 dataset loading requires boto3. This feature is under development.",
},
},
params: {
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 32733c6ad7a..b515c907db0 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -45,6 +45,38 @@
height: 40px;
background: linear-gradient(to top, var(--sidebar), transparent);
}
+ /* Model picker list: once scrolled, the top edge fades so rows dissolve as
+ they pass under the pinned search / tab bar. */
+ .model-list-scroll.is-scrolled {
+ -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 14px);
+ mask-image: linear-gradient(to bottom, transparent 0, #000 14px);
+ }
+ /* Bottom edge fades while more rows sit below the fold. */
+ .model-list-scroll.is-bottom-faded {
+ -webkit-mask-image: linear-gradient(
+ to bottom,
+ #000 calc(100% - 16px),
+ transparent
+ );
+ mask-image: linear-gradient(to bottom, #000 calc(100% - 16px), transparent);
+ }
+ /* Both edges fade when scrolled with rows above and below. */
+ .model-list-scroll.is-scrolled.is-bottom-faded {
+ -webkit-mask-image: linear-gradient(
+ to bottom,
+ transparent 0,
+ #000 14px,
+ #000 calc(100% - 16px),
+ transparent
+ );
+ mask-image: linear-gradient(
+ to bottom,
+ transparent 0,
+ #000 14px,
+ #000 calc(100% - 16px),
+ transparent
+ );
+ }
/* RAG chip strip: sidebar-style bottom fade while more chips sit below
the scroll fold (JS-toggled). */
.rag-docs-bottom-fade {
@@ -952,12 +984,14 @@
/* Model selector: drop the inset edge ring, keep the soft drop shadow.
Pin --radius to the light value so the corners match in both themes. */
.unsloth-model-selector-menu.menu-soft-surface {
- --radius: 1.1rem;
+ --radius: 1.25rem;
box-shadow: 0 var(--menu-soft-offset-y) var(--menu-soft-blur)
var(--menu-soft-spread) var(--menu-soft-shadow);
}
.dark .unsloth-model-selector-menu.menu-soft-surface {
+ /* Match the left sidebar background. */
+ background-color: var(--sidebar);
box-shadow: none;
}
diff --git a/studio/frontend/src/lib/hf-cache.ts b/studio/frontend/src/lib/hf-cache.ts
deleted file mode 100644
index eebb3ce4b2e..00000000000
--- a/studio/frontend/src/lib/hf-cache.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-// 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";
-
-/**
- * Thin caching + throttling layer over `modelInfo()` from @huggingface/hub.
- *
- * - TTL cache: avoids re-fetching the same model within CACHE_TTL_MS
- * - In-flight dedup: concurrent callers for the same key share one request
- * - Concurrency limiter: at most MAX_CONCURRENT requests in parallel;
- * the rest queue and fire as slots free up
- */
-
-const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
-// HF API allows bursts but rate-limits sustained traffic; 3 parallel requests
-// keeps startup snappy while staying well under the observed throttle threshold.
-const MAX_CONCURRENT = 3;
-
-// ── Cache & in-flight maps ──────────────────────────────────────
-
-// Extend ModelEntry with the fields we always request, so callers avoid
-// unsafe casts to access safetensors/tags.
-export type CachedResult = ModelEntry & {
- safetensors?: { total?: number; parameters?: Record<string, number> };
- tags?: string[];
-};
-
-interface CacheEntry {
- data: CachedResult;
- ts: number;
-}
-
-const cache = new Map<string, CacheEntry>();
-const inflight = new Map<string, Promise<CachedResult>>();
-
-// ── Concurrency semaphore ───────────────────────────────────────
-
-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();
- }
-}
-
-// ── Public API ──────────────────────────────────────────────────
-
-// Always request the superset of fields any consumer needs so a single
-// cache entry covers all callers (e.g. ["safetensors"] and ["safetensors","tags"]).
-const ALL_FIELDS: ("safetensors" | "tags")[] = ["safetensors", "tags"];
-
-function isStale(key: string): boolean {
- const hit = cache.get(key);
- if (!hit) return true;
- return Date.now() - hit.ts >= CACHE_TTL_MS;
-}
-
-function cacheKey(name: string, token: string | undefined): string {
- if (!token) {
- return `${name}::anon`;
- }
- // Use last 8 chars as a lightweight fingerprint so different tokens get
- // separate cache entries without storing the full secret in memory.
- return `${name}::${token.slice(-8)}`;
-}
-
-function extractToken(
- params: Parameters<typeof modelInfo>[0],
-): string | undefined {
- // The @huggingface/hub CredentialsParams union supports two forms:
- // { accessToken: "hf_..." } -- current preferred form
- // { credentials: { accessToken: "..." }} -- deprecated form
- // Check both so the cache key is correct regardless of which form callers use.
- if (params.accessToken) {
- return params.accessToken;
- }
- if (params.credentials && "accessToken" in params.credentials) {
- return params.credentials.accessToken;
- }
- return undefined;
-}
-
-/**
- * Pre-populate the cache with data from a listModels result.
- * Only writes if the key is not already fresh -- never overwrites a recent
- * modelInfo response with a listing response.
- */
-export function primeCacheFromListing(
- name: string,
- token: string | undefined,
- data: CachedResult,
-): void {
- if (!name) return;
- const key = cacheKey(name, token);
- if (!isStale(key)) return; // already fresh, don't overwrite
- 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);
-
- // 1. Return from cache if fresh
- if (!isStale(key)) {
- return cache.get(key)!.data;
- }
-
- // 2. Share in-flight request if one exists
- const flying = inflight.get(key);
- if (flying) {
- return flying;
- }
-
- // 3. New request, gated by concurrency semaphore
- 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);
- // For public models, also prime the anonymous cache slot so the VRAM
- // hook (which reads without credentials) hits cache. Skip gated/private
- // models to avoid leaking auth-scoped metadata into the anonymous slot.
- const r = result as CachedResult & { gated?: false | "auto" | "manual"; private?: boolean };
- if (token && !r.private && !r.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;
-}