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
Studio: say when a scan folder cannot be read instead of showing no models (#9053)
Michael Han0eb6b6c93110
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.pyindex 2210398b666..75f713b53cc 100644--- a/studio/backend/hub/schemas/inventory.py+++ b/studio/backend/hub/schemas/inventory.py@@ -288,6 +288,10 @@ class ScanFolderInfo(BaseModel):id: int = Field(..., description = "Database row ID")path: str = Field(..., description = "Normalized absolute path")created_at: str = Field(..., description = "ISO 8601 creation timestamp")+ status: str = Field(+ default = "ok",+ description = "Last scan result: ok, permission_denied, missing, or unreadable",+ )class ScanFoldersResponse(BaseModel):diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex 10747cbe601..a929830b409 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -37,6 +37,12 @@ from hub.utils.paths import (from hub.services.models import common as model_commonfrom hub.services.models.ollama import scan_ollama_dirfrom utils.hidden_models import is_hidden_model+from utils.paths.scan_folder_health import (+ annotate_scan_folders,+ note_scan_folder_scanned,+ record_scan_failure,+ refresh_failed_scan_folders,+)logger = get_logger(__name__)_MAX_MODELS_PER_CUSTOM_FOLDER = 200@@ -689,7 +695,9 @@ async def _collect_models_from_default_sources(lambda path: _discover_hf_cache(path, entry_limit = _MAX_CUSTOM_FOLDER_ENTRIES),folder_path,)- custom_sources.append((folder_path, discovered))+ # Carry the registered path: the status registry is keyed on the row, not+ # on the normalized Path this scan walks.+ custom_sources.append((folder_path, discovered, str(folder["path"])))state_repositories.extend(("model", model_id, folder_path) for _repo, model_id, _updated in discovered)@@ -721,7 +729,7 @@ async def _collect_models_from_default_sources(for ollama_dir in ollama_dirs:local_models += await _scan_source("Ollama", scan_ollama_dir, ollama_dir)- for folder_path, discovered in custom_sources:+ for folder_path, discovered, row_path in custom_sources:try:custom_models = await asyncio.to_thread(_scan_custom_folder,@@ -732,7 +740,13 @@ async def _collect_models_from_default_sources()except Exception as e:logger.warning("Skipping unreadable scan folder %s: %s", folder_path, e)+ # Only an OS failure is something the user can fix, so only that is shown.+ if isinstance(e, OSError):+ record_scan_failure(row_path, e)continue+ # Off the loop, like the scan above it: the probe opens directories, and on a+ # stalled network mount scandir sits in the kernel with nothing to yield to.+ await asyncio.to_thread(note_scan_folder_scanned, row_path, found = bool(custom_models))local_models.extend(_promote_to_custom_source(model) for model in custom_models)return local_models@@ -1019,7 +1033,10 @@ def get_models_folder_response() -> dict:def get_scan_folders_response() -> dict:- return {"folders": list_scan_folders()}+ folders = list_scan_folders()+ # Opening the dialog is how a fixed folder clears, so recheck the bad ones.+ refresh_failed_scan_folders(folders)+ return {"folders": annotate_scan_folders(folders)}def add_scan_folder_response(path: str) -> dict:diff --git a/studio/backend/hub/storage/scan_folders.py b/studio/backend/hub/storage/scan_folders.pyindex a88317662ec..c19f43fac9a 100644--- a/studio/backend/hub/storage/scan_folders.py+++ b/studio/backend/hub/storage/scan_folders.py@@ -17,6 +17,7 @@ from datetime import datetime, timezonefrom storage.studio_db import get_connectionfrom hub.utils.paths import normalize_pathfrom utils.paths.external_media import is_linux_run_media_path, is_local_filesystem_root+from utils.paths.scan_folder_health import is_readable_dirfrom utils.paths.sensitive import (contains_sensitive_path_component as _shared_contains_sensitive_path_component,)@@ -125,8 +126,6 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:raise ValueError("Path does not exist")if not os.path.isdir(normalized):raise ValueError("Path must be a directory, not a file")- if not os.access(normalized, os.R_OK | os.X_OK):- raise ValueError("Path is not readable")if is_local_filesystem_root(normalized):# A local fs root ("/", "C:\\") would expose denied system dirs via browse;# a UNC share root (\\server\share) has none under it and stays registerable.@@ -142,6 +141,10 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:continueraise ValueError(f"Path under {prefix} is not allowed")+ # Last, so a denied path is never opened. Mirrors studio_db.py.+ if not is_readable_dir(normalized):+ raise ValueError("Path is not readable")+conn = get_connection()try:_ensure_schema(conn)diff --git a/studio/backend/models/models.py b/studio/backend/models/models.pyindex b4adf0614d0..4ae90080557 100644--- a/studio/backend/models/models.py+++ b/studio/backend/models/models.py@@ -283,6 +283,10 @@ class ScanFolderInfo(BaseModel):id: int = Field(..., description = "Database row ID")path: str = Field(..., description = "Normalized absolute path")created_at: str = Field(..., description = "ISO 8601 creation timestamp")+ status: str = Field(+ default = "ok",+ description = "Last scan result: ok, permission_denied, missing, or unreadable",+ )class BrowseEntry(BaseModel):diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 77c7660bbcc..28bf3745b9f 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -72,6 +72,13 @@ def _safe_is_dir(path) -> bool:return False+from utils.paths.scan_folder_health import (+ annotate_scan_folders,+ note_scan_folder_scanned,+ record_scan_failure,+ refresh_failed_scan_folders,+)+# Shared with the hub inventory scans; private aliases kept for existing importers.# ``_HF_REPO_ID_RE`` is the Hub repo id shape ("owner/name"); anything else is a path.from utils.hidden_models import (@@ -1015,7 +1022,10 @@ def collect_local_models()except OSError as e:logger.warning("Skipping unreadable scan folder %s: %s", folder_path, e)+ # Keep the reason so the folder list can show it instead of nothing.+ record_scan_failure(str(folder.get("path", folder_path)), e)continue+ note_scan_folder_scanned(str(folder.get("path", folder_path)), found = bool(custom_models))local_models += [m.model_copy(update = {"source": "custom"}) for m in custom_models]# Deduplicate, but always keep custom folder entries (keyed by (id, source)) so they show@@ -1206,7 +1216,11 @@ async def list_local_models(async def get_scan_folders(current_subject: str = Depends(get_current_subject)):"""List all registered custom model scan folders."""from storage.studio_db import list_scan_folders- return {"folders": list_scan_folders()}++ folders = list_scan_folders()+ # Opening the dialog is how a fixed folder clears, so recheck the bad ones.+ await asyncio.to_thread(refresh_failed_scan_folders, folders)+ return {"folders": annotate_scan_folders(folders)}@router.post("/scan-folders", response_model = ScanFolderInfo, status_code = 201)diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex a373dc35fd1..ef707a79917 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -29,6 +29,7 @@ from utils.paths import (studio_db_path,)from utils.paths.external_media import is_linux_run_media_path, is_local_filesystem_root+from utils.paths.scan_folder_health import is_readable_dirfrom utils.paths.sensitive import (contains_sensitive_path_component as _shared_contains_sensitive_path_component,)@@ -1548,8 +1549,6 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:raise ValueError("Path does not exist")if not os.path.isdir(normalized):raise ValueError("Path must be a directory, not a file")- if not os.access(normalized, os.R_OK | os.X_OK):- raise ValueError("Path is not readable")# Reject a local filesystem root ("/", or a bare "C:\\"): registering one seeds the browse# allowlist above denied system dirs. A UNC share root has none under it, so it stays# allowed (it was registerable before this guard). Mirrors scan_folders.py.@@ -1567,6 +1566,12 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:continueraise ValueError(f"Path under {prefix} is not allowed")+ # Last, so a denied path is never opened: os.access alone passes on folders+ # macOS TCC or a Windows ACL still refuses at scan time, which is how a+ # registered folder ends up looking empty instead of blocked.+ if not is_readable_dir(normalized):+ raise ValueError("Path is not readable")+conn = get_connection()try:now = datetime.now(timezone.utc).isoformat()diff --git a/studio/backend/tests/test_linux_external_media_paths.py b/studio/backend/tests/test_linux_external_media_paths.pyindex 8373cdd6bb2..9fb482cf408 100644--- a/studio/backend/tests/test_linux_external_media_paths.py+++ b/studio/backend/tests/test_linux_external_media_paths.py@@ -56,6 +56,9 @@ def _stub_linux_path_checks(monkeypatch, module):monkeypatch.setattr(module.os.path, "exists", lambda _p: True)monkeypatch.setattr(module.os.path, "isdir", lambda _p: True)monkeypatch.setattr(module.os, "access", lambda _p, _mode: True)+ # The mount does not exist on the test host, so the readability probe that+ # opens the directory has to be part of the same pretence.+ monkeypatch.setattr(module, "is_readable_dir", lambda _p: True)def _stub_hub_scan_folder_db(monkeypatch):diff --git a/studio/backend/tests/test_scan_folder_health.py b/studio/backend/tests/test_scan_folder_health.pynew file mode 100644index 00000000000..f7359278a37--- /dev/null+++ b/studio/backend/tests/test_scan_folder_health.py@@ -0,0 +1,857 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A registered folder Unsloth cannot read must say so, not look empty.++Covers the add-time probe (os.access alone passes paths macOS TCC still+refuses), the status the scan records when a folder stops being readable, and+that reading the status back never touches the disk.+"""++import errno+import os+import stat+from pathlib import Path++import pytest++from utils.paths.scan_folder_health import (+ STATUS_MISSING,+ STATUS_OK,+ STATUS_PARTIAL,+ STATUS_PERMISSION_DENIED,+ STATUS_UNKNOWN,+ STATUS_UNREADABLE,+ annotate_scan_folders,+ classify_scan_error,+ clear_scan_failure,+ is_readable_dir,+ note_scan_folder_scanned,+ probe_folder,+ probe_status,+ record_scan_failure,+ refresh_failed_scan_folders,+ scan_folder_status,+)+++# os.geteuid is missing on Windows, and a skipif condition is evaluated at import,+# so the check has to be resolved before the decorator sees it.+requires_posix_permissions = pytest.mark.skipif(+ os.name == "nt" or getattr(os, "geteuid", lambda: 0)() == 0,+ reason = "needs POSIX mode bits and a non-root user",+)++[email protected](autouse = True)+def _clean_registry():+ """Each test starts with no remembered failures."""+ import utils.paths.scan_folder_health as health++ health._failed.clear()+ yield+ health._failed.clear()+++def test_a_readable_directory_passes_the_probe(tmp_path: Path):+ (tmp_path / "model.gguf").write_bytes(b"stub")+ assert is_readable_dir(str(tmp_path)) is True+++def test_an_empty_directory_still_passes(tmp_path: Path):+ # Nothing to list is not the same as refusing to list.+ empty = tmp_path / "empty"+ empty.mkdir()+ assert is_readable_dir(str(empty)) is True+++@requires_posix_permissions+def test_a_chmod_000_directory_fails_the_probe(tmp_path: Path):+ denied = tmp_path / "denied"+ denied.mkdir()+ (denied / "model.gguf").write_bytes(b"stub")+ denied.chmod(0o000)+ try:+ assert is_readable_dir(str(denied)) is False+ finally:+ denied.chmod(stat.S_IRWXU)+++def test_the_probe_catches_what_os_access_misses(tmp_path: Path, monkeypatch):+ """The macOS TCC shape: mode bits say yes, opening the directory says no.++ This is the case the old os.access-only check accepted, which then showed+ the user a folder with no models in it and no reason why.+ """+ (tmp_path / "model.gguf").write_bytes(b"stub")+ assert os.access(str(tmp_path), os.R_OK | os.X_OK) is True++ def _refuse(path, *args, **kwargs):+ raise PermissionError(errno.EPERM, "Operation not permitted", str(path))++ monkeypatch.setattr(os, "scandir", _refuse)+ assert is_readable_dir(str(tmp_path)) is False+++def test_a_missing_directory_fails_the_probe(tmp_path: Path):+ assert is_readable_dir(str(tmp_path / "gone")) is False+++ "error, expected",+ [+ (PermissionError(errno.EACCES, "Permission denied"), STATUS_PERMISSION_DENIED),+ (PermissionError(errno.EPERM, "Operation not permitted"), STATUS_PERMISSION_DENIED),+ (FileNotFoundError(errno.ENOENT, "No such file or directory"), STATUS_MISSING),+ (NotADirectoryError(errno.ENOTDIR, "Not a directory"), STATUS_MISSING),+ (OSError(errno.EIO, "Input/output error"), STATUS_UNREADABLE),+ (OSError("no errno at all"), STATUS_UNREADABLE),+ ],+)+def test_scan_errors_classify_into_statuses(error: OSError, expected: str):+ assert classify_scan_error(error) == expected+++def test_an_unknown_folder_reports_ok():+ assert scan_folder_status("/models/never-scanned") == STATUS_OK+++def test_a_recorded_failure_is_readable_back():+ record_scan_failure("/models/denied", PermissionError(errno.EACCES, "Permission denied"))+ assert scan_folder_status("/models/denied") == STATUS_PERMISSION_DENIED+++def test_a_folder_that_reads_again_clears_its_failure():+ record_scan_failure("/models/denied", PermissionError(errno.EACCES, "Permission denied"))+ clear_scan_failure("/models/denied")+ assert scan_folder_status("/models/denied") == STATUS_OK+++def test_clearing_an_unknown_folder_is_harmless():+ clear_scan_failure("/models/never-scanned")+ assert scan_folder_status("/models/never-scanned") == STATUS_OK+++def test_the_registry_stays_bounded():+ import utils.paths.scan_folder_health as health+ for i in range(health._MAX_TRACKED + 5):+ record_scan_failure(f"/models/{i}", PermissionError(errno.EACCES, "Permission denied"))+ assert len(health._failed) <= health._MAX_TRACKED+++def test_annotate_marks_healthy_folders_ok():+ rows = [{"id": 1, "path": "/models/a", "created_at": "2026-01-01"}]+ assert annotate_scan_folders(rows) == [+ {"id": 1, "path": "/models/a", "created_at": "2026-01-01", "status": STATUS_OK}+ ]+++def test_annotate_marks_only_the_folder_that_failed():+ record_scan_failure("/models/b", PermissionError(errno.EACCES, "Permission denied"))+ rows = [+ {"id": 1, "path": "/models/a", "created_at": "2026-01-01"},+ {"id": 2, "path": "/models/b", "created_at": "2026-01-02"},+ ]+ statuses = {row["path"]: row["status"] for row in annotate_scan_folders(rows)}+ assert statuses == {"/models/a": STATUS_OK, "/models/b": STATUS_PERMISSION_DENIED}+++def test_annotate_does_not_mutate_the_database_rows():+ rows = [{"id": 1, "path": "/models/a", "created_at": "2026-01-01"}]+ annotate_scan_folders(rows)+ assert "status" not in rows[0]+++def test_a_healthy_folder_costs_a_bounded_number_of_opens(tmp_path: Path, monkeypatch):+ """The scan probes even when models were found, so the bound is the guarantee.++ A denied model sits next to readable ones and nothing raises, so the only way+ to know is to ask, and the only thing keeping that cheap is the open budget.+ """+ import utils.paths.scan_folder_health as health++ for i in range(health._PROBE_OPEN_LIMIT * 4):+ (tmp_path / f"model{i}").mkdir()++ opened: list[str] = []+ real_scandir = os.scandir++ def counting_scandir(path, *args, **kwargs):+ opened.append(str(path))+ return real_scandir(path, *args, **kwargs)++ monkeypatch.setattr(os, "scandir", counting_scandir)+ note_scan_folder_scanned(str(tmp_path), found = True)+ assert scan_folder_status(str(tmp_path)) == STATUS_OK+ assert len(opened) <= health._PROBE_OPEN_LIMIT+++@requires_posix_permissions+def test_a_folder_with_one_denied_model_says_so(tmp_path: Path):+ """Partial denial hides models without the list looking wrong.++ The readable model makes the scan succeed, so nothing raises and nothing is+ empty, yet the denied one is silently absent.+ """+ good = tmp_path / "good"+ good.mkdir()+ (good / "model.gguf").write_bytes(b"stub")+ bad = tmp_path / "bad"+ bad.mkdir()+ bad.chmod(0o000)+ try:+ note_scan_folder_scanned(str(tmp_path), found = True)+ assert scan_folder_status(str(tmp_path)) == STATUS_PARTIAL+ finally:+ bad.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_a_partial_folder_is_not_reported_as_unreadable(tmp_path: Path):+ """The folder works, so the copy must not claim it cannot be read."""+ bad = tmp_path / "bad"+ bad.mkdir()+ bad.chmod(0o000)+ try:+ note_scan_folder_scanned(str(tmp_path), found = True)+ assert scan_folder_status(str(tmp_path)) == STATUS_PARTIAL++ note_scan_folder_scanned(str(tmp_path), found = False)+ assert scan_folder_status(str(tmp_path)) == STATUS_PERMISSION_DENIED+ finally:+ bad.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_the_recheck_keeps_a_partial_folder_partial(tmp_path: Path):+ bad = tmp_path / "bad"+ bad.mkdir()+ bad.chmod(0o000)+ rows = [{"id": 1, "path": str(tmp_path), "created_at": "2026-01-01"}]+ try:+ note_scan_folder_scanned(str(tmp_path), found = True)+ refresh_failed_scan_folders(rows)+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PARTIAL+ finally:+ bad.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_the_real_scan_flags_a_folder_with_one_denied_model(tmp_path: Path):+ from routes.models import collect_local_models++ folder = tmp_path / "models"+ good = folder / "good"+ good.mkdir(parents = True)+ (good / "model.gguf").write_bytes(b"stub")+ (good / "config.json").write_text("{}", encoding = "utf-8")+ bad = folder / "bad"+ bad.mkdir()+ (bad / "model.gguf").write_bytes(b"stub")+ bad.chmod(0o000)+ rows = [{"id": 1, "path": str(folder), "created_at": "2026-01-01"}]+ try:+ found = collect_local_models(tmp_path / "root", custom_folders = list(rows))+ assert [m for m in found if m.source == "custom"], "the readable model still lists"+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PARTIAL+ finally:+ bad.chmod(stat.S_IRWXU)+++def test_a_healthy_folder_stays_ok_when_models_were_found(tmp_path: Path):+ (tmp_path / "model.gguf").write_bytes(b"stub")+ note_scan_folder_scanned(str(tmp_path), found = True)+ assert scan_folder_status(str(tmp_path)) == STATUS_OK+++def test_a_folder_that_disappeared_reports_missing(tmp_path: Path):+ # Unmounted drive or renamed folder: the scanners return nothing, same as empty.+ note_scan_folder_scanned(str(tmp_path / "gone"), found = False)+ assert scan_folder_status(str(tmp_path / "gone")) == STATUS_MISSING+++def test_an_empty_folder_that_is_still_there_stays_ok(tmp_path: Path):+ note_scan_folder_scanned(str(tmp_path), found = False)+ assert scan_folder_status(str(tmp_path)) == STATUS_OK+++@requires_posix_permissions+def test_the_real_scan_records_a_folder_it_cannot_read(tmp_path: Path):+ """End to end through collect_local_models, the scan behind the model list."""+ from routes.models import collect_local_models++ denied = tmp_path / "denied"+ denied.mkdir()+ (denied / "model.gguf").write_bytes(b"stub")+ denied.chmod(0o000)+ rows = [{"id": 1, "path": str(denied), "created_at": "2026-01-01"}]+ try:+ collect_local_models(tmp_path, custom_folders = list(rows))+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PERMISSION_DENIED++ # And it recovers on its own once the folder is readable again.+ denied.chmod(stat.S_IRWXU)+ collect_local_models(tmp_path, custom_folders = list(rows))+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_OK+ finally:+ denied.chmod(stat.S_IRWXU)+++ "winerror, expected",+ [+ (5, STATUS_PERMISSION_DENIED), # ERROR_ACCESS_DENIED+ (65, STATUS_PERMISSION_DENIED), # ERROR_NETWORK_ACCESS_DENIED+ (21, STATUS_MISSING), # ERROR_NOT_READY: nothing in the card reader+ (53, STATUS_MISSING), # ERROR_BAD_NETPATH+ (267, STATUS_MISSING), # ERROR_DIRECTORY+ (23, STATUS_UNREADABLE), # ERROR_CRC: the drive is failing+ (31, STATUS_UNREADABLE), # ERROR_GEN_FAILURE+ ],+)+def test_windows_errors_classify_from_the_native_code(winerror, expected):+ """Windows errno is a lossy translation, so read the native code first.++ CPython's PC/errmap.h folds 27 distinct winerrors onto EACCES, only two of+ which are access denials. Going by errno alone tells a user whose drive is+ unplugged to fix the folder's permissions.+ """+ error = OSError(errno.EACCES, "simulated")+ error.winerror = winerror+ assert classify_scan_error(error) == expected+++def test_a_posix_error_is_unaffected_by_the_windows_branch():+ assert classify_scan_error(PermissionError(errno.EACCES, "denied")) == (+ STATUS_PERMISSION_DENIED+ )+ assert classify_scan_error(FileNotFoundError(errno.ENOENT, "gone")) == STATUS_MISSING+++def test_a_model_deleted_mid_scan_does_not_condemn_the_folder(tmp_path: Path):+ """A child in the listing and gone by the time it is opened proves nothing.++ Downloads create and rename temp directories inside a scan folder constantly,+ so treating a vanished child as the folder's own status told a user who was+ merely downloading a model that some of their models could not be read.+ """+ folder = tmp_path / "models"+ keep = folder / "keep"+ keep.mkdir(parents = True)+ (keep / "model.gguf").write_bytes(b"stub")+ doomed = folder / "downloading.tmp"+ doomed.mkdir()++ real_scandir = os.scandir++ class _Listed:+ """A finished listing, so the entry survives the directory going away."""++ def __init__(self, entries):+ self._entries = iter(entries)++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def __iter__(self):+ return self._entries++ def __next__(self):+ return next(self._entries)++ def _vanishing(path = "."):+ # Read the listing to completion, then delete the temp dir. The entry is+ # still in what we hand back, exactly as when a download renames it away+ # between the folder being listed and the child being opened.+ if str(path) == str(folder) and doomed.exists():+ with real_scandir(path) as entries:+ listed = list(entries)+ doomed.rmdir()+ return _Listed(listed)+ return real_scandir(path)++ monkey = pytest.MonkeyPatch()+ monkey.setattr(os, "scandir", _vanishing)+ try:+ note_scan_folder_scanned(str(folder), found = True)+ finally:+ monkey.undo()++ assert scan_folder_status(str(folder)) == STATUS_OK+++def test_the_folder_itself_disappearing_still_reports_missing(tmp_path: Path):+ """The guard above must not swallow the case the feature exists for."""+ note_scan_folder_scanned(str(tmp_path / "never-existed"), found = False)+ assert scan_folder_status(str(tmp_path / "never-existed")) == STATUS_MISSING+++def test_the_hub_scan_probes_off_the_event_loop(tmp_path: Path):+ """The probe opens directories, so it cannot run on the loop.++ Every other filesystem step in ``_collect_models_from_default_sources`` is+ already wrapped in ``asyncio.to_thread``. This one opens up to 64 directories+ per registered folder, and on a stalled network mount ``scandir`` sits in the+ kernel with nothing to yield to, so the whole Studio server stops answering.+ """+ import asyncio as _asyncio++ import hub.services.models.local_inventory as inventory++ folder = tmp_path / "models"+ (folder / "some-model").mkdir(parents = True)+ (folder / "some-model" / "model.gguf").write_bytes(b"stub")+ rows = [{"id": 1, "path": str(folder), "created_at": "2026-01-01"}]++ on_loop: list[bool] = []++ def _spy(path, *, found):+ try:+ _asyncio.get_running_loop()+ except RuntimeError:+ on_loop.append(False)+ else:+ on_loop.append(True)++ monkey = pytest.MonkeyPatch()+ monkey.setattr(inventory, "note_scan_folder_scanned", _spy)+ try:+ _asyncio.run(+ inventory._collect_models_from_default_sources(+ tmp_path,+ tmp_path / "hf",+ tmp_path / "legacy",+ tmp_path / "default",+ [],+ [],+ [],+ list(rows),+ )+ )+ finally:+ monkey.undo()++ assert on_loop == [False], "the folder probe ran on the event loop"+++@requires_posix_permissions+def test_the_hub_scan_records_a_folder_it_cannot_read(tmp_path: Path):+ """The Hub inventory has its own custom-folder loop, and it feeds the dialog.++ /api/hub/models/local goes through here, not through collect_local_models,+ so a status the dialog can show has to be recorded on this path too.+ """+ import asyncio as _asyncio++ from hub.services.models.local_inventory import _collect_models_from_default_sources++ denied = tmp_path / "denied"+ denied.mkdir()+ (denied / "model.gguf").write_bytes(b"stub")+ denied.chmod(0o000)+ rows = [{"id": 1, "path": str(denied), "created_at": "2026-01-01"}]++ def scan():+ return _asyncio.run(+ _collect_models_from_default_sources(+ tmp_path,+ tmp_path / "hf",+ tmp_path / "legacy",+ tmp_path / "default",+ [],+ [],+ [],+ list(rows),+ )+ )++ try:+ scan()+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PERMISSION_DENIED++ denied.chmod(stat.S_IRWXU)+ scan()+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_OK+ finally:+ denied.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_a_root_that_lists_but_hides_every_model_is_not_ok(tmp_path: Path):+ """Mixed permissions: the root reads fine, the model under it does not.++ The scanners skip an unreadable child silently, so this arrives as the same+ empty list as a genuinely empty folder.+ """+ denied_child = tmp_path / "modelA"+ denied_child.mkdir()+ (denied_child / "model.gguf").write_bytes(b"stub")+ denied_child.chmod(0o000)+ try:+ assert probe_status(str(tmp_path)) == STATUS_OK+ assert probe_status(str(tmp_path), children = True) == STATUS_PERMISSION_DENIED+ finally:+ denied_child.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_the_real_scan_flags_a_folder_whose_models_are_all_denied(tmp_path: Path):+ from routes.models import collect_local_models++ folder = tmp_path / "models"+ denied_child = folder / "modelA"+ denied_child.mkdir(parents = True)+ (denied_child / "model.gguf").write_bytes(b"stub")+ denied_child.chmod(0o000)+ rows = [{"id": 1, "path": str(folder), "created_at": "2026-01-01"}]+ try:+ collect_local_models(tmp_path / "root", custom_folders = list(rows))+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PERMISSION_DENIED+ finally:+ denied_child.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_a_denied_model_under_a_readable_publisher_is_not_ok(tmp_path: Path):+ """The LM Studio shape: <root>/<publisher>/<model>, denied at the model.++ Both levels above it list fine, so a probe that stops at the first level+ reports ok while the scan returns nothing.+ """+ model = tmp_path / "publisher" / "modelA"+ model.mkdir(parents = True)+ (model / "model.gguf").write_bytes(b"stub")+ model.chmod(0o000)+ try:+ assert probe_status(str(tmp_path), children = True) == STATUS_PERMISSION_DENIED+ finally:+ model.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_the_real_scan_flags_a_denied_model_two_levels_down(tmp_path: Path):+ from routes.models import collect_local_models++ folder = tmp_path / "models"+ model = folder / "publisher" / "modelA"+ model.mkdir(parents = True)+ (model / "model.gguf").write_bytes(b"stub")+ model.chmod(0o000)+ rows = [{"id": 1, "path": str(folder), "created_at": "2026-01-01"}]+ try:+ collect_local_models(tmp_path / "root", custom_folders = list(rows))+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PERMISSION_DENIED+ finally:+ model.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_the_deep_probe_finds_the_denial_in_a_few_opens(tmp_path: Path, monkeypatch):+ """Depth first, so the whole-mount-denied case costs three opens, not a walk."""+ denied = tmp_path / "publisher" / "modelA"+ denied.mkdir(parents = True)+ denied.chmod(0o000)++ opened: list[str] = []+ real_scandir = os.scandir++ def counting_scandir(path, *args, **kwargs):+ opened.append(str(path))+ return real_scandir(path, *args, **kwargs)++ monkeypatch.setattr(os, "scandir", counting_scandir)+ try:+ assert probe_status(str(tmp_path), children = True) == STATUS_PERMISSION_DENIED+ # Root, publisher, model.+ assert len(opened) == 3+ finally:+ denied.chmod(stat.S_IRWXU)+++def test_this_file_can_be_collected_without_geteuid(monkeypatch):+ """Windows has no os.geteuid, and a skipif condition runs at import time."""+ source = Path(__file__).read_text(encoding = "utf-8")+ monkeypatch.delattr(os, "geteuid", raising = False)+ monkeypatch.setattr(os, "name", "nt")+ namespace: dict = {"__name__": "windows_collection_probe"}+ # The module body is what pytest evaluates while collecting.+ exec(compile(source, __file__, "exec"), namespace)+++def test_the_child_probe_is_bounded(tmp_path: Path, monkeypatch):+ """A folder with many readable children must not turn into a walk."""+ import utils.paths.scan_folder_health as health++ for i in range(health._PROBE_OPEN_LIMIT * 3):+ (tmp_path / f"child{i}").mkdir()++ opened: list[str] = []+ real_scandir = os.scandir++ def counting_scandir(path, *args, **kwargs):+ opened.append(str(path))+ return real_scandir(path, *args, **kwargs)++ monkeypatch.setattr(os, "scandir", counting_scandir)+ # Too wide to finish inside the budget, so the answer is "did not see+ # everything", not "healthy". Only an exhaustive probe may report ok.+ assert probe_status(str(tmp_path), children = True) == STATUS_UNKNOWN+ # One shared budget across the whole walk, however deep or wide the tree.+ assert len(opened) <= health._PROBE_OPEN_LIMIT+++def test_reopening_the_dialog_clears_a_folder_the_user_fixed(tmp_path: Path):+ """The row tells the user to fix it and come back, so coming back must work.++ Nothing rescans between inventory scans, so the folder list has to recheck.+ """+ (tmp_path / "model.gguf").write_bytes(b"stub")+ rows = [{"id": 1, "path": str(tmp_path), "created_at": "2026-01-01"}]+ record_scan_failure(str(tmp_path), PermissionError(errno.EACCES, "Permission denied"))+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PERMISSION_DENIED++ refresh_failed_scan_folders(rows)+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_OK+++@requires_posix_permissions+def test_reopening_the_dialog_keeps_a_folder_that_is_still_denied(tmp_path: Path):+ denied = tmp_path / "denied"+ denied.mkdir()+ denied.chmod(0o000)+ rows = [{"id": 1, "path": str(denied), "created_at": "2026-01-01"}]+ record_scan_failure(str(denied), PermissionError(errno.EACCES, "Permission denied"))+ try:+ refresh_failed_scan_folders(rows)+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PERMISSION_DENIED+ finally:+ denied.chmod(stat.S_IRWXU)+++def test_the_recheck_updates_a_status_that_changed(tmp_path: Path):+ gone = tmp_path / "gone"+ rows = [{"id": 1, "path": str(gone), "created_at": "2026-01-01"}]+ record_scan_failure(str(gone), PermissionError(errno.EACCES, "Permission denied"))+ refresh_failed_scan_folders(rows)+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_MISSING+++def test_the_recheck_leaves_healthy_folders_alone(monkeypatch):+ """No folder is marked bad, so the folder list must not open anything."""++ def _boom(*args, **kwargs):+ raise AssertionError("the folder list touched the filesystem")++ for name in ("scandir", "listdir", "stat", "access"):+ monkeypatch.setattr(os, name, _boom)++ rows = [{"id": 1, "path": "/models/a", "created_at": "2026-01-01"}]+ refresh_failed_scan_folders(rows)+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_OK+++def test_the_recheck_only_opens_the_folder_that_failed(tmp_path: Path, monkeypatch):+ good = tmp_path / "good"+ good.mkdir()+ bad = tmp_path / "bad"+ bad.mkdir()+ record_scan_failure(str(bad), PermissionError(errno.EACCES, "Permission denied"))++ opened: list[str] = []+ real_scandir = os.scandir++ def counting_scandir(path, *args, **kwargs):+ opened.append(str(path))+ return real_scandir(path, *args, **kwargs)++ monkeypatch.setattr(os, "scandir", counting_scandir)+ refresh_failed_scan_folders(+ [+ {"id": 1, "path": str(good), "created_at": "2026-01-01"},+ {"id": 2, "path": str(bad), "created_at": "2026-01-02"},+ ]+ )+ assert opened == [str(bad)]+++@requires_posix_permissions+def test_an_exhausted_budget_does_not_clear_a_known_failure(tmp_path: Path):+ """Running out of budget proves nothing, so it must not report healthy.++ The folder is too wide to finish probing, and the denied directory sits past+ the cutoff, so a probe that treated exhaustion as ok would drop the warning.+ """+ import utils.paths.scan_folder_health as health++ for i in range(health._PROBE_OPEN_LIMIT * 3):+ (tmp_path / f"model{i:03d}").mkdir()+ # Deterministically past the budget: pick by real listing order, not by name.+ order = [entry.name for entry in os.scandir(tmp_path)]+ denied = tmp_path / order[-1]+ denied.chmod(0o000)+ try:+ record_scan_failure(str(tmp_path), PermissionError(errno.EACCES, "Permission denied"))+ health._failed[str(tmp_path)] = (STATUS_PARTIAL, str(denied))++ note_scan_folder_scanned(str(tmp_path), found = True)+ assert scan_folder_status(str(tmp_path)) == STATUS_PARTIAL+ finally:+ denied.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_a_wide_folder_still_clears_once_it_is_fixed(tmp_path: Path):+ """The flip side: recovery cannot depend on the probe reaching the tail."""+ import utils.paths.scan_folder_health as health++ for i in range(health._PROBE_OPEN_LIMIT * 3):+ (tmp_path / f"model{i:03d}").mkdir()+ order = [entry.name for entry in os.scandir(tmp_path)]+ fixed = tmp_path / order[-1]+ # Recorded as the cause, but readable again by the time the scan runs.+ health._failed[str(tmp_path)] = (STATUS_PARTIAL, str(fixed))++ note_scan_folder_scanned(str(tmp_path), found = True)+ assert scan_folder_status(str(tmp_path)) == STATUS_OK+++@requires_posix_permissions+def test_a_partial_folder_that_disappears_reports_missing(tmp_path: Path):+ """Deleting the folder outranks "some models could not be read"."""+ import shutil++ folder = tmp_path / "models"+ bad = folder / "bad"+ bad.mkdir(parents = True)+ bad.chmod(0o000)+ rows = [{"id": 1, "path": str(folder), "created_at": "2026-01-01"}]++ note_scan_folder_scanned(str(folder), found = True)+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PARTIAL++ bad.chmod(stat.S_IRWXU)+ shutil.rmtree(folder)+ refresh_failed_scan_folders(rows)+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_MISSING+++def test_the_internal_unknown_status_never_reaches_the_api(tmp_path: Path):+ """STATUS_UNKNOWN is a probe result, not something the UI can render."""+ import utils.paths.scan_folder_health as health++ for i in range(health._PROBE_OPEN_LIMIT * 3):+ (tmp_path / f"model{i:03d}").mkdir()+ rows = [{"id": 1, "path": str(tmp_path), "created_at": "2026-01-01"}]++ note_scan_folder_scanned(str(tmp_path), found = True)+ refresh_failed_scan_folders(rows)+ assert annotate_scan_folders(rows)[0]["status"] != STATUS_UNKNOWN+ assert STATUS_UNKNOWN not in {status for status, _cause in health._failed.values()}+++def test_reading_status_never_touches_the_filesystem(monkeypatch):+ """The folder list must stay a dict lookup: no stat, no listing, no cost.++ Every filesystem entry point raises, so any disk access fails the test.+ """+ record_scan_failure("/models/b", PermissionError(errno.EACCES, "Permission denied"))++ def _boom(*args, **kwargs):+ raise AssertionError("scan folder status touched the filesystem")++ for name in ("scandir", "listdir", "stat", "lstat", "access", "open"):+ monkeypatch.setattr(os, name, _boom)+ monkeypatch.setattr(os.path, "exists", _boom)+ monkeypatch.setattr(os.path, "isdir", _boom)++ rows = [+ {"id": 1, "path": "/models/a", "created_at": "2026-01-01"},+ {"id": 2, "path": "/models/b", "created_at": "2026-01-02"},+ ]+ statuses = {row["path"]: row["status"] for row in annotate_scan_folders(rows)}+ assert statuses == {"/models/a": STATUS_OK, "/models/b": STATUS_PERMISSION_DENIED}+ assert scan_folder_status("/models/b") == STATUS_PERMISSION_DENIED+++@requires_posix_permissions+def test_a_denied_hf_snapshot_commit_directory_is_not_ok(tmp_path: Path):+ """The HF cache keeps the files one level below <publisher>/<model>.++ <root>/models--org--name/snapshots/<commit>/ is where the weights are; refuse+ it and every directory above it still lists, so a depth that stops at+ ``snapshots`` calls the folder healthy while the model is gone from the list.+ """+ repo = tmp_path / "models--org--model"+ (repo / "blobs").mkdir(parents = True)+ (repo / "blobs" / "deadbeef").write_bytes(b"stub")+ (repo / "refs").mkdir()+ (repo / "refs" / "main").write_text("a" * 40, encoding = "utf-8")+ commit = repo / "snapshots" / ("a" * 40)+ commit.mkdir(parents = True)+ (commit / "config.json").write_text("{}", encoding = "utf-8")+ commit.chmod(0o000)+ try:+ status, cause = probe_folder(str(tmp_path), children = True)+ assert status == STATUS_PERMISSION_DENIED+ assert cause == str(commit)++ note_scan_folder_scanned(str(tmp_path), found = False)+ assert scan_folder_status(str(tmp_path)) == STATUS_PERMISSION_DENIED+ finally:+ commit.chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_the_snapshot_level_costs_nothing_on_a_plain_folder(tmp_path: Path, monkeypatch):+ """Only a directory named ``snapshots`` buys the extra level.++ A diffusers pipeline keeps component directories under each model, so raising+ the depth for everything would spend the budget on <publisher>/<model>/<part>.+ """+ part = tmp_path / "publisher" / "model" / "transformer"+ part.mkdir(parents = True)+ (part / "denied").mkdir()+ (part / "denied").chmod(0o000)++ opened: list[str] = []+ real_scandir = os.scandir++ def counting_scandir(path, *args, **kwargs):+ opened.append(str(path))+ return real_scandir(path, *args, **kwargs)++ monkeypatch.setattr(os, "scandir", counting_scandir)+ try:+ # Root, publisher, model. The component level is still out of reach.+ assert probe_status(str(tmp_path), children = True) == STATUS_OK+ assert len(opened) == 3+ finally:+ (part / "denied").chmod(stat.S_IRWXU)+++@requires_posix_permissions+def test_a_partial_folder_whose_root_is_denied_stops_saying_partial(tmp_path: Path):+ """Once the registered root refuses, nothing in it can be scanned.++ Telling the user only some models could not be read sends them looking for+ the one bad model in a folder none of which is readable.+ """+ bad = tmp_path / "bad"+ bad.mkdir()+ bad.chmod(0o000)+ rows = [{"id": 1, "path": str(tmp_path), "created_at": "2026-01-01"}]+ try:+ note_scan_folder_scanned(str(tmp_path), found = True)+ assert scan_folder_status(str(tmp_path)) == STATUS_PARTIAL++ tmp_path.chmod(0o000)+ try:+ refresh_failed_scan_folders(rows)+ assert annotate_scan_folders(rows)[0]["status"] == STATUS_PERMISSION_DENIED+ finally:+ tmp_path.chmod(stat.S_IRWXU)+ finally:+ bad.chmod(stat.S_IRWXU)diff --git a/studio/backend/utils/paths/scan_folder_health.py b/studio/backend/utils/paths/scan_folder_health.pynew file mode 100644index 00000000000..910c09529db--- /dev/null+++ b/studio/backend/utils/paths/scan_folder_health.py@@ -0,0 +1,262 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Readability of user-registered model scan folders.++Two halves of one problem: prove a folder can be listed before registering it,+and remember the folders a later scan could not read so the UI can say so+instead of showing an empty model list.+"""++from __future__ import annotations++import errno+import os+from typing import Optional++# Readable, or not scanned yet.+STATUS_OK = "ok"+# Refused by the OS: mode bits, an ACL, macOS TCC, Windows Controlled Folder Access.+STATUS_PERMISSION_DENIED = "permission_denied"+# Deleted, renamed, or on an unmounted volume.+STATUS_MISSING = "missing"+# Any other OSError: I/O error, dead network mount, symlink loop.+STATUS_UNREADABLE = "unreadable"+# The folder works, but something inside it is refused, so models are missing+# from the list without the list looking wrong.+STATUS_PARTIAL = "partial"+# Internal only: the probe ran out of budget before it saw everything, so it+# proved nothing. Never recorded and never sent to the UI.+STATUS_UNKNOWN = "unknown"+++# Deep enough for <root>/<publisher>/<model>, the LM Studio and HF cache shape.+_PROBE_DEPTH = 2+# Total opens for one probe, whatever the shape. Bounds the cost; the depth does not.+_PROBE_OPEN_LIMIT = 64+# A huggingface_hub cache keeps the files one level below that, in+# <root>/models--org--name/snapshots/<commit>/, and that commit directory is the+# only place the weights are. Refuse it and every directory above it still lists+# fine, while the cache scan drops the model without raising, so the folder looks+# healthy and empty at once. Costs one extra open per cached revision, and only in+# a directory actually named this, so no other layout pays for it.+_HF_SNAPSHOTS_DIR = "snapshots"+++def _probe_dir(path: str, *, depth: int, budget: list[int]) -> tuple[str, Optional[str]]:+ """Open ``path``, then its subdirectories down to ``depth``, depth first.++ Returns the status and the directory that refused. Depth first so a denied+ model is found in three opens rather than after every publisher. ``budget``+ is shared across the walk and spent one per open. Running out returns+ ``STATUS_UNKNOWN``: the tail was never looked at, which is not the same as+ finding it healthy.+ """+ if budget[0] <= 0:+ return STATUS_UNKNOWN, None+ budget[0] -= 1+ subdirs: list[tuple[str, str]] = []+ truncated = False+ try:+ with os.scandir(path) as entries:+ if depth <= 0:+ # Only need to know it opens.+ next(entries, None)+ return STATUS_OK, None+ for entry in entries:+ if len(subdirs) >= budget[0]:+ truncated = True+ break+ try:+ if entry.is_dir():+ subdirs.append((entry.name, entry.path))+ except OSError as error:+ return classify_scan_error(error), entry.path+ except OSError as error:+ return classify_scan_error(error), path+ for name, subdir in subdirs:+ child_depth = depth - 1+ if child_depth <= 0 and name == _HF_SNAPSHOTS_DIR:+ # Spend one more level here rather than raising the depth everywhere:+ # a diffusers pipeline keeps component directories under each model, so+ # a blanket extra level would burn the budget on folders shaped+ # <root>/<publisher>/<model>/<component>.+ child_depth = 1+ status, cause = _probe_dir(subdir, depth = child_depth, budget = budget)+ if status == STATUS_MISSING:+ # It was in the listing a moment ago and is gone now: a model being+ # deleted, or a download renaming its temp directory away mid-walk.+ # That says nothing about the folder the user registered. The folder+ # itself disappearing is still caught by the scandir above.+ continue+ if status != STATUS_OK:+ return status, cause or subdir+ return (STATUS_UNKNOWN, None) if truncated else (STATUS_OK, None)+++def probe_folder(path: str, *, children: bool = False) -> tuple[str, Optional[str]]:+ """Status of ``path`` plus the directory that refused, if any."""+ if not children:+ return _probe_dir(path, depth = 0, budget = [1])+ return _probe_dir(path, depth = _PROBE_DEPTH, budget = [_PROBE_OPEN_LIMIT])+++def probe_status(path: str, *, children: bool = False) -> str:+ """Open ``path`` and report what the OS says. No walking.++ With ``children``, also open what is under it. A root can list fine while the+ models below it are denied, and the scanners skip an unreadable entry+ silently, so both arrive as the same empty list.+ """+ return probe_folder(path, children = children)[0]+++def is_readable_dir(path: str) -> bool:+ """True only if ``path`` can actually be listed.++ ``os.access`` answers from mode bits alone, so it returns True for a+ directory macOS TCC or a Windows ACL still refuses. Opening the directory is+ the authoritative answer and costs one syscall on a path the user just picked.+ """+ if not os.access(path, os.R_OK | os.X_OK):+ return False+ return probe_status(path) == STATUS_OK+++# Windows reports the real reason in ``winerror``; ``errno`` is a lossy translation of+# it, and CPython's PC/errmap.h folds ERROR_NOT_READY, ERROR_CRC, ERROR_GEN_FAILURE and+# every other media or device failure onto EACCES. Without this, an ejected card reader+# or an unmounted volume tells the user to go and fix the folder's permissions.+_WINDOWS_PERMISSION = frozenset((5, 65, 1314))+_WINDOWS_MISSING = frozenset((2, 3, 15, 20, 21, 53, 55, 67, 161, 206, 267))+++def classify_scan_error(error: OSError) -> str:+ """Map an error the scan already raised onto a status the UI can render."""+ # Absent on POSIX, and None unless CPython set it, so this never shadows errno.+ winerror = getattr(error, "winerror", None)+ if winerror is not None:+ if winerror in _WINDOWS_PERMISSION:+ return STATUS_PERMISSION_DENIED+ return STATUS_MISSING if winerror in _WINDOWS_MISSING else STATUS_UNREADABLE+ if isinstance(error, PermissionError) or error.errno in (errno.EACCES, errno.EPERM):+ return STATUS_PERMISSION_DENIED+ if isinstance(error, FileNotFoundError) or error.errno in (errno.ENOENT, errno.ENOTDIR):+ return STATUS_MISSING+ return STATUS_UNREADABLE+++# Read on every folder list, written only when a probe finds something wrong.+# Each value is (status, the directory that refused), so a recheck can settle a+# folder in one open instead of walking it again. Bounded by the folder count.+_MAX_TRACKED = 256+_failed: dict[str, tuple[str, str]] = {}+++def _record(path: str, status: str, cause: str) -> None:+ if len(_failed) >= _MAX_TRACKED:+ _failed.clear()+ _failed[path] = (status, cause)+++def record_scan_failure(path: str, error: OSError) -> None:+ """Remember why a scan skipped ``path``."""+ _record(path, classify_scan_error(error), path)+++def clear_scan_failure(path: str) -> None:+ """Forget a past failure once the folder reads again."""+ if _failed:+ _failed.pop(path, None)+++def note_scan_folder_scanned(path: str, *, found: bool) -> None:+ """Record the outcome of a scan of ``path``.++ Empty, gone, refused, or working with one model refused: the scanners return+ the same list for all of them, because they swallow the error per entry. So+ ask the OS instead of trying to read it back out of them. Bounded by+ ``_PROBE_OPEN_LIMIT`` opens per folder.+ """+ status, cause = probe_folder(path, children = True)+ if status == STATUS_UNKNOWN:+ # Budget gone before the tail was reached, so this proves nothing either+ # way. Settle it on the one directory that refused last time.+ _recheck_cause(path)+ return+ if status == STATUS_OK:+ clear_scan_failure(path)+ return+ # Models came back, so the folder itself is fine and only part of it is+ # refused. Saying it cannot be read would contradict the rows on screen.+ if found:+ status = STATUS_PARTIAL+ _record(path, status, cause or path)+++def _recheck_cause(path: str) -> None:+ """Clear ``path`` if the directory that refused last time opens now.++ One open, and it does not depend on the probe reaching that directory again,+ so recovery works on a folder too wide to walk inside the budget.+ """+ entry = _failed.get(path)+ if entry is None:+ return+ if probe_status(entry[1]) == STATUS_OK:+ _failed.pop(path, None)+++def scan_folder_status(path: str) -> str:+ """Last known status for ``path``. A dict lookup, never touches the disk."""+ if not _failed:+ return STATUS_OK+ entry = _failed.get(path)+ return STATUS_OK if entry is None else entry[0]+++def refresh_failed_scan_folders(folders: list[dict]) -> None:+ """Re-check the folders currently marked bad, and only those.++ The row tells the user to fix permissions and reopen the dialog, so reopening+ has to be able to clear it. Nothing else rechecks between inventory scans.+ A healthy folder is not in the registry, so it is never opened here.+ """+ if not _failed:+ return+ for folder in folders:+ path = str(folder.get("path", ""))+ entry = _failed.get(path)+ if entry is None:+ continue+ previous = entry[0]+ status, cause = probe_folder(path, children = True)+ if status == STATUS_UNKNOWN:+ _recheck_cause(path)+ continue+ if status == STATUS_OK:+ _failed.pop(path, None)+ continue+ if (+ previous == STATUS_PARTIAL+ and status == STATUS_PERMISSION_DENIED+ and cause is not None+ and cause != path+ ):+ # The probe cannot see that models were found, so keep the wording+ # the scan chose. A folder that is gone still replaces it below.+ # Only while the refusal is still something inside the folder: when+ # the registered root itself is the one refusing, nothing can be+ # scanned any more, and "some models could not be read" would be+ # telling the user the wrong half of the problem.+ status = STATUS_PARTIAL+ _record(path, status, cause or path)+++def annotate_scan_folders(folders: list[dict]) -> list[dict]:+ """Copy each folder row with its status attached."""+ if not _failed:+ return [{**folder, "status": STATUS_OK} for folder in folders]+ return [+ {**folder, "status": scan_folder_status(str(folder.get("path", "")))} for folder in folders+ ]diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 58f4fd06cf2..b3afb903858 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -661,6 +661,8 @@ export interface ScanFolderInfo {id: number;path: string;created_at: string;+ /** Result of the last scan. Absent on older backends, which means "ok". */+ status?: "ok" | "permission_denied" | "missing" | "unreadable" | "partial";}export async function listScanFolders(): Promise<ScanFolderInfo[]> {diff --git a/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsx b/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsxindex bef2f797478..f038141a5b2 100644--- a/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsx+++ b/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsx@@ -21,6 +21,7 @@ import {addScanFolder,listScanFolders,removeScanFolder,+ scanFolderStatusCopy,} from "@/features/hub";import { FolderBrowser } from "@/features/model-picker";import {@@ -468,6 +469,7 @@ export function OnDeviceFoldersDialog({) : (sortedFolders.map((folder) => {const removing = pending === `remove:${folder.id}`;+ const problem = scanFolderStatusCopy(folder.status);return (<divkey={folder.id}@@ -505,6 +507,14 @@ export function OnDeviceFoldersDialog({{folder.path}</TooltipContent></Tooltip>+ {problem ? (+ <p+ data-testid={`scan-folder-problem-${folder.id}`}+ className="mt-1 text-ui-10p5 text-amber-600 dark:text-amber-500"+ >+ {problem.title}. {problem.hint}+ </p>+ ) : null}</div>{isTauri ? (<Tooltip>diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.tsindex 0ca85599107..f71d1662e12 100644--- a/studio/frontend/src/features/hub/index.ts+++ b/studio/frontend/src/features/hub/index.ts@@ -93,6 +93,8 @@ export {} from "./stores/hf-token-store";export { useInventoryVersion } from "./stores/inventory-events";export { looksLikeLocalPath, localPathCacheKey } from "./lib/local-path";+export { scanFolderStatusCopy } from "./lib/scan-folder-status";+export type { ScanFolderStatus } from "./lib/scan-folder-status";export { hubTokenHeader } from "./lib/hub-token-header";export {ggufVariantsMatch,diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.tsindex b23ffd835f1..43085fdc72a 100644--- a/studio/frontend/src/features/hub/inventory/api.ts+++ b/studio/frontend/src/features/hub/inventory/api.ts@@ -12,6 +12,7 @@ import { localPathCacheKey } from "@/features/hub/lib/local-path";import { isHuggingFaceOffline } from "@/features/hub/lib/network";import { fingerprintToken } from "@/features/hub/lib/token-fingerprint";import { bumpInventoryVersion } from "@/features/hub/stores/inventory-events";+import type { ScanFolderStatus } from "../lib/scan-folder-status";import type { LocalSource } from "./constants";import { bumpGgufVariantsCacheVersion } from "./gguf-variants-cache-events";@@ -154,6 +155,8 @@ export interface ScanFolderInfo {id: number;path: string;created_at: string;+ /** Result of the last scan. Absent on older backends, which means "ok". */+ status?: ScanFolderStatus;}export interface GgufVariantDetail {diff --git a/studio/frontend/src/features/hub/lib/scan-folder-status.ts b/studio/frontend/src/features/hub/lib/scan-folder-status.tsnew file mode 100644index 00000000000..76280b0e4af--- /dev/null+++ b/studio/frontend/src/features/hub/lib/scan-folder-status.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Copy for a scan folder the backend could not read.+ *+ * A folder Unsloth is denied looks exactly like an empty one in the model list,+ * so the row has to say which it is and where to fix it.+ */++export type ScanFolderStatus =+ | "ok"+ | "permission_denied"+ | "missing"+ | "unreadable"+ | "partial";++export interface ScanFolderStatusCopy {+ title: string;+ hint: string;+}++/** Rough host detection: only picks which settings screen to name. */+function hostPlatform(userAgent: string): "mac" | "windows" | "other" {+ if (/Mac|iPhone|iPad/i.test(userAgent)) return "mac";+ if (/Win/i.test(userAgent)) return "windows";+ return "other";+}++function permissionHint(userAgent: string): string {+ switch (hostPlatform(userAgent)) {+ case "mac":+ return "Grant access in System Settings > Privacy & Security > Files and Folders, then reopen this dialog.";+ case "windows":+ return "Check the folder's security permissions, or allow Unsloth in Controlled Folder Access, then reopen this dialog.";+ default:+ return "Check the folder's permissions, then reopen this dialog.";+ }+}++export function scanFolderStatusCopy(+ status: ScanFolderStatus | undefined,+ userAgent: string = typeof navigator === "undefined" ? "" : navigator.userAgent,+): ScanFolderStatusCopy | null {+ switch (status) {+ case "permission_denied":+ return {+ title: "Unsloth is not allowed to read this folder",+ hint: permissionHint(userAgent),+ };+ case "partial":+ return {+ title: "Some models in this folder could not be read",+ hint: permissionHint(userAgent),+ };+ case "missing":+ return {+ title: "This folder is no longer there",+ hint: "It was moved, renamed, or is on a drive that is not connected.",+ };+ case "unreadable":+ return {+ title: "This folder could not be read",+ hint: "The drive may be disconnected or failing. Check it, then reopen this dialog.",+ };+ default:+ return null;+ }+}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.tsxindex 4e2b4dcb795..17074c47c20 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@@ -56,6 +56,7 @@ import {hfApiToken,isHiddenModelId,jobKeyOf,+ scanFolderStatusCopy,useDownloadManagerStore,useHfTokenStore,useOnlineStatus,@@ -5560,34 +5561,47 @@ export function HubModelPicker({{/* Folder paths */}{!customFoldersCollapsed &&- scanFolders.map((f) => (- <div- key={f.id}- className="group flex items-center gap-1.5 px-2.5 py-0.5"- >- <HugeiconsIcon- icon={Folder02Icon}- className="size-3 shrink-0 text-muted-foreground/40"- />- <span- className="min-w-0 flex-1 truncate font-mono text-ui-10 text-muted-foreground/70"- title={f.path}- >- {f.path}- </span>- <button- type="button"- onClick={() => handleRemoveFolder(f.id)}- aria-label={`Remove folder ${f.path}`}- className="shrink-0 rounded p-1 text-foreground/70 transition-colors hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive"+ scanFolders.map((f) => {+ const problem = scanFolderStatusCopy(f.status);+ return (+ <div+ key={f.id}+ className="group flex items-center gap-1.5 px-2.5 py-0.5"><HugeiconsIcon- icon={Cancel01Icon}- className="size-3"+ icon={Folder02Icon}+ className="size-3 shrink-0 text-muted-foreground/40"/>- </button>- </div>- ))}+ <div className="min-w-0 flex-1">+ <span+ className="block truncate font-mono text-ui-10 text-muted-foreground/70"+ title={f.path}+ >+ {f.path}+ </span>+ {problem ? (+ <span+ className="block truncate text-ui-10 text-amber-600 dark:text-amber-500"+ title={problem.hint}+ >+ {problem.title}+ </span>+ ) : null}+ </div>+ <button+ type="button"+ onClick={() => handleRemoveFolder(f.id)}+ aria-label={`Remove folder ${f.path}`}+ className="shrink-0 rounded p-1 text-foreground/70 transition-colors hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive"+ >+ <HugeiconsIcon+ icon={Cancel01Icon}+ className="size-3"+ />+ </button>+ </div>+ );+ })}{/* Recommended folders */}{!customFoldersCollapsed &&diff --git a/studio/frontend/tests/scan-folder-status.test.ts b/studio/frontend/tests/scan-folder-status.test.tsnew file mode 100644index 00000000000..5c485d53737--- /dev/null+++ b/studio/frontend/tests/scan-folder-status.test.ts@@ -0,0 +1,94 @@+// 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 { readFile } from "node:fs/promises";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { scanFolderStatusCopy } = await import(+ "../src/features/hub/lib/scan-folder-status.ts"+);++const MAC = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)";+const WINDOWS = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)";+const LINUX = "Mozilla/5.0 (X11; Linux x86_64)";++test("a healthy folder shows nothing", () => {+ assert.equal(scanFolderStatusCopy("ok", MAC), null);+});++test("a folder from an older backend shows nothing", () => {+ assert.equal(scanFolderStatusCopy(undefined, MAC), null);+});++test("a denied folder says so instead of looking empty", () => {+ const copy = scanFolderStatusCopy("permission_denied", MAC);+ assert.ok(copy);+ assert.match(copy.title, /not allowed to read/i);+});++test("the permission hint names the screen that fixes it", () => {+ assert.match(+ scanFolderStatusCopy("permission_denied", MAC)!.hint,+ /System Settings > Privacy & Security > Files and Folders/,+ );+ assert.match(+ scanFolderStatusCopy("permission_denied", WINDOWS)!.hint,+ /Controlled Folder Access/,+ );+ // No screen worth naming on Linux, so the hint stays generic.+ assert.match(+ scanFolderStatusCopy("permission_denied", LINUX)!.hint,+ /permissions/i,+ );+});++test("a missing folder is not reported as a permission problem", () => {+ const copy = scanFolderStatusCopy("missing", MAC);+ assert.ok(copy);+ assert.match(copy.title, /no longer there/i);+ assert.doesNotMatch(copy.hint, /permission/i);+});++test("a partial folder does not claim the whole folder is blocked", () => {+ const copy = scanFolderStatusCopy("partial", MAC);+ assert.ok(copy);+ assert.match(copy.title, /some models/i);+ assert.doesNotMatch(copy.title, /not allowed/i);+ // Same fix, so the same hint.+ assert.match(copy.hint, /Files and Folders/);+});++test("an unreadable folder points at the drive", () => {+ const copy = scanFolderStatusCopy("unreadable", MAC);+ assert.ok(copy);+ assert.match(copy.hint, /drive/i);+});++test("the model picker renders the status on its folder rows too", async () => {+ const source = await readFile(+ new URL(+ "../src/features/model-picker/components/model-selector/pickers.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(source, /scanFolderStatusCopy\(f\.status\)/);+ assert.match(source, /\{problem\.title\}/);+});++test("the folders dialog renders the status on the row", async () => {+ const source = await readFile(+ new URL(+ "../src/features/hub/catalog/on-device-folders-dialog.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(source, /scanFolderStatusCopy\(folder\.status\)/);+ assert.match(source, /\{problem\.title\}\. \{problem\.hint\}/);+});