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: reveal and delete for LM Studio, Ollama, custom-folder and other local models (#13507)

Michael Han090365dd273e
diff --git a/studio/backend/hub/routes/inventory.py b/studio/backend/hub/routes/inventory.py
index bf0893ec0b1..ca301f4ce1b 100644
--- a/studio/backend/hub/routes/inventory.py
+++ b/studio/backend/hub/routes/inventory.py
@@ -54,6 +54,7 @@ from hub.services.models import (
downloads,
gguf_variants,
local_inventory,
+ local_model_actions,
)
router = APIRouter()
@@ -352,6 +353,30 @@ async def orphan_companions(
)
[email protected]("/local/reveal")
+async def reveal_local_model(
+ path: str = Body(...),
+ id: Optional[str] = Body(None),
+ current_subject: str = Depends(get_current_subject),
+):
+ """Reveal an on-device model outside the HF cache. `id` picks one of several rows sharing a path."""
+ return await local_model_actions.reveal_local_model_response(
+ resolve_host_path_reference(path) or path, resolve_host_path_reference(id) or id
+ )
+
+
[email protected]("/local/delete")
+async def delete_local_model(
+ path: str = Body(...),
+ id: Optional[str] = Body(None),
+ current_subject: str = Depends(get_current_subject),
+):
+ """Delete an on-device model outside the HF cache listed by /local."""
+ return await local_model_actions.delete_local_model_response(
+ resolve_host_path_reference(path) or path, resolve_host_path_reference(id) or id
+ )
+
+
@router.delete(
"/delete-cached",
response_model = DeleteCachedModelResponse,
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
index 54ecfc0f69c..cf3d23be6cf 100644
--- a/studio/backend/hub/services/models/common.py
+++ b/studio/backend/hub/services/models/common.py
@@ -454,6 +454,9 @@ def _local_path_can_chat(path: str | Path, base_model: Optional[str] = None) ->
return _base_transformers_can_chat(base, revision, model_path) if base else None
+LOCAL_DELETE_SOURCES = frozenset({"models_dir", "lmstudio", "custom", "ollama", "hermes", "omlx"})
+
+
def _capabilities_for_format(
model_format: ModelFormat,
source: str,
@@ -470,7 +473,7 @@ def _capabilities_for_format(
return LocalModelCapabilities(
can_train = can_train,
can_chat = can_chat and is_complete,
- can_delete = source == "hf_cache",
+ can_delete = source == "hf_cache" or source in LOCAL_DELETE_SOURCES,
can_download = False,
requires_variant = requires_variant,
supports_lora = model_format in {"safetensors", "checkpoint"} and is_complete,
diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.py
index 611e07e4e07..d138e78cdfc 100644
--- a/studio/backend/hub/services/models/deletion.py
+++ b/studio/backend/hub/services/models/deletion.py
@@ -620,6 +620,13 @@ def _loaded_id_matches_repo(loaded_id: str, repo_id: str) -> bool:
loaded_path = Path(loaded_id).expanduser().resolve(strict = False)
except (OSError, RuntimeError, ValueError):
return False
+ # An on-device model outside the cache is named by its path (local_model_actions).
+ if Path(repo_id).is_absolute():
+ try:
+ held = Path(repo_id).resolve(strict = False)
+ except (OSError, RuntimeError, ValueError):
+ return False
+ return loaded_path == held or loaded_path.is_relative_to(held)
for repo_dir in iter_repo_cache_dirs("model", repo_id):
try:
resolved_repo = repo_dir.resolve(strict = False)
diff --git a/studio/backend/hub/services/models/local_model_actions.py b/studio/backend/hub/services/models/local_model_actions.py
new file mode 100644
index 00000000000..831dd946126
--- /dev/null
+++ b/studio/backend/hub/services/models/local_model_actions.py
@@ -0,0 +1,234 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Reveal and delete for on-device models outside the Hugging Face cache (LM Studio, custom
+folders, ./models, Ollama, Hermes, oMLX). Only a path the local inventory lists is accepted, so
+callers cannot probe or remove arbitrary files."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import shutil
+from pathlib import Path
+
+from fastapi import HTTPException
+from loggers import get_logger
+
+from hub.schemas.inventory import LocalModelInfo
+from hub.services.models import account_access, deletion, local_inventory, ollama
+from hub.services.models import common as model_common
+from hub.utils.host_paths import scrub_paths
+
+logger = get_logger(__name__)
+
+LOCAL_SOURCES = model_common.LOCAL_DELETE_SOURCES
+
+
+def _identity(raw: str | os.PathLike) -> str:
+ return os.path.normcase(os.path.realpath(os.path.expanduser(str(raw))))
+
+
+async def _listed_row(
+ path: str,
+ sources: frozenset[str],
+ row_id: str | None = None,
+) -> LocalModelInfo:
+ if not path or not path.strip():
+ raise HTTPException(status_code = 400, detail = "path is required")
+ wanted = _identity(path)
+ listing = await local_inventory.list_local_models_response()
+ matches = [
+ row
+ for row in listing.models
+ if row.source in sources
+ and row.path
+ and _identity(row.path) == wanted
+ # Ollama tags aliasing one blob share a path; the row id tells them apart.
+ and (row_id is None or row_id in (row.id, row.load_id))
+ ]
+ # Only distinct Ollama tags over one blob differ; mixed-format rows of one dir act alike.
+ targets = {(row.load_id or row.id) if row.source == "ollama" else None for row in matches}
+ if len(targets) > 1:
+ raise HTTPException(status_code = 400, detail = "Several models share this path; pass its id")
+ if not matches:
+ raise HTTPException(status_code = 404, detail = "Model not found on device")
+ return matches[0]
+
+
+def _hf_cache_roots() -> set[str]:
+ sources = local_inventory._local_inventory_sources()
+ roots = (sources.hf_cache_dir, sources.legacy_hf, sources.hf_default, *sources.known_hf_caches)
+ return {_identity(root) for root in roots if str(root)}
+
+
+def _protected_roots(custom_folders: list[dict]) -> set[str]:
+ sources = local_inventory._local_inventory_sources()
+ roots: list[Path | str] = [
+ Path("./models"),
+ *sources.lm_dirs,
+ *sources.ollama_dirs,
+ *sources.hermes_dirs,
+ *sources.omlx_dirs,
+ *(str(folder.get("path") or "") for folder in custom_folders),
+ ]
+ return {_identity(root) for root in roots if str(root)} | _hf_cache_roots()
+
+
+def _delete_blocking(target: Path, protected: set[str]) -> None:
+ is_link = target.is_symlink()
+ # A symlink alias is judged by where it sits, not where it points: only the alias is removed.
+ resolved = (
+ os.path.join(_identity(target.parent), os.path.normcase(target.name))
+ if is_link
+ else _identity(target)
+ )
+ # HF cache files go through delete-cached, which coordinates downloads and shared blobs.
+ for root in _hf_cache_roots():
+ if resolved.startswith(root.rstrip(os.sep) + os.sep):
+ raise HTTPException(
+ status_code = 400,
+ detail = "This model is in the Hugging Face cache; delete it from there",
+ )
+ # A scan root (or its ancestor) as a row would take the whole scanned folder.
+ for root in protected:
+ if resolved == root or root.startswith(resolved.rstrip(os.sep) + os.sep):
+ raise HTTPException(
+ status_code = 400,
+ detail = "This model is a scanned folder itself; remove the folder instead",
+ )
+ if target.is_dir() and not is_link:
+ shutil.rmtree(target)
+ elif is_link or target.exists():
+ from utils.models.model_config import colocated_split_shards
+
+ # A split GGUF row names its first shard; unlink() leaves a symlinked shard's target.
+ shards, _ = colocated_split_shards(target)
+ for shard in shards or [target]:
+ shard.unlink(missing_ok = True)
+ else:
+ raise HTTPException(status_code = 404, detail = "Model not found on device")
+ # LM Studio nests publisher/repo/: drop folders the delete left empty, up to the scan root.
+ parent = Path(os.path.realpath(target.parent))
+ while _identity(parent) not in protected and parent != parent.parent:
+ try:
+ parent.rmdir()
+ except OSError:
+ break
+ parent = parent.parent
+
+
+def _ollama_ref(row: LocalModelInfo) -> str:
+ for candidate in (row.load_id, row.id, row.path):
+ if candidate and ollama.is_ollama_manifest_ref(candidate):
+ return candidate
+ ref = ollama.ollama_manifest_ref_for_path(row.path)
+ if not ref:
+ raise HTTPException(status_code = 404, detail = "Model not found on device")
+ return ref
+
+
+def _load_state_blocks_delete(paths: tuple[str, ...]) -> str | None:
+ for path in paths:
+ if deletion._llama_cpp_blocks_delete(path, None) or (
+ deletion._inference_backend_blocks_delete(path)
+ ):
+ return "Unload the model before deleting"
+ detail = deletion._diffusion_blocks_delete(path) or deletion._video_blocks_delete(path)
+ if detail:
+ return detail
+ if _dictation_holds(path):
+ return "Unload the audio model before deleting"
+ if _primary_loading(path):
+ return "A model load is using this model; wait for it to finish"
+ return None
+
+
+def _primary_loading(path: str) -> bool:
+ # deletion._inference_backend_blocks_delete reads loading_models on kept slots only.
+ try:
+ from core.inference.orchestrator import peek_inference_backend
+ primary = peek_inference_backend()
+ except Exception as e: # noqa: BLE001 -- unavailable is not "in use", as in deletion.py
+ logger.debug("Inference backend unavailable during a local delete guard: %s", e)
+ return False
+ loading = getattr(primary, "loading_models", ()) if primary is not None else ()
+ return any(deletion._loaded_id_matches_repo(str(m), path) for m in loading or ())
+
+
+def _dictation_holds(path: str) -> bool:
+ try:
+ from core.inference.stt_audiocpp_sidecar import get_audio_cpp_stt_sidecar
+ sidecar = get_audio_cpp_stt_sidecar()
+ except Exception as e: # noqa: BLE001 -- unavailable is not "in use", as in deletion.py
+ logger.debug("Dictation sidecar unavailable during a local delete guard: %s", e)
+ return False
+ return any(
+ isinstance(name, str) and deletion._loaded_id_matches_repo(name, path)
+ for name in (sidecar.loaded_model, sidecar.loading_model)
+ )
+
+
+async def reveal_local_model_response(path: str, row_id: str | None = None) -> dict:
+ account_access.require_installation_owner()
+ from utils.paths.path_utils import reveal_in_file_manager
+
+ row = await _listed_row(path, LOCAL_SOURCES, row_id)
+ target = Path(row.path)
+ try:
+ await asyncio.to_thread(reveal_in_file_manager, target)
+ except FileNotFoundError:
+ raise HTTPException(status_code = 404, detail = "Model not found on device")
+ except Exception as e:
+ logger.error("Failed to reveal %s: %s", scrub_paths(str(target)), scrub_paths(e))
+ raise HTTPException(status_code = 500, detail = "Failed to open file manager")
+ return {"status": "ok"}
+
+
+async def delete_local_model_response(path: str, row_id: str | None = None) -> dict:
+ account_access.require_installation_owner()
+ row = await _listed_row(path, LOCAL_SOURCES, row_id)
+ target = Path(row.path)
+ ollama_ref = await asyncio.to_thread(_ollama_ref, row) if row.source == "ollama" else None
+ # A load may name the listed or resolved path, or Ollama's manifest ref or link dirs.
+ spellings = [row.path, os.path.realpath(row.path)]
+ if ollama_ref:
+ spellings.append(ollama_ref)
+ spellings.extend(str(d) for d in ollama.ollama_model_ref_link_dirs(ollama_ref))
+ spellings = tuple(dict.fromkeys(spellings))
+ try:
+ blocks = await asyncio.to_thread(_load_state_blocks_delete, spellings)
+ except Exception as e:
+ logger.warning("Load-state verification failed for a local delete: %s", scrub_paths(e))
+ raise HTTPException(status_code = 503, detail = deletion._LOAD_STATE_UNVERIFIABLE_DETAIL)
+ if blocks:
+ raise HTTPException(status_code = 400, detail = blocks)
+
+ # Not _load_custom_folders: it reads a failure as "no folders", unprotecting every scan root.
+ try:
+ custom_folders = await asyncio.to_thread(local_inventory.list_scan_folders)
+ except Exception as e: # noqa: BLE001 -- fail closed on any read error
+ logger.warning("Could not read scan folders for a local delete: %s", scrub_paths(e))
+ raise HTTPException(status_code = 503, detail = "Could not read the scanned folders; try again")
+ protected = await asyncio.to_thread(_protected_roots, custom_folders)
+ try:
+ if ollama_ref:
+ await asyncio.to_thread(ollama.delete_ollama_model_ref, ollama_ref)
+ else:
+ await asyncio.to_thread(_delete_blocking, target, protected)
+ except HTTPException:
+ raise
+ except ollama.OllamaModelBusy as e:
+ raise HTTPException(status_code = 400, detail = str(e))
+ except ValueError:
+ raise HTTPException(status_code = 404, detail = "Model not found on device")
+ except OSError as e:
+ logger.error("Failed to delete %s: %s", scrub_paths(str(target)), scrub_paths(e))
+ raise HTTPException(status_code = 500, detail = "Failed to delete the model files")
+ finally:
+ from core.inference.local_model_resolver import invalidate_index
+ from hub.services.models import cache_inventory
+
+ cache_inventory.invalidate_hf_cache_scans()
+ invalidate_index()
+ return {"status": "deleted"}
diff --git a/studio/backend/hub/services/models/ollama.py b/studio/backend/hub/services/models/ollama.py
index 67335e0a594..31ebbf2f793 100644
--- a/studio/backend/hub/services/models/ollama.py
+++ b/studio/backend/hub/services/models/ollama.py
@@ -705,3 +705,71 @@ def acquire_ollama_model_ref(ref: str) -> OllamaModelLease:
except BaseException:
lock.release()
raise
+
+
+def _manifest_digests(manifest: object) -> set[str]:
+ if not isinstance(manifest, dict):
+ return set()
+ entries = [manifest.get("config"), *(manifest.get("layers") or [])]
+ return {
+ entry["digest"]
+ for entry in entries
+ if isinstance(entry, dict) and isinstance(entry.get("digest"), str)
+ }
+
+
+def ollama_model_ref_link_dirs(ref: str) -> list[Path]:
+ """Every directory a load of *ref* may have put its ``.gguf`` links in."""
+ tag_file, ollama_dir = _validated_ollama_manifest_location(ref)
+ rel = _manifest_rel_path(tag_file, ollama_dir / "manifests")
+ if rel is None:
+ return []
+ return [root / _manifest_stem_hash(rel) for root in _ollama_links_roots(ollama_dir)]
+
+
+class OllamaModelBusy(RuntimeError):
+ """A load holds the tag's materialization lease."""
+
+
+def delete_ollama_model_ref(ref: str) -> None:
+ """``ollama rm`` for *ref*: the tag's manifest, the blobs no other tag references, and the links
+ a load made. Layers shared with another tag (one base under several tags) stay."""
+ import shutil
+
+ tag_file, ollama_dir = _validated_ollama_manifest_location(ref)
+ lock = _materialization_lock(tag_file, ollama_dir)
+ if not lock.acquire(blocking = False):
+ raise OllamaModelBusy("A model load is using this Ollama model")
+ try:
+ manifests_root = ollama_dir / "manifests"
+ link_dirs = ollama_model_ref_link_dirs(ref)
+ try:
+ manifest = json.loads(tag_file.read_text(encoding = "utf-8-sig"))
+ except (json.JSONDecodeError, OSError, UnicodeDecodeError) as e:
+ raise ValueError(f"Could not read Ollama manifest: {e}") from e
+ owned = _manifest_digests(manifest)
+ for other in manifests_root.rglob("*"):
+ if not _safe_is_file(other) or os.path.realpath(other) == str(tag_file):
+ continue
+ try:
+ owned -= _manifest_digests(json.loads(other.read_text(encoding = "utf-8-sig")))
+ except (json.JSONDecodeError, OSError, UnicodeDecodeError):
+ # An unreadable manifest might reference any blob, so keep them all.
+ owned = set()
+ break
+ tag_file.unlink()
+ parent = tag_file.parent
+ while parent != manifests_root and path_is_same_or_child(parent, manifests_root):
+ try:
+ parent.rmdir()
+ except OSError:
+ break
+ parent = parent.parent
+ for digest in owned:
+ blob = _ollama_blob_path(ollama_dir / "blobs", digest)
+ if blob is not None:
+ blob.unlink(missing_ok = True)
+ for link_dir in link_dirs:
+ shutil.rmtree(link_dir, ignore_errors = True)
+ finally:
+ lock.release()
diff --git a/studio/backend/tests/test_cache_inventory_path_boundary.py b/studio/backend/tests/test_cache_inventory_path_boundary.py
index cfa2d75f68d..216913dc6f1 100644
--- a/studio/backend/tests/test_cache_inventory_path_boundary.py
+++ b/studio/backend/tests/test_cache_inventory_path_boundary.py
@@ -534,6 +534,8 @@ _ROUTES_WITHOUT_HOST_PATHS = {
"get_active_downloads": "repo ids and byte counts",
"delete_impact": "repo ids, byte counts and blockers",
"delete_cached_model": "status, repo id and variant",
+ "reveal_local_model": "status only",
+ "delete_local_model": "status only",
}
diff --git a/studio/backend/tests/test_local_model_actions.py b/studio/backend/tests/test_local_model_actions.py
new file mode 100644
index 00000000000..fa3536ac05f
--- /dev/null
+++ b/studio/backend/tests/test_local_model_actions.py
@@ -0,0 +1,322 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Reveal and delete for LM Studio / custom-folder / ./models rows: only listed paths, never a
+scan root, never a loaded model."""
+
+import asyncio
+import json
+import os
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+from hub.schemas.inventory import LocalModelInfo, LocalModelListResponse
+from hub.services.models import account_access, local_inventory, local_model_actions as actions
+
+REAL_GUARD = actions._load_state_blocks_delete
+
+
+def _row(path: Path, source: str) -> LocalModelInfo:
+ return LocalModelInfo(id = str(path), display_name = path.name, path = str(path), source = source)
+
+
+def lm_root(tmp_path, monkeypatch):
+ root = tmp_path / "lmstudio"
+ model = root / "unsloth" / "gemma-GGUF"
+ model.mkdir(parents = True)
+ (model / "gemma-Q4.gguf").write_bytes(b"GGUF")
+ folder = tmp_path / "custom"
+ (folder / "solo").mkdir(parents = True)
+ rows = [
+ _row(model, "lmstudio"),
+ _row(folder, "custom"),
+ _row(tmp_path / "hf" / "models--a--b", "hf_cache"),
+ _row(tmp_path / "ollama" / "blob", "ollama"),
+ ]
+
+ async def listing(models_dir: str = "./models"):
+ return LocalModelListResponse(models_dir = "", hf_cache_dir = "", models = rows)
+
+ sources = local_inventory._LocalInventorySources(
+ tmp_path / "hf", tmp_path / "legacy", tmp_path / "default", (root,), (), (), (), ()
+ )
+ monkeypatch.setattr(local_inventory, "list_local_models_response", listing)
+ monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: sources)
+
+ monkeypatch.setattr(local_inventory, "list_scan_folders", lambda: [{"path": str(folder)}])
+ monkeypatch.setattr(account_access, "require_installation_owner", lambda: None)
+ monkeypatch.setattr(actions, "_load_state_blocks_delete", lambda paths: None)
+ return root, model, folder
+
+
+def test_delete_removes_listed_lmstudio_model_and_empty_publisher(lm_root):
+ root, model, _ = lm_root
+ asyncio.run(actions.delete_local_model_response(str(model)))
+ assert not model.exists()
+ assert not model.parent.exists()
+ assert root.is_dir()
+
+
+def test_delete_refuses_unlisted_path_and_hf_cache_rows(lm_root, tmp_path):
+ root, model, _ = lm_root
+ stray = root / "unsloth" / "other"
+ stray.mkdir()
+ for path in (stray, tmp_path / "hf" / "models--a--b"):
+ with pytest.raises(HTTPException) as caught:
+ asyncio.run(actions.delete_local_model_response(str(path)))
+ assert caught.value.status_code == 404
+ assert stray.is_dir() and model.is_dir()
+
+
+def _ollama_store(tmp_path, monkeypatch):
+ from hub.services.models import ollama
+
+ store = tmp_path / "ollama_store"
+ blobs = store / "blobs"
+ blobs.mkdir(parents = True)
+ for name in ("sha256-own", "sha256-shared", "sha256-cfg"):
+ (blobs / name).write_bytes(b"x")
+ library = store / "manifests" / "registry.ollama.ai" / "library"
+ own = {
+ "config": {"digest": "sha256:cfg"},
+ "layers": [{"digest": "sha256:own"}, {"digest": "sha256:shared"}],
+ }
+ other = {"layers": [{"digest": "sha256:shared"}]}
+ (library / "gone").mkdir(parents = True)
+ (library / "kept").mkdir(parents = True)
+ (library / "gone" / "latest").write_text(json.dumps(own))
+ (library / "kept" / "latest").write_text(json.dumps(other))
+ monkeypatch.setattr(ollama, "_known_ollama_dirs", lambda: [store])
+ ref = ollama._ollama_manifest_ref(Path(os.path.realpath(library / "gone" / "latest")))
+ return store, ref
+
+
+def test_delete_ollama_tag_keeps_layers_another_tag_uses(lm_root, tmp_path, monkeypatch):
+ store, ref = _ollama_store(tmp_path, monkeypatch)
+ blob = store / "blobs" / "sha256-own"
+ row = LocalModelInfo(
+ id = ref, load_id = ref, display_name = "gone:latest", path = str(blob), source = "ollama"
+ )
+
+ async def listing(models_dir: str = "./models"):
+ return LocalModelListResponse(models_dir = "", hf_cache_dir = "", models = [row])
+
+ monkeypatch.setattr(local_inventory, "list_local_models_response", listing)
+ asyncio.run(actions.delete_local_model_response(str(blob)))
+ library = store / "manifests" / "registry.ollama.ai" / "library"
+ assert not (library / "gone").exists()
+ assert (library / "kept" / "latest").is_file()
+ assert sorted(p.name for p in (store / "blobs").iterdir()) == ["sha256-shared"]
+
+
+def test_delete_split_gguf_takes_every_shard(lm_root, tmp_path, monkeypatch):
+ hermes = tmp_path / "hermes"
+ hermes.mkdir()
+ shards = [hermes / f"big-0000{i}-of-00002.gguf" for i in (1, 2)]
+ for shard in shards:
+ shard.write_bytes(b"GGUF")
+ keep = hermes / "other.gguf"
+ keep.write_bytes(b"GGUF")
+ row = _row(shards[0], "hermes")
+
+ async def listing(models_dir: str = "./models"):
+ return LocalModelListResponse(models_dir = "", hf_cache_dir = "", models = [row])
+
+ monkeypatch.setattr(local_inventory, "list_local_models_response", listing)
+ asyncio.run(actions.delete_local_model_response(str(shards[0])))
+ assert not any(s.exists() for s in shards)
+ assert keep.is_file()
+
+
+def test_delete_refuses_a_row_that_is_the_scan_folder_itself(lm_root):
+ _, _, folder = lm_root
+ with pytest.raises(HTTPException) as caught:
+ asyncio.run(actions.delete_local_model_response(str(folder)))
+ assert caught.value.status_code == 400
+ assert (folder / "solo").is_dir()
+
+
+def test_delete_refuses_a_loaded_model(lm_root, monkeypatch):
+ _, model, _ = lm_root
+ monkeypatch.setattr(
+ actions, "_load_state_blocks_delete", lambda paths: "Unload the model before deleting"
+ )
+ with pytest.raises(HTTPException) as caught:
+ asyncio.run(actions.delete_local_model_response(str(model)))
+ assert caught.value.status_code == 400
+ assert model.is_dir()
+
+
+def test_load_guard_matches_a_gguf_loaded_from_inside_the_folder(lm_root, monkeypatch):
+ from hub.services.models import deletion
+
+ _, model, _ = lm_root
+ loaded = str(model / "gemma-Q4.gguf")
+ monkeypatch.setattr(
+ deletion,
+ "_llama_cpp_blocks_delete",
+ lambda path, variant: deletion._loaded_id_matches_repo(loaded, path),
+ )
+ monkeypatch.setattr(deletion, "_inference_backend_blocks_delete", lambda path: False)
+ monkeypatch.setattr(deletion, "_diffusion_blocks_delete", lambda path: None)
+ monkeypatch.setattr(deletion, "_video_blocks_delete", lambda path: None)
+ assert REAL_GUARD((str(model),)) == "Unload the model before deleting"
+
+
+def test_reveal_accepts_listed_ollama_row_and_rejects_hf_cache(lm_root, tmp_path, monkeypatch):
+ import utils.paths.path_utils as path_utils
+
+ target = tmp_path / "ollama" / "blob"
+ target.parent.mkdir(parents = True)
+ target.write_bytes(b"x")
+ seen = []
+ monkeypatch.setattr(path_utils, "reveal_in_file_manager", lambda path: seen.append(path))
+ asyncio.run(actions.reveal_local_model_response(str(target)))
+ assert seen == [target]
+ with pytest.raises(HTTPException) as caught:
+ asyncio.run(actions.reveal_local_model_response(str(tmp_path / "hf" / "models--a--b")))
+ assert caught.value.status_code == 404
+
+
+def test_ollama_alias_tags_sharing_a_blob_delete_the_chosen_tag(lm_root, tmp_path, monkeypatch):
+ from hub.services.models import ollama
+
+ store, gone_ref = _ollama_store(tmp_path, monkeypatch)
+ library = store / "manifests" / "registry.ollama.ai" / "library"
+ kept_ref = ollama._ollama_manifest_ref(Path(os.path.realpath(library / "kept" / "latest")))
+ blob = store / "blobs" / "sha256-shared"
+ rows = [
+ LocalModelInfo(
+ id = kept_ref, load_id = kept_ref, display_name = "kept", path = str(blob), source = "ollama"
+ ),
+ LocalModelInfo(
+ id = gone_ref, load_id = gone_ref, display_name = "gone", path = str(blob), source = "ollama"
+ ),
+ ]
+
+ async def listing(models_dir: str = "./models"):
+ return LocalModelListResponse(models_dir = "", hf_cache_dir = "", models = rows)
+
+ monkeypatch.setattr(local_inventory, "list_local_models_response", listing)
+ asyncio.run(actions.delete_local_model_response(str(blob), gone_ref))
+ assert not (library / "gone").exists()
+ assert (library / "kept" / "latest").is_file()
+
+
+def test_dictation_sidecar_holding_the_model_blocks_delete(lm_root, monkeypatch):
+ import types
+
+ import core.inference.stt_audiocpp_sidecar as sidecar_module
+
+ _, model, _ = lm_root
+ sidecar = types.SimpleNamespace(loaded_model = str(model / "gemma-Q4.gguf"), loading_model = None)
+ monkeypatch.setattr(sidecar_module, "get_audio_cpp_stt_sidecar", lambda: sidecar)
+ assert actions._dictation_holds(str(model))
+ sidecar.loaded_model = None
+ assert not actions._dictation_holds(str(model))
+
+
+def test_custom_row_inside_an_hf_cache_is_left_to_delete_cached(lm_root, tmp_path, monkeypatch):
+ snapshot = tmp_path / "hf" / "models--a--b" / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ row = _row(snapshot, "custom")
+
+ async def listing(models_dir: str = "./models"):
+ return LocalModelListResponse(models_dir = "", hf_cache_dir = "", models = [row])
+
+ monkeypatch.setattr(local_inventory, "list_local_models_response", listing)
+ with pytest.raises(HTTPException) as caught:
+ asyncio.run(actions.delete_local_model_response(str(snapshot)))
+ assert caught.value.status_code == 400
+ assert snapshot.is_dir()
+
+
+def test_primary_backend_loading_the_model_blocks_delete(lm_root, monkeypatch):
+ import types
+
+ import core.inference.orchestrator as orchestrator
+
+ _, model, _ = lm_root
+ backend = types.SimpleNamespace(loading_models = [str(model)], active_model_name = None)
+ monkeypatch.setattr(orchestrator, "peek_inference_backend", lambda: backend)
+ assert actions._primary_loading(str(model))
+ backend.loading_models = []
+ assert not actions._primary_loading(str(model))
+
+
+def _listing_of(monkeypatch, *rows):
+ async def listing(models_dir: str = "./models"):
+ return LocalModelListResponse(models_dir = "", hf_cache_dir = "", models = list(rows))
+
+ monkeypatch.setattr(local_inventory, "list_local_models_response", listing)
+
+
+def test_symlink_alias_into_an_hf_cache_unlinks_only_the_alias(lm_root, tmp_path, monkeypatch):
+ _, _, folder = lm_root
+ snapshot = tmp_path / "hf" / "models--a--b" / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ alias = folder / "alias"
+ alias.symlink_to(snapshot, target_is_directory = True)
+ _listing_of(monkeypatch, _row(alias, "custom"))
+ asyncio.run(actions.delete_local_model_response(str(alias)))
+ assert not alias.is_symlink() and snapshot.is_dir()
+
+
+def test_symlinked_split_shards_lose_every_alias_but_keep_targets(lm_root, tmp_path, monkeypatch):
+ _, _, folder = lm_root
+ store = tmp_path / "store"
+ store.mkdir()
+ links = []
+ for i in (1, 2):
+ real = store / f"big-0000{i}-of-00002.gguf"
+ real.write_bytes(b"GGUF")
+ link = folder / real.name
+ link.symlink_to(real)
+ links.append(link)
+ _listing_of(monkeypatch, _row(links[0], "custom"))
+ asyncio.run(actions.delete_local_model_response(str(links[0])))
+ assert not any(link.is_symlink() for link in links)
+ assert all((store / link.name).is_file() for link in links)
+
+
+def test_local_sources_advertise_can_delete():
+ from hub.services.models.common import _capabilities_for_format
+ for source in ("lmstudio", "custom", "ollama", "hermes", "omlx", "models_dir", "hf_cache"):
+ assert _capabilities_for_format("gguf", source).can_delete
+
+
+def test_ollama_tags_sharing_a_blob_need_an_id(lm_root, tmp_path, monkeypatch):
+ blob = tmp_path / "blob"
+ blob.write_bytes(b"x")
+ rows = [
+ LocalModelInfo(id = ref, load_id = ref, display_name = ref, path = str(blob), source = "ollama")
+ for ref in ("ollama-manifest:a", "ollama-manifest:b")
+ ]
+ _listing_of(monkeypatch, *rows)
+ with pytest.raises(HTTPException) as caught:
+ asyncio.run(actions.delete_local_model_response(str(blob)))
+ assert caught.value.status_code == 400
+ assert blob.is_file()
+
+
+def test_format_rows_of_one_mixed_directory_still_delete(lm_root, monkeypatch):
+ _, model, _ = lm_root
+ _listing_of(monkeypatch, _row(model, "lmstudio"), _row(model, "lmstudio"))
+ asyncio.run(actions.delete_local_model_response(str(model), str(model)))
+ assert not model.exists()
+
+
+def test_unreadable_scan_folders_fail_closed(lm_root, monkeypatch):
+ _, model, _ = lm_root
+
+ def broken():
+ raise OSError("database is locked")
+
+ monkeypatch.setattr(local_inventory, "list_scan_folders", broken)
+ with pytest.raises(HTTPException) as caught:
+ asyncio.run(actions.delete_local_model_response(str(model)))
+ assert caught.value.status_code == 503
+ assert model.is_dir()
diff --git a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
index 8ed594f0861..c696f0fed0e 100644
--- a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
@@ -2,6 +2,9 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useHfEndpoint } from "@/lib/hf-endpoint";
+import { revealCachedModel } from "@/features/chat";
+import { useRevealLabel } from "@/features/library/reveal";
+import { toast } from "@/lib/toast";
import { ModelMemoryBarFor } from "@/components/model-memory-bar";
import {
Popover,
@@ -16,7 +19,12 @@ import {
import { useVramBudgetFraction } from "@/hooks/use-vram-budget-fraction";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { cn } from "@/lib/utils";
-import { Alert02Icon, CubeIcon, Share05Icon } from "@hugeicons/core-free-icons";
+import {
+ Alert02Icon,
+ CubeIcon,
+ Folder01Icon,
+ Share05Icon,
+} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useCallback, useMemo, useState } from "react";
import {
@@ -30,7 +38,10 @@ import {
type BaseModelSource,
type LocalModelInfo,
type ModelInventoryFormat,
+ DELETABLE_LOCAL_SOURCES,
deleteCachedModel,
+ deleteLocalModel,
+ revealLocalModel,
} from "../inventory";
import { formatBytes } from "../lib/format";
import type { HubModelRunSelection } from "../lib/model-run-selection";
@@ -186,6 +197,36 @@ function BaseModelReference({
);
}
+/** Null unless this is the owner on the backend's own machine with a file manager. */
+function CardRevealButton({ onReveal }: { onReveal: () => Promise<unknown> }) {
+ const revealLabel = useRevealLabel();
+ if (!revealLabel) return null;
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={revealLabel}
+ onClick={(e) => {
+ e.stopPropagation();
+ onReveal().catch((err) => {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to open file manager",
+ );
+ });
+ }}
+ className="inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-muted hover:text-foreground focus-visible:opacity-100 group-hover/dl:opacity-100"
+ >
+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="tooltip-compact">
+ {revealLabel}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
export function LocalOnDeviceCard({
modelId,
displayName,
@@ -246,12 +287,17 @@ export function LocalOnDeviceCard({
// Update availability is derived from the GGUF variant metadata; offline rows
// keep the button hidden because there is no remote revision to fetch.
const online = useOnlineStatus();
+ const isCacheRow = source === "hf_cache";
const deleteImpact = useDeleteImpact(
- deleteOpen && Boolean(repoId),
+ deleteOpen && isCacheRow && Boolean(repoId),
repoId ?? "",
);
const { deleting, runDelete } = useCardDelete({
action: async () => {
+ if (!isCacheRow) {
+ await deleteLocalModel(path, modelId);
+ return;
+ }
if (!repoId) return;
// Delete is only offered for hf_cache rows (see canDelete), so `path` is
// the cache snapshot path: pass it so the delete targets the cache this
@@ -259,7 +305,7 @@ export function LocalOnDeviceCard({
await deleteCachedModel(repoId, undefined, hfToken || undefined, path);
},
resourceName: "model",
- successMessage: () => `Deleted ${repoId}`,
+ successMessage: () => `Deleted ${isCacheRow ? repoId : displayName}`,
onSuccess: () => {
setDeleteOpen(false);
onChange?.();
@@ -295,8 +341,7 @@ export function LocalOnDeviceCard({
}));
const canDelete =
- source === "hf_cache" &&
- !!repoId &&
+ (isCacheRow ? !!repoId : DELETABLE_LOCAL_SOURCES.has(source) && !!path) &&
!isActive &&
!isLoading &&
!runPending;
@@ -569,10 +614,19 @@ export function LocalOnDeviceCard({
)}
{canDelete && (
<CardDeleteButton
- label={`Delete ${repoId}`}
+ label={`Delete ${isCacheRow ? repoId : displayName}`}
onClick={() => setDeleteOpen(true)}
/>
)}
+ {(isCacheRow ? repoId : path) && (
+ <CardRevealButton
+ onReveal={() =>
+ isCacheRow && repoId
+ ? revealCachedModel(repoId)
+ : revealLocalModel(path, modelId)
+ }
+ />
+ )}
<PathInfoButton path={path} />
</div>
</div>
@@ -634,19 +688,28 @@ export function LocalOnDeviceCard({
onOpenChange={(o) => {
if (!o && !deleting) setDeleteOpen(false);
}}
- title="Delete cached model?"
+ title={isCacheRow ? "Delete cached model?" : "Delete local model?"}
deleting={deleting}
// Same gate the model row menu applies: when an installed image model still needs these
// assets the summary says so, and leaving Delete enabled only bought the user a 400.
blocked={(deleteImpact?.blocked_by.length ?? 0) > 0}
onConfirm={() => void runDelete()}
description={
- <>
- This will remove{" "}
- <span className="font-medium text-foreground">{repoId}</span> and
- its downloaded files from disk. You can re-download it later.
- <DeleteImpactSummary impact={deleteImpact} />
- </>
+ isCacheRow ? (
+ <>
+ This will remove{" "}
+ <span className="font-medium text-foreground">{repoId}</span> and
+ its downloaded files from disk. You can re-download it later.
+ <DeleteImpactSummary impact={deleteImpact} />
+ </>
+ ) : (
+ <>
+ This will permanently remove{" "}
+ <span className="font-medium text-foreground">{displayName}</span>{" "}
+ from{" "}
+ <span className="break-all font-mono text-xs">{path}</span>.
+ </>
+ )
}
/>
<UpdateConfirmDialog
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
index 6aa080e42a5..58d21e7e098 100644
--- a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
@@ -12,7 +12,10 @@ import {
import {
type GgufVariantDetail,
deleteCachedDataset,
+ DELETABLE_LOCAL_SOURCES,
deleteCachedModel,
+ deleteLocalModel,
+ revealLocalModel,
formatLocalUpdated,
listGgufVariants,
useGgufVariantsCacheVersion,
@@ -627,6 +630,13 @@ export const InventoryRow = memo(function InventoryRow({
? row.repoId
: null;
const canDelete = cacheDeletableRepoId !== null;
+ const localActionPath =
+ !isDataset &&
+ row.kind === "local" &&
+ row.source !== "hf_cache" &&
+ row.path
+ ? row.path
+ : null;
const partialRepoId =
row.partial && !row.companionPrefetch
? row.kind === "cache"
@@ -798,6 +808,34 @@ export const InventoryRow = memo(function InventoryRow({
onDeleted: onChange,
} : undefined}
/>
+ ) : localActionPath && row.kind === "local" ? (
+ <ModelRowMenu
+ ariaLabel={`More options for ${rowModelId}`}
+ buttonClassName="pointer-events-auto hub-modal-pe-guard size-8 opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 [@media(pointer:coarse)]:opacity-100"
+ iconClassName="size-4"
+ onReveal={() => revealLocalModel(localActionPath, row.loadId)}
+ del={
+ DELETABLE_LOCAL_SOURCES.has(row.source)
+ ? {
+ title: "Delete local model?",
+ description: (
+ <>
+ This will permanently remove{" "}
+ <span className="font-medium text-foreground">{title}</span>{" "}
+ from{" "}
+ <span className="break-all font-mono text-xs">
+ {localActionPath}
+ </span>
+ .
+ </>
+ ),
+ successMessage: `Deleted ${title}`,
+ onConfirm: () => deleteLocalModel(localActionPath, row.loadId),
+ onDeleted: onChange,
+ }
+ : undefined
+ }
+ />
) : null;
// Compact master pane: drop the capability column and collapse size + date
diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.ts
index bd4f09d49d9..06b64df215c 100644
--- a/studio/frontend/src/features/hub/index.ts
+++ b/studio/frontend/src/features/hub/index.ts
@@ -70,7 +70,10 @@ export {
dedupeSameSourceHubCacheRows,
defaultCapabilities,
deleteCachedDataset,
+ DELETABLE_LOCAL_SOURCES,
deleteCachedModel,
+ deleteLocalModel,
+ revealLocalModel,
epochMillisecondsToSeconds,
fetchInventorySource,
findCompleteHfCacheLocalRow,
diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.ts
index 140c5d48661..a52eb0af033 100644
--- a/studio/frontend/src/features/hub/inventory/api.ts
+++ b/studio/frontend/src/features/hub/inventory/api.ts
@@ -432,6 +432,39 @@ export async function deleteCachedModel(
}
}
+export const DELETABLE_LOCAL_SOURCES: ReadonlySet<string> = new Set([
+ "models_dir",
+ "lmstudio",
+ "custom",
+ "ollama",
+ "hermes",
+ "omlx",
+]);
+
+/** `id` (the row's load id) picks between Ollama tags that share one blob path. */
+export async function revealLocalModel(path: string, id?: string): Promise<void> {
+ const response = await authFetch("/api/hub/local/reveal", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ path, id }),
+ });
+ await throwIfNotOk(response);
+}
+
+export async function deleteLocalModel(path: string, id?: string): Promise<void> {
+ const response = await authFetch("/api/hub/local/delete", {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ path, id }),
+ });
+ try {
+ await throwIfNotOk(response);
+ bumpInventoryVersion();
+ } finally {
+ invalidateGgufVariantsCache(path);
+ }
+}
+
export async function listScanFolders(): Promise<ScanFolderInfo[]> {
const response = await authFetch("/api/hub/scan-folders");
const data = await parseJsonOrThrow<{ folders: ScanFolderInfo[] }>(response);
diff --git a/studio/frontend/src/features/hub/inventory/index.ts b/studio/frontend/src/features/hub/inventory/index.ts
index 1fbe6734c26..5d79e85cf11 100644
--- a/studio/frontend/src/features/hub/inventory/index.ts
+++ b/studio/frontend/src/features/hub/inventory/index.ts
@@ -15,7 +15,10 @@ export {
listCachedGguf,
listCachedModels,
deleteCachedDataset,
+ DELETABLE_LOCAL_SOURCES,
deleteCachedModel,
+ deleteLocalModel,
+ revealLocalModel,
fetchDeleteImpact,
fetchOrphanCompanions,
invalidateGgufVariantsCache,
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index 035c57e1622..dbb7733dc22 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -61,9 +61,12 @@ import {
HubOptionMenu,
TrainIcon,
TransportConflictDialog,
+ DELETABLE_LOCAL_SOURCES,
deleteCachedModel,
+ deleteLocalModel,
invalidateGgufVariantsCache,
listGgufVariants as listGgufVariantsCached,
+ revealLocalModel,
useGgufVariantsCacheVersions,
useHubInfiniteScroll,
isHuggingFaceOffline,
@@ -6831,6 +6834,35 @@ export function HubModelPicker({
);
};
+ const renderLocalRowMenu = (m: LocalModelInfo) => {
+ const name = m.model_id ?? m.display_name;
+ return (
+ <ModelRowMenu
+ ariaLabel={`More options for ${name}`}
+ onReveal={() => revealLocalModel(m.path, m.id)}
+ del={
+ DELETABLE_LOCAL_SOURCES.has(m.source)
+ ? {
+ title: "Delete local model?",
+ description: (
+ <>
+ This will permanently remove{" "}
+ <span className="font-medium text-foreground">{name}</span>{" "}
+ from{" "}
+ <span className="break-all font-mono text-xs">{m.path}</span>.
+ </>
+ ),
+ successMessage: `Deleted ${name}`,
+ disabled: deleteDisabled,
+ onConfirm: () => deleteLocalModel(m.path, m.id),
+ onDeleted: refreshLocalModelsList,
+ }
+ : undefined
+ }
+ />
+ );
+ };
+
const renderAdditionalOnDeviceModelRow = (model: ModelOption) => {
const optionKey = makeModelOptionKey("additional-on-device", model.id);
const isSelected = value === model.id;
@@ -7706,7 +7738,11 @@ export function HubModelPicker({
);
return (
<div key={m.id}>
- <div className="group flex items-center">
+ <div
+ className={downloadedRowShellClassName(
+ value === m.id,
+ )}
+ >
<div className="min-w-0 flex-1">
<ModelRow
label={m.model_id ?? m.display_name}
@@ -7759,8 +7795,7 @@ export function HubModelPicker({
}
alignMeta="device"
vramStatus={null}
- // The downloaded rows' inset, so columns line up across sections.
- className="pr-1"
+ className={downloadedRowButtonClassName}
/>
</div>
<span className={ROW_ACTIONS_CLASS}>
@@ -7790,6 +7825,7 @@ export function HubModelPicker({
}
/>
)}
+ {renderLocalRowMenu(m)}
</span>
</div>
{isGguf &&
@@ -7850,7 +7886,11 @@ export function HubModelPicker({
const optionKey = makeModelOptionKey("lm-studio", m.id);
return (
<div key={m.id}>
- <div className="group flex items-center">
+ <div
+ className={downloadedRowShellClassName(
+ value === m.id,
+ )}
+ >
<div className="min-w-0 flex-1">
<ModelRow
label={m.model_id ?? m.display_name}
@@ -7902,8 +7942,7 @@ export function HubModelPicker({
}
alignMeta="device"
vramStatus={null}
- // The downloaded rows' inset, so columns line up across sections.
- className="pr-1"
+ className={downloadedRowButtonClassName}
/>
</div>
<span className={ROW_ACTIONS_CLASS}>
@@ -7933,6 +7972,7 @@ export function HubModelPicker({
}
/>
)}
+ {renderLocalRowMenu(m)}
</span>
</div>
{isGguf && !isGgufFile && isGgufExpanded(m.id) && (
@@ -7984,7 +8024,11 @@ export function HubModelPicker({
const optionKey = makeModelOptionKey("local-dir", m.id);
return (
<div key={m.id}>
- <div className="group flex items-center">
+ <div
+ className={downloadedRowShellClassName(
+ value === m.id,
+ )}
+ >
<div className="min-w-0 flex-1">
<ModelRow
label={m.model_id ?? m.display_name}
@@ -8032,8 +8076,7 @@ export function HubModelPicker({
}
alignMeta="device"
vramStatus={null}
- // The downloaded rows' inset, so columns line up across sections.
- className="pr-1"
+ className={downloadedRowButtonClassName}
/>
</div>
<span className={ROW_ACTIONS_CLASS}>
@@ -8063,6 +8106,7 @@ export function HubModelPicker({
}
/>
)}
+ {renderLocalRowMenu(m)}
</span>
</div>
{isGguf && !isGgufFile && isGgufExpanded(m.id) && (
diff --git a/studio/frontend/tests/local-model-row-actions.test.ts b/studio/frontend/tests/local-model-row-actions.test.ts
new file mode 100644
index 00000000000..73a0de78753
--- /dev/null
+++ b/studio/frontend/tests/local-model-row-actions.test.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const read = (path: string) =>
+ readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf-8");
+
+const API = read("../src/features/hub/inventory/api.ts");
+const PICKERS = read(
+ "../src/features/model-picker/components/model-selector/pickers.tsx",
+);
+const HUB_ROWS = read("../src/features/hub/catalog/models-catalog-rows.tsx");
+const CARD = read("../src/features/hub/catalog/local-on-device-card.tsx");
+
+test("local reveal and delete go through the path-checked hub routes", () => {
+ assert.match(API, /authFetch\("\/api\/hub\/local\/reveal"/);
+ assert.match(API, /authFetch\("\/api\/hub\/local\/delete", \{\s*method: "DELETE"/);
+ // Mirrors LOCAL_SOURCES in local_model_actions.py.
+ assert.match(
+ API,
+ /DELETABLE_LOCAL_SOURCES[^=]*= new Set\(\[\s*"models_dir",\s*"lmstudio",\s*"custom",\s*"ollama",\s*"hermes",\s*"omlx",\s*\]\)/,
+ );
+});
+
+test("picker local rows reveal by path and offer delete only for deletable sources", () => {
+ assert.match(PICKERS, /onReveal=\{\(\) => revealLocalModel\(m\.path, m\.id\)\}/);
+ assert.match(PICKERS, /DELETABLE_LOCAL_SOURCES\.has\(m\.source\)\s*\?/);
+ assert.match(PICKERS, /onConfirm: \(\) => deleteLocalModel\(m\.path, m\.id\)/);
+});
+
+test("hub rows and the on-device card act on non-cache rows by path", () => {
+ assert.match(HUB_ROWS, /row\.source !== "hf_cache" &&\s*row\.path/);
+ assert.match(HUB_ROWS, /onReveal=\{\(\) => revealLocalModel\(localActionPath, row\.loadId\)\}/);
+ assert.match(CARD, /await deleteLocalModel\(path, modelId\)/);
+ assert.match(CARD, /DELETABLE_LOCAL_SOURCES\.has\(source\) && !!path/);
+ assert.match(CARD, /: revealLocalModel\(path, modelId\)/);
+});
diff --git a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
index 04429ea4aa2..2247449dfec 100644
--- a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
+++ b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
@@ -132,8 +132,10 @@ test("the parameter chip leads its column, so the modality gap is the cluster's
PICKERS,
/alignMeta === "hub"\n\s*\? cn\("justify-end", META_COLUMN\.paramWide\)\n\s*: cn\("justify-start", META_COLUMN\.param\)/,
);
- // Every On Device section ends its rows at one inset, so chips line up across sections.
- assert.equal(PICKERS.split('className="pr-1"').length - 1, 3, "the custom folder rows");
+ // Local rows share the downloaded rows' button and shell: same inset, full-width hover.
+ assert.match(PICKERS, /downloadedRowButtonClassName =\s*"bg-transparent pr-1/);
+ assert.equal(PICKERS.split('className="pr-1"').length - 1, 0);
+ assert.equal(PICKERS.split("{renderLocalRowMenu(m)}").length - 1, 3);
});