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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix duplicate GGUF rows in custom model folders (#9975)
Lee Jacksonf6294f8a9941
diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.pyindex 1b1d3b6134d..92b132f4de7 100644--- a/studio/backend/core/inference/local_model_resolver.py+++ b/studio/backend/core/inference/local_model_resolver.py@@ -397,6 +397,7 @@ def _build_index() -> dict[str, _LocalGgufEntry]:_resolve_hf_cache_dir,_is_hidden_model,)+ from hub.utils.gguf import dedupe_custom_gguf_rows, suppress_grouped_gguf_file_rowsfrom utils.paths import legacy_hf_cache_dir, hf_default_cache_dir, lmstudio_model_dirsfrom utils.hf_cache_settings import known_hf_hub_cachesfrom core.inference.model_ids import public_model_id@@ -455,14 +456,17 @@ def _build_index() -> dict[str, _LocalGgufEntry]:logger.debug("auto-switch: LM Studio scan failed: %s", exc)try:from storage.studio_db import list_scan_folders++ custom_found = []for folder in list_scan_folders():try:fp = Path(folder["path"])- found += (+ custom_found += dedupe_custom_gguf_rows(_scan_models_dir(fp, limit = 200) + _scan_hf_once(fp) + _scan_lmstudio_dir(fp))except Exception as exc:logger.debug("auto-switch: scan folder %r failed: %s", folder, exc)+ found += suppress_grouped_gguf_file_rows(custom_found)except Exception as exc:logger.debug("auto-switch: scan folders enumerate failed: %s", exc)for info in found:diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex 1a350f7e895..5f2e5a00021 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -22,7 +22,7 @@ from hub.storage.scan_folders import (list_scan_folders,remove_scan_folder,)-from hub.utils import download_manifest, inventory_scan as hf_cache_scan+from hub.utils import download_manifest, gguf, inventory_scan as hf_cache_scanfrom hub.utils.paths import (hf_default_cache_dir,legacy_hf_cache_dir,@@ -584,6 +584,11 @@ def _inventory_path_identity(raw_path: str) -> str:return os.path.normcase(raw)+def _inventory_physical_identity(raw_path: str) -> str:+ """physical identity for an existing discovered path without lossy name folding."""+ return gguf.local_path_physical_identity(raw_path)++def _coerce_scan_folder_path(raw_path: str) -> str:"""Normalize a scan registration target; the registry stores directories, so a pasted weight-file path is reduced to its parent folder."""if not raw_path or not raw_path.strip():@@ -803,6 +808,8 @@ def _scan_custom_folder(selectable.append(model)elif detect_gguf_model(model.path, model_root = str(folder_path)) is not None:selectable.append(model)++ selectable = gguf.dedupe_custom_gguf_rows(selectable)remaining = _MAX_MODELS_PER_CUSTOM_FOLDER - len(selectable)if remaining > 0:selectable.extend(scan_ollama_dir(folder_path, limit = remaining))@@ -856,9 +863,16 @@ def _dedupe_local_models(local_models: List[LocalModelInfo]) -> list[LocalModelImodel.format_variant or "",))+ elif model.source == "custom":+ key = _local_inventory_id(+ "custom",+ model.model_format,+ _inventory_physical_identity(model.path),+ None,+ )else:row_key = model.inventory_id or model.id- key = f"{row_key}\x00custom" if model.source == "custom" else row_key+ key = row_keyexisting = deduped.get(key)prefer_candidate = existing is Noneif existing is not None:@@ -875,8 +889,12 @@ def _dedupe_local_models(local_models: List[LocalModelInfo]) -> list[LocalModelI)if prefer_candidate:deduped[key] = model++ deduped_values = list(deduped.values())+ custom_values = [model for model in deduped_values if model.source == "custom"]return sorted(- deduped.values(),+ [model for model in deduped_values if model.source != "custom"]+ + gguf.suppress_grouped_gguf_file_rows(custom_values),key = lambda item: item.updated_at or 0,reverse = True,)@@ -896,6 +914,10 @@ def _filter_hidden_models(local_models: List[LocalModelInfo]) -> list[LocalModelreturn visible+def _filter_and_dedupe_local_models(local_models: List[LocalModelInfo]) -> list[LocalModelInfo]:+ return _dedupe_local_models(_filter_hidden_models(local_models))++async def _scan_local_models_response(models_dir: str, custom_folders: list[dict], sources: _LocalInventorySources) -> LocalModelListResponse:@@ -925,7 +947,7 @@ async def _scan_local_models_response(known_hf_caches,custom_folders,)- models = _dedupe_local_models(_filter_hidden_models(local_models))+ models = await asyncio.to_thread(_filter_and_dedupe_local_models, local_models)return LocalModelListResponse(models_dir = str(models_root),hf_cache_dir = str(hf_cache_dir),diff --git a/studio/backend/hub/tests/test_custom_gguf_discovery.py b/studio/backend/hub/tests/test_custom_gguf_discovery.pynew file mode 100644index 00000000000..8e760607ba1--- /dev/null+++ b/studio/backend/hub/tests/test_custom_gguf_discovery.py@@ -0,0 +1,626 @@+# 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 json+import os+from pathlib import Path+from types import SimpleNamespace++import pytest++from hub.services.models import local_inventory+from hub.utils import gguf+from utils.models.model_config import detect_gguf_model, _find_local_gguf_by_variant+++def _write_gguf(path: Path, size: int = 4) -> Path:+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_bytes(b"G" * size)+ return path+++def _custom_rows(*roots: Path):+ rows = []+ for root in roots:+ rows.extend(+ local_inventory._promote_to_custom_source(row)+ for row in local_inventory._scan_custom_folder(root)+ )+ return local_inventory._dedupe_local_models(rows)+++def _symlink_dir(alias: Path, target: Path) -> None:+ if not hasattr(os, "symlink"):+ pytest.skip("symlinks unavailable")+ try:+ alias.symlink_to(target, target_is_directory = True)+ except OSError as error:+ pytest.skip(f"symlink creation unavailable: {error}")+++def _symlink_file(alias: Path, target: Path) -> None:+ if not hasattr(os, "symlink"):+ pytest.skip("symlinks unavailable")+ try:+ alias.symlink_to(target)+ except OSError as error:+ pytest.skip(f"symlink creation unavailable: {error}")+++def test_checkpoint_family_matches_quantized_and_split_variants():+ assert gguf.gguf_checkpoint_family("model-a-Q4_K_M.gguf") == "model-a"+ assert gguf.gguf_checkpoint_family("model-a-Q8_0.gguf") == "model-a"+ assert gguf.gguf_checkpoint_family("model-Q4_K_M-00001-of-00002.gguf") == "model"+ assert gguf.gguf_checkpoint_family("model-Q4_K_M-00002-of-00002.gguf") == "model"+++def test_checkpoint_family_keeps_distinct_models_separate():+ assert gguf.gguf_checkpoint_family("model-a-Q4_K_M.gguf") == "model-a"+ assert gguf.gguf_checkpoint_family("model-b-Q4_K_M.gguf") == "model-b"+ assert gguf.gguf_checkpoint_family("alpha.gguf") == "alpha"+ assert gguf.gguf_checkpoint_family("beta.gguf") == "beta"+ assert gguf.gguf_checkpoint_family("Model-A-Q4_K_M.gguf") == "Model-A"+++def test_checkpoint_family_normalizes_quant_directories_and_windows_separators():+ assert gguf.gguf_checkpoint_family("Q4_K_M/model.gguf") == "model"+ assert gguf.gguf_checkpoint_family(r"Q8_0\model.gguf") == "model"+ assert gguf.gguf_checkpoint_family("Q8_0/model-a-Q8_0.gguf") == "model-a"+ assert gguf.gguf_checkpoint_family("Q4_K_M.gguf") is None+++def test_same_checkpoint_quantizations_use_one_grouped_row(tmp_path):+ root = tmp_path / "root"+ model = root / "model-a"+ q4 = _write_gguf(model / "model-a-Q4_K_M.gguf", 8)+ q8 = _write_gguf(model / "model-a-Q8_0.gguf", 16)++ assert [Path(row.path) for row in _custom_rows(root)] == [model]+ variants, _ = gguf.list_local_gguf_variants(str(model), model_root = str(root))+ assert {variant.quant for variant in variants} == {"Q4_K_M", "Q8_0"}+ assert Path(detect_gguf_model(str(model), model_root = str(root))) == q8+ assert Path(_find_local_gguf_by_variant(str(model), "Q4_K_M", model_root = str(root))) == q4+++def test_distinct_checkpoints_sharing_a_quant_use_file_rows(tmp_path):+ root = tmp_path / "root"+ holder = root / "publisher"+ model_a = _write_gguf(holder / "model-a-Q4_K_M.gguf")+ model_b = _write_gguf(holder / "model-b-Q4_K_M.gguf")++ rows = _custom_rows(root)++ assert {Path(row.path) for row in rows} == {model_a, model_b}+ assert all(not row.capabilities.requires_variant for row in rows)+++ ("first_name", "second_name"),+ [+ ("model-a-Q4_K_M.gguf", "model.a-Q4_K_M.gguf"),+ ("Model-A-Q4_K_M.gguf", "model-a-Q4_K_M.gguf"),+ ("model-a-Q4_K_M.gguf", "model.a-Q8_0.gguf"),+ ("Model-A-Q4_K_M.gguf", "model-a-Q8_0.gguf"),+ ],+)+def test_checkpoint_names_preserve_exact_identity(tmp_path, first_name, second_name):+ root = tmp_path / "root"+ holder = root / "holder"+ first = _write_gguf(holder / first_name)+ second = _write_gguf(holder / second_name)+ if first.samefile(second):+ pytest.skip("filesystem does not preserve the distinct names")++ rows = _custom_rows(root)++ assert {Path(row.path) for row in rows} == {first, second}+++def test_unqualified_distinct_checkpoints_use_file_rows(tmp_path):+ root = tmp_path / "root"+ holder = root / "holder"+ alpha = _write_gguf(holder / "alpha.gguf")+ beta = _write_gguf(holder / "beta.gguf")++ assert {Path(row.path) for row in _custom_rows(root)} == {alpha, beta}+++def test_bare_quant_filenames_use_the_parent_model_group(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ q4 = _write_gguf(model / "Q4_K_M.gguf")+ q8 = _write_gguf(model / "Q8_0.gguf")++ assert [Path(row.path) for row in _custom_rows(root)] == [model]+ variants, _ = gguf.list_local_gguf_variants(str(model), model_root = str(root))+ assert {Path(variant.filename).name for variant in variants} == {q4.name, q8.name}+++def test_bare_quant_shards_use_the_parent_model_group(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "Q4_K_M-00001-of-00002.gguf")+ _write_gguf(model / "Q4_K_M-00002-of-00002.gguf")++ rows = _custom_rows(root)++ assert [Path(row.path) for row in rows] == [model]+++def test_overlapping_parent_and_model_roots_keep_the_grouped_row(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "model-Q4_K_M.gguf")++ assert [Path(row.path) for row in _custom_rows(root, model)] == [model]+++def test_symlinked_parent_and_real_model_roots_keep_one_row(tmp_path):+ real_model = tmp_path / "outside" / "model"+ _write_gguf(real_model / "model-Q4_K_M.gguf")+ _write_gguf(real_model / "model-Q8_0.gguf")+ alias_root = tmp_path / "aliases"+ alias_root.mkdir()+ alias_model = alias_root / "model"+ _symlink_dir(alias_model, real_model)++ rows = _custom_rows(alias_root, real_model)++ assert len(rows) == 1+ assert Path(rows[0].path).resolve() == real_model.resolve()+++def test_loose_file_symlink_dedupes_by_physical_identity(tmp_path):+ root = tmp_path / "root"+ target = _write_gguf(root / "model-Q4_K_M.gguf")+ alias = root / "latest.gguf"+ _symlink_file(alias, target)++ rows = _custom_rows(root)++ assert len(rows) == 1+ assert Path(rows[0].path).samefile(target)+++def test_loose_symlink_into_grouped_model_does_not_add_a_row(tmp_path):+ grouped_root = tmp_path / "grouped-root"+ model = grouped_root / "model"+ target = _write_gguf(model / "model-Q4_K_M.gguf")+ loose_root = tmp_path / "loose-root"+ loose_root.mkdir()+ _symlink_file(loose_root / "model-Q4_K_M.gguf", target)++ rows = _custom_rows(grouped_root, loose_root)++ assert [Path(row.path) for row in rows] == [model]+++def test_renamed_loose_symlink_into_grouped_model_does_not_add_a_row(tmp_path):+ grouped_root = tmp_path / "grouped-root"+ model = grouped_root / "model"+ target = _write_gguf(model / "model-Q4_K_M.gguf")+ loose_root = tmp_path / "loose-root"+ loose_root.mkdir()+ _symlink_file(loose_root / "latest.gguf", target)++ rows = _custom_rows(grouped_root, loose_root)++ assert [Path(row.path) for row in rows] == [model]+++def test_symlinked_and_real_parent_roots_dedupe_group_rows(tmp_path):+ real_root = tmp_path / "real"+ real_model = real_root / "model"+ _write_gguf(real_model / "model-Q4_K_M.gguf")+ _write_gguf(real_model / "model-Q8_0.gguf")+ alias_root = tmp_path / "aliases"+ alias_root.mkdir()+ _symlink_dir(alias_root / "model", real_model)++ rows = _custom_rows(real_root, alias_root)++ assert len(rows) == 1+ assert Path(rows[0].path).resolve() == real_model.resolve()+++def test_split_gguf_shards_stay_grouped(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "model-Q4_K_M-00001-of-00002.gguf")+ _write_gguf(model / "model-Q4_K_M-00002-of-00002.gguf")++ assert [Path(row.path) for row in _custom_rows(root)] == [model]+++def test_pre_quant_split_markers_stay_grouped(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "model-00001-of-00002-Q4_K_M.gguf")+ _write_gguf(model / "model-00002-of-00002-Q4_K_M.gguf")++ assert [Path(row.path) for row in _custom_rows(root)] == [model]+++def test_minimax_h3_partitions_stay_grouped(tmp_path):+ root = tmp_path / "root"+ model = root / "minimax-h3"+ _write_gguf(model / "minimax_h3_fl2va-Q4_K_M.gguf")+ _write_gguf(model / "minimax_h3_ref2va-Q4_K_M.gguf")++ assert [Path(row.path) for row in _custom_rows(root)] == [model]+++def test_symlinked_variant_stays_grouped_and_loadable(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ target = _write_gguf(tmp_path / "outside" / "model-Q4_K_M.gguf")+ model.mkdir(parents = True)+ _symlink_file(model / target.name, target)++ rows = _custom_rows(root)++ assert [Path(row.path) for row in rows] == [model]+ assert Path(detect_gguf_model(str(model), model_root = str(root))).samefile(target)+++def test_loose_gguf_models_stay_separate(tmp_path):+ root = tmp_path / "root"+ alpha = _write_gguf(root / "alpha-Q4_K_M.gguf")+ beta = _write_gguf(root / "beta-Q8_0.gguf")++ assert {Path(row.path) for row in _custom_rows(root)} == {alpha, beta}+++def test_direct_custom_model_root_keeps_loose_variants(tmp_path):+ root = tmp_path / "direct-model-root"+ q4 = _write_gguf(root / "model-Q4_K_M.gguf")+ q8 = _write_gguf(root / "model-Q8_0.gguf")++ assert {Path(row.path) for row in _custom_rows(root)} == {q4, q8}+++def test_direct_custom_model_root_dedupes_split_shards(tmp_path):+ root = tmp_path / "direct-model-root"+ first = _write_gguf(root / "Q4_K_M-00001-of-00002.gguf", 11)+ _write_gguf(root / "Q4_K_M-00002-of-00002.gguf", 7)++ rows = _custom_rows(root)++ assert len(rows) == 1+ assert Path(rows[0].path) == first+ assert rows[0].size_bytes == 18+ assert Path(detect_gguf_model(rows[0].path, model_root = str(root))) == first+++def test_direct_split_prefix_matching_follows_the_loader(tmp_path):+ root = tmp_path / "direct-model-root"+ first = _write_gguf(root / "Model-Q4_K_M-00001-of-00002.gguf", 11)+ _write_gguf(root / "model-Q4_K_M-00002-of-00002.gguf", 7)++ rows = _custom_rows(root)++ assert [(Path(row.path), row.size_bytes) for row in rows] == [(first, 18)]+++def test_incomplete_direct_split_is_not_collapsed(tmp_path):+ root = tmp_path / "direct-model-root"+ first = _write_gguf(root / "model-Q4_K_M-00001-of-00003.gguf")+ third = _write_gguf(root / "model-Q4_K_M-00003-of-00003.gguf")++ rows = _custom_rows(root)++ assert {Path(row.path) for row in rows} == {first, third}+++def test_two_digit_split_like_names_stay_separate(tmp_path):+ root = tmp_path / "root"+ holder = root / "holder"+ names = ("model-Q4_K_M-01-of-02.gguf", "model-Q4_K_M-02-of-02.gguf")+ expected = {_write_gguf(holder / name) for name in names}++ rows = _custom_rows(root)++ assert {Path(row.path) for row in rows} == expected+++def test_nested_independent_gguf_models_do_not_share_a_parent_group(tmp_path):+ root = tmp_path / "root"+ publisher = root / "publisher"+ loose = _write_gguf(publisher / "model-a-Q4_K_M.gguf")+ nested = publisher / "model-b"+ _write_gguf(nested / "model-b-Q8_0.gguf")++ rows = _custom_rows(root)++ assert {Path(row.path) for row in rows} == {loose, nested}+ variants, _ = gguf.list_local_gguf_variants(str(nested), model_root = str(root))+ assert [variant.quant for variant in variants] == ["Q8_0"]+ assert _find_local_gguf_by_variant(str(nested), "Q4_K_M", model_root = str(root)) is None+++def test_nested_quant_directory_stays_in_the_parent_group(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "model-a-Q4_K_M.gguf")+ _write_gguf(model / "Q8_0" / "model-a-Q8_0.gguf")++ rows = _custom_rows(root)++ assert [Path(row.path) for row in rows] == [model]+ variants, _ = gguf.list_local_gguf_variants(str(model), model_root = str(root))+ assert {variant.quant for variant in variants} == {"Q4_K_M", "Q8_0"}+++def test_overlapping_nested_quant_root_keeps_the_parent_group(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "model-a-Q4_K_M.gguf")+ quant_dir = model / "Q8_0"+ _write_gguf(quant_dir / "model-a-Q8_0.gguf")+ (quant_dir / "config.json").write_text("{}", encoding = "utf-8")++ rows = _custom_rows(root, quant_dir)++ assert [Path(row.path) for row in rows] == [model]+++def test_quant_named_independent_model_root_stays_selectable(tmp_path):+ root = tmp_path / "root"+ parent = root / "parent"+ _write_gguf(parent / "model-a-Q4_K_M.gguf")+ (parent / "config.json").write_text("{}", encoding = "utf-8")+ child = parent / "Q8_0"+ _write_gguf(child / "model-b-Q8_0.gguf")+ (child / "config.json").write_text("{}", encoding = "utf-8")++ rows = _custom_rows(root, child)++ assert {Path(row.path) for row in rows} == {parent, child}+++def test_symlinked_nested_quant_root_keeps_the_real_parent_group(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "model-a-Q4_K_M.gguf")+ quant_dir = model / "Q8_0"+ _write_gguf(quant_dir / "model-a-Q8_0.gguf")+ (quant_dir / "config.json").write_text("{}", encoding = "utf-8")+ alias_model = tmp_path / "alias-model"+ _symlink_dir(alias_model, model)++ rows = _custom_rows(root, alias_model / "Q8_0")++ assert [Path(row.path) for row in rows] == [model]+++def test_overlapping_nested_independent_model_root_stays_selectable(tmp_path):+ root = tmp_path / "root"+ parent = root / "parent"+ _write_gguf(parent / "parent-Q4_K_M.gguf")+ (parent / "config.json").write_text("{}", encoding = "utf-8")+ child = parent / "child"+ _write_gguf(child / "child-Q8_0.gguf")+ (child / "config.json").write_text("{}", encoding = "utf-8")++ rows = _custom_rows(root, child)++ assert {Path(row.path) for row in rows} == {parent, child}+++def test_overlapping_nested_independent_loose_root_stays_selectable(tmp_path):+ root = tmp_path / "root"+ parent = root / "parent"+ _write_gguf(parent / "parent-Q4_K_M.gguf")+ (parent / "config.json").write_text("{}", encoding = "utf-8")+ child = parent / "child"+ loose = _write_gguf(child / "child-Q8_0.gguf")++ rows = _custom_rows(root, child)++ assert {Path(row.path) for row in rows} == {parent, loose}+++def test_aliased_nested_independent_loose_root_stays_selectable(tmp_path):+ root = tmp_path / "root"+ parent = root / "parent"+ _write_gguf(parent / "parent-Q4_K_M.gguf")+ (parent / "config.json").write_text("{}", encoding = "utf-8")+ child = parent / "child"+ loose = _write_gguf(child / "child-Q8_0.gguf")+ alias_child = tmp_path / "alias-child"+ _symlink_dir(alias_child, child)++ rows = _custom_rows(root, alias_child)++ assert {Path(row.path).resolve() for row in rows} == {parent.resolve(), loose.resolve()}+++def test_mixed_nested_roots_dedupe_only_the_matching_quant_group(tmp_path):+ root = tmp_path / "root"+ parent = root / "parent"+ _write_gguf(parent / "model-a-Q4_K_M.gguf")+ (parent / "config.json").write_text("{}", encoding = "utf-8")+ quant_dir = parent / "Q8_0"+ _write_gguf(quant_dir / "model-a-Q8_0.gguf")+ (quant_dir / "config.json").write_text("{}", encoding = "utf-8")+ child = parent / "child"+ _write_gguf(child / "child-Q4_K_M.gguf")+ (child / "config.json").write_text("{}", encoding = "utf-8")++ rows = _custom_rows(root, quant_dir, child)++ assert {Path(row.path) for row in rows} == {parent, child}+++def test_big_endian_companion_does_not_leave_a_duplicate_loose_row(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "model-Q4_K_M.gguf")+ _write_gguf(model / "model-Q4_K_M-be.gguf")++ rows = _custom_rows(root, model)++ assert [Path(row.path) for row in rows] == [model]+++def test_mtp_companion_does_not_leave_a_duplicate_loose_row(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "model-Q4_K_M.gguf")+ _write_gguf(model / "MTP" / "model-Q8_0.gguf")++ rows = _custom_rows(root, model)++ assert [Path(row.path) for row in rows] == [model]+++def test_nested_symlinked_variant_directory_stays_selectable(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ q4 = _write_gguf(model / "model-a-Q4_K_M.gguf")+ q8_dir = tmp_path / "outside" / "Q8_0"+ q8 = _write_gguf(q8_dir / "model-a-Q8_0.gguf")+ alias = model / "Q8_0"+ _symlink_dir(alias, q8_dir)++ rows = _custom_rows(root)++ assert {Path(row.path) for row in rows} == {q4, alias}+ variants, _ = gguf.list_local_gguf_variants(str(alias), model_root = str(root))+ assert [variant.quant for variant in variants] == ["Q8_0"]+ assert Path(_find_local_gguf_by_variant(str(alias), "Q8_0", model_root = str(root))).samefile(q8)+++def test_windows_junction_child_is_suppressed_when_parent_walk_sees_it(tmp_path, monkeypatch):+ model = tmp_path / "root" / "model"+ q4 = _write_gguf(model / "model-a-Q4_K_M.gguf")+ outside = tmp_path / "outside" / "Q8_0"+ q8 = _write_gguf(outside / "model-a-Q8_0.gguf")+ child = model / "Q8_0"+ _symlink_dir(child, outside)+ linked_q8 = child / q8.name+ parent_row = SimpleNamespace(model_format = "gguf", partial = False, path = str(model))+ child_row = SimpleNamespace(model_format = "gguf", partial = False, path = str(child))++ monkeypatch.setattr(+ gguf,+ "iter_gguf_files",+ lambda directory, recursive = False: iter(+ [q4, linked_q8] if directory == model else [linked_q8]+ ),+ )++ assert gguf.suppress_grouped_gguf_file_rows([parent_row, child_row]) == [parent_row]+++def test_windows_junction_independent_child_stays_selectable(tmp_path, monkeypatch):+ model = tmp_path / "root" / "model"+ q4 = _write_gguf(model / "model-a-Q4_K_M.gguf")+ outside = tmp_path / "outside" / "child"+ q8 = _write_gguf(outside / "child-Q8_0.gguf")+ child = model / "child"+ _symlink_dir(child, outside)+ linked_q8 = child / q8.name+ parent_row = SimpleNamespace(model_format = "gguf", partial = False, path = str(model))+ child_row = SimpleNamespace(model_format = "gguf", partial = False, path = str(child))++ monkeypatch.setattr(+ gguf,+ "iter_gguf_files",+ lambda directory, recursive = False: iter(+ [q4, linked_q8] if directory == model else [linked_q8]+ ),+ )++ assert gguf.suppress_grouped_gguf_file_rows([parent_row, child_row]) == [+ parent_row,+ child_row,+ ]+++def test_lmstudio_publisher_model_layout_keeps_its_model_id(tmp_path):+ root = tmp_path / "lmstudio"+ model = root / "publisher" / "model"+ _write_gguf(model / "model-Q4_K_M.gguf")+ _write_gguf(model / "model-Q8_0.gguf")++ rows = local_inventory._scan_custom_folder(root)++ assert [(Path(row.path), row.model_id) for row in rows] == [(model, "publisher/model")]+++def test_mixed_gguf_and_safetensors_keep_one_row_per_format(tmp_path):+ root = tmp_path / "root"+ model = root / "hybrid"+ _write_gguf(model / "hybrid-Q4_K_M.gguf")+ _write_gguf(model / "model.safetensors")+ (model / "config.json").write_text(json.dumps({"model_type": "llama"}))++ rows = _custom_rows(root)++ assert {(Path(row.path), row.model_format) for row in rows} == {+ (model, "gguf"),+ (model, "safetensors"),+ }+++def test_incomplete_custom_models_stay_hidden(tmp_path):+ root = tmp_path / "root"+ partial = root / "partial"+ partial.mkdir(parents = True)+ (partial / "config.json").write_text("{}")+ _write_gguf(partial / "model.gguf.incomplete")+ complete = _write_gguf(root / "complete.gguf")++ assert [Path(row.path) for row in _custom_rows(root)] == [complete]+++def test_mixed_case_gguf_suffixes_stay_grouped(tmp_path):+ root = tmp_path / "root"+ model = root / "model"+ _write_gguf(model / "model-Q4_K_M.GGUF")+ _write_gguf(model / "model-Q8_0.GguF")++ assert [Path(row.path) for row in _custom_rows(root)] == [model]+++def test_symlinked_model_directory_stays_grouped(tmp_path):+ real_model = tmp_path / "outside" / "model"+ _write_gguf(real_model / "model-Q4_K_M.gguf")+ _write_gguf(real_model / "model-Q8_0.gguf")+ root = tmp_path / "root"+ root.mkdir()+ alias = root / "model-alias"+ _symlink_dir(alias, real_model)++ assert [Path(row.path) for row in _custom_rows(root)] == [alias]+++def test_physical_identity_preserves_native_posix_names(tmp_path):+ if os.sep == "\\":+ pytest.skip("names are not distinct on Windows")+ backslash_root = tmp_path / "model\\one"+ nested_root = tmp_path / "model" / "one"+ trailing_root = tmp_path / "model "+ plain_root = tmp_path / "model"+ paths = {+ _write_gguf(backslash_root / "model-Q4_K_M.gguf"),+ _write_gguf(nested_root / "model-Q4_K_M.gguf"),+ _write_gguf(trailing_root / "model-Q4_K_M.gguf"),+ _write_gguf(plain_root / "model-Q4_K_M.gguf"),+ }++ discovered = [+ local_inventory._promote_to_custom_source(+ local_inventory._local_model_info(+ scan_path = path,+ load_path = path,+ source = "lmstudio",+ model_format = "gguf",+ )+ )+ for path in paths+ ]+ rows = local_inventory._dedupe_local_models(discovered)++ assert {Path(row.path) for row in rows} == pathsdiff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex bf6098f00e2..ded44508c2a 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -244,6 +244,71 @@ def test_custom_inventory_filters_dspark_companions_at_registered_root(tmp_path)assert local_inventory._scan_custom_folder(root) == []+def test_custom_inventory_groups_nested_gguf_files_once(tmp_path):+ """A model folder is one picker row whose GGUF files are its variants.++ The generic custom-folder scan already publishes that directory. The LM+ Studio compatibility pass must not also publish every GGUF inside it as a+ second top-level model.+ """+ root = tmp_path / "hub"+ model_dir = root / "qwen38-27b-qat"+ model_dir.mkdir(parents = True)+ for quant in ("q2_0", "q3_k_m"):+ (model_dir / f"qwen38-27b-qat-{quant}.gguf").write_bytes(b"GGUF")++ rows = local_inventory._scan_custom_folder(root)++ assert [Path(row.path) for row in rows] == [model_dir]+++def test_custom_inventory_keeps_lmstudio_publisher_model_layout(tmp_path):+ root = tmp_path / "lmstudio"+ model_dir = root / "publisher" / "model"+ model_dir.mkdir(parents = True)+ (model_dir / "model-q4_k_m.gguf").write_bytes(b"GGUF")++ rows = local_inventory._scan_custom_folder(root)++ assert [(Path(row.path), row.model_id) for row in rows] == [(model_dir, "publisher/model")]+++def test_custom_inventory_keeps_file_row_beneath_partial_group(tmp_path, monkeypatch):+ root = tmp_path / "hub"+ model_dir = root / "model"+ model_dir.mkdir(parents = True)+ model_file = model_dir / "model-q4_k_m.gguf"+ model_file.write_bytes(b"GGUF")+ partial_group = model_common._local_model_info(+ scan_path = model_dir,+ load_path = model_dir,+ source = "hf_cache",+ model_format = "gguf",+ model_id = "publisher/model",+ partial = True,+ )+ complete_file = model_common._local_model_info(+ scan_path = model_file,+ load_path = model_file,+ source = "lmstudio",+ model_format = "gguf",+ )+ monkeypatch.setattr(local_inventory, "_scan_models_dir", lambda *_a, **_kw: [])+ monkeypatch.setattr(+ local_inventory,+ "_scan_hf_cache",+ lambda *_a, **_kw: [partial_group],+ )+ monkeypatch.setattr(+ local_inventory,+ "_scan_lmstudio_dir",+ lambda *_a, **_kw: [complete_file],+ )+ monkeypatch.setattr(local_inventory, "scan_ollama_dir", lambda *_a, **_kw: [])++ assert local_inventory._scan_custom_folder(root) == [partial_group, complete_file]++def test_unregistered_variant_identity_stays_scan_relative(tmp_path):from utils.models.model_config import list_local_gguf_variants@@ -919,6 +984,30 @@ def test_local_inventory_scan_stops_retrying_under_constant_invalidation(monkeypassert local_inventory._local_inventory_flights == {}+def test_local_inventory_filters_and_dedupes_off_event_loop(monkeypatch):+ main_thread = threading.get_ident()+ worker_threads = []+ original_dedupe = local_inventory._dedupe_local_models++ async def collect(*_args, **_kwargs):+ return []++ def record_dedupe(rows):+ worker_threads.append(threading.get_ident())+ return original_dedupe(rows)++ monkeypatch.setattr(local_inventory, "_collect_models_from_default_sources", collect)+ monkeypatch.setattr(local_inventory, "_dedupe_local_models", record_dedupe)++ asyncio.run(+ local_inventory._scan_local_models_response(+ "./models", [], local_inventory._local_inventory_sources()+ )+ )++ assert worker_threads and worker_threads[0] != main_thread++@pytest.mark.parametrize("change_kind", ["folders", "epoch"])def test_local_inventory_requests_share_scan(monkeypatch, change_kind):# What the flight key needs from the helper is that it is total and stable ondiff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex 123cf5f2a07..eb52d898cd6 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -456,6 +456,340 @@ def gguf_variant_family(filename: str) -> str:return _unknown_gguf_variant_key(filename)+def gguf_checkpoint_family(filename: str) -> Optional[str]:+ """the exact checkpoint name shared by quant variants, or ``None`` when unnamed."""+ path = filename.replace("\\", "/")+ family_parts = gguf_variant_family(path).split("/")+ basename = family_parts.pop()+ family_parts = [+ segment for segment in family_parts if segment and not _is_quant_directory(segment)+ ]+ quant = quant_token_with_bpw(basename)+ if quant is not None:+ basename = re.sub(re.escape(quant), "", basename, count = 1, flags = re.IGNORECASE)+ family = "/".join((*family_parts, basename))+ return family.strip("-_. /\t\r\n") or None+++def local_path_physical_identity(raw_path: str) -> str:+ """Identity for an existing local path without folding valid filename characters."""+ try:+ path = os.path.realpath(os.path.expanduser(raw_path))+ stat = os.stat(path)+ if stat.st_ino:+ return "\x00".join(("stat", str(stat.st_dev), str(stat.st_ino)))+ return f"path\x00{path}"+ except (OSError, UnicodeError, ValueError):+ return f"path\x00{os.path.abspath(os.path.expanduser(raw_path))}"+++def should_group_local_gguf_files(filenames: Sequence[str]) -> bool:+ """Whether filenames are variants of one selectable checkpoint."""+ if len(filenames) == 1:+ return True++ families = {gguf_checkpoint_family(filename) for filename in filenames}+ variant_keys = [gguf_variant_key(filename) for filename in filenames]+ exact_families_by_variant: dict[str, set[str]] = {}+ for filename, variant_key in zip(filenames, variant_keys):+ exact_families_by_variant.setdefault(variant_key.casefold(), set()).add(+ gguf_variant_family(filename)+ )+ has_ambiguous_variant = any(+ len(exact_families) > 1 for exact_families in exact_families_by_variant.values()+ )+ return (+ not has_ambiguous_variant+ and (families == {None} or (None not in families and len(families) == 1))+ ) or all(is_h3_denoiser_variant_key(key) for key in variant_keys)+++def suppress_grouped_gguf_file_rows(rows: Sequence[object]) -> list:+ """Drop rows already represented by a physical GGUF directory row."""+ from utils.models.model_config import _extract_quant_label as _loader_quant++ def row_path_is_dir(row) -> bool:+ try:+ return Path(getattr(row, "path", "")).is_dir()+ except OSError:+ return False++ grouped_rows = [+ (row, Path(os.path.abspath(os.path.expanduser(getattr(row, "path", "")))))+ for row in rows+ if getattr(row, "model_format", None) == "gguf"+ and not getattr(row, "partial", False)+ and row_path_is_dir(row)+ ]+ if not grouped_rows:+ return list(rows)++ paths_by_group = {+ id(row): list(iter_gguf_files(directory, recursive = True)) for row, directory in grouped_rows+ }+ physical_ancestors_by_group = {+ id(row): {+ local_path_physical_identity(str(parent))+ for parent in Path(os.path.realpath(directory)).parents+ }+ for row, directory in grouped_rows+ }+ families_by_group = {}+ for row, directory in grouped_rows:+ families_by_file = {}+ for file in paths_by_group[id(row)]:+ try:+ filename = str(file.relative_to(directory))+ except ValueError:+ filename = file.name+ if (+ is_mmproj_filename(file.name)+ or is_imatrix_filename(file.name)+ or is_mtp_drafter_path(filename)+ or is_appledouble_metadata(file)+ or is_big_endian_gguf_path(filename, _loader_quant(filename))+ ):+ continue+ file_identity = local_path_physical_identity(str(file))+ families_by_file.setdefault(file_identity, set()).add(gguf_checkpoint_family(filename))+ families_by_group[id(row)] = families_by_file++ nested_groups_to_drop = set()+ for row, directory in grouped_rows:+ families_by_file = families_by_group[id(row)]+ if not families_by_file:+ continue+ physical_ancestors = physical_ancestors_by_group[id(row)]+ for parent_row, parent_directory in grouped_rows:+ if row is parent_row:+ continue+ parent_families_by_file = families_by_group[id(parent_row)]+ parent_identity = local_path_physical_identity(getattr(parent_row, "path", ""))+ try:+ lexically_nested = bool(directory.relative_to(parent_directory).parts)+ except ValueError:+ lexically_nested = False+ matching_families = [+ families & parent_families_by_file.get(file_identity, set())+ for file_identity, families in families_by_file.items()+ ]+ outside_families = set().union(+ *(+ families+ for file_identity, families in parent_families_by_file.items()+ if file_identity not in families_by_file+ )+ )+ if (+ (lexically_nested or parent_identity in physical_ancestors)+ and all(matching_families)+ and (+ not outside_families+ or all(families & outside_families for families in matching_families)+ )+ ):+ nested_groups_to_drop.add(id(row))+ break++ filtered = []+ for row in rows:+ if id(row) in nested_groups_to_drop:+ continue+ if getattr(row, "model_format", None) == "gguf" and not row_path_is_dir(row):+ path = getattr(row, "path", "")+ loose_path = Path(os.path.abspath(os.path.expanduser(path)))+ file_identity = local_path_physical_identity(path)+ family = gguf_checkpoint_family(Path(path).name)+ resolved_parent = Path(os.path.realpath(loose_path.parent))+ physical_parent_ancestry = {+ local_path_physical_identity(str(parent))+ for parent in (resolved_parent, *resolved_parent.parents)+ }+ for grouped_row, directory in grouped_rows:+ grouped_families = families_by_group[id(grouped_row)].get(file_identity, set())+ if not grouped_families:+ continue+ try:+ lexically_nested = bool(loose_path.relative_to(directory).parts)+ except ValueError:+ lexically_nested = False+ grouped_identity = local_path_physical_identity(getattr(grouped_row, "path", ""))+ if (+ not lexically_nested and grouped_identity not in physical_parent_ancestry+ ) or family in grouped_families:+ break+ else:+ filtered.append(row)+ continue+ continue+ filtered.append(row)+ return filtered+++def dedupe_custom_gguf_rows(rows: Sequence[object]) -> list:+ """Remove scanner overlap while preserving independently loadable GGUF checkpoints."""+ from utils.models.model_config import colocated_split_shards++ def row_path_is_dir(row) -> bool:+ try:+ return Path(getattr(row, "path", "")).is_dir()+ except OSError:+ return False++ deduped = list(rows)+ split_groups: dict[tuple[str, ...], list[tuple[object, Path, list[Path]]]] = {}+ for row in deduped:+ path = Path(getattr(row, "path", ""))+ if (+ getattr(row, "source", None) not in {"models_dir", "lmstudio"}+ or getattr(row, "model_format", None) != "gguf"+ or getattr(row, "partial", False)+ or row_path_is_dir(row)+ ):+ continue+ shards, complete = colocated_split_shards(path)+ if not complete or len(shards) < 2:+ continue+ key = tuple(local_path_physical_identity(str(shard)) for shard in shards)+ split_groups.setdefault(key, []).append((row, path, shards))++ dropped_rows: set[int] = set()+ replacement_rows: dict[int, object] = {}+ for candidates in split_groups.values():+ shards = candidates[0][2]+ first_identity = local_path_physical_identity(str(shards[0]))+ chosen = next(+ (+ row+ for row, path, _shards in candidates+ if local_path_physical_identity(str(path)) == first_identity+ ),+ None,+ )+ if chosen is None:+ continue+ for row, _path, _shards in candidates:+ if row is not chosen:+ dropped_rows.add(id(row))+ if hasattr(chosen, "size_bytes"):+ size_bytes = 0+ for shard in shards:+ try:+ size_bytes += shard.stat().st_size+ except OSError:+ pass+ replacement_rows[id(chosen)] = chosen.model_copy(update = {"size_bytes": size_bytes})++ deduped = [replacement_rows.get(id(row), row) for row in deduped if id(row) not in dropped_rows]++ grouped_dirs = {+ local_path_physical_identity(getattr(row, "path", ""))+ for row in deduped+ if getattr(row, "source", None) != "lmstudio"+ and getattr(row, "model_format", None) == "gguf"+ and not getattr(row, "partial", False)+ and row_path_is_dir(row)+ }+ gguf_dirs = [+ Path(getattr(row, "path", ""))+ for row in deduped+ if getattr(row, "model_format", None) == "gguf"+ and not getattr(row, "partial", False)+ and row_path_is_dir(row)+ ]+ files_by_parent: dict[str, list[Path]] = {}+ for row in deduped:+ path = Path(getattr(row, "path", ""))+ if (+ getattr(row, "source", None) == "lmstudio"+ and getattr(row, "model_format", None) == "gguf"+ and not getattr(row, "partial", False)+ and not row_path_is_dir(row)+ ):+ files_by_parent.setdefault(local_path_physical_identity(str(path.parent)), []).append(+ path+ )++ grouped_decisions = {+ parent: should_group_local_gguf_files([path.name for path in files])+ for parent, files in files_by_parent.items()+ if parent in grouped_dirs+ }+ if not grouped_decisions:+ return deduped++ grouped_paths = {+ local_path_physical_identity(str(path)): path+ for path in gguf_dirs+ if local_path_physical_identity(str(path)) in grouped_decisions+ }+ nested_groups_to_drop: set[str] = set()+ for parent_identity, parent_path in grouped_paths.items():+ nested_paths = []+ for candidate in gguf_dirs:+ if candidate == parent_path:+ continue+ try:+ candidate.relative_to(parent_path)+ except ValueError:+ continue+ nested_paths.append(candidate)+ if not nested_paths:+ continue++ filenames = [path.name for path in files_by_parent[parent_identity]]+ nested_identities = set()+ parent_visible_files = {+ local_path_physical_identity(str(file))+ for file in iter_gguf_files(parent_path, recursive = True)+ }+ for nested_path in nested_paths:+ nested_identities.add(local_path_physical_identity(str(nested_path)))+ try:+ relative_parent = nested_path.relative_to(parent_path)+ nested_files = [+ file+ for file in nested_path.iterdir()+ if file.is_file()+ and is_gguf_filename(file.name)+ and not is_mmproj_filename(file.name)+ and not is_imatrix_filename(file.name)+ and not is_mtp_drafter_path(file.name)+ and not is_appledouble_metadata(file)+ ]+ except OSError:+ grouped_decisions[parent_identity] = False+ break+ if not nested_files or any(+ local_path_physical_identity(str(file)) not in parent_visible_files+ for file in nested_files+ ):+ grouped_decisions[parent_identity] = False+ break+ filenames.extend(str(relative_parent / file.name) for file in nested_files)+ else:+ grouped_decisions[parent_identity] = should_group_local_gguf_files(filenames)+ if grouped_decisions[parent_identity]:+ nested_groups_to_drop.update(nested_identities)++ filtered = []+ for row in deduped:+ path = Path(getattr(row, "path", ""))+ is_dir = row_path_is_dir(row)+ identity = local_path_physical_identity(str(path if is_dir else path.parent))+ keep_group = grouped_decisions.get(identity)+ if getattr(row, "model_format", None) == "gguf" and (+ (+ keep_group is not None+ and ((is_dir and not keep_group) or (not is_dir and keep_group))+ )+ or (is_dir and local_path_physical_identity(str(path)) in nested_groups_to_drop)+ ):+ continue+ filtered.append(row)+ return filtered++def extract_quant_label(filename: str) -> str:return extract_quant_token(filename) or _unknown_gguf_variant_key(filename)diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 840ace5fa30..a0f9d256881 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -1030,6 +1030,7 @@ def collect_local_models(must already be validated/trusted by the caller."""from storage.studio_db import list_scan_folders+ from hub.utils import gguf as gguf_utilsfrom utils.models.model_config import detect_gguf_modelsources = sources or _compat_local_inventory_sources()@@ -1138,6 +1139,7 @@ def collect_local_models(is not None):custom_models.append(model)+ custom_models = gguf_utils.dedupe_custom_gguf_rows(custom_models)if len(custom_models) < _MAX_MODELS_PER_FOLDER:custom_models += _scan_ollama_dir(folder_path,@@ -1156,7 +1158,19 @@ def collect_local_models(deduped: dict[str, LocalModelInfo] = {}for model in local_models:semantic_id = model.model_id if model.source == "hf_cache" and model.model_id else model.id- key = f"{semantic_id}\x00custom" if model.source == "custom" else semantic_id+ if model.source == "custom":+ physical_identity = gguf_utils.local_path_physical_identity(model.path)+ if (+ model.model_id+ and model.model_id.startswith("ollama/")+ and any(+ part in (".studio_links", "ollama_links") for part in Path(model.path).parts+ )+ ):+ physical_identity = "\x00".join((model.model_id, physical_identity))+ key = "\x00".join((physical_identity, model.model_format or "", "custom"))+ else:+ key = semantic_idexisting = deduped.get(key)prefer_model = existing is Noneif existing is not None and model.source == existing.source == "hf_cache":@@ -1169,8 +1183,11 @@ def collect_local_models(if prefer_model:deduped[key] = model+ deduped_values = list(deduped.values())+ custom_values = [model for model in deduped_values if model.source == "custom"]models = sorted(- deduped.values(),+ [model for model in deduped_values if model.source != "custom"]+ + gguf_utils.suppress_grouped_gguf_file_rows(custom_values),key = lambda item: item.updated_at or 0,reverse = True,)diff --git a/studio/backend/tests/test_local_model_format.py b/studio/backend/tests/test_local_model_format.pyindex 3e70a817257..c57b2b0a23a 100644--- a/studio/backend/tests/test_local_model_format.py+++ b/studio/backend/tests/test_local_model_format.py@@ -42,6 +42,214 @@ def _touch(path: Path) -> Path:return path+def _empty_compat_sources(tmp_path: Path):+ empty = tmp_path / "empty"+ return models_route._CompatLocalInventorySources(+ empty / "active",+ empty / "legacy",+ empty / "default",+ (),+ (),+ )+++def test_compat_inventory_groups_custom_gguf_variants(tmp_path):+ root = tmp_path / "custom"+ model = root / "publisher"+ _touch(model / "model-Q4_K_M.gguf")+ _touch(model / "model-Q8_0.gguf")++ rows = models_route.collect_local_models(+ tmp_path / "models",+ custom_folders = [{"path": str(root)}],+ sources = _empty_compat_sources(tmp_path),+ )++ assert [(row.source, Path(row.path)) for row in rows] == [("custom", model)]+++def test_compat_inventory_preserves_distinct_custom_ggufs(tmp_path):+ root = tmp_path / "custom"+ holder = root / "publisher"+ first = _touch(holder / "model-a-Q4_K_M.gguf")+ second = _touch(holder / "model-b-Q4_K_M.gguf")++ rows = models_route.collect_local_models(+ tmp_path / "models",+ custom_folders = [{"path": str(root)}],+ sources = _empty_compat_sources(tmp_path),+ )++ assert {Path(row.path) for row in rows} == {first, second}+++def test_compat_inventory_dedupes_overlapping_custom_roots(tmp_path):+ root = tmp_path / "custom"+ model = root / "publisher"+ _touch(model / "model-Q4_K_M.gguf")+ _touch(model / "model-Q8_0.gguf")++ rows = models_route.collect_local_models(+ tmp_path / "models",+ custom_folders = [{"path": str(root)}, {"path": str(model)}],+ sources = _empty_compat_sources(tmp_path),+ )++ assert [(row.source, Path(row.path)) for row in rows] == [("custom", model)]+++def test_compat_inventory_dedupes_nested_quant_root(tmp_path):+ root = tmp_path / "custom"+ model = root / "publisher"+ _touch(model / "model-a-Q4_K_M.gguf")+ quant_dir = model / "Q8_0"+ _touch(quant_dir / "model-a-Q8_0.gguf")+ (quant_dir / "config.json").write_text("{}", encoding = "utf-8")++ rows = models_route.collect_local_models(+ tmp_path / "models",+ custom_folders = [{"path": str(root)}, {"path": str(quant_dir)}],+ sources = _empty_compat_sources(tmp_path),+ )++ assert [(row.source, Path(row.path)) for row in rows] == [("custom", model)]+++def test_compat_inventory_preserves_nested_independent_model_root(tmp_path):+ root = tmp_path / "custom"+ parent = root / "parent"+ _touch(parent / "parent-Q4_K_M.gguf")+ (parent / "config.json").write_text("{}", encoding = "utf-8")+ child = parent / "child"+ _touch(child / "child-Q8_0.gguf")+ (child / "config.json").write_text("{}", encoding = "utf-8")++ rows = models_route.collect_local_models(+ tmp_path / "models",+ custom_folders = [{"path": str(root)}, {"path": str(child)}],+ sources = _empty_compat_sources(tmp_path),+ )++ assert {(row.source, Path(row.path)) for row in rows} == {+ ("custom", parent),+ ("custom", child),+ }+++def test_compat_inventory_keeps_custom_section_copy(tmp_path):+ root = tmp_path / "models"+ model = root / "publisher"+ q4 = _touch(model / "model-Q4_K_M.gguf")+ q8 = _touch(model / "model-Q8_0.gguf")++ rows = models_route.collect_local_models(+ root,+ custom_folders = [{"path": str(model)}],+ sources = _empty_compat_sources(tmp_path),+ )++ assert {(row.source, Path(row.path)) for row in rows} == {+ ("models_dir", model),+ ("custom", q4),+ ("custom", q8),+ }+++def test_compat_inventory_does_not_cross_dedupe_default_sources(tmp_path):+ root = tmp_path / "models"+ holder = root / "publisher"+ first = _touch(holder / "model-a-Q4_K_M.gguf")+ second = _touch(holder / "model-b-Q4_K_M.gguf")+ empty = _empty_compat_sources(tmp_path)+ sources = empty._replace(lm_dirs = (root,))++ rows = models_route.collect_local_models(+ root,+ custom_folders = [],+ sources = sources,+ )++ assert {(row.source, Path(row.path)) for row in rows} == {+ ("models_dir", holder),+ ("lmstudio", first),+ ("lmstudio", second),+ }+++def test_compat_inventory_preserves_ollama_tags_sharing_a_blob(tmp_path):+ root = tmp_path / "ollama"+ digest = "sha256-model"+ _touch(root / "blobs" / digest)+ manifest = json.dumps(+ {+ "layers": [+ {+ "mediaType": "application/vnd.ollama.image.model",+ "digest": digest.replace("-", ":", 1),+ }+ ]+ }+ )+ tags = root / "manifests" / "registry.ollama.ai" / "library" / "model"+ tags.mkdir(parents = True)+ for tag in ("latest", "v1"):+ (tags / tag).write_text(manifest, encoding = "utf-8")++ rows = models_route.collect_local_models(+ tmp_path / "models",+ custom_folders = [{"path": str(root)}],+ sources = _empty_compat_sources(tmp_path),+ )++ assert {row.model_id for row in rows} == {"ollama/model:latest", "ollama/model:v1"}+++def test_compat_inventory_preserves_same_ollama_tag_from_distinct_stores(tmp_path):+ roots = [tmp_path / "ollama-one", tmp_path / "ollama-two"]+ for index, root in enumerate(roots):+ digest = f"sha256-model-{index}"+ _touch(root / "blobs" / digest)+ tag = root / "manifests" / "registry.ollama.ai" / "library" / "model" / "latest"+ tag.parent.mkdir(parents = True)+ tag.write_text(+ json.dumps(+ {+ "layers": [+ {+ "mediaType": "application/vnd.ollama.image.model",+ "digest": digest.replace("-", ":", 1),+ }+ ]+ }+ ),+ encoding = "utf-8",+ )++ rows = models_route.collect_local_models(+ tmp_path / "models",+ custom_folders = [{"path": str(root)} for root in roots],+ sources = _empty_compat_sources(tmp_path),+ )++ assert [row.model_id for row in rows] == ["ollama/model:latest"] * 2+ assert len({Path(row.path).resolve() for row in rows}) == 2+++def test_compat_inventory_dedupes_lmstudio_publisher_named_ollama(tmp_path):+ root = tmp_path / "lmstudio"+ model = root / "ollama" / "foo"+ _touch(model / "foo-Q4_K_M.gguf")+ (model / "config.json").write_text("{}", encoding = "utf-8")++ rows = models_route.collect_local_models(+ tmp_path / "models",+ custom_folders = [{"path": str(root)}, {"path": str(model)}],+ sources = _empty_compat_sources(tmp_path),+ )++ assert [Path(row.path) for row in rows] == [model]++def test_local_adapter_chat_capability_uses_its_local_base(tmp_path):from hub.services.models.common import _classify_local_pathdiff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex be3dfdf48db..3f92eda2f6d 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -2578,6 +2578,52 @@ def test_build_index_survives_a_failing_scanner(tmp_path, monkeypatch):assert any(e.loader_id == "org/Repo-GGUF" for e in index.values())+def test_build_index_groups_overlapping_custom_gguf_roots(tmp_path, monkeypatch):+ import routes.models as models_route+ from storage import studio_db+ from utils import hf_cache_settings+ import utils.paths as paths++ root = tmp_path / "custom"+ model = root / "publisher"+ model.mkdir(parents = True)+ (model / "model-Q4_K_M.gguf").write_bytes(b"x")+ quant_dir = model / "Q8_0"+ quant_dir.mkdir()+ (quant_dir / "model-Q8_0.gguf").write_bytes(b"xx")+ (quant_dir / "config.json").write_text("{}", encoding = "utf-8")+ scan_models_dir = models_route._scan_models_dir+ scan_lmstudio_dir = models_route._scan_lmstudio_dir++ monkeypatch.setattr(+ models_route,+ "_scan_models_dir",+ lambda path, **kwargs: scan_models_dir(path, **kwargs) if path in {root, quant_dir} else [],+ )+ monkeypatch.setattr(+ models_route,+ "_scan_lmstudio_dir",+ lambda path: scan_lmstudio_dir(path) if path in {root, quant_dir} else [],+ )+ monkeypatch.setattr(models_route, "_scan_hf_cache", lambda *a, **k: [])+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: tmp_path / "active")+ monkeypatch.setattr(models_route, "_is_hidden_model", lambda *a, **k: False)+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [])+ monkeypatch.setattr(paths, "legacy_hf_cache_dir", lambda: None)+ monkeypatch.setattr(paths, "hf_default_cache_dir", lambda: None)+ monkeypatch.setattr(paths, "lmstudio_model_dirs", lambda: [])+ monkeypatch.setattr(+ studio_db,+ "list_scan_folders",+ lambda: [{"path": str(root)}, {"path": str(quant_dir)}],+ )++ index = resolver._build_index()++ assert {entry.load_path for entry in index.values()} == {str(model)}+ assert {entry.variants for entry in index.values()} == {("Q4_K_M", "Q8_0")}++def test_non_gguf_entries_skip_gguf_sibling_revision_scans(tmp_path, monkeypatch):from types import SimpleNamespace