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: list Ollama models in the chat picker and load their manifest refs (#9237)
Shubhankar Tripathyd55753f46a74
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex f26fd574041..3db058108b8 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -4423,6 +4423,9 @@ class LlamaCppBackend:self._port: Optional[int] = Noneself._model_identifier: Optional[str] = Noneself._gguf_path: Optional[str] = None+ # Snapshot of the exact file(s) handed to the resident process. A local+ # link can be atomically retargeted while `_gguf_path` stays unchanged.+ self._gguf_load_identity: Optional[tuple] = Noneself._hf_repo: Optional[str] = None# Separate MTP drafter launched with the current model; reload-dedup# key so a drafter that appears next to the weights forces a reload.@@ -10690,6 +10693,7 @@ class LlamaCppBackend:# Publish state before the health wait (mirrors the llama-server path).self._gguf_path = model_path+ self._gguf_load_identity = self._gguf_load_source_identity(model_path)self._hf_repo = hf_repoself._is_vision = Falseself._is_audio = False # clear any prior TTS/audio model's routing flag@@ -18632,6 +18636,7 @@ class LlamaCppBackend:# set BEFORE the spawn: load_progress() reads _gguf_path for# the mmap progress total while the health wait runs.self._gguf_path = model_path+ self._gguf_load_identity = self._gguf_load_source_identity(model_path, mmproj_path)self._hf_repo = hf_repoself._mtp_draft_path = launch_mtp_draft_pathself._mtp_draft_suppressed_path = _pv_suppressed_draft_path@@ -20132,6 +20137,12 @@ class LlamaCppBackend:):return Falseif intent.gguf_path is not None and self._gguf_path:+ resident_identity = getattr(self, "_gguf_load_identity", None)+ if resident_identity is not None:+ candidate_identity = LlamaCppBackend._gguf_load_source_identity(+ intent.gguf_path, intent.mmproj_path+ )+ return candidate_identity == resident_identitytry:return Path(self._gguf_path).resolve() == Path(intent.gguf_path).resolve()except OSError:@@ -20248,6 +20259,7 @@ class LlamaCppBackend:logger.info(f"Unloaded GGUF model: {self._model_identifier}")self._model_identifier = Noneself._gguf_path = None+ self._gguf_load_identity = Noneself._hf_repo = Noneself._mtp_draft_path = Noneself._mtp_draft_suppressed_path = None@@ -21063,6 +21075,50 @@ class LlamaCppBackend:self._flash_attn_enabled,)+ @staticmethod+ def _gguf_load_source_identity(path: str, mmproj_path: Optional[str] = None) -> Optional[tuple]:+ """Identity of the exact GGUF inode(s) handed to the resident process."""+ p = Path(path)+ paths = [p]+ match = _SHARD_FULL_RE.match(p.name)+ if match:+ prefix, _first, total = match.groups()+ paths = [+ p.with_name(f"{prefix}-{index:05d}-of-{total}{p.suffix}")+ for index in range(1, int(total) + 1)+ ]+ try:+ identity = []+ for shard in paths:+ resolved = shard.resolve()+ stat = shard.stat()+ identity.append(+ (+ str(resolved),+ stat.st_dev,+ stat.st_ino,+ stat.st_size,+ stat.st_mtime_ns,+ )+ )+ if mmproj_path:+ projector = Path(mmproj_path)+ resolved = projector.resolve()+ stat = projector.stat()+ identity.append(+ (+ "mmproj",+ str(resolved),+ stat.st_dev,+ stat.st_ino,+ stat.st_size,+ stat.st_mtime_ns,+ )+ )+ return tuple(identity)+ except (OSError, RuntimeError):+ return None+def _gguf_file_identity(self, path) -> Optional[tuple]:# (size, mtime_ns) per shard: a split GGUF keys KV validity on every sibling.p = Path(path)@@ -24147,8 +24203,8 @@ class LlamaCppBackend:# characters per token than four. This path has a# tokenizer, so hand it over and let the check spend# the budget as exactly as it computes it.- kwargs["conversation_token_counter"] = (- lambda text: self.count_chat_tokens(+ kwargs["conversation_token_counter"] = lambda text: (+ self.count_chat_tokens([{"role": "tool", "content": text}],None,None,diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex 12f147f5ba7..eb2ce5f0b14 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -823,11 +823,14 @@ def _scan_custom_folder(selectable.append(model)elif detect_gguf_model(model.path, model_root = str(folder_path)) is not None:selectable.append(model)+ remaining = _MAX_MODELS_PER_CUSTOM_FOLDER - len(selectable)+ if remaining > 0:+ selectable.extend(scan_ollama_dir(folder_path, limit = remaining))return selectable[:_MAX_MODELS_PER_CUSTOM_FOLDER]def _promote_to_custom_source(model: LocalModelInfo) -> LocalModelInfo:- if model.source == "hf_cache":+ if model.source in {"hf_cache", "ollama"}:return modelreturn model.model_copy(update = {diff --git a/studio/backend/hub/services/models/ollama.py b/studio/backend/hub/services/models/ollama.pyindex da30f7e98c7..c8ab245367c 100644--- a/studio/backend/hub/services/models/ollama.py+++ b/studio/backend/hub/services/models/ollama.py@@ -16,6 +16,8 @@ from __future__ import annotationsimport hashlibimport jsonimport os++import threadingimport uuidfrom pathlib import Pathfrom typing import List, Optional@@ -42,11 +44,56 @@ _OLLAMA_BLOB_NAME_CHARS = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._+-")+_OLLAMA_LOADABLE_LAYER_MEDIA_TYPES = frozenset(+ {+ "application/vnd.ollama.image.model",+ "application/vnd.ollama.image.projector",+ # License text does not affect model behavior and does not need to be+ # carried into llama.cpp.+ "application/vnd.ollama.image.license",+ }+)++_OLLAMA_MATERIALIZE_LOCKS: dict[str, threading.Lock] = {}+_OLLAMA_MATERIALIZE_LOCKS_GUARD = threading.Lock()+++class OllamaModelLease:+ def __init__(self, path: str, lock: threading.Lock):+ self.path = path+ self._lock = lock+ self._released = False++ def release(self) -> None:+ if not self._released:+ self._released = True+ self._lock.release()+def _ollama_manifest_ref(tag_file: Path) -> str:return f"{_OLLAMA_MANIFEST_REF_PREFIX}{quote(str(tag_file), safe = '')}"+def is_ollama_manifest_ref(ref: str) -> bool:+ """True when *ref* is an opaque ``ollama-manifest:`` inventory reference."""+ return ref.startswith(_OLLAMA_MANIFEST_REF_PREFIX)+++def _unsupported_ollama_layer_media_types(layers: list[object]) -> tuple[str, ...]:+ """Layer types whose behavior the direct llama.cpp load cannot preserve."""+ unsupported: set[str] = set()+ for layer in layers:+ if not isinstance(layer, dict):+ unsupported.add("<invalid layer>")+ continue+ media_type = layer.get("mediaType")+ if not isinstance(media_type, str) or not media_type:+ unsupported.add("<missing mediaType>")+ elif media_type not in _OLLAMA_LOADABLE_LAYER_MEDIA_TYPES:+ unsupported.add(media_type)+ return tuple(sorted(unsupported))++def _safe_is_file(path: Path) -> bool:try:return path.is_file()@@ -188,6 +235,7 @@ def _ollama_model_info_from_manifest(*,materialize_links: bool = False,links_root: Optional[Path] = None,+ reject_unsupported_layers: bool = False,) -> Optional[LocalModelInfo]:manifests_root = ollama_dir / "manifests"blobs_dir = ollama_dir / "blobs"@@ -214,14 +262,24 @@ def _ollama_model_info_from_manifest(if not repo_name:return None+ def invalid_manifest(reason: str) -> Optional[LocalModelInfo]:+ message = f"Invalid Ollama manifest: {reason}"+ if reject_unsupported_layers:+ raise ValueError(message)+ logger.debug("Skipping %s (%s)", tag_file, message)+ return None+try:manifest = json.loads(tag_file.read_text(encoding = "utf-8-sig"))except (json.JSONDecodeError, OSError, UnicodeDecodeError) as e:- logger.debug("Skipping unreadable/invalid Ollama manifest %s: %s", tag_file, e)- return None+ return invalid_manifest(str(e))+ if not isinstance(manifest, dict):+ return invalid_manifest("top level must be a JSON object")config = manifest.get("config", {})- config_digest = config.get("digest", "") if isinstance(config, dict) else ""+ if not isinstance(config, dict):+ return invalid_manifest("config must be a JSON object")+ config_digest = config.get("digest", "")model_type = ""file_type = ""if config_digest and blobs_dir.is_dir():@@ -229,49 +287,132 @@ def _ollama_model_info_from_manifest(if config_blob is not None and _safe_is_file(config_blob):try:cfg = json.loads(config_blob.read_text(encoding = "utf-8-sig"))- model_type = cfg.get("model_type", "")- file_type = cfg.get("file_type", "")except (json.JSONDecodeError, OSError, UnicodeDecodeError) as e:- logger.debug("Could not parse Ollama config blob %s: %s", config_blob, e)+ return invalid_manifest(f"config blob could not be parsed: {e}")+ if not isinstance(cfg, dict):+ return invalid_manifest("config blob must be a JSON object")+ model_type = cfg.get("model_type", "")+ file_type = cfg.get("file_type", "")layers = manifest.get("layers") or []if not isinstance(layers, list):return None+ unsupported_layers = _unsupported_ollama_layer_media_types(layers)+ if unsupported_layers:+ rendered_layers = ", ".join(unsupported_layers)+ if reject_unsupported_layers:+ raise ValueError(+ "Ollama manifest contains unsupported runtime layers that Studio cannot preserve: "+ f"{rendered_layers}"+ )+ logger.debug(+ "Skipping Ollama manifest %s with unsupported runtime layers: %s",+ tag_file,+ rendered_layers,+ )+ return None+model_blob: Optional[Path] = None+ projector_blob: Optional[Path] = Nonegguf_link_path: Optional[str] = Nonestem_hash = hashlib.sha256(rel.as_posix().encode()).hexdigest()[:10]model_link_dir = links_root / stem_hash if links_root is not None else Nonesafe_name = repo_name.replace("/", "-")- quant = f"-{file_type}" if file_type else ""for layer in layers:if not isinstance(layer, dict):continuemedia = layer.get("mediaType", "")digest = layer.get("digest", "")- if not digest:+ if media not in {+ "application/vnd.ollama.image.model",+ "application/vnd.ollama.image.projector",+ }:continue-+ candidate = _ollama_blob_path(blobs_dir, digest) if digest else None+ if candidate is None or not _safe_is_file(candidate):+ layer_name = "model" if media.endswith(".model") else "projector"+ return invalid_manifest(f"{layer_name} blob is missing")if media == "application/vnd.ollama.image.model":- candidate = _ollama_blob_path(blobs_dir, digest)- if candidate is None or not _safe_is_file(candidate):- continuemodel_blob = candidate- if materialize_links and model_link_dir is not None:- link_name = f"{safe_name}-{tag}{quant}.gguf"- gguf_link_path = _make_ollama_blob_link(model_link_dir, link_name, candidate)-- elif materialize_links and media == "application/vnd.ollama.image.projector":- candidate = _ollama_blob_path(blobs_dir, digest)- if candidate is not None and _safe_is_file(candidate) and model_link_dir is not None:- mmproj_name = f"{safe_name}-{tag}-mmproj.gguf"- _make_ollama_blob_link(model_link_dir, mmproj_name, candidate)+ else:+ projector_blob = candidateif model_blob is None:- return None- if materialize_links and not gguf_link_path:- return None+ return invalid_manifest("model blob is missing")++ if materialize_links:+ if model_link_dir is None:+ return invalid_manifest("link directory is unavailable")+ link_name = f"{safe_name}-{tag}.gguf"+ mmproj_name = f"{safe_name}-{tag}-mmproj.gguf"+ projector_link = _contained_link_path(model_link_dir, mmproj_name)+ if projector_link is None:+ return invalid_manifest("projector link name is unsafe")+ previous_projector: Optional[Path] = None+ previous_projector_hardlink: Optional[Path] = None+ try:+ if projector_link.is_symlink():+ try:+ previous_projector = projector_link.resolve(strict = True)+ except FileNotFoundError:+ pass+ elif projector_link.exists():+ previous_projector_hardlink = model_link_dir / (+ f".{mmproj_name}.rollback-{uuid.uuid4().hex[:8]}"+ )+ os.link(str(projector_link), str(previous_projector_hardlink))+ except (OSError, RuntimeError) as e:+ return invalid_manifest(f"existing projector link could not be preserved: {e}")++ try:+ if projector_blob is not None:+ if not _make_ollama_blob_link(model_link_dir, mmproj_name, projector_blob):+ return invalid_manifest("could not materialize projector blob")+ else:+ try:+ if projector_link.is_symlink() or projector_link.exists():+ projector_link.unlink()+ except OSError as e:+ return invalid_manifest(f"stale projector link could not be removed: {e}")++ gguf_link_path = _make_ollama_blob_link(model_link_dir, link_name, model_blob)+ if not gguf_link_path:+ restored = False+ if previous_projector_hardlink is not None:+ try:+ os.replace(str(previous_projector_hardlink), str(projector_link))+ restored = True+ except OSError:+ pass+ elif previous_projector is not None:+ restored = bool(+ _make_ollama_blob_link(model_link_dir, mmproj_name, previous_projector)+ )+ else:+ try:+ if projector_link.is_symlink() or projector_link.exists():+ projector_link.unlink()+ restored = True+ except OSError:+ pass+ if not restored:+ return invalid_manifest(+ "could not materialize model blob or restore the previous projector"+ )+ return invalid_manifest("could not materialize model blob")+ finally:+ if previous_projector_hardlink is not None:+ try:+ if previous_projector_hardlink.exists():+ previous_projector_hardlink.unlink()+ except OSError as e:+ logger.debug(+ "Could not clean up Ollama projector rollback link %s: %s",+ previous_projector_hardlink,+ e,+ )suffix = ""if model_type:@@ -356,29 +497,47 @@ def scan_ollama_dir(def _ollama_dir_for_manifest(tag_file: Path) -> Optional[Path]:- """Discovered Ollama root whose ``manifests/`` contains *tag_file*, or ``None``. Validating against known roots keeps a crafted reference from driving materialization to an arbitrary path."""- for ollama_dir in ollama_model_dirs():+ """Return a discovered or registered Ollama root containing *tag_file*."""+ known_dirs = list(ollama_model_dirs())+ try:+ from hub.storage.scan_folders import list_scan_folders+ known_dirs.extend(+ Path(folder["path"]).expanduser()+ for folder in list_scan_folders()+ if folder.get("path")+ )+ except Exception as e:+ logger.debug("Could not load registered Ollama roots: %s", e)+ for ollama_dir in known_dirs:if path_is_same_or_child(tag_file, ollama_dir / "manifests"):return ollama_dirreturn None-def materialize_ollama_model_ref(ref: str) -> str:- """Resolve an ``ollama-manifest:`` reference to a loadable ``.gguf`` path,- creating the writable symlink/hardlink on demand.-- Raises ``ValueError`` if the reference is malformed, points outside a- discovered Ollama models directory, or cannot be materialized.- """+def _validated_ollama_manifest_location(ref: str) -> tuple[Path, Path]:if not ref.startswith(_OLLAMA_MANIFEST_REF_PREFIX):raise ValueError("Not an Ollama manifest reference")-- tag_file = Path(unquote(ref[len(_OLLAMA_MANIFEST_REF_PREFIX) :]))-+ try:+ tag_file = Path(os.path.realpath(unquote(ref[len(_OLLAMA_MANIFEST_REF_PREFIX) :])))+ except (OSError, ValueError) as e:+ raise ValueError(f"Invalid Ollama manifest reference: {e}") from eollama_dir = _ollama_dir_for_manifest(tag_file)if ollama_dir is None:raise ValueError("Reference is outside any known Ollama models directory")+ try:+ canonical_ollama_dir = Path(os.path.realpath(str(ollama_dir)))+ except (OSError, ValueError) as e:+ raise ValueError(f"Invalid Ollama models directory: {e}") from e+ return tag_file, canonical_ollama_dir+++def _materialization_lock(tag_file: Path) -> threading.Lock:+ key = os.path.normcase(str(tag_file))+ with _OLLAMA_MATERIALIZE_LOCKS_GUARD:+ return _OLLAMA_MATERIALIZE_LOCKS.setdefault(key, threading.Lock())++def _materialize_ollama_model_ref_unlocked(tag_file: Path, ollama_dir: Path) -> str:links_root = _ollama_links_dir(ollama_dir)if links_root is None:raise ValueError("No writable location for Ollama .gguf links")@@ -388,7 +547,27 @@ def materialize_ollama_model_ref(ref: str) -> str:tag_file,materialize_links = True,links_root = links_root,+ reject_unsupported_layers = True,)if info is None or not info.path:raise ValueError("Could not materialize Ollama model from manifest")return info.path+++def materialize_ollama_model_ref(ref: str) -> str:+ """Resolve an Ollama ref while serializing updates to its model/projector pair."""+ tag_file, ollama_dir = _validated_ollama_manifest_location(ref)+ with _materialization_lock(tag_file):+ return _materialize_ollama_model_ref_unlocked(tag_file, ollama_dir)+++def acquire_ollama_model_ref(ref: str) -> OllamaModelLease:+ """Materialize and keep the pair stable until the caller releases the lease."""+ tag_file, ollama_dir = _validated_ollama_manifest_location(ref)+ lock = _materialization_lock(tag_file)+ lock.acquire()+ try:+ return OllamaModelLease(_materialize_ollama_model_ref_unlocked(tag_file, ollama_dir), lock)+ except BaseException:+ lock.release()+ raisediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex b3e32da6a62..a597d743d72 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -50,6 +50,11 @@ from utils.models import extract_model_size_b as _extract_model_size_bfrom utils.api_errors import openai_error_body, anthropic_error_body, error_body_for_pathfrom utils.upload_limits import STT_AUDIO_B64_MAX_CHARS, STT_AUDIO_RAW_MAX_BYTESfrom hub.dependencies import get_hf_token+from hub.services.models.ollama import (+ acquire_ollama_model_ref,+ is_ollama_manifest_ref,+ materialize_ollama_model_ref,+)from core.inference.audio_errors import (AudioBackendUnsupportedError,AudioGenerationCancelledError,@@ -181,6 +186,12 @@ _install_httpcore_asyncgen_silencer()# that bounded work out of the default executor, which drives local token streaming._STATUS_PROBE_EXECUTOR = ThreadPoolExecutor(max_workers = 2, thread_name_prefix = "inference-status")++# Lease waiters must not consume default workers needed by the current holder.+_OLLAMA_LEASE_EXECUTOR = ThreadPoolExecutor(+ max_workers = 2, thread_name_prefix = "inference-ollama-lease"+)+# Stop has to preempt exactly when the box is busy, so it gets its own workers for the same reason# the probes above do. Every /images/generate sits in the default executor for the whole run (it# blocks on the backend's serial _generate_lock), so concurrent generations can occupy that pool@@ -5023,7 +5034,12 @@ def _active_gguf_intent(# A repo or directory variant has not been resolved to a file yet. Do# not inherit the resident file or source matching would compare that# file with itself and ignore a requested quant switch.- gguf_path = source.gguf_path if model_identifier.lower().endswith(".gguf") else None,+ gguf_path = (+ source.gguf_path+ if is_ollama_manifest_ref(model_identifier)+ or model_identifier.lower().endswith(".gguf")+ else None+ ),hf_variant = request.gguf_variant or source.hf_variant,chat_template_override = chat_template_override,extra_args = effective_extra,@@ -5040,9 +5056,61 @@ def _active_gguf_intent()+def _public_model_identifier(requested: str, resolved: str) -> str:+ return requested if is_ollama_manifest_ref(requested) else resolved+++async def _lease_ollama_model_ref(+ request: LoadRequest | ValidateModelRequest, *, operation: str, stack: ExitStack+) -> Optional[str]:+ if not is_ollama_manifest_ref(request.model_path):+ return None+ loop = asyncio.get_running_loop()+ lease_future = loop.run_in_executor(+ _OLLAMA_LEASE_EXECUTOR, acquire_ollama_model_ref, request.model_path+ )+ try:+ lease = await asyncio.shield(lease_future)+ except asyncio.CancelledError:++ def _release_cancelled_lease(done):+ try:+ done.result().release()+ except BaseException:+ pass++ lease_future.add_done_callback(_release_cancelled_lease)+ raise+ except ValueError as exc:+ logger.warning("inference.ollama_materialize_failed: %s", exc)+ raise HTTPException(+ status_code = 400,+ detail = redact_native_paths(str(exc)),+ ) from exc+ stack.callback(lease.release)+ return lease.path++def _resolve_model_identifier_for_request(- request: LoadRequest | ValidateModelRequest, *, operation: str+ request: LoadRequest | ValidateModelRequest,+ *,+ operation: str,+ resolved_ollama_path: Optional[str] = None,) -> tuple[str, str, bool]:+ if is_ollama_manifest_ref(request.model_path):+ # The read-only inventory scan hands the picker an opaque manifest+ # reference; the load path owns the filesystem write that turns it into+ # a loadable .gguf link (hub/services/models/ollama.py).+ if resolved_ollama_path is None:+ try:+ resolved_ollama_path = materialize_ollama_model_ref(request.model_path)+ except ValueError as exc:+ logger.warning("inference.ollama_materialize_failed: %s", exc)+ raise HTTPException(+ status_code = 400,+ detail = redact_native_paths(str(exc)),+ ) from exc+ return resolved_ollama_path, Path(resolved_ollama_path).name, Falseif not request.native_path_lease:return request.model_path, request.model_path, Falsetry:@@ -7629,9 +7697,11 @@ def _resolve_gguf_load_intent(n_parallel: int,) -> GgufLoadIntent:"""Resolve source, companions, settings, and placement into one load value."""++ public_model_identifier = _public_model_identifier(request.model_path, config.identifier)if config.gguf_hf_repo:source = GgufLoadIntent(- model_identifier = config.identifier,+ model_identifier = public_model_identifier,hf_repo = config.gguf_hf_repo,hf_variant = config.gguf_variant,hf_token = request.hf_token,@@ -7662,7 +7732,7 @@ def _resolve_gguf_load_intent(log_native_fallback = True,)source = GgufLoadIntent(- model_identifier = config.identifier,+ model_identifier = public_model_identifier,gguf_path = config.gguf_file,mmproj_path = config.gguf_mmproj_file,mtp_draft_path = config.gguf_mtp_file,@@ -8691,9 +8761,21 @@ async def _load_model_impl(# request's managed offload flags against the stripped launch state.request = request.model_copy(update = {"llama_extra_args": extra_llama_args})+ resolved_ollama_path = await _lease_ollama_model_ref(+ request,+ operation = "load-model",+ stack = gguf_load_stack,+ )model_identifier, model_log_label, native_grant_backed = (- _resolve_model_identifier_for_request(request, operation = "load-model")+ _resolve_model_identifier_for_request(+ request,+ operation = "load-model",+ resolved_ollama_path = resolved_ollama_path,+ ))++ # Keep the inventory ref public while loading the materialized artifact.+ public_model_identifier = _public_model_identifier(request.model_path, model_identifier)# Version switching is handled by the subprocess-based inference# backend -- no ensure_transformers_version() needed here.@@ -8737,6 +8819,7 @@ async def _load_model_impl(is_local_model = _loaded_is_local_model(llama_backend, native_grant_backed, llama_backend.model_identifier),+ inference_identifier = model_identifier,)is_direct_gguf_request = model_identifier.lower().endswith(".gguf")@@ -8745,7 +8828,7 @@ async def _load_model_impl(_active_gguf_intent(request,llama_backend,- model_identifier = model_identifier,+ model_identifier = public_model_identifier,chat_template_override = effective_chat_template_override,n_parallel = _n_parallel,native_grant_backed = native_grant_backed,@@ -8851,7 +8934,7 @@ async def _load_model_impl(extra_llama_args = _resolve_inherited_extra_args(request,config,- model_identifier,+ public_model_identifier,extra_llama_args,effective_chat_template_override,)@@ -9180,7 +9263,7 @@ async def _load_model_impl()_close_load_event(_load_event,- model_log_label if native_grant_backed else config.identifier,+ model_log_label if native_grant_backed else public_model_identifier,request.gguf_variant or getattr(llama_backend, "hf_variant", None),)# Clear any idle-unload reload stash now, not only on the next poll.@@ -9206,7 +9289,7 @@ async def _load_model_impl(return _gguf_load_response(llama_backend,"loaded",- model_log_label if native_grant_backed else config.identifier,+ model_log_label if native_grant_backed else public_model_identifier,display_name = model_log_label if native_grant_backed else config.display_name,is_local_model = config.is_local,inference_identifier = config.identifier,@@ -9597,9 +9680,20 @@ async def validate_model(native_grant_backed = Falsemodel_log_label = request.model_path++ ollama_load_stack = ExitStack()try:+ resolved_ollama_path = await _lease_ollama_model_ref(+ request,+ operation = "validate-model",+ stack = ollama_load_stack,+ )model_identifier, model_log_label, native_grant_backed = (- _resolve_model_identifier_for_request(request, operation = "validate-model")+ _resolve_model_identifier_for_request(+ request,+ operation = "validate-model",+ resolved_ollama_path = resolved_ollama_path,+ ))# The frontend validates before it loads, so this needs the same guard as@@ -9630,7 +9724,10 @@ async def validate_model(# fourth argument unchanged and a --ctx-size the load is about to use would# be missing from the estimate that approves it.effective_extra_args = _resolve_inherited_extra_args(- request, config, model_identifier, getattr(request, "llama_extra_args", None)+ request,+ config,+ _public_model_identifier(request.model_path, model_identifier),+ getattr(request, "llama_extra_args", None),)# The caller's list is judged BEFORE anything rewrites it, exactly as /load@@ -9971,6 +10068,9 @@ async def validate_model(detail = "Invalid model",)+ finally:+ ollama_load_stack.close()+def _upgrade_check_config_target(request: TransformersUpgradeCheckRequest) -> str:"""The config.json this load will actually read, by the remote-code scan's precedence.diff --git a/studio/backend/tests/test_llama_extra_args_compatibility.py b/studio/backend/tests/test_llama_extra_args_compatibility.pyindex a0d13b89d37..15cb7711ebc 100644--- a/studio/backend/tests/test_llama_extra_args_compatibility.py+++ b/studio/backend/tests/test_llama_extra_args_compatibility.py@@ -268,7 +268,10 @@ def test_validate_sizes_itself_with_the_arguments_the_caller_sent():"_resolve_inherited_extra_args(\n request, config, model_identifier, None\n )"not in source)- assert 'model_identifier, getattr(request, "llama_extra_args", None)' in source+ assert (+ "_public_model_identifier(request.model_path, model_identifier),\n"+ ' getattr(request, "llama_extra_args", None),' in source+ )class _Request:llama_extra_args = ["--ctx-size", "8192"]diff --git a/studio/backend/tests/test_ollama_manifest_load_resolution.py b/studio/backend/tests/test_ollama_manifest_load_resolution.pynew file mode 100644index 00000000000..cf87ee724d8--- /dev/null+++ b/studio/backend/tests/test_ollama_manifest_load_resolution.py@@ -0,0 +1,668 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""POST /load resolves opaque ``ollama-manifest:`` inventory references.++The read-only hub inventory scan returns Ollama rows whose load id is an+``ollama-manifest:`` reference (hub/services/models/ollama.py); the load path+owns the filesystem write that turns one into a loadable ``.gguf`` link. These+tests pin that hand-off at ``_resolve_model_identifier_for_request``, which both+the load and validate routes go through.+"""++from __future__ import annotations++import json+from pathlib import Path+from urllib.parse import quote++import pytest+from fastapi import HTTPException+++def _write_ollama_store(root: Path, *, extra_layers: tuple[str, ...] = ()) -> Path:+ """A minimal Ollama layout whose optional extra layers resolve to real blobs."""+ digest_value = "a" * 64+ blob = root / "blobs" / f"sha256-{digest_value}"+ blob.parent.mkdir(parents = True)+ blob.write_bytes(b"GGUF-not-really")++ layers = [+ {+ "mediaType": "application/vnd.ollama.image.model",+ "digest": f"sha256:{digest_value}",+ }+ ]+ for index, media_type in enumerate(extra_layers, start = 1):+ layer_digest = f"{index:064x}"+ (root / "blobs" / f"sha256-{layer_digest}").write_text("{}", encoding = "utf-8")+ layers.append(+ {+ "mediaType": media_type,+ "digest": f"sha256:{layer_digest}",+ }+ )++ tag_file = root / "manifests" / "registry.ollama.ai" / "library" / "llama3" / "latest"+ tag_file.parent.mkdir(parents = True)+ tag_file.write_text(+ json.dumps(+ {+ "config": {},+ "layers": layers,+ }+ ),+ encoding = "utf-8",+ )+ return tag_file+++def _manifest_ref(tmp_path: Path, monkeypatch) -> str:+ from hub.services.models import ollama++ root = tmp_path / "ollama"+ _write_ollama_store(root)+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])++ rows = ollama.scan_ollama_dir(root)+ assert len(rows) == 1+ ref = rows[0].load_id+ assert ollama.is_ollama_manifest_ref(ref)+ return ref+++def test_custom_folder_scan_preserves_ollama_rows(tmp_path):+ from hub.services.models import local_inventory++ root = tmp_path / "custom-ollama"+ _write_ollama_store(root)++ rows = [+ local_inventory._promote_to_custom_source(row)+ for row in local_inventory._scan_custom_folder(root)+ ]++ assert len(rows) == 1+ assert rows[0].source == "ollama"+ assert rows[0].load_id.startswith("ollama-manifest:")+++def test_registered_custom_ollama_ref_can_be_materialized(tmp_path, monkeypatch):+ from hub.services.models import ollama+ from hub.storage import scan_folders++ root = tmp_path / "registered-ollama"+ _write_ollama_store(root)+ ref = ollama.scan_ollama_dir(root)[0].load_id+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [])+ monkeypatch.setattr(scan_folders, "list_scan_folders", lambda: [{"path": str(root)}])++ assert Path(ollama.materialize_ollama_model_ref(ref)).is_file()+++def test_load_resolves_a_manifest_ref_to_a_gguf_link(tmp_path, monkeypatch):+ from models.inference import LoadRequest+ from routes.inference import _resolve_model_identifier_for_request++ ref = _manifest_ref(tmp_path, monkeypatch)+ identifier, label, native_grant_backed = _resolve_model_identifier_for_request(+ LoadRequest(model_path = ref), operation = "load-model"+ )++ assert identifier.endswith(".gguf")+ assert Path(identifier).is_file(), "the .gguf link must be materialized"+ assert label == Path(identifier).name, "logs get the link name, not the opaque ref"+ assert native_grant_backed is False+++def test_public_identity_keeps_the_manifest_ref():+ from inspect import getsource++ from routes.inference import _public_model_identifier, validate_model++ ref = "ollama-manifest:%2Fhome%2Fu%2F.ollama%2Fmanifests%2Fllama3"+ assert _public_model_identifier(ref, "/tmp/.studio_links/llama3.gguf") == ref+ assert _public_model_identifier("owner/model", "owner/model") == "owner/model"+ assert "_public_model_identifier(request.model_path, model_identifier)" in getsource(+ validate_model+ )+++def test_retagged_manifest_replaces_one_hardlink_and_invalidates_loaded_identity(+ tmp_path, monkeypatch+):+ from types import SimpleNamespace++ from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend+ from hub.services.models import ollama++ root = tmp_path / "ollama-retagged"+ tag_file = _write_ollama_store(root)+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])++ def deny_symlink(*_args, **_kwargs):+ raise OSError("symlinks disabled")++ monkeypatch.setattr(Path, "symlink_to", deny_symlink)+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"++ first_path = ollama.materialize_ollama_model_ref(ref)+ first_resolved = Path(first_path).resolve()+ first_stat = first_resolved.stat()+ first_identity = (+ (+ str(first_resolved),+ first_stat.st_dev,+ first_stat.st_ino,+ first_stat.st_size,+ first_stat.st_mtime_ns,+ ),+ )+ assert Path(first_path).read_bytes() == b"GGUF-not-really"++ replacement_digest = "b" * 64+ replacement_blob = root / "blobs" / f"sha256-{replacement_digest}"+ replacement_blob.write_bytes(b"GGUF-replacement")+ manifest = json.loads(tag_file.read_text(encoding = "utf-8"))+ manifest["layers"][0]["digest"] = f"sha256:{replacement_digest}"++ replacement_config_digest = "c" * 64+ (root / "blobs" / f"sha256-{replacement_config_digest}").write_text(+ json.dumps({"file_type": "Q8_0"}), encoding = "utf-8"+ )+ manifest["config"] = {"digest": f"sha256:{replacement_config_digest}"}+ tag_file.write_text(json.dumps(manifest), encoding = "utf-8")++ second_path = ollama.materialize_ollama_model_ref(ref)++ assert second_path == first_path+ assert Path(second_path).read_bytes() == b"GGUF-replacement"+ assert list((root / ".studio_links").rglob("*.gguf")) == [Path(second_path)]++ resident = SimpleNamespace(+ is_loaded = True,+ _model_identifier = ref,+ _gguf_path = first_path,+ _gguf_load_identity = first_identity,+ )+ replacement_intent = GgufLoadIntent(model_identifier = ref, gguf_path = second_path)+ assert not LlamaCppBackend.matches_load_source(resident, replacement_intent)+++def test_missing_projector_retag_is_rejected_before_main_link_changes(tmp_path, monkeypatch):+ from hub.services.models import ollama++ root = tmp_path / "ollama-missing-projector"+ tag_file = _write_ollama_store(+ root,+ extra_layers = ("application/vnd.ollama.image.projector",),+ )+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"++ model_path = ollama.materialize_ollama_model_ref(ref)+ projector_path = next(Path(model_path).parent.glob("*-mmproj.gguf"))++ replacement_digest = "b" * 64+ (root / "blobs" / f"sha256-{replacement_digest}").write_bytes(b"GGUF-replacement")+ manifest = json.loads(tag_file.read_text(encoding = "utf-8"))+ manifest["layers"][0]["digest"] = f"sha256:{replacement_digest}"+ manifest["layers"][1]["digest"] = f"sha256:{'c' * 64}"+ tag_file.write_text(json.dumps(manifest), encoding = "utf-8")++ with pytest.raises(ValueError, match = "projector"):+ ollama.materialize_ollama_model_ref(ref)++ assert Path(model_path).read_bytes() == b"GGUF-not-really"+ assert projector_path.read_bytes() == b"{}"++[email protected]("remove_projector", [False, True])+def test_dangling_projector_link_can_be_replaced_or_removed(+ tmp_path, monkeypatch, remove_projector+):+ from hub.services.models import ollama++ root = tmp_path / "ollama-dangling-projector"+ tag_file = _write_ollama_store(+ root,+ extra_layers = ("application/vnd.ollama.image.projector",),+ )+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"+ model_path = ollama.materialize_ollama_model_ref(ref)+ projector_path = next(Path(model_path).parent.glob("*-mmproj.gguf"))++ manifest = json.loads(tag_file.read_text(encoding = "utf-8"))+ if remove_projector:+ manifest["layers"] = manifest["layers"][:1]+ else:+ projector_digest = "c" * 64+ (root / "blobs" / f"sha256-{projector_digest}").write_bytes(b"GGUF-projector-replacement")+ manifest["layers"][1]["digest"] = f"sha256:{projector_digest}"+ tag_file.write_text(json.dumps(manifest), encoding = "utf-8")++ real_is_symlink = Path.is_symlink+ real_resolve = Path.resolve++ def is_symlink(path):+ return path == projector_path or real_is_symlink(path)++ def resolve(path, *args, **kwargs):+ if path == projector_path and kwargs.get("strict"):+ raise FileNotFoundError(projector_path)+ return real_resolve(path, *args, **kwargs)++ monkeypatch.setattr(Path, "is_symlink", is_symlink)+ monkeypatch.setattr(Path, "resolve", resolve)++ assert ollama.materialize_ollama_model_ref(ref) == model_path+ if remove_projector:+ assert not projector_path.exists()+ else:+ assert projector_path.read_bytes() == b"GGUF-projector-replacement"+++def test_failed_main_retag_restores_the_previous_projector(tmp_path, monkeypatch):+ from hub.services.models import ollama++ root = tmp_path / "ollama-pair-rollback"+ tag_file = _write_ollama_store(+ root,+ extra_layers = ("application/vnd.ollama.image.projector",),+ )++ def deny_symlink(*_args, **_kwargs):+ raise OSError("symlinks disabled")++ monkeypatch.setattr(Path, "symlink_to", deny_symlink)+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"+ model_path = ollama.materialize_ollama_model_ref(ref)+ projector_path = next(Path(model_path).parent.glob("*-mmproj.gguf"))++ model_digest = "b" * 64+ projector_digest = "c" * 64+ model_blob = root / "blobs" / f"sha256-{model_digest}"+ projector_blob = root / "blobs" / f"sha256-{projector_digest}"+ model_blob.write_bytes(b"GGUF-replacement")+ projector_blob.write_bytes(b"GGUF-projector-replacement")+ manifest = json.loads(tag_file.read_text(encoding = "utf-8"))+ manifest["layers"][0]["digest"] = f"sha256:{model_digest}"+ manifest["layers"][1]["digest"] = f"sha256:{projector_digest}"+ tag_file.write_text(json.dumps(manifest), encoding = "utf-8")++ make_link = ollama._make_ollama_blob_link++ def fail_replacement_model(link_dir, link_name, target):+ if target == model_blob:+ return None+ return make_link(link_dir, link_name, target)++ monkeypatch.setattr(ollama, "_make_ollama_blob_link", fail_replacement_model)+ with pytest.raises(ValueError, match = "model blob"):+ ollama.materialize_ollama_model_ref(ref)++ assert Path(model_path).read_bytes() == b"GGUF-not-really"+ assert projector_path.read_bytes() == b"{}"+++def test_materialization_lease_blocks_a_concurrent_retag(tmp_path, monkeypatch):+ import threading++ from hub.services.models import ollama++ root = tmp_path / "ollama-materialization-lease"+ tag_file = _write_ollama_store(root)+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"++ alternate_ref = ref.replace("%2F", "%2f")+ assert alternate_ref != ref+ lease = ollama.acquire_ollama_model_ref(ref)++ replacement_digest = "b" * 64+ (root / "blobs" / f"sha256-{replacement_digest}").write_bytes(b"GGUF-replacement")+ manifest = json.loads(tag_file.read_text(encoding = "utf-8"))+ manifest["layers"][0]["digest"] = f"sha256:{replacement_digest}"+ tag_file.write_text(json.dumps(manifest), encoding = "utf-8")++ started = threading.Event()+ finished = threading.Event()++ def retag():+ started.set()+ ollama.materialize_ollama_model_ref(alternate_ref)+ finished.set()++ worker = threading.Thread(target = retag)+ worker.start()+ assert started.wait(1)+ assert not finished.wait(0.1)+ lease.release()+ worker.join(timeout = 1)++ assert finished.is_set()+ assert Path(lease.path).read_bytes() == b"GGUF-replacement"+++def test_waiting_route_lease_does_not_starve_the_default_executor(tmp_path, monkeypatch):+ import asyncio+ import threading+ from concurrent.futures import ThreadPoolExecutor+ from contextlib import ExitStack++ from hub.services.models import ollama+ from models.inference import ValidateModelRequest+ from routes import inference++ root = tmp_path / "ollama-route-lease"+ tag_file = _write_ollama_store(root)+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"+ request = ValidateModelRequest(model_path = ref)++ real_acquire = inference.acquire_ollama_model_ref+ waiter_started = threading.Event()+ calls_lock = threading.Lock()+ calls = 0++ def observed_acquire(model_ref):+ nonlocal calls+ with calls_lock:+ calls += 1+ is_waiter = calls == 2+ if is_waiter:+ waiter_started.set()+ return real_acquire(model_ref)++ monkeypatch.setattr(inference, "acquire_ollama_model_ref", observed_acquire)++ async def scenario():+ asyncio.get_running_loop().set_default_executor(ThreadPoolExecutor(max_workers = 1))+ first_stack = ExitStack()+ second_stack = ExitStack()+ await inference._lease_ollama_model_ref(+ request, operation = "validate-model", stack = first_stack+ )+ waiter = asyncio.create_task(+ inference._lease_ollama_model_ref(+ request, operation = "validate-model", stack = second_stack+ )+ )+ for _ in range(100):+ if waiter_started.is_set():+ break+ await asyncio.sleep(0.01)+ assert waiter_started.is_set()+ try:+ progressed = await asyncio.wait_for(asyncio.to_thread(lambda: True), timeout = 1)+ except TimeoutError:+ progressed = False+ finally:+ first_stack.close()+ await asyncio.wait_for(waiter, timeout = 1)+ second_stack.close()+ return progressed++ assert asyncio.run(scenario())+++def test_projector_removal_deletes_the_stale_link(tmp_path, monkeypatch):+ from hub.services.models import ollama++ root = tmp_path / "ollama-projector-removed"+ tag_file = _write_ollama_store(+ root,+ extra_layers = ("application/vnd.ollama.image.projector",),+ )+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"++ model_path = ollama.materialize_ollama_model_ref(ref)+ projector_path = next(Path(model_path).parent.glob("*-mmproj.gguf"))+ manifest = json.loads(tag_file.read_text(encoding = "utf-8"))+ manifest["layers"] = manifest["layers"][:1]+ tag_file.write_text(json.dumps(manifest), encoding = "utf-8")++ assert ollama.materialize_ollama_model_ref(ref) == model_path+ assert not projector_path.exists()+++def test_projector_only_retag_invalidates_loaded_identity(tmp_path, monkeypatch):+ from types import SimpleNamespace++ from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend+ from hub.services.models import ollama++ root = tmp_path / "ollama-projector-retagged"+ tag_file = _write_ollama_store(+ root,+ extra_layers = ("application/vnd.ollama.image.projector",),+ )+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"++ model_path = ollama.materialize_ollama_model_ref(ref)+ projector_path = next(Path(model_path).parent.glob("*-mmproj.gguf"))+ first_identity = LlamaCppBackend._gguf_load_source_identity(model_path, str(projector_path))++ replacement_digest = "c" * 64+ replacement_blob = root / "blobs" / f"sha256-{replacement_digest}"+ replacement_blob.write_bytes(b"GGUF-projector-replacement")+ manifest = json.loads(tag_file.read_text(encoding = "utf-8"))+ manifest["layers"][1]["digest"] = f"sha256:{replacement_digest}"+ tag_file.write_text(json.dumps(manifest), encoding = "utf-8")++ assert ollama.materialize_ollama_model_ref(ref) == model_path+ assert Path(projector_path).read_bytes() == b"GGUF-projector-replacement"++ resident = SimpleNamespace(+ is_loaded = True,+ _model_identifier = ref,+ _gguf_path = model_path,+ _gguf_load_identity = first_identity,+ )+ replacement_intent = GgufLoadIntent(+ model_identifier = ref,+ gguf_path = model_path,+ mmproj_path = str(projector_path),+ )+ assert not LlamaCppBackend.matches_load_source(resident, replacement_intent)+++def test_ollama_intent_loads_the_link_but_keeps_the_manifest_identity(tmp_path, monkeypatch):+ from types import SimpleNamespace++ from models.inference import LoadRequest+ from routes.inference import (+ _active_gguf_intent,+ _LoadPlacement,+ _llama_status_model_ids,+ _resolve_gguf_load_intent,+ _resolve_model_identifier_for_request,+ )++ ref = _manifest_ref(tmp_path, monkeypatch)+ resolved, _, _ = _resolve_model_identifier_for_request(+ LoadRequest(model_path = ref), operation = "load-model"+ )+ config = SimpleNamespace(+ identifier = resolved,+ gguf_hf_repo = None,+ gguf_file = resolved,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ gguf_variant = None,+ is_vision = False,+ )++ intent = _resolve_gguf_load_intent(+ config,+ LoadRequest(model_path = ref),+ native_grant_backed = False,+ chat_template_override = None,+ extra_args = None,+ placement = _LoadPlacement(None, None, False, None),+ n_parallel = 1,+ )++ assert intent.gguf_path == resolved+ assert intent.model_identifier == ref++ backend = SimpleNamespace(+ model_identifier = intent.model_identifier,+ _native_grant_backed = False,+ _native_display_label = None,+ _openai_advertised_id = None,+ )+ assert _llama_status_model_ids(backend) == (ref, ref)++ active_backend = SimpleNamespace(+ extra_args = None,+ last_load_intent = intent,+ hf_repo = None,+ gguf_path = resolved,+ hf_variant = None,+ layer_preserves_tensor_intent = False,+ )+ active_intent = _active_gguf_intent(+ LoadRequest(model_path = ref),+ active_backend,+ model_identifier = ref,+ chat_template_override = None,+ n_parallel = 1,+ native_grant_backed = False,+ )+ assert active_intent.model_identifier == ref+ assert active_intent.gguf_path == resolved+++_UNSUPPORTED_RUNTIME_LAYERS = (+ "application/vnd.ollama.image.params",+ "application/vnd.ollama.image.template",+ "application/vnd.ollama.image.system",+ "application/vnd.ollama.image.messages",+ "application/vnd.ollama.image.adapter",+ "application/vnd.ollama.image.prompt",+ "application/vnd.ollama.image.future-runtime",+)+++def _rich_manifest_ref(tmp_path: Path, monkeypatch) -> tuple[Path, str]:+ from hub.services.models import ollama++ root = tmp_path / "ollama-rich"+ tag_file = _write_ollama_store(root, extra_layers = _UNSUPPORTED_RUNTIME_LAYERS)+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"+ return root, ref+++def test_rich_manifest_is_withheld_from_inventory(tmp_path, monkeypatch):+ from hub.services.models import ollama+ root, _ = _rich_manifest_ref(tmp_path, monkeypatch)++ assert ollama.scan_ollama_dir(root) == []+++def test_rich_manifest_ref_is_rejected_without_creating_links(tmp_path, monkeypatch):+ from models.inference import LoadRequest+ from routes.inference import _resolve_model_identifier_for_request++ root, ref = _rich_manifest_ref(tmp_path, monkeypatch)++ with pytest.raises(HTTPException) as excinfo:+ _resolve_model_identifier_for_request(LoadRequest(model_path = ref), operation = "load-model")++ assert excinfo.value.status_code == 400+ assert "unsupported runtime layers" in str(excinfo.value.detail).lower()+ for media_type in _UNSUPPORTED_RUNTIME_LAYERS:+ assert media_type in str(excinfo.value.detail)+ links_root = root / ".studio_links"+ assert not links_root.exists() or not any(path.is_file() for path in links_root.rglob("*"))+++def test_license_metadata_does_not_hide_a_plain_manifest(tmp_path, monkeypatch):+ from hub.services.models import ollama++ root = tmp_path / "ollama-licensed"+ _write_ollama_store(+ root,+ extra_layers = ("application/vnd.ollama.image.license",),+ )+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])++ rows = ollama.scan_ollama_dir(root)+ assert len(rows) == 1+ assert ollama.is_ollama_manifest_ref(rows[0].load_id)+++def test_non_object_manifest_ref_is_a_400(tmp_path, monkeypatch):+ from hub.services.models import ollama+ from models.inference import LoadRequest+ from routes.inference import _resolve_model_identifier_for_request++ root = tmp_path / "ollama-non-object-manifest"+ tag_file = _write_ollama_store(root)+ tag_file.write_text("[]", encoding = "utf-8")+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"++ assert ollama.scan_ollama_dir(root) == []+ with pytest.raises(HTTPException) as excinfo:+ _resolve_model_identifier_for_request(LoadRequest(model_path = ref), operation = "load-model")+ assert excinfo.value.status_code == 400+ assert "manifest" in str(excinfo.value.detail).lower()+++def test_non_object_config_blob_ref_is_a_400(tmp_path, monkeypatch):+ from hub.services.models import ollama+ from models.inference import LoadRequest+ from routes.inference import _resolve_model_identifier_for_request++ root = tmp_path / "ollama-non-object-config"+ tag_file = _write_ollama_store(root)+ config_digest = "b" * 64+ (root / "blobs" / f"sha256-{config_digest}").write_text("[]", encoding = "utf-8")+ manifest = json.loads(tag_file.read_text(encoding = "utf-8"))+ manifest["config"] = {"digest": f"sha256:{config_digest}"}+ tag_file.write_text(json.dumps(manifest), encoding = "utf-8")+ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [root])+ ref = f"ollama-manifest:{quote(str(tag_file), safe = '')}"++ assert ollama.scan_ollama_dir(root) == []+ with pytest.raises(HTTPException) as excinfo:+ _resolve_model_identifier_for_request(LoadRequest(model_path = ref), operation = "load-model")+ assert excinfo.value.status_code == 400+ assert "config blob" in str(excinfo.value.detail).lower()+++def test_a_ref_outside_known_ollama_dirs_is_a_400(tmp_path, monkeypatch):+ from hub.services.models import ollama+ from models.inference import LoadRequest+ from routes.inference import _resolve_model_identifier_for_request++ monkeypatch.setattr(ollama, "ollama_model_dirs", lambda: [tmp_path / "elsewhere"])++ outside = tmp_path / "not-ollama" / "manifests" / "x" / "y" / "latest"+ ref = f"ollama-manifest:{outside}"+ with pytest.raises(HTTPException) as excinfo:+ _resolve_model_identifier_for_request(LoadRequest(model_path = ref), operation = "load-model")+ assert excinfo.value.status_code == 400+++def test_non_ollama_paths_take_the_existing_path(tmp_path):+ from models.inference import LoadRequest+ from routes.inference import _resolve_model_identifier_for_request++ identifier, label, native_grant_backed = _resolve_model_identifier_for_request(+ LoadRequest(model_path = "unsloth/model-GGUF"), operation = "load-model"+ )+ assert (identifier, label, native_grant_backed) == (+ "unsloth/model-GGUF",+ "unsloth/model-GGUF",+ False,+ )diff --git a/studio/backend/tests/test_tunnel_safe_long_post.py b/studio/backend/tests/test_tunnel_safe_long_post.pyindex 0b75a864216..72b59816eff 100644--- a/studio/backend/tests/test_tunnel_safe_long_post.py+++ b/studio/backend/tests/test_tunnel_safe_long_post.py@@ -331,7 +331,7 @@ def _stub_unsloth_load_over_a_resident_gguf(route, monkeypatch, *, teardown):monkeypatch.setattr(route,"_resolve_model_identifier_for_request",- lambda request, operation: (request.model_path, request.model_path, False),+ lambda request, operation, **_kwargs: (request.model_path, request.model_path, False),)monkeypatch.setattr(route,diff --git a/studio/backend/tests/test_validate_model_error.py b/studio/backend/tests/test_validate_model_error.pyindex a62919f80db..db26edf00ba 100644--- a/studio/backend/tests/test_validate_model_error.py+++ b/studio/backend/tests/test_validate_model_error.py@@ -47,7 +47,7 @@ def _provoke(monkeypatch.setattr(inf,"_resolve_model_identifier_for_request",- lambda request, operation: ("org/repo", "org/repo", native),+ lambda request, operation, **_kwargs: ("org/repo", "org/repo", native),)def _raise(*_args, **_kwargs):@@ -104,7 +104,7 @@ def _drive_validate(monkeypatch, *, is_gguf: bool):monkeypatch.setattr(inf,"_resolve_model_identifier_for_request",- lambda request, operation: ("org/mixed-repo", "org/mixed-repo", False),+ lambda request, operation, **_kwargs: ("org/mixed-repo", "org/mixed-repo", False),)config = SimpleNamespace(identifier = "org/mixed-repo",@@ -220,7 +220,7 @@ def _drive_validate_lora(monkeypatch, *, adapter_needs_trc, base_needs_trc):monkeypatch.setattr(inf,"_resolve_model_identifier_for_request",- lambda request, operation: (adapter, adapter, False),+ lambda request, operation, **_kwargs: (adapter, adapter, False),)config = SimpleNamespace(identifier = adapter,diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 21b2be2f5ef..00fc91b1fb6 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -2193,8 +2193,11 @@ const IMAGE_OR_VIDEO_TASKS: ReadonlySet<string> = new Set(["image-diffusion-unsupported",]);-// Scan folders the picker exposes. hf_cache is already in the cached lists,-// and ollama links are not loadable.+// Scan folders the picker exposes. hf_cache is already in the cached lists.+// ollama stays out by policy: its rows load through the picker, but the API+// auto-switch index never resolves them (local_model_resolver.py skips the+// Ollama scanner), so auto-loading one would promise an API identity that+// cannot be reached.const AUTO_LOAD_LOCAL_SOURCES: ReadonlySet<string> = new Set(["models_dir","lmstudio",diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex b3afb903858..88efd2d108b 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -534,7 +534,7 @@ export interface LocalModelInfo {id: string;display_name: string;path: string;- source: "models_dir" | "hf_cache" | "lmstudio" | "custom";+ source: "models_dir" | "hf_cache" | "lmstudio" | "ollama" | "custom";model_id?: string | null;// Backend-detected weights format ("gguf" when known), for folders whose name lacks -GGUF.model_format?: string | null;diff --git a/studio/frontend/src/features/chat/local-model-options.ts b/studio/frontend/src/features/chat/local-model-options.tsindex b972d77200a..71e789ba5c2 100644--- a/studio/frontend/src/features/chat/local-model-options.ts+++ b/studio/frontend/src/features/chat/local-model-options.ts@@ -1,21 +1,20 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-import type { LocalModelInfo } from "@/features/hub/inventory/api";-import type { LoraModelOption } from "@/features/model-picker/components/model-selector/types";+import type { LocalModelInfo } from "@/features/hub";+import type { LoraModelOption } from "@/features/model-picker";/** The device-inventory sources Chat lists as local models.*- * Deliberately the same set as the picker's `PICKER_LOCAL_SOURCES`, and `ollama` is- * deliberately absent from both. The compat endpoint Chat used to call materialized a- * `.gguf` link eagerly and handed back a loadable path, while `/api/hub/local` scans- * read-only and returns an opaque `ollama-manifest:` reference that only- * `materialize_ollama_model_ref` can resolve. Nothing calls that yet, so offering these- * rows would produce entries that fail on selection rather than load.+ * Deliberately the same set as the picker's `PICKER_LOCAL_SOURCES`. `/api/hub/local`+ * scans read-only, so an Ollama row's id is an opaque `ollama-manifest:` reference;+ * POST /load resolves it through `materialize_ollama_model_ref`, which creates the+ * `.gguf` link on demand, so the reference is loadable as-is.*/const CHAT_LOCAL_SOURCES: ReadonlySet<LocalModelInfo["source"]> = new Set(["lmstudio","models_dir",+ "ollama","custom",]);@@ -23,6 +22,8 @@ function baseModelLabel(source: LocalModelInfo["source"]): string {switch (source) {case "lmstudio":return "LM Studio";+ case "ollama":+ return "Ollama";case "custom":return "Custom Folders";default:@@ -57,12 +58,11 @@ export function chatLocalModelOptions(baseModel: baseModelLabel(model.source),updatedAt: model.updated_at ?? undefined,source: "local" as const,- // Only a single .gguf file, which is the one local shape the picker loads- // straight through as a GGUF (`localDirectGgufMeta`). A GGUF DIRECTORY is- // deliberately left alone: that row expands to pick a quant, and the- // variant it yields is not something a chat row records, so claiming GGUF- // for it would send llama-server flags for a quant nobody chose.- ...(model.path.toLowerCase().endsWith(".gguf") ? { isGguf: true } : {}),+ isGguf:+ model.source === "ollama" || model.path.toLowerCase().endsWith(".gguf")+ ? true+ : undefined,+ isDirectGguf: model.source === "ollama" ? true : undefined,});}return options;diff --git a/studio/frontend/src/features/hub/lib/model-identity.ts b/studio/frontend/src/features/hub/lib/model-identity.tsindex a84f623ae56..6d6545714a7 100644--- a/studio/frontend/src/features/hub/lib/model-identity.ts+++ b/studio/frontend/src/features/hub/lib/model-identity.ts@@ -194,13 +194,19 @@ export function residentModelIdMatches(}// Ollama's blobs reach the picker through a symlink dir that local_model_resolver.py refuses-// to index, so mirroring their settings would advertise a load that cannot happen.+// to index, so mirroring their settings would advertise a load that cannot happen. The+// inventory's opaque `ollama-manifest:` references resolve to those same skipped links, so+// they carry the same non-promise.const OLLAMA_LINK_SEGMENTS = new Set([".studio_links", "ollama_links"]);+const OLLAMA_MANIFEST_REF_PREFIX = "ollama-manifest:";export function isOllamaLinkPath(modelId: string | null | undefined): boolean {if (!modelId) {return false;}+ if (modelId.startsWith(OLLAMA_MANIFEST_REF_PREFIX)) {+ return true;+ }return modelId.replace(BACKSLASHES_RE, "/").split("/")diff --git a/studio/frontend/src/features/model-picker/components/model-selector/local-gguf-policy.ts b/studio/frontend/src/features/model-picker/components/model-selector/local-gguf-policy.tsnew file mode 100644index 00000000000..d493ae08e12--- /dev/null+++ b/studio/frontend/src/features/model-picker/components/model-selector/local-gguf-policy.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { LoraModelOption } from "./types";++export type LocalGgufKind = "direct" | "variants" | null;++/** Resolve local GGUF interaction semantics without letting repo-name heuristics+ * override an explicit one-artifact inventory source such as Ollama. */+export function localGgufKindFor(+ option: Pick<LoraModelOption, "source" | "isDirectGguf">,+ looksLikeVariantRepo: boolean,+): LocalGgufKind {+ if (option.source !== "local") {+ return null;+ }+ if (option.isDirectGguf === true) {+ return "direct";+ }+ return looksLikeVariantRepo ? "variants" : 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 17074c47c20..96ff5d24c64 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@@ -142,6 +142,7 @@ import {groupForRepoId,} from "./model-catalog";import { curatedArtifactIsOfferable } from "./host-artifact-policy";+import { localGgufKindFor } from "./local-gguf-policy";import { ModelDeleteAction } from "./model-delete-action";import { ModelLoadSettingsAction } from "./model-load-settings-action";import { ModelRowMenu } from "./model-row-menu";@@ -2696,8 +2697,14 @@ export function HubModelPicker({() => pickerInventory.localModels.filter((m) => m.source === "models_dir"),[pickerInventory.localModels],);+ // Ollama rows list alongside custom folders: both are user-managed stores+ // outside ./models, and an Ollama root added as a custom folder is where+ // the missing rows were expected (#9226).const customFolderModels = useMemo(- () => pickerInventory.localModels.filter((m) => m.source === "custom"),+ () =>+ pickerInventory.localModels.filter(+ (m) => m.source === "custom" || m.source === "ollama",+ ),[pickerInventory.localModels],);useEffect(() => {@@ -5721,9 +5728,12 @@ export function HubModelPicker({// folders) in addition to name/path so the row classifies// and loads through the same GGUF path as the filter.const isGguf = localModelIsGguf(m);- // Single .gguf files (e.g. Ollama blobs) load directly;- // GGUF repos/directories expand to pick a variant.- const isDirectGguf = isGgufFile;+ // Single .gguf files load directly; GGUF repos and+ // directories expand to pick a variant. An Ollama+ // manifest reference names one blob, so it is direct+ // too: POST /load materializes its .gguf link.+ const isDirectGguf =+ isGgufFile || m.source === "ollama";const optionKey = makeModelOptionKey("custom-folder",m.id,@@ -5744,7 +5754,9 @@ export function HubModelPicker({loadedModelId,activeGgufVariant,m.id,- isGgufFile+ // Direct loads set no active variant, so+ // requiring one never reads as loaded.+ isDirectGguf? "ignore": isGguf? "required"@@ -6548,8 +6560,12 @@ function FineTunedRows({const isExportedGguf = isExported && isGguf;const canDelete = canDeleteLoraModel(adapter);const isTrainingFull = isTraining && isMerged;- const isLocalGgufDir =- isLocal && (isGgufRepo(adapter.id) || isGgufRepo(adapter.name));+ const localGgufKind = localGgufKindFor(+ adapter,+ isGgufRepo(adapter.id) || isGgufRepo(adapter.name),+ );+ const isLocalGgufDir = localGgufKind === "variants";+ const isLocalDirectGguf = localGgufKind === "direct";// A checkpoint that fine-tunes a TTS/STT model has to reach the Audio page:// chat/completions cannot serve it and reports the adapter as "not downloaded".// The pipeline tag is what onSelect routes on, so carry the detected codec as one.@@ -6557,13 +6573,13 @@ function FineTunedRows({source: isLocal ? "local" : isExported ? "exported" : "lora",isLora: !isLocal && !isMerged && !isGguf,isDownloaded: true,- isGguf: false,+ isGguf: isLocalDirectGguf,pipelineTag: audioPipelineTagFor(adapter.audioType, true),};const canConfigure = !(isLocalGgufDir || isExportedGguf);const optionKey = makeModelOptionKey("lora", adapter.id);const tag = isLocal- ? isLocalGgufDir+ ? isLocalGgufDir || isLocalDirectGguf? "GGUF": "Local": isGguf@@ -6576,7 +6592,7 @@ function FineTunedRows({: "LoRA": "LoRA";const meta = isLocal- ? isLocalGgufDir+ ? isLocalGgufDir || isLocalDirectGguf? "GGUF": "Local": isTrainingFull@@ -6596,7 +6612,11 @@ function FineTunedRows({loadedModelId,activeGgufVariant,adapter.id,- isLocalGgufDir || isExportedGguf ? "required" : "none",+ isLocalDirectGguf+ ? "ignore"+ : isLocalGgufDir || isExportedGguf+ ? "required"+ : "none",)}optionProps={loraModelList.getOptionProps(optionKey,diff --git a/studio/frontend/src/features/model-picker/components/model-selector/types.ts b/studio/frontend/src/features/model-picker/components/model-selector/types.tsindex 18b5bc006ab..bc60a23f1ec 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/types.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/types.ts@@ -24,6 +24,10 @@ export interface LoraModelOption extends ModelOption {baseModel?: string;updatedAt?: number;source?: "training" | "exported" | "local";++ /** This local GGUF is one directly loadable artifact, not a repo whose quant+ * variants must be listed first. */+ isDirectGguf?: boolean;exportType?: "lora" | "merged" | "gguf";/** Codec when the checkpoint fine-tunes an audio model, else null. */audioType?: string | null;diff --git a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.tsindex 663d6528999..9823c796c0a 100644--- a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts+++ b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts@@ -20,6 +20,7 @@ import { allowedHiddenModelIdMatches } from "../components/model-selector/audio-const PICKER_LOCAL_SOURCES: ReadonlySet<LocalSource> = new Set(["lmstudio","models_dir",+ "ollama","custom",]);diff --git a/studio/frontend/tests/chat-local-model-options.test.ts b/studio/frontend/tests/chat-local-model-options.test.tsindex f0c8b96c964..f599b626b70 100644--- a/studio/frontend/tests/chat-local-model-options.test.ts+++ b/studio/frontend/tests/chat-local-model-options.test.ts@@ -12,9 +12,11 @@ import { registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();-const { chatLocalModelOptions } = await import(- "../src/features/chat/local-model-options.ts"-);+const { chatLocalModelOptions } =+ await import("../src/features/chat/local-model-options.ts");++const { localGgufKindFor } =+ await import("../src/features/model-picker/components/model-selector/local-gguf-policy.ts");function row(over: Record<string, unknown> = {}) {return {@@ -29,21 +31,27 @@ function row(over: Record<string, unknown> = {}) {} as never;}-test("Ollama rows are withheld until their refs are loadable", () => {- // /api/hub/local scans read-only and returns an opaque `ollama-manifest:` id that only- // materialize_ollama_model_ref can turn into a .gguf path, and nothing calls that yet.- // The picker withholds these rows for the same reason (PICKER_LOCAL_SOURCES), so Chat- // matches it: an entry that fails on click is worse than one that is not offered.- assert.deepEqual(- chatLocalModelOptions([- row({- id: "ollama-manifest:%2Fhome%2Fu%2F.ollama%2Fmanifests%2Fllama3",- display_name: "llama3",- source: "ollama",- }),- ]),- [],- );+test("Ollama rows are offered under their own label", () => {+ // /api/hub/local scans read-only and returns an opaque `ollama-manifest:` id;+ // POST /load resolves it through materialize_ollama_model_ref, so the reference+ // is loadable as-is and Chat lists it like the picker does (PICKER_LOCAL_SOURCES).+ const options = chatLocalModelOptions([+ row({+ id: "ollama-manifest:%2Fhome%2Fu%2F.ollama%2Fmanifests%2Fllama3",+ display_name: "llama3-GGUF-q4",+ source: "ollama",+ model_format: "gguf",+ }),+ ]);+ assert.equal(options.length, 1);+ const option = options[0];+ assert.ok(option);+ assert.equal(option.name, "llama3-GGUF-q4");+ assert.equal(option.baseModel, "Ollama");+ assert.equal(option.isGguf, true);+ assert.equal(option.isDirectGguf, true);+ // An explicit one-artifact source outranks a name that looks like a GGUF repo.+ assert.equal(localGgufKindFor(option, true), "direct");});test("a directory with two weight formats yields one option per load id", () => {@@ -58,7 +66,12 @@ test("a directory with two weight formats yields one option per load id", () =>}),]);assert.equal(options.length, 1);- assert.equal(options[0]?.id, "/models/demo");+ const option = options[0];+ assert.ok(option);+ assert.equal(option.id, "/models/demo");+ assert.equal(option.isDirectGguf, undefined);+ assert.equal(localGgufKindFor(option, false), null);+ assert.equal(localGgufKindFor(option, true), "variants");});test("hf_cache rows stay out of the local list", () => {