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
Refuse an image / video GGUF before launching llama-server, and open it on its own page (#8584)
Daniel Hana3ed5b591301
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 0da3b015fc9..b7f35ccb62d 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -699,6 +699,14 @@ def _hf_unreachable() -> bool:return hf_unreachable()+# Separates "nothing remembered" from a remembered verdict of None (not a media GGUF).+_MISS = object()+++# GGUF unsigned value-type id -> byte width (uint8, uint16, uint32, uint64).+_GGUF_UINT_WIDTHS = {0: 1, 2: 2, 4: 4, 10: 8}++@contextlib.contextmanagerdef _hf_offline_if_unreachable():"""Force HF offline for this block only when the Hub is unreachable; restores on exit@@ -1873,6 +1881,51 @@ def _gguf_files_for_variant(files: Iterable[str], variant: str) -> list[str]:return sorted(f for f in main_files if boundary.search(f.lower()))+def _resolve_variant_gguf_files(+ hf_repo: str,+ hf_variant: Optional[str],+ hf_token: Optional[str] = None,+) -> tuple[Optional[str], list[str]]:+ """Which file in ``hf_repo`` this variant means, plus its extra shards.++ Repo listing, then the local HF cache, then a name synthesised from the repo id; every+ tier fails soft (``(None, [])`` means "no opinion"). Module level, not inside+ ``_download_gguf``, so the pre-teardown header probe resolves exactly the file the+ download will open -- two copies of this cascade would let the two drift.+ """+ gguf_filename: Optional[str] = None+ gguf_extra_shards: list[str] = []+ if not hf_variant:+ return None, []+ try:+ from huggingface_hub import list_repo_files++ files = list_repo_files(hf_repo, token = hf_token)+ gguf_files = _gguf_files_for_variant(files, hf_variant)+ if gguf_files:+ gguf_filename = gguf_files[0]+ gguf_extra_shards = _gguf_extra_shards(gguf_files, gguf_filename)+ except Exception as e:+ logger.warning(f"Could not list repo files: {e}")++ # Fall back to the local cache when the repo listing is unavailable.+ if not gguf_filename:+ cached_name, cached_shards = _cached_variant_resolution(hf_repo, hf_variant)+ if cached_name:+ gguf_filename = cached_name+ gguf_extra_shards = cached_shards+ logger.info(+ "Resolved variant %s -> %s from local HF cache",+ hf_variant,+ gguf_filename,+ )++ if not gguf_filename:+ repo_name = hf_repo.split("/")[-1].replace("-GGUF", "")+ gguf_filename = f"{repo_name}-{hf_variant}.gguf"+ return gguf_filename, gguf_extra_shards++# Below this many B params, draft-mtp regresses vs spec-off (bench in# _build_speculative_flags); auto mode drops MTP under it._MTP_MIN_SIZE_B = 3.0@@ -3324,6 +3377,9 @@ class LlamaCppBackend:# runner, not llama-server. Set from the GGUF architecture at load.self._architecture: Optional[str] = Noneself._is_diffusion: bool = False+ # Whole header walked? Separates "declares no architecture" from "unreadable".+ self._gguf_header_parsed: bool = False+ self._gguf_split_index: Optional[int] = Noneself._diffusion_visual_bin: Optional[str] = Noneself._healthy = Falseself._load_rss_hwm = (None, 0) # (pid, peak VmRSS) for load_progress@@ -7159,6 +7215,179 @@ class LlamaCppBackend:if self._gguf_path_is_diffusion(gguf_path, model_identifier):raise ValueError(_VULKAN_DIFFUSION_GPU_IDS_ERROR)+ @classmethod+ def _non_chat_gguf_refusal_for_path(+ cls, gguf_path: str, model_identifier: Optional[str]+ ) -> Optional[str]:+ """``_non_chat_gguf_refusal`` for a file on disk, so it can be raised before Phase 1+ tears the running model down -- refusing after costs the user their resident chat+ model to answer a question the header already answers. Same probe-instance trick as+ ``_gguf_path_is_diffusion``: reading into ``self`` would overwrite the live model's+ metadata with a file we are about to reject."""+ probe = object.__new__(cls)+ probe._model_identifier = model_identifier+ probe._read_gguf_metadata(gguf_path)+ return probe._non_chat_gguf_refusal(gguf_path)++ @classmethod+ def non_chat_gguf_refusal_for_intent(cls, intent) -> Optional[str]:+ """The header verdict for a resolved load intent, or None.++ ``load_model``'s copy runs before its own teardown, but by then the ROUTE has already+ evicted a resident Images/Video pipeline via ``acquire_for(CHAT)`` and cancelled the+ running generations. Asking here first spares both; the in-load checks stay as the+ backstop for paths that skip the route. Fails open exactly as they do."""+ try:+ gguf_path = getattr(intent, "gguf_path", None)+ hf_repo = getattr(intent, "hf_repo", None)+ identifier = getattr(intent, "model_identifier", None)+ if gguf_path and not hf_repo and Path(gguf_path).is_file():+ return cls._non_chat_gguf_refusal_for_path(gguf_path, identifier)+ if hf_repo:+ hf_variant = getattr(intent, "hf_variant", None)+ # Same offline window as the download: the probe asks the Hub before reading+ # any local header, and those calls would otherwise wait out their retry+ # backoff on an unreachable Hub.+ with _hf_offline_if_unreachable():+ verdict = cls._remote_non_chat_gguf_verdict(+ hf_repo = hf_repo,+ hf_variant = hf_variant,+ hf_token = getattr(intent, "hf_token", None),+ model_identifier = identifier,+ )+ cls._hand_over_route_verdict(hf_repo, hf_variant, verdict)+ return verdict+ except Exception as e: # noqa: BLE001 -- a probe that failed is not a verdict+ logger.debug("Non-chat GGUF preflight failed for the route: %s", e)+ return None++ # Each ask is a repo listing, a cache verification and a range request, every one bounded+ # at 15s, so the route HANDS OVER what it learned rather than making a slow Hub pay twice.+ # Written only by the route entry point and taken once by the load it belongs to, so a+ # verdict can never outlive its load; the age bound only covers a route ask no load+ # ever came for.+ _HANDOFF_TTL_S = 120.0+ _route_verdict_handoff: Optional[+ tuple[tuple[Optional[str], Optional[str]], Optional[str], float]+ ] = None++ @classmethod+ def _take_route_verdict(cls, hf_repo, hf_variant):+ """The verdict the route just took for this key, or ``_MISS``. Consumed on read."""+ handoff = cls._route_verdict_handoff+ if handoff is None:+ return _MISS+ key, verdict, at = handoff+ if key != (hf_repo, hf_variant) or (time.monotonic() - at) >= cls._HANDOFF_TTL_S:+ return _MISS+ cls._route_verdict_handoff = None+ return verdict++ @classmethod+ def _hand_over_route_verdict(cls, hf_repo, hf_variant, verdict) -> None:+ cls._route_verdict_handoff = ((hf_repo, hf_variant), verdict, time.monotonic())++ @classmethod+ def _remote_non_chat_gguf_refusal(+ cls,+ *,+ hf_repo: str,+ hf_variant: Optional[str],+ hf_token: Optional[str],+ model_identifier: Optional[str],+ ) -> Optional[str]:+ """``_non_chat_gguf_refusal_for_path`` for a repo load, decided from a header-sized+ BYTE RANGE instead of the checkpoint, so the verdict lands before Phase 1 tears the+ resident model down. The Model Hub sends a repo id for every Hub model, so leaving+ this to the post-download check meant a media GGUF opened into a chat killed the+ live model to answer a question its own header answers; downloading first would+ trade the teardown for tens of GB.++ A 256 KiB prefix is decisive for exactly the files this refuses: measured over the+ Hub, flux / flux2 / cosmos / wan / sd3 finish the KV walk in 144-145 bytes and+ LTX-2, the largest seen, in 3,987, while a chat model's ``tokenizer.ggml.tokens``+ pushes its KV block into the megabytes (Qwen3-0.6B 5.93 MB, Llama-3.2-1B 7.82 MB) --+ so a chat prefix cuts mid-KV, ``_gguf_header_parsed`` stays False and there is no+ verdict.++ Fails open at every step (no filename, unreachable Hub, a 200 instead of a 206, too+ short a prefix) since the post-download check is the backstop. It can only make a+ refusal cheaper, never refuse a load the full-file check would have allowed.++ Takes the route's verdict for this intent when there is one, rather than repeating+ the listing, cache verification and range request it just paid for."""+ handed_over = cls._take_route_verdict(hf_repo, hf_variant)+ if handed_over is not _MISS:+ logger.debug("Reusing the header verdict the route already took for %s", hf_repo)+ return handed_over+ return cls._remote_non_chat_gguf_verdict(+ hf_repo = hf_repo,+ hf_variant = hf_variant,+ hf_token = hf_token,+ model_identifier = model_identifier,+ )++ @classmethod+ def _remote_non_chat_gguf_verdict(+ cls,+ *,+ hf_repo: str,+ hf_variant: Optional[str],+ hf_token: Optional[str],+ model_identifier: Optional[str],+ ) -> Optional[str]:+ """The uncached probe: one listing, one cache resolution, one range read."""+ try:+ from core.inference.diffusion_compat import (+ _read_gguf_header,+ _read_local_header,+ )+ except Exception as e: # noqa: BLE001 -- an unavailable probe is not a verdict+ logger.debug("GGUF header probe unavailable: %s", e)+ return None+ try:+ gguf_filename, shards = _resolve_variant_gguf_files(hf_repo, hf_variant, hf_token)+ if not gguf_filename:+ return None+ # A cached copy answers this with no request, and is the only thing that can+ # answer it with the Hub down. Resolved with the SAME precedence AND the same+ # verification _download_gguf uses -- cached_gguf_for_load at+ # verify_sizes = True, then the listing's filename -- because that is the file+ # the load will open. Anything else (a truncated snapshot judged here but+ # skipped there, a repo that renamed the file for a quant) lets the probe judge+ # one GGUF and the load open another. verify_sizes fails open on unreachable+ # metadata, so the probe still answers offline.+ local = cached_gguf_for_load(hf_repo, hf_variant, verify_sizes = True, hf_token = hf_token)+ if local is None and not hf_variant:+ # No variant means cached_gguf_for_load declines outright, so mirror the other+ # half of _download_gguf: the complete candidate for this filename, size-checked+ # against its own revision. Never the bare local path -- a candidate the verified+ # lookup just REJECTED would come straight back through it, and the probe would+ # judge a truncated snapshot the load is about to redownload.+ candidate = _cached_complete_candidate(hf_repo, gguf_filename, list(shards))+ if candidate is not None and _cached_candidate_matches_revision_size(+ hf_repo, candidate, hf_token+ ):+ local = candidate[0]+ prefix = (+ _read_local_header(local)+ if local+ else _read_gguf_header(hf_repo, gguf_filename, hf_token)+ )+ # Magic, version and the two counts: anything shorter is not a GGUF at all.+ if len(prefix) < 24:+ return None+ with tempfile.TemporaryDirectory(prefix = "unsloth-gguf-probe-") as probe_dir:+ # Named after the real file: a GGUF declaring no architecture is judged by+ # its name, and a temp name would lose the page pointer.+ probe_path = os.path.join(probe_dir, os.path.basename(gguf_filename))+ with open(probe_path, "wb") as handle:+ handle.write(prefix)+ return cls._non_chat_gguf_refusal_for_path(probe_path, model_identifier)+ except Exception as e: # noqa: BLE001 -- a probe that failed is not a verdict+ logger.debug("Non-chat GGUF header probe failed for %s: %s", hf_repo, e)+ return None+def _read_gguf_metadata(self, gguf_path: str) -> None:"""Read context_length, architecture params, and chat_template from a GGUF header.@@ -7205,6 +7434,8 @@ class LlamaCppBackend:self._nextn_predict_layers = Noneself._architecture = Noneself._is_diffusion = False+ self._gguf_header_parsed = False+ self._gguf_split_index = Nonetry:canvas_seen = False@@ -7241,6 +7472,8 @@ class LlamaCppBackend:_version = struct.unpack("<I", f.read(4))[0]_tensor_count, kv_count = struct.unpack("<QQ", f.read(16))+ # Set by the loop's `else` below: True only if no truncation `break` fired.+ kv_complete = Falsefor _ in range(kv_count):# Tolerate truncated input (e.g. a partial header from an# HTTP byte-range fetch): bail out so the resolver@@ -7258,6 +7491,20 @@ class LlamaCppBackend:if len(vtype_bytes) < 4:breakvtype = struct.unpack("<I", vtype_bytes)[0]+ # gguf-split puts the whole metadata block in shard 1 and gives every+ # later shard only split.no / split.count / split.tensors.count+ # (measured on unsloth/DeepSeek-R1-GGUF: shard 1 has 48 KV pairs from+ # general.architecture = "deepseek2", shard 2 has those 3). Read the+ # INDEX, not the presence: shard 1 carries these keys too, so presence+ # alone would cover a whole set rather than its tail.+ if key == "split.no":+ width = _GGUF_UINT_WIDTHS.get(vtype)+ if width is not None:+ raw = f.read(width)+ if len(raw) < width:+ break+ self._gguf_split_index = int.from_bytes(raw, "little")+ continueexcept (struct.error, UnicodeDecodeError):break@@ -7348,6 +7595,8 @@ class LlamaCppBackend:# fetch); break so the resolver fallback runs on# what we have.break+ else:+ kv_complete = True# GGUF metadata has no key-order contract. Pooling can precede# general.architecture, so bind the buffered value after the sweep.@@ -7409,6 +7658,10 @@ class LlamaCppBackend:hf_repo_candidates,)+ # Only with the whole walk done does ``_architecture is None`` mean "declares no+ # architecture" rather than "the read stopped early" -- what the preflight needs.+ self._gguf_header_parsed = kv_complete+if self._context_length:logger.info(f"GGUF metadata: context_length={self._context_length}")if self._chat_template:@@ -7831,36 +8084,10 @@ class LlamaCppBackend:)hf_repo = resolved_hf_repo- # Resolve the filename from the variant- gguf_filename = None- gguf_extra_shards: list[str] = []- if hf_variant:- try:- from huggingface_hub import list_repo_files-- files = list_repo_files(hf_repo, token = hf_token)- gguf_files = _gguf_files_for_variant(files, hf_variant)- if gguf_files:- gguf_filename = gguf_files[0]- gguf_extra_shards = _gguf_extra_shards(gguf_files, gguf_filename)- except Exception as e:- logger.warning(f"Could not list repo files: {e}")-- # Fall back to the local cache when the repo listing is unavailable.- if not gguf_filename:- cached_name, cached_shards = _cached_variant_resolution(hf_repo, hf_variant)- if cached_name:- gguf_filename = cached_name- gguf_extra_shards = cached_shards- logger.info(- "Resolved variant %s -> %s from local HF cache",- hf_variant,- gguf_filename,- )-- if not gguf_filename:- repo_name = hf_repo.split("/")[-1].replace("-GGUF", "")- gguf_filename = f"{repo_name}-{hf_variant}.gguf"+ # Resolve the filename from the variant (shared with the pre-teardown header probe)+ gguf_filename, gguf_extra_shards = _resolve_variant_gguf_files(+ hf_repo, hf_variant, hf_token+ )# Prefer the existing model. Updates use force=True to fetch a new revision.if not force:@@ -8856,22 +9083,259 @@ class LlamaCppBackend:# https://huggingface.co/collections/unsloth/unsloth-diffusion-ggufs.# Matched exactly (not a substring) so a chat arch containing "wan"/"sd1"# (e.g. "taiwan") isn't misrouted to Images.- _DIFFUSION_ARCHES = frozenset(+ _IMAGE_ARCHES = frozenset(("qwen_image","flux",+ )+ )+ # Archs shared by more than one family, so the header alone does NOT say whether the+ # Images page can run the file: Z-Image's DiT is a Lumina2 derivative, so its GGUFs+ # declare "lumina2" too (measured on unsloth/Z-Image-Turbo-GGUF/z-image-turbo-Q2_K.gguf+ # and on calcuis/lumina-gguf). ``routes.models._arch_to_task`` resolves these from the+ # repo id and the filename and tags the rest ``image-diffusion-unsupported``, hiding+ # them from the Images picker, so the refusal must run the SAME resolution before it+ # names that page -- e.g. ``neta-art/neta-lumina-gguf/checkpoint-e3_s9658-*.gguf``+ # declares "lumina2" and resolves to no family ("lumina-2" is not aliased to bare+ # "lumina"). Mirrors ``routes.models._AMBIGUOUS_DIFFUSION_GGUF_ARCHS``.+ _AMBIGUOUS_IMAGE_ARCHES = frozenset(("lumina2",))+ # Text-to-video archs the Video page can offer. Split from the image set so the refusal+ # names Video: sending a Wan / LTX-2 GGUF to Images is a second dead end.+ _VIDEO_ARCHES = frozenset(+ (+ "ltxv",+ "wan",+ )+ )+ # Media archs Studio recognises but NO page can run, so the refusal must not promise+ # one. Mirrors ``routes.models._UNSUPPORTED_DIFFUSION_GGUF_ARCHS``, which tags these+ # ``image-diffusion-unsupported`` and so hides them from the Images AND Video pickers.+ # * "cosmos": no VideoFamily exists at all (``detect_video_family`` returns None for+ # every cosmos repo id and for override="cosmos"), and the published cosmos GGUFs+ # are Cosmos-Predict2-14B-Text2Image, which Images cannot assemble either.+ # * "hyvid": HunyuanVideo 1.0 has no VideoFamily, and the 1.5 GGUFs that do map to+ # one are still tagged unsupported (that family ships no ``gguf_repo``).+ # * "sd1" / "sd3" / "sdxl" / "aura" / "hidream": unsupported on the image side for+ # the same reason, so "use the Images page" was always an empty promise.+ # Kept inside _DIFFUSION_ARCHES so the pre-launch refusal still fires, it just names no+ # destination. Mirrors the whole set: a partial mirror leaves the same dead end.+ _UNRUNNABLE_MEDIA_ARCHES = frozenset(+ (+ "cosmos",+ "hyvid","sd1",- "sdxl","sd3",+ "sdxl","aura","hidream",- "cosmos",- "ltxv",- "hyvid",- "wan",- "lumina2",))+ _DIFFUSION_ARCHES = (+ _IMAGE_ARCHES | _AMBIGUOUS_IMAGE_ARCHES | _VIDEO_ARCHES | _UNRUNNABLE_MEDIA_ARCHES+ )++ # Not architectures: the literal placeholders gguf-connector writes into+ # general.architecture for its diffusion GGUFs (gguf-org/flux2-dev-gguf and+ # calcuis/cosmos-predict2-gguf both declare "pig"); ComfyUI-GGUF special cases the same+ # two. llama.cpp knows neither, so without this they slip past the arch sets and die in+ # llama-server as the opaque failure this preflight exists to prevent.+ _PLACEHOLDER_ARCHES = frozenset(("pig", "cow"))++ @staticmethod+ def _video_arch_is_pickable(+ arch: Optional[str], gguf_path: Optional[str], model_identifier: Optional[str]+ ) -> bool:+ """Whether the Video page would actually OFFER this GGUF.++ Same fixed order ``_arch_to_task`` asks in: the ARCHITECTURE first, since some map+ straight to a family (``detect_video_family("", override = "ltxv")`` resolves LTX-2+ with no name to go on), then the repo id, then the filename. Whatever resolves must+ not be an MoE (the GGUF loader cannot assemble those) and must be buildable by the+ video engine -- bare "wan" resolves nothing and QuantStack/Wan2.2-T2V-A14B-GGUF+ resolves an MoE, so neither is promised the page."""+ try:+ from core.inference.video_families import detect_video_family++ from routes.models import _video_family_buildable++ fam = detect_video_family("", override = (arch or "").strip().lower() or None)+ if fam is None:+ for needle in (model_identifier, os.path.basename(gguf_path or "")):+ if not needle:+ continue+ fam = detect_video_family(needle)+ if fam is not None:+ break+ if fam is None:+ return False+ return not getattr(fam, "is_moe", False) and _video_family_buildable(fam)+ except Exception as e: # noqa: BLE001 -- never lose the page over a probe failure+ logger.debug("Family probe failed for video arch: %s", e)+ return True++ @staticmethod+ def _ambiguous_image_arch_is_pickable(+ gguf_path: Optional[str], model_identifier: Optional[str]+ ) -> bool:+ """Whether the Images page would actually OFFER this shared-arch GGUF.++ The same three questions ``routes.models._arch_to_task`` asks in its+ ``_AMBIGUOUS_DIFFUSION_GGUF_ARCHS`` branch, over the same evidence (repo id, then+ filename): does a family resolve, can a GGUF transformer be assembled for it, can an+ engine on THIS host build it. Both sides must answer alike -- the picker's answer is+ what decides whether the row the refusal points at exists.++ Imported lazily inside the function since ``routes`` imports this module, so the+ canonical classifier cannot be imported from here.++ Fails OPEN on a probe error, like every family probe on the listing side: naming the+ page is a nicety, not worth losing over a broken import."""+ try:+ from core.inference.diffusion_engine_router import family_buildable_here+ from core.inference.diffusion_families import (+ detect_family_for_pick,+ family_gguf_loadable,+ )++ for needle in (model_identifier, os.path.basename(gguf_path or "")):+ if not needle:+ continue+ fam = detect_family_for_pick(needle)+ if fam is not None:+ return family_gguf_loadable(fam) and family_buildable_here(+ fam, model_kind = "gguf"+ )+ return False+ except Exception as e: # noqa: BLE001 -- never lose the page over a probe failure+ logger.debug("Family probe failed for ambiguous image arch: %s", e)+ return True++ def _non_chat_gguf_refusal(self, gguf_path: str) -> Optional[str]:+ """Why this GGUF cannot be a chat model, decided from its own header BEFORE+ llama-server is launched; None when there is no such verdict.++ Otherwise a media GGUF opened in a chat runs the whole download-and-launch path only+ to die in llama-server as "llama-server failed to start", with no hint that the file+ was never a chat model (the reported Video-model case).++ The header alone is enough to be certain, in two ways:++ * A declared architecture in the image / video sets. llama.cpp has no such+ architectures, so this is exactly the failure it would hit, one launch earlier.+ * NO ``general.architecture`` at all -- a mandatory key for anything llama.cpp can+ load, and Unsloth's video GGUFs (MiniMax-H3) carry a bare tensor header with zero+ KV pairs, so they never reach the arch test. Gated on ``_gguf_header_parsed`` so a+ read that FAILED still gets its chance in llama-server.++ Naming the destination page is the point, so when the architecture does not say+ which it is, the family detectors are asked about the repo id and the filename."""+ arch = (self._architecture or "").strip().lower()+ # A declared media arch is the whole answer, and it is KV #0 in every GGUF measured,+ # so the remote probe's prefix can carry it even where bulkier later metadata leaves+ # the walk unfinished. The walk still gates the no-architecture fallback below, the+ # one case where an incomplete read is indistinguishable from declaring nothing.+ if arch not in self._DIFFUSION_ARCHES and not getattr(self, "_gguf_header_parsed", False):+ return None+ if arch in self._PLACEHOLDER_ARCHES:+ # Names no architecture, so treat it like a GGUF that declares none and let the+ # name-based branch below name a page.+ arch = ""+ if arch:+ if arch in self._UNRUNNABLE_MEDIA_ARCHES:+ return (+ f"This is an image / video generation GGUF (architecture '{arch}'), "+ "which cannot run as a chat model. Unsloth Studio cannot run this "+ "architecture at all: neither the Images page nor the Video page "+ "accepts it."+ )+ if arch in self._VIDEO_ARCHES:+ # Shared like the image archs: the canonical classifier resolves a+ # VideoFamily by name and rejects an MoE the GGUF loader cannot assemble,+ # so "wan" alone does not mean the Video page will list it.+ if self._video_arch_is_pickable(arch, gguf_path, self._model_identifier):+ return (+ f"This is a text-to-video GGUF (architecture '{arch}'), which "+ "cannot run as a chat model. Open it from the Video page instead."+ )+ return (+ f"This is a text-to-video GGUF (architecture '{arch}'), which cannot "+ "run as a chat model. Studio cannot assemble this particular model "+ "from a GGUF, so the Video page does not list it either."+ )+ if arch in self._IMAGE_ARCHES:+ return (+ f"This is an image-generation GGUF (architecture '{arch}'), which "+ "cannot run as a chat model. Open it from the Images page instead."+ )+ if arch in self._AMBIGUOUS_IMAGE_ARCHES:+ if self._ambiguous_image_arch_is_pickable(gguf_path, self._model_identifier):+ return (+ f"This is an image-generation GGUF (architecture '{arch}'), which "+ "cannot run as a chat model. Open it from the Images page instead."+ )+ return (+ f"This is an image-generation GGUF (architecture '{arch}'), which "+ "cannot run as a chat model. Studio could not tell which model family "+ f"this file belongs to -- '{arch}' is shared by several -- so the "+ "Images page cannot assemble it either."+ )+ return None++ # A shard past the first of a gguf-split set declares no architecture (shard 1 holds+ # it) but is no media GGUF, and llama.cpp's own "model must be loaded with the first+ # split" is more use than "carries no metadata". Needs split.no > 0 AND nothing+ # declared: shard 1 carries the split keys too, and a placeholder arch is blanked+ # above, so a looser test would wave through the very files the placeholder handling+ # exists to catch. Only reachable with a hand-written variant anyway: every producer+ # here strips the shard suffix and sorts, landing on shard 1.+ if self._architecture is None and (self._gguf_split_index or 0) > 0:+ return None++ # No architecture declared: not loadable by llama-server whatever it is. Say which+ # page runs it when the identifiers make that clear.+ needles = [n for n in (self._model_identifier, os.path.basename(gguf_path or "")) if n]+ # Naming a page answers to the same predicates as the arch branches above: a family+ # that resolves is not enough, the picker also drops an MoE it cannot assemble and a+ # family no installed engine can build. So detect first, then ask whether the page+ # would list it, rather than pointing at a page the model is missing from.+ try:+ from core.inference.video_families import detect_video_family+ if any(detect_video_family(n) is not None for n in needles):+ if self._video_arch_is_pickable(None, gguf_path, self._model_identifier):+ return (+ "This is a text-to-video model, not a chat model: its GGUF carries "+ "no llama.cpp model metadata, so llama-server cannot load it. Open "+ "it from the Video page instead."+ )+ return (+ "This is a text-to-video model, not a chat model, and its GGUF carries "+ "no llama.cpp model metadata. Studio cannot assemble this particular "+ "model from a GGUF either, so the Video page does not list it."+ )+ except Exception as e: # noqa: BLE001 -- naming the page is a nicety, never a gate+ logger.debug("Video family probe failed during non-chat GGUF preflight: %s", e)+ try:+ from core.inference.diffusion_families import detect_family+ if any(detect_family(n) is not None for n in needles):+ if self._ambiguous_image_arch_is_pickable(gguf_path, self._model_identifier):+ return (+ "This is an image-generation model, not a chat model: its GGUF "+ "carries no llama.cpp model metadata, so llama-server cannot load "+ "it. Open it from the Images page instead."+ )+ return (+ "This is an image-generation model, not a chat model, and its GGUF "+ "carries no llama.cpp model metadata. Studio cannot assemble this "+ "particular model from a GGUF either, so the Images page does not list "+ "it."+ )+ except Exception as e: # noqa: BLE001+ logger.debug("Image family probe failed during non-chat GGUF preflight: %s", e)+ return (+ "This GGUF carries no llama.cpp model metadata (no general.architecture), so "+ "llama-server cannot load it as a chat model. Image and video GGUFs are "+ "packaged this way -- try the Images or Video page, or pick a chat GGUF."+ )# Distro package names for the shared libraries the Linux prebuilt links,# so the loader failure below can say what to install.@@ -9081,13 +9545,44 @@ class LlamaCppBackend:arch_match = re.search(r"unknown model architecture:\s*'([^']+)'", lowered)if arch_match:arch = arch_match.group(1)- if arch in LlamaCppBackend._DIFFUSION_ARCHES:+ if arch in LlamaCppBackend._UNRUNNABLE_MEDIA_ARCHES:+ return (+ f"'{arch}' is an image / video generation GGUF, which llama-server "+ "cannot run as a chat/completion model. Unsloth Studio cannot run "+ "this architecture at all: neither the Images page nor the Video "+ "page accepts it."+ )+ if arch in LlamaCppBackend._VIDEO_ARCHES:+ if LlamaCppBackend._video_arch_is_pickable(arch, gguf_path, model_identifier):+ return (+ f"'{arch}' is a text-to-video GGUF, which llama-server "+ "cannot run as a chat/completion model. Open it from "+ "Unsloth's Video page instead of a chat."+ )+ return (+ f"'{arch}' is a text-to-video GGUF, which llama-server cannot run as "+ "a chat/completion model. Studio cannot assemble this particular "+ "model from a GGUF, so the Video page does not list it either."+ )+ if arch in LlamaCppBackend._IMAGE_ARCHES or (+ arch in LlamaCppBackend._AMBIGUOUS_IMAGE_ARCHES+ and LlamaCppBackend._ambiguous_image_arch_is_pickable(gguf_path, model_identifier)+ ):return (f"'{arch}' is a diffusion (image-generation) GGUF, which ""llama-server cannot run as a chat/completion model. Use ""Unsloth's Images page to generate with local diffusion ""GGUFs such as FLUX and Qwen-Image.")+ if arch in LlamaCppBackend._AMBIGUOUS_IMAGE_ARCHES:+ # Same shared-arch resolution as the pre-launch refusal: unresolved means+ # the Images picker tags it image-diffusion-unsupported and hides the row.+ return (+ f"'{arch}' is a diffusion (image-generation) GGUF, which "+ "llama-server cannot run as a chat/completion model. Unsloth Studio "+ f"could not tell which model family this file is -- '{arch}' is "+ "shared by several -- so the Images page cannot assemble it either."+ )if is_ollama:return ("Some Ollama models do not work with llama.cpp. Try a "@@ -10212,13 +10707,6 @@ class LlamaCppBackend:# Resolve llama-server now but defer a not-found error: a block-diffusion# GGUF uses the diffusion runner, and its arch is only known after the header.binary = self._find_llama_server_binary()- # Kept so a stand-down blamed on the binary can later tell a real update- # from the same file still being installed.- self._launch_binary_revision = self._binary_revision(binary)- # Cleared per load, not only where the fetch runs: a local-file load never- # reaches the DFlash fetch, and a verdict left over from the previous model- # would make every Apply for this one reload.- self._dflash_retry_needed = False# Every capability answer shaping this launch, latching whether any was a# guess. Accumulated, not sampled: the decisions straddle the whole load (slot@@ -10340,6 +10828,59 @@ class LlamaCppBackend:):raise ValueError(_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR)+ # An image / video GGUF already on disk is refused HERE, before the teardown:+ # the header answers this without llama-server, so there is no reason to make+ # the user pay their resident chat model for it.+ if gguf_path and not hf_repo and Path(gguf_path).is_file():+ _early_non_chat = self._non_chat_gguf_refusal_for_path(gguf_path, model_identifier)+ if _early_non_chat:+ logger.error(+ "Refusing non-chat GGUF before teardown: %s (%s)",+ _early_non_chat,+ gguf_path,+ )+ raise ValueError(_early_non_chat)++ # The same refusal for a REPO load, which is what the Model Hub actually sends:+ # the route resolves every Hub model to hf_repo, so leaving this to the+ # post-download check killed the live model first in the reported case. The file+ # does not exist yet, but a header-sized byte range decides it (see+ # _remote_non_chat_gguf_refusal). When a preflight above already fetched the+ # file, judge that instead -- same verdict, no request. Fails open into the+ # post-download check below, which stays as the backstop.+ if hf_repo:+ # Same offline guard the download below uses: the probe asks the Hub twice+ # before reading any local header (the file listing, then the cached+ # candidate's revision sizes), and each would wait out its retry backoff,+ # putting two timeouts in front of a cached load that needs no network. The+ # guard is memoised and only bites when the Hub really is unreachable.+ with _hf_offline_if_unreachable():+ _early_non_chat = (+ self._non_chat_gguf_refusal_for_path(+ _preflight_model_path, model_identifier+ )+ if _preflight_model_path+ else self._remote_non_chat_gguf_refusal(+ hf_repo = hf_repo,+ hf_variant = hf_variant,+ hf_token = hf_token,+ model_identifier = model_identifier,+ )+ )+ if _early_non_chat:+ logger.error(+ "Refusing non-chat GGUF before teardown: %s (%s)",+ _early_non_chat,+ hf_repo,+ )+ raise ValueError(_early_non_chat)++ # The probe can take a moment on a slow Hub, so re-read the cancel flag rather+ # than tearing down a healthy server for a load that was called off.+ if _load_cancelled():+ logger.info("Load cancelled before teardown")+ return False+# ── Phase 1: kill old process (under lock, fast) ──────────_replaying_cpu_fallback = intent.cpu_fallbackwith self._lock:@@ -10347,6 +10888,21 @@ class LlamaCppBackend:if not _replaying_cpu_fallback:self._cpu_fallback_reason = Noneself._cleanup_cpu_fallback_runtime()+ # Both describe the process just killed, so they are reset HERE rather than+ # where the binary is resolved: everything above can bail with the old server+ # still running (a stand-down, a non-chat refusal, a cancel), and resetting on+ # the way past would tell the next Apply that the resident process launched from+ # the binary installed now and is owed no DFlash retry -- so an Apply after+ # `unsloth studio update` or a retryable sidecar failure would dedupe against it+ # instead of relaunching. Nothing between the two points reads either field.+ #+ # Kept so a stand-down blamed on the binary can later tell a real update+ # from the same file still being installed.+ self._launch_binary_revision = self._binary_revision(binary)+ # Cleared per load, not only where the fetch runs: a local-file load never+ # reaches the DFlash fetch, and a verdict left over from the previous model+ # would make every Apply for this one reload.+ self._dflash_retry_needed = False# ── Phase 2: download (NO lock held, so cancel can proceed) ──# mtp_draft_path arrives set for local Gemma loads (detected@@ -10508,6 +11064,13 @@ class LlamaCppBackend:logger.info("Load cancelled after download phase")return False+ # Backstop for everything the pre-teardown probes fail open on: refuse from the+ # header rather than watching llama-server die as "failed to start".+ non_chat = self._non_chat_gguf_refusal(model_path)+ if non_chat:+ logger.error("Refusing non-chat GGUF: %s (%s)", non_chat, model_path)+ raise ValueError(non_chat)+# Block-diffusion GGUFs (DiffusionGemma) cannot run on llama-server;# serve them with the diffusion runner (same OpenAI-compat interface).if self._is_diffusion:diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 2545351cb70..5fe18889b87 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -8088,6 +8088,17 @@ async def _load_model_impl(request.speculative_type,))+ # Ahead of the arbiter: acquire_for evicts a resident Images/Video pipeline and the+ # confirmation below cancels the running generations, both before load_model's own+ # copy of this check runs. A header-sized read spares them. Fails open into that copy.+ if config.is_gguf and gguf_intent is not None:+ _non_chat = await asyncio.to_thread(+ llama_backend.non_chat_gguf_refusal_for_intent, gguf_intent+ )+ if _non_chat:+ logger.error("Refusing non-chat GGUF before the GPU handoff: %s", _non_chat)+ raise HTTPException(status_code = 400, detail = _non_chat)+if chat_load_needs_gpu:await asyncio.to_thread(acquire_for,diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 934f3be9ab6..fc42b4f17ca 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -3977,6 +3977,11 @@ _UNSUPPORTED_DIFFUSION_GGUF_ARCHS = frozenset(# derivative, so its GGUFs declare "lumina2"; these resolve from the repo/file name._AMBIGUOUS_DIFFUSION_GGUF_ARCHS = frozenset({"lumina2"})+# Literal placeholders gguf-connector writes into general.architecture for its diffusion+# GGUFs. Mirrors LlamaCppBackend._PLACEHOLDER_ARCHES, which does the same normalisation on+# the load side; the two must agree or a row is offered to chat and then refused by it.+_PLACEHOLDER_DIFFUSION_GGUF_ARCHS = frozenset({"pig", "cow"})+# Video GGUF archs the video backend CAN load (LTX-2.x ships as "ltxv", the Wan community GGUFs as "wan")._VIDEO_GGUF_ARCHS = frozenset({"ltxv", "wan"})_VIDEO_GEN_TASK = "text-to-video"@@ -4069,6 +4074,33 @@ def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = (if arch is None:return Nonea = arch.lower()+ if a in _PLACEHOLDER_DIFFUSION_GGUF_ARCHS:+ # Not an architecture at all: gguf-connector writes these literals in place of one+ # (gguf-org/flux2-dev-gguf and calcuis/cosmos-predict2-gguf both declare "pig").+ # Being non-null they used to fall past every media branch to "text-generation", so+ # a diffusion GGUF was offered to chat and only refused at load. Only gguf-connector+ # writes them and only for diffusion GGUFs, so the row is never a chat model:+ # resolve the page by name, and stay unsupported when neither answers.+ from core.inference.video_families import detect_video_family++ for hint in name_hints:+ fam = detect_video_family(hint) if hint else None+ if fam is not None:+ if not getattr(fam, "is_moe", False) and _video_family_buildable(fam):+ return _VIDEO_GEN_TASK+ return _UNSUPPORTED_DIFFUSION_TASK+ # An image family has to RESOLVE, not merely fail open: _gguf_family_buildable is+ # permissive by design for a branch whose arch already says "image GGUF", and a+ # placeholder says nothing, so it would advertise Images for anything.+ from core.inference.diffusion_families import detect_family_for_pick++ if any(detect_family_for_pick(hint) is not None for hint in name_hints if hint):+ return (+ "text-to-image"+ if _gguf_family_buildable(name_hints)+ else _UNSUPPORTED_DIFFUSION_TASK+ )+ return _UNSUPPORTED_DIFFUSION_TASKif a in _DIFFUSION_GGUF_ARCHS:# Third gate, mirroring the cached-repo picker: a family no engine here can build can only fail.if not _gguf_family_buildable(name_hints):diff --git a/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py b/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.pynew file mode 100644index 00000000000..481998872b0--- /dev/null+++ b/studio/backend/tests/test_llama_cpp_non_chat_gguf_preflight.py@@ -0,0 +1,397 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""CPU-only unit tests for the pre-launch non-chat GGUF refusal.++Reported: a text-to-video model opened from the Model Hub landed in a chat, ran the whole+download-and-launch path, and died as "llama-server failed to start". ``_non_chat_gguf_refusal``+decides that from the GGUF header instead, and names the page that does run it.++Unsloth's video GGUFs (MiniMax-H3) carry a bare tensor header with ZERO KV pairs, so there is no+``general.architecture`` to match -- which is why "declares no architecture" is a verdict here,+and why it has to be told apart from "the header could not be read".+"""++from __future__ import annotations++import struct+from pathlib import Path++import pytest++from core.inference.llama_cpp import LlamaCppBackend++GGUF_MAGIC = 0x46554747+++def _write_gguf(+ path: Path,+ *,+ arch: str | None,+ tensor_count: int = 1,+) -> Path:+ """Minimal GGUF header: magic, version, counts, then one optional+ ``general.architecture`` string KV. The parser never reads the tensor data."""+ body = b""+ kv_count = 0+ if arch is not None:+ key = b"general.architecture"+ val = arch.encode()+ body += struct.pack("<Q", len(key)) + key+ body += struct.pack("<I", 8) # STRING+ body += struct.pack("<Q", len(val)) + val+ kv_count = 1+ header = struct.pack("<II", GGUF_MAGIC, 3) + struct.pack("<QQ", tensor_count, kv_count)+ path.write_bytes(header + body)+ return path+++def _refusal(+ tmp_path: Path,+ *,+ arch: str | None,+ name: str,+ identifier: str | None = None,+):+ gguf = _write_gguf(tmp_path / name, arch = arch)+ backend = LlamaCppBackend()+ backend._model_identifier = identifier+ backend._read_gguf_metadata(str(gguf))+ return backend, backend._non_chat_gguf_refusal(str(gguf))+++def test_chat_arch_is_not_refused(tmp_path):+ backend, message = _refusal(tmp_path, arch = "llama", name = "chat.gguf")+ assert backend._architecture == "llama"+ assert backend._gguf_header_parsed is True+ assert message is None+++def test_image_arch_names_the_images_page(tmp_path):+ _, message = _refusal(tmp_path, arch = "flux", name = "flux.gguf")+ assert message is not None+ assert "Images page" in message+ assert "Video page" not in message+++def test_video_arch_names_the_video_page(tmp_path):+ _, message = _refusal(tmp_path, arch = "ltxv", name = "ltx.gguf")+ assert message is not None+ assert "Video page" in message+ assert "Images page" not in message+++def test_diffusiongemma_arch_is_left_to_the_diffusion_runner(tmp_path):+ # A block-diffusion LANGUAGE model IS servable by the diffusion runner.+ backend, message = _refusal(tmp_path, arch = "diffusiongemma", name = "dg.gguf")+ assert backend._is_diffusion is True+ assert message is None+++def test_metadata_less_video_gguf_is_refused_and_named(tmp_path):+ # The shape of unsloth/MiniMax-H3-GGUF: valid GGUF, zero KV pairs, no architecture.+ backend, message = _refusal(+ tmp_path,+ arch = None,+ name = "minimax_h3_fl2va_pruned-Q2_K.gguf",+ identifier = "unsloth/MiniMax-H3-GGUF",+ )+ assert backend._architecture is None+ assert backend._gguf_header_parsed is True+ assert message is not None+ assert "Video page" in message+++def test_metadata_less_gguf_of_unknown_family_still_refuses(tmp_path):+ # No architecture means llama-server cannot load it, but no page can be promised.+ _, message = _refusal(tmp_path, arch = None, name = "mystery.gguf", identifier = "x/mystery")+ assert message is not None+ assert "general.architecture" in message+++def test_unreadable_header_yields_no_verdict(tmp_path):+ # A non-GGUF file and a GGUF truncated mid-KV must both fall through to llama-server+ # rather than being refused as "declares no architecture".+ not_gguf = tmp_path / "notes.txt"+ not_gguf.write_bytes(b"this is not a gguf file at all")+ backend = LlamaCppBackend()+ backend._read_gguf_metadata(str(not_gguf))+ assert backend._gguf_header_parsed is False+ assert backend._non_chat_gguf_refusal(str(not_gguf)) is None++ full = _write_gguf(tmp_path / "chat.gguf", arch = "llama")+ truncated = tmp_path / "truncated.gguf"+ # Keep the counts (which promise a KV pair) but cut the KV itself away.+ truncated.write_bytes(full.read_bytes()[:24])+ backend2 = LlamaCppBackend()+ backend2._read_gguf_metadata(str(truncated))+ assert backend2._architecture is None+ assert backend2._gguf_header_parsed is False+ assert backend2._non_chat_gguf_refusal(str(truncated)) is None+++def test_verdict_requires_a_parsed_header_even_if_called_directly(tmp_path):+ # A caller that skipped _read_gguf_metadata gets no verdict, not a refusal built on a+ # never-populated architecture.+ backend = LlamaCppBackend()+ assert backend._non_chat_gguf_refusal(str(tmp_path / "unread.gguf")) is None++[email protected]("arch", sorted(LlamaCppBackend._DIFFUSION_ARCHES))+def test_every_media_arch_is_refused_before_launch(tmp_path, arch):+ _, message = _refusal(tmp_path, arch = arch, name = f"{arch}.gguf")+ assert message is not None+ assert "cannot run as a chat model" in message+++def test_the_path_probe_does_not_touch_the_live_backend(tmp_path):+ # The refusal runs BEFORE Phase 1 kills the resident model, so reading the header into+ # `self` would overwrite the LIVE model's metadata with the file being rejected.+ live = LlamaCppBackend()+ live._model_identifier = "unsloth/Qwen3-0.6B-GGUF"+ live._architecture = "qwen3"+ live._context_length = 40960+ live._gguf_header_parsed = True++ video = _write_gguf(tmp_path / "minimax_h3-Q2_K.gguf", arch = None)+ message = LlamaCppBackend._non_chat_gguf_refusal_for_path(str(video), "unsloth/MiniMax-H3-GGUF")+ assert message is not None and "Video page" in message+ # The resident model's metadata is untouched.+ assert live._architecture == "qwen3"+ assert live._context_length == 40960+ assert live._model_identifier == "unsloth/Qwen3-0.6B-GGUF"+++def test_the_path_probe_agrees_with_the_instance_check(tmp_path):+ # One verdict, two entry points: disagreement means a load refused on one path and+ # launched on the other.+ for arch, name in (("llama", "chat.gguf"), ("flux", "flux.gguf"), ("ltxv", "ltx.gguf")):+ gguf = _write_gguf(tmp_path / name, arch = arch)+ backend = LlamaCppBackend()+ backend._model_identifier = None+ backend._read_gguf_metadata(str(gguf))+ assert backend._non_chat_gguf_refusal(str(gguf)) == (+ LlamaCppBackend._non_chat_gguf_refusal_for_path(str(gguf), None)+ )+++ "identifier,name",+ [+ # Measured headers (byte-range read of the live repos): both declare "lumina2".+ ("unsloth/Z-Image-Turbo-GGUF", "z-image-turbo-Q2_K.gguf"),+ ("Immac/NetaYume-Lumina-Image-2.0-GGUF", "NetaYumev2plus_unet_q2_k.gguf"),+ # The family keyword lives only in the filename, as it does for a local copy.+ (None, "lumina2-q4_k_m.gguf"),+ ],+)+def test_a_resolvable_shared_arch_still_names_the_images_page(tmp_path, identifier, name):+ _, message = _refusal(tmp_path, arch = "lumina2", name = name, identifier = identifier)+ assert message is not None+ assert "Open it from the Images page" in message+++def test_an_unresolvable_shared_arch_promises_no_page(tmp_path):+ # "lumina2" is shared: Z-Image's DiT is a Lumina2 derivative, so the header alone does+ # not say which family a file is. neta-art/neta-lumina-gguf ships REAL lumina2 GGUFs+ # (measured on the live repo: general.architecture = "lumina2", 400 tensors) whose repo+ # id and filename resolve to no family -- "lumina-2" is deliberately not aliased to bare+ # "lumina" -- so routes.models._arch_to_task tags them image-diffusion-unsupported and+ # the Images picker never lists them.+ _, message = _refusal(+ tmp_path,+ arch = "lumina2",+ name = "checkpoint-e3_s9658-Q2_K.gguf",+ identifier = "neta-art/neta-lumina-gguf",+ )+ assert message is not None+ assert "cannot run as a chat model" in message+ assert "Open it from the" not in message+++def test_the_shared_arch_verdict_matches_the_pickers(tmp_path):+ # The invariant: the refusal names the Images page exactly when+ # routes.models._arch_to_task says the row is selectable there, or the message points at+ # a list the model is not in.+ from routes.models import _AMBIGUOUS_DIFFUSION_GGUF_ARCHS, _arch_to_task+ assert LlamaCppBackend._AMBIGUOUS_IMAGE_ARCHES == _AMBIGUOUS_DIFFUSION_GGUF_ARCHS+ for identifier, name in (+ ("unsloth/Z-Image-Turbo-GGUF", "z-image-turbo-Q2_K.gguf"),+ ("neta-art/neta-lumina-gguf", "checkpoint-e3_s9658-Q2_K.gguf"),+ ("Immac/NetaYume-Lumina-Image-2.0-GGUF", "NetaYumev2plus_unet_q2_k.gguf"),+ (None, "some-random-denoiser.gguf"),+ ):+ for arch in sorted(LlamaCppBackend._AMBIGUOUS_IMAGE_ARCHES):+ _, message = _refusal(tmp_path, arch = arch, name = name, identifier = identifier)+ task = _arch_to_task(arch, name_hints = (identifier, name))+ picker_lists_it = task == "text-to-image"+ assert ("Open it from the Images page" in message) is picker_lists_it, (+ identifier,+ name,+ message,+ )+++def test_the_unrunnable_set_mirrors_the_canonical_one():+ # Two places must not drift: routes.models tags these image-diffusion-unsupported, which+ # hides them from the Images AND Video pickers, so naming either page sends the user to+ # an empty list.+ from routes.models import _UNSUPPORTED_DIFFUSION_GGUF_ARCHS++ assert LlamaCppBackend._UNRUNNABLE_MEDIA_ARCHES == _UNSUPPORTED_DIFFUSION_GGUF_ARCHS+ # ...and a runnable set may never overlap it, or the destination is a promise again.+ assert not (LlamaCppBackend._IMAGE_ARCHES & _UNSUPPORTED_DIFFUSION_GGUF_ARCHS)+ assert not (LlamaCppBackend._VIDEO_ARCHES & _UNSUPPORTED_DIFFUSION_GGUF_ARCHS)++[email protected]("arch", sorted(LlamaCppBackend._UNRUNNABLE_MEDIA_ARCHES))+def test_an_unrunnable_media_arch_promises_no_page(tmp_path, arch):+ _, message = _refusal(tmp_path, arch = arch, name = f"{arch}.gguf")+ assert message is not None+ # Refused, but WITHOUT being sent anywhere: no page can run these.+ assert "neither the Images page nor the Video page" in message+ assert "Open it from the" not in message++[email protected]("repo", ["gguf-org/flux2-dev-gguf", "calcuis/cosmos-predict2-gguf"])+def test_a_placeholder_architecture_still_refuses(tmp_path, repo):+ # gguf-connector writes a literal "pig" in place of an architecture; measured on+ # gguf-org/flux2-dev-gguf/flux2-dev-iq4_nl.gguf. Without normalising it the file slips+ # past every set and dies opaquely in llama-server.+ _, message = _refusal(tmp_path, arch = "pig", name = "flux2-dev-iq4_nl.gguf", identifier = repo)+ assert message is not None+ assert "cannot" in message+++def test_a_placeholder_architecture_matches_the_picker_verdict(tmp_path):+ # The placeholder carries no family, so both sides fall back to the repo id and filename+ # and have to agree, or the Images page is named for a file its picker drops.+ from routes.models import _arch_to_task+ for identifier, name, page_named in (+ ("gguf-org/flux2-dev-gguf", "flux2-dev-iq4_nl.gguf", True),+ ("calcuis/cosmos-predict2-gguf", "cosmos-predict2-q4_0.gguf", False),+ ("someone/mystery-gguf", "mystery-q4_0.gguf", False),+ ):+ for arch in sorted(LlamaCppBackend._PLACEHOLDER_ARCHES):+ _, message = _refusal(tmp_path, arch = arch, name = name, identifier = identifier)+ assert message is not None+ task = _arch_to_task(arch, name_hints = (identifier, name))+ assert (task == "text-to-image") is page_named, (identifier, arch, task)+ assert ("Open it from the Images page" in message) is page_named, message+++def test_an_unassemblable_video_arch_promises_no_page(tmp_path):+ # Wan 2.2 A14B is a two-expert MoE the Video backend cannot assemble, and Wan 2.1's repo+ # ids resolve to no family, so _arch_to_task tags both image-diffusion-unsupported and+ # the Video picker never lists them. The header says "wan" for all three, so the refusal+ # has to consult the same family resolution rather than trusting the arch.+ from routes.models import _arch_to_task+ for identifier, name, page_named in (+ ("QuantStack/Wan2.2-TI2V-5B-GGUF", "Wan2.2-TI2V-5B-Q4_K_M.gguf", True),+ ("QuantStack/Wan2.2-T2V-A14B-GGUF", "Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf", False),+ ("QuantStack/Wan2.1-T2V-14B-GGUF", "Wan2.1-T2V-14B-Q4_K_M.gguf", False),+ ):+ _, message = _refusal(tmp_path, arch = "wan", name = name, identifier = identifier)+ assert message is not None+ task = _arch_to_task("wan", name_hints = (identifier, name))+ assert (task == "text-to-video") is page_named, (identifier, task)+ assert ("Open it from the Video page" in message) is page_named, message+++def test_an_arch_that_names_its_own_family_still_gets_the_video_page(tmp_path):+ # _arch_to_task asks detect_video_family("", override = arch) FIRST, and "ltxv" resolves+ # LTX-2 with no name to go on, so a generically named LTX GGUF IS listed on the Video+ # page. Resolving by repo id and filename alone answered the opposite.+ from routes.models import _arch_to_task+ for identifier, name in (+ ("someone/generic-gguf", "model-Q4_K_M.gguf"),+ (None, "checkpoint-q4_0.gguf"),+ ("Lightricks/LTX-Video-gguf", "ltxv-2b-Q4_K_M.gguf"),+ ):+ _, message = _refusal(tmp_path, arch = "ltxv", name = name, identifier = identifier)+ assert message is not None+ assert _arch_to_task("ltxv", name_hints = (identifier, name)) == "text-to-video"+ assert "Open it from the Video page" in message, (identifier, name, message)+++def _write_split_shard(path: Path) -> Path:+ """A gguf-split shard past the first: split.no / split.count / split.tensors.count and no+ general.architecture, as measured on unsloth/DeepSeek-R1-GGUF shard 2."""+ body = b""+ for key, value in ((b"split.no", 1), (b"split.count", 30), (b"split.tensors.count", 34)):+ body += struct.pack("<Q", len(key)) + key+ body += struct.pack("<I", 4) # UINT32+ body += struct.pack("<I", value)+ path.write_bytes(struct.pack("<II", GGUF_MAGIC, 3) + struct.pack("<QQ", 34, 3) + body)+ return path+++def test_a_trailing_split_shard_gets_no_verdict(tmp_path):+ # Shard 1 carries the architecture for the whole set, so a later shard declares none.+ # Refusing it as a media GGUF would misname a chat model; llama.cpp's own "must be+ # loaded with the first split" is the accurate answer.+ gguf = _write_split_shard(tmp_path / "DeepSeek-R1.BF16-00002-of-00030.gguf")+ backend = LlamaCppBackend()+ backend._model_identifier = "unsloth/DeepSeek-R1-GGUF"+ backend._read_gguf_metadata(str(gguf))+ assert backend._gguf_header_parsed is True+ assert backend._architecture is None+ assert backend._non_chat_gguf_refusal(str(gguf)) is None+++def test_a_metadata_less_gguf_that_is_not_a_shard_is_still_refused(tmp_path):+ # The no-architecture verdict still catches MiniMax-H3's zero-KV files: only the split+ # keys buy an exemption.+ _, message = _refusal(tmp_path, arch = None, name = "video-dit-Q4_K_M.gguf")+ assert message is not None+++def test_the_first_shard_is_the_one_a_variant_resolves_to():+ # Why the exemption above only has to cover hand-written variant strings: every producer+ # strips the shard suffix and the matches are sorted, so shard 1 leads and the rest ride+ # along as extra shards.+ from core.inference.llama_cpp import _gguf_extra_shards, _gguf_files_for_variant+ files = [f"BF16/model-BF16-{i:05d}-of-00010.gguf" for i in range(1, 11)]+ for variant in ("BF16", "BF16/model-BF16"):+ picked = _gguf_files_for_variant(files, variant)+ assert picked and picked[0].endswith("-00001-of-00010.gguf"), variant+ assert len(_gguf_extra_shards(picked, picked[0])) == 9+++def test_a_split_placeholder_media_gguf_is_still_refused(tmp_path):+ # The split exemption needs split.no > 0 AND nothing declared. A placeholder arch is+ # blanked before the name-based branch, so keying on the split keys alone would wave+ # through the very files the placeholder handling exists to catch -- shard 1 carries+ # those keys too.+ body = b""+ key, val = b"general.architecture", b"pig"+ body += struct.pack("<Q", len(key)) + key + struct.pack("<I", 8)+ body += struct.pack("<Q", len(val)) + val+ for k, v in ((b"split.no", 0), (b"split.count", 2)):+ body += struct.pack("<Q", len(k)) + k + struct.pack("<I", 4) + struct.pack("<I", v)+ gguf = tmp_path / "flux2-dev-iq4_nl-00001-of-00002.gguf"+ gguf.write_bytes(struct.pack("<II", GGUF_MAGIC, 3) + struct.pack("<QQ", 1, 3) + body)+ backend = LlamaCppBackend()+ backend._model_identifier = "gguf-org/flux2-dev-gguf"+ backend._read_gguf_metadata(str(gguf))+ assert backend._gguf_split_index == 0+ message = backend._non_chat_gguf_refusal(str(gguf))+ assert message is not None+ assert "Open it from the Images page" in message+++def test_the_metadata_less_branch_asks_what_the_pickers_ask(tmp_path):+ # A family that resolves is not enough for the arch branches, nor here: routes.models+ # drops an MoE the loader cannot assemble, so the Video page would not list Wan 2.2 A14B+ # however its GGUF is packaged.+ from routes.models import _arch_to_task+ for identifier, name, page_named in (+ ("QuantStack/Wan2.2-TI2V-5B-GGUF", "Wan2.2-TI2V-5B-Q4_K_M.gguf", True),+ ("QuantStack/Wan2.2-T2V-A14B-GGUF", "Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf", False),+ ):+ _, message = _refusal(tmp_path, arch = None, name = name, identifier = identifier)+ assert message is not None+ assert (+ _arch_to_task("wan", name_hints = (identifier, name)) == "text-to-video"+ ) is page_named+ assert ("Open it from the Video page" in message) is page_named, messagediff --git a/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.py b/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.pynew file mode 100644index 00000000000..2dffed5eee7--- /dev/null+++ b/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.py@@ -0,0 +1,623 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""CPU-only unit tests for the non-chat GGUF refusal on a REPO load.++The local-file refusal already runs before Phase 1; a repo load did not, because the file+only exists after Phase 2, so the resident chat model had already been killed for a load+that was never going to start. That is the path the Model Hub takes (the route resolves+every Hub model to hf_repo), so it was the reported case, not an API-only corner.++The fix decides it from a header-sized byte range instead of the download. Measured over the+Hub, media GGUFs finish their KV walk in 144-3,987 bytes while a chat model's+tokenizer.ggml.tokens array pushes its KV block past 5 MB, so a 256 KiB prefix is decisive+for the first and truncated for the second -- and truncated means no verdict, which is the+direction it has to fail in.+"""++from __future__ import annotations++import contextlib+import inspect+import struct+from pathlib import Path++import pytest++import core.inference.diffusion_compat as diffusion_compat+import core.inference.llama_cpp as llama_cpp_module+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend++GGUF_MAGIC = 0x46554747+++def _gguf_bytes(+ *,+ arch: str | None,+ tensor_count: int = 1,+ declared_kv: int | None = None,+) -> bytes:+ """A GGUF header as BYTES. ``declared_kv`` overstates the KV count without writing the+ pairs -- the shape a byte-range prefix of a chat model has: the counts say more is+ coming and the buffer ends first."""+ body = b""+ kv_count = 0+ if arch is not None:+ key = b"general.architecture"+ val = arch.encode()+ body += struct.pack("<Q", len(key)) + key+ body += struct.pack("<I", 8) # STRING+ body += struct.pack("<Q", len(val)) + val+ kv_count = 1+ if declared_kv is not None:+ kv_count = declared_kv+ return struct.pack("<II", GGUF_MAGIC, 3) + struct.pack("<QQ", tensor_count, kv_count) + body+++def _probe(+ monkeypatch,+ *,+ header: bytes,+ filename: str = "model-Q4_K_M.gguf",+ identifier = None,+ local: str | None = None,+ patch_cache: bool = True,+):+ """Run the remote probe against a canned header, recording whether it went to the Hub."""+ requests: list[tuple[str, str]] = []++ def _fake_remote(repo_id, gguf_filename, hf_token):+ requests.append((repo_id, gguf_filename))+ return header++ monkeypatch.setattr(+ llama_cpp_module, "_resolve_variant_gguf_files", lambda *_a, **_k: (filename, [])+ )+ # The verified cache lookup is the only way a local copy enters the probe; a test with+ # its own stub for it passes patch_cache = False.+ if patch_cache:+ monkeypatch.setattr(llama_cpp_module, "cached_gguf_for_load", lambda *_a, **_k: local)+ monkeypatch.setattr(diffusion_compat, "_read_gguf_header", _fake_remote)+ message = LlamaCppBackend._remote_non_chat_gguf_refusal(+ hf_repo = "owner/model",+ hf_variant = "Q4_K_M",+ hf_token = None,+ model_identifier = identifier,+ )+ return message, requests+++# ── the verdict itself ────────────────────────────────────────────────────────────+++ "arch, page",+ [+ ("flux", "Images page"),+ ("ltxv", "Video page"),+ ("wan", "Video page"),+ ("sd3", "Images page"),+ ],+)+def test_a_media_repo_gguf_is_refused_from_its_header_alone(monkeypatch, arch, page):+ # 144-145 bytes on the Hub for every one of these: three KV pairs and no vocabulary.+ message, requests = _probe(monkeypatch, header = _gguf_bytes(arch = arch))+ assert message is not None+ assert page in message+ assert requests == [("owner/model", "model-Q4_K_M.gguf")]+++def test_a_placeholder_arch_repo_gguf_is_refused(monkeypatch):+ # gguf-connector writes a literal "pig"; the probe must normalise it like the on-disk+ # check does, or a 20 GB flux2 download still costs the resident model.+ message, _ = _probe(+ monkeypatch,+ header = _gguf_bytes(arch = "pig"),+ filename = "flux2-dev-q4_k_m.gguf",+ identifier = "gguf-org/flux2-dev-gguf",+ )+ assert message is not None+ assert "Images page" in message+++def test_the_filename_survives_into_the_verdict(monkeypatch):+ # With no general.architecture the page is named off the file name, so the prefix is+ # spooled under the REAL name and not a temp one.+ message, _ = _probe(+ monkeypatch,+ header = _gguf_bytes(arch = None),+ filename = "wan2.2-ti2v-5b-Q4_K_M.gguf",+ )+ assert message is not None+ assert "Video page" in message+++def test_an_ambiguous_arch_is_resolved_from_the_real_filename(monkeypatch):+ # A shared architecture is resolved from the repo id and the FILE NAME: the other reason+ # the prefix is spooled under its real name.+ if not getattr(LlamaCppBackend, "_AMBIGUOUS_IMAGE_ARCHES", None):+ pytest.skip("no ambiguous image archs on this build")+ message, _ = _probe(+ monkeypatch,+ header = _gguf_bytes(arch = sorted(LlamaCppBackend._AMBIGUOUS_IMAGE_ARCHES)[0]),+ filename = "z-image-turbo-Q2_K.gguf",+ identifier = "unsloth/Z-Image-Turbo-GGUF",+ )+ assert message is not None+ assert "Open it from the Images page" in message+++def test_a_chat_repo_gguf_is_not_refused(monkeypatch):+ message, _ = _probe(monkeypatch, header = _gguf_bytes(arch = "qwen3"))+ assert message is None+++# ── fail-open, in every direction ─────────────────────────────────────────────────+++def test_a_prefix_cut_mid_kv_yields_no_verdict(monkeypatch):+ # The chat-model case for real: 256 KiB of a 5.9 MB KV block. The counts promise 32+ # pairs, one arrives, the buffer ends. _gguf_header_parsed stays False, so "declares no+ # architecture" must not be read out of a read that simply stopped early.+ message, _ = _probe(monkeypatch, header = _gguf_bytes(arch = "llama", declared_kv = 32))+ assert message is None+++def test_an_unreachable_hub_yields_no_verdict(monkeypatch):+ # _read_gguf_header returns b"" for offline, a 401, a deadline, or a proxy that+ # answered 200 instead of 206.+ message, _ = _probe(monkeypatch, header = b"")+ assert message is None+++def test_an_unresolvable_filename_yields_no_verdict(monkeypatch):+ monkeypatch.setattr(+ llama_cpp_module, "_resolve_variant_gguf_files", lambda *_a, **_k: (None, [])+ )+ called = []+ monkeypatch.setattr(+ diffusion_compat, "_read_gguf_header", lambda *_a, **_k: called.append(True) or b""+ )+ assert (+ LlamaCppBackend._remote_non_chat_gguf_refusal(+ hf_repo = "owner/model", hf_variant = None, hf_token = None, model_identifier = None+ )+ is None+ )+ # No filename means no request either: there is nothing to ask for.+ assert called == []+++def test_a_probe_that_raises_yields_no_verdict(monkeypatch):+ def _boom(*_a, **_k):+ raise ConnectionError("hub unreachable")++ monkeypatch.setattr(+ llama_cpp_module, "_resolve_variant_gguf_files", lambda *_a, **_k: ("m.gguf", [])+ )+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *_a, **_k: None)+ monkeypatch.setattr(diffusion_compat, "_read_gguf_header", _boom)+ assert (+ LlamaCppBackend._remote_non_chat_gguf_refusal(+ hf_repo = "owner/model",+ hf_variant = "Q4_K_M",+ hf_token = None,+ model_identifier = None,+ )+ is None+ )+++def test_a_cached_copy_is_read_off_disk_instead_of_the_hub(monkeypatch, tmp_path):+ # A cached file answers this with no request, the only way the verdict survives an+ # unreachable Hub.+ cached = tmp_path / "ltx-2-19b-dev-Q4_K_M.gguf"+ cached.write_bytes(_gguf_bytes(arch = "ltxv"))+ message, requests = _probe(+ monkeypatch,+ header = b"", # would fail open if the probe went to the network+ filename = "ltx-2-19b-dev-Q4_K_M.gguf",+ local = str(cached),+ )+ assert message is not None and "Video page" in message+ assert requests == []+++# ── the invariant the whole item is about ─────────────────────────────────────────+++def test_the_remote_probe_agrees_with_the_other_two_entry_points(tmp_path, monkeypatch):+ # Three entry points, one verdict: otherwise a load is refused on one path and launched+ # on another.+ for arch, name in (("llama", "chat.gguf"), ("flux", "flux.gguf"), ("ltxv", "ltx.gguf")):+ header = _gguf_bytes(arch = arch)+ gguf = tmp_path / name+ gguf.write_bytes(header)+ backend = LlamaCppBackend()+ backend._model_identifier = None+ backend._read_gguf_metadata(str(gguf))+ instance = backend._non_chat_gguf_refusal(str(gguf))+ by_path = LlamaCppBackend._non_chat_gguf_refusal_for_path(str(gguf), None)+ remote, _ = _probe(monkeypatch, header = header, filename = name)+ assert instance == by_path == remote, arch+++def test_the_repo_refusal_sits_above_the_teardown_in_source():+ src = inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)+ remote = src.index("self._remote_non_chat_gguf_refusal(")+ teardown = src.index("# ── Phase 1: kill old process")+ assert remote < teardown+ # And the post-download check stays as the backstop for what the probe fails open on.+ assert src.index("non_chat = self._non_chat_gguf_refusal(model_path)") > teardown+++def _repo_load(monkeypatch, backend, order):+ monkeypatch.setattr(backend, "_find_llama_server_binary", lambda **_kwargs: "/bin/llama")+ monkeypatch.setattr(backend, "_is_vulkan_backend", lambda _binary = None: False)+ monkeypatch.setattr(backend, "_backend_lacks_gpu_lib", lambda _binary = None: False)+ monkeypatch.setattr(backend, "_kill_process", lambda: order.append("kill"))+ monkeypatch.setattr(llama_cpp_module, "_resolve_repo_id_casing", lambda repo: repo)+ monkeypatch.setattr(+ llama_cpp_module, "_hf_offline_if_unreachable", lambda: contextlib.nullcontext()+ )+ monkeypatch.setattr(+ llama_cpp_module, "_resolve_variant_gguf_files", lambda *_a, **_k: ("m-Q4_K_M.gguf", [])+ )+ monkeypatch.setattr(diffusion_compat, "_local_gguf_path", lambda *_a, **_k: None)+++def test_a_media_repo_load_keeps_the_resident_model_and_never_downloads(monkeypatch):+ # The regression. Before the fix this killed the live server, downloaded the whole+ # media GGUF, and only then raised.+ backend = LlamaCppBackend()+ order: list[str] = []+ _repo_load(monkeypatch, backend, order)+ monkeypatch.setattr(+ backend, "_download_gguf", lambda **_kwargs: order.append("download") or "/cache/m.gguf"+ )+ monkeypatch.setattr(+ diffusion_compat, "_read_gguf_header", lambda *_a, **_k: _gguf_bytes(arch = "wan")+ )++ with pytest.raises(ValueError, match = "Video page"):+ backend.load_model(+ GgufLoadIntent(+ hf_repo = "unsloth/Wan2.2-TI2V-5B-GGUF",+ hf_variant = "Q4_K_M",+ model_identifier = "unsloth/Wan2.2-TI2V-5B-GGUF",+ )+ )++ # Neither the teardown nor the multi-GB download happened.+ assert order == []+++def test_a_chat_repo_load_still_proceeds_past_the_teardown(monkeypatch):+ # A prefix the probe cannot finish must not become a refusal: the load carries on.+ backend = LlamaCppBackend()+ order: list[str] = []+ _repo_load(monkeypatch, backend, order)++ def _download(**_kwargs):+ order.append("download")+ raise RuntimeError("stop here")++ monkeypatch.setattr(backend, "_download_gguf", _download)+ monkeypatch.setattr(+ diffusion_compat,+ "_read_gguf_header",+ lambda *_a, **_k: _gguf_bytes(arch = "qwen3", declared_kv = 32),+ )++ with pytest.raises(RuntimeError, match = "stop here"):+ backend.load_model(+ GgufLoadIntent(+ hf_repo = "unsloth/Qwen3-0.6B-GGUF",+ hf_variant = "Q4_K_M",+ model_identifier = "unsloth/Qwen3-0.6B-GGUF",+ )+ )++ assert order == ["kill", "download"]+++def test_a_preflighted_file_is_judged_without_a_second_request(monkeypatch, tmp_path):+ # When a GPU-pin preflight already fetched the file the verdict is free, and that path+ # used to skip the refusal entirely.+ media = tmp_path / "flux1-dev-Q4_K_S.gguf"+ media.write_bytes(_gguf_bytes(arch = "flux"))+ backend = LlamaCppBackend()+ order: list[str] = []+ _repo_load(monkeypatch, backend, order)+ monkeypatch.setattr(backend, "_is_vulkan_backend", lambda _binary = None: True)+ monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None: [(0, 1024, 2048)])+ monkeypatch.setattr(+ backend, "_download_gguf", lambda **_kwargs: order.append("download") or str(media)+ )+ monkeypatch.setattr(backend, "_gguf_path_is_diffusion", lambda *_args: False)+ monkeypatch.setattr(+ diffusion_compat,+ "_read_gguf_header",+ lambda *_a, **_k: pytest.fail("the preflighted file must be judged directly"),+ )++ with pytest.raises(ValueError, match = "Images page"):+ backend.load_model(+ GgufLoadIntent(+ hf_repo = "city96/FLUX.1-dev-gguf",+ hf_variant = "Q4_K_S",+ model_identifier = "city96/FLUX.1-dev-gguf",+ gpu_ids = [0],+ )+ )++ assert order == ["download"]+ assert Path(media).is_file()+++def test_the_cached_file_the_load_will_open_is_the_one_judged(monkeypatch, tmp_path):+ # _download_gguf resolves its local copy through cached_gguf_for_load, which walks the+ # cached variant candidates rather than the current listing's filename. The probe follows+ # it, or a repo that renamed the file for a quant would let the probe judge one GGUF and+ # the load open another. The listing name here is deliberately not the cached one.+ cached = tmp_path / "renamed-ltx-2-19b-dev-Q4_K_M.gguf"+ cached.write_bytes(_gguf_bytes(arch = "ltxv"))+ monkeypatch.setattr(llama_cpp_module, "cached_gguf_for_load", lambda *_a, **_k: str(cached))+ message, requests = _probe(+ monkeypatch,+ header = b"",+ filename = "listing-Q4_K_M.gguf",+ patch_cache = False,+ )+ assert message is not None and "Video page" in message+ assert requests == []+++def test_nothing_cached_means_the_hub_is_asked(monkeypatch, tmp_path):+ # With no verified cache hit the probe range-reads the Hub rather than an unverified+ # path: a candidate the verified lookup rejected is one _download_gguf will skip anyway.+ message, requests = _probe(+ monkeypatch,+ header = _gguf_bytes(arch = "ltxv"),+ filename = "ltx-2-19b-dev-Q4_K_M.gguf",+ local = None,+ )+ assert message is not None and "Video page" in message+ assert requests == [("owner/model", "ltx-2-19b-dev-Q4_K_M.gguf")]+++def test_a_refused_load_leaves_the_resident_process_state_alone(monkeypatch):+ # The refusal spares the resident server, so it has to spare what describes it. Resetting+ # the launch revision would say the live process launched from the binary installed NOW,+ # so an Apply after `unsloth studio update` would dedupe against it instead of+ # relaunching; clearing the DFlash verdict loses a retry the same way.+ backend = LlamaCppBackend()+ order: list[str] = []+ _repo_load(monkeypatch, backend, order)+ backend._launch_binary_revision = ("llama-server", 1, 111.0)+ backend._dflash_retry_needed = True+ monkeypatch.setattr(+ backend, "_download_gguf", lambda **_kwargs: order.append("download") or "/cache/m.gguf"+ )+ monkeypatch.setattr(+ diffusion_compat, "_read_gguf_header", lambda *_a, **_k: _gguf_bytes(arch = "wan")+ )++ with pytest.raises(ValueError, match = "Video page"):+ backend.load_model(+ GgufLoadIntent(+ hf_repo = "unsloth/Wan2.2-TI2V-5B-GGUF",+ hf_variant = "Q4_K_M",+ model_identifier = "unsloth/Wan2.2-TI2V-5B-GGUF",+ )+ )++ assert order == []+ assert backend._launch_binary_revision == ("llama-server", 1, 111.0)+ assert backend._dflash_retry_needed is True+++def test_the_per_load_resets_sit_below_the_teardown_in_source():+ src = inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)+ teardown = src.index("# ── Phase 1: kill old process")+ assert src.index("self._launch_binary_revision = self._binary_revision(binary)") > teardown+ assert src.index("self._dflash_retry_needed = False") > teardown+++def test_the_cached_probe_is_verified_the_way_the_loader_verifies_it(monkeypatch, tmp_path):+ # cached_gguf_for_load(verify_sizes = True) is what _download_gguf uses, so a snapshot+ # truncated after its header is skipped there. Judging it here would classify bytes the+ # load never opens, refusing a valid chat repo off a stale snapshot.+ cached = tmp_path / "ltx-2-19b-dev-Q4_K_M.gguf"+ cached.write_bytes(_gguf_bytes(arch = "ltxv"))+ seen: list[bool] = []++ def _cached(+ _repo,+ _variant,+ *,+ verify_sizes = False,+ hf_token = None,+ ):+ seen.append(verify_sizes)+ return str(cached) if verify_sizes else "/should/not/be/used.gguf"++ monkeypatch.setattr(llama_cpp_module, "cached_gguf_for_load", _cached)+ message, requests = _probe(+ monkeypatch, header = b"", filename = "listing-Q4_K_M.gguf", patch_cache = False+ )+ assert seen == [True]+ assert message is not None and "Video page" in message+ assert requests == []+++def test_a_declared_media_arch_is_acted_on_before_the_walk_finishes(monkeypatch, tmp_path):+ # general.architecture is KV #0 in every GGUF measured, so a repo with bulky later+ # metadata can declare a media arch inside the 256 KiB prefix and still leave the KV walk+ # unfinished. Discarding that verdict put the teardown and the full download back.+ header = _gguf_bytes(arch = "flux", declared_kv = 4096)+ message, _requests = _probe(monkeypatch, header = header, filename = "flux1-dev-Q4_K_M.gguf")+ assert message is not None and "Images page" in message++ # The no-architecture fallback still needs the complete walk: an unfinished read is+ # indistinguishable from a file that declares nothing.+ quiet = _probe(+ monkeypatch, header = _gguf_bytes(arch = None, declared_kv = 4096), filename = "mystery-Q4_K_M.gguf"+ )[0]+ assert quiet is None+++def test_the_probe_runs_under_the_same_offline_guard_as_the_download(monkeypatch):+ # With the Hub unreachable and the model cached, the probe's two Hub calls (the file+ # listing, then the cached candidate's revision sizes) would each wait out their retry+ # backoff before any local header is read. The download has always run under the guard;+ # the probe has to as well, or a cached load pays two timeouts for a free verdict.+ backend = LlamaCppBackend()+ order: list[str] = []+ _repo_load(monkeypatch, backend, order)+ entered: list[str] = []++ @contextlib.contextmanager+ def _guard():+ entered.append("enter")+ yield True++ monkeypatch.setattr(llama_cpp_module, "_hf_offline_if_unreachable", _guard)++ guarded: list[bool] = []++ def _probe_call(**_kwargs):+ # Recorded, not asserted: an assert here would be swallowed by the raises() below.+ guarded.append(bool(entered))+ return None++ monkeypatch.setattr(backend, "_remote_non_chat_gguf_refusal", _probe_call)+ monkeypatch.setattr(+ backend, "_download_gguf", lambda **_kwargs: order.append("download") or "/cache/m.gguf"+ )++ with pytest.raises(Exception):+ backend.load_model(+ GgufLoadIntent(+ hf_repo = "unsloth/Qwen3-0.6B-GGUF",+ hf_variant = "Q4_K_M",+ model_identifier = "unsloth/Qwen3-0.6B-GGUF",+ )+ )+ assert guarded == [True], guarded+++def test_the_probe_guard_sits_above_the_teardown_in_source():+ src = inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)+ guarded = src.index("with _hf_offline_if_unreachable():\n _early_non_chat")+ assert guarded < src.index("# ── Phase 1: kill old process")+++def test_the_route_entry_point_judges_an_intent_before_the_arbiter(monkeypatch, tmp_path):+ # What the route calls. load_model's own copy runs before ITS teardown but after+ # acquire_for has evicted a resident pipeline and cancelled the running chats.+ media = tmp_path / "ltx-2-19b-dev-Q4_K_M.gguf"+ media.write_bytes(_gguf_bytes(arch = "ltxv"))+ intent = GgufLoadIntent(+ model_identifier = "unsloth/LTX-2-GGUF",+ gguf_path = str(media),+ )+ message = LlamaCppBackend.non_chat_gguf_refusal_for_intent(intent)+ assert message is not None and "Video page" in message++ chat = tmp_path / "qwen3-0.6b-Q4_K_M.gguf"+ chat.write_bytes(_gguf_bytes(arch = "qwen3"))+ assert (+ LlamaCppBackend.non_chat_gguf_refusal_for_intent(+ GgufLoadIntent(model_identifier = "unsloth/Qwen3-0.6B-GGUF", gguf_path = str(chat))+ )+ is None+ )+++def test_the_route_entry_point_fails_open(monkeypatch, tmp_path):+ # A probe that raises is not a verdict: the load proceeds, its own checks back it up.+ def _boom(*_a, **_k):+ raise RuntimeError("hub down")++ monkeypatch.setattr(LlamaCppBackend, "_remote_non_chat_gguf_refusal", _boom)+ assert (+ LlamaCppBackend.non_chat_gguf_refusal_for_intent(+ GgufLoadIntent(model_identifier = "owner/model", hf_repo = "owner/model")+ )+ is None+ )+++def test_the_route_asks_before_it_takes_the_gpu():+ # Source order, since the eviction it protects is the arbiter's, not the loader's.+ import inspect as _inspect++ from routes import inference as inference_routes++ src = _inspect.getsource(inference_routes)+ refusal = src.index("non_chat_gguf_refusal_for_intent")+ acquire = src.index("lambda: gguf_load_stack.enter_context(chat_load_in_flight())")+ assert refusal < acquire+++def test_the_route_hands_its_verdict_to_the_load(monkeypatch, tmp_path):+ # The route and the loader ask for the same intent seconds apart, and each ask is a+ # listing, a cache verification and a range request. The second takes the first's answer.+ calls: list[str] = []++ def _verdict(**kwargs):+ calls.append(kwargs["hf_repo"])+ return "This is a text-to-video GGUF. Open it from the Video page instead."++ monkeypatch.setattr(LlamaCppBackend, "_remote_non_chat_gguf_verdict", _verdict)+ monkeypatch.setattr(LlamaCppBackend, "_route_verdict_handoff", None)+ intent = GgufLoadIntent(+ model_identifier = "unsloth/LTX-2-GGUF",+ hf_repo = "unsloth/LTX-2-GGUF",+ hf_variant = "Q4_K_M",+ )+ assert LlamaCppBackend.non_chat_gguf_refusal_for_intent(intent) is not None+ assert calls == ["unsloth/LTX-2-GGUF"]++ # The load that follows reuses it...+ reused = LlamaCppBackend._remote_non_chat_gguf_refusal(+ hf_repo = "unsloth/LTX-2-GGUF",+ hf_variant = "Q4_K_M",+ hf_token = None,+ model_identifier = "unsloth/LTX-2-GGUF",+ )+ assert reused is not None+ assert calls == ["unsloth/LTX-2-GGUF"]++ # ...exactly once. A second load probes for itself rather than trusting a stale answer.+ LlamaCppBackend._remote_non_chat_gguf_refusal(+ hf_repo = "unsloth/LTX-2-GGUF",+ hf_variant = "Q4_K_M",+ hf_token = None,+ model_identifier = "unsloth/LTX-2-GGUF",+ )+ assert calls == ["unsloth/LTX-2-GGUF"] * 2+++def test_a_handoff_for_another_model_is_not_taken(monkeypatch):+ calls: list[str] = []++ def _verdict(**kwargs):+ calls.append(kwargs["hf_repo"])+ return None++ monkeypatch.setattr(LlamaCppBackend, "_remote_non_chat_gguf_verdict", _verdict)+ monkeypatch.setattr(LlamaCppBackend, "_route_verdict_handoff", None)+ LlamaCppBackend.non_chat_gguf_refusal_for_intent(+ GgufLoadIntent(model_identifier = "owner/a", hf_repo = "owner/a", hf_variant = "Q4_K_M")+ )+ LlamaCppBackend._remote_non_chat_gguf_refusal(+ hf_repo = "owner/b", hf_variant = "Q4_K_M", hf_token = None, model_identifier = "owner/b"+ )+ assert calls == ["owner/a", "owner/b"]+ # A different variant of the same repo is a different file, so it is not taken either.+ LlamaCppBackend._remote_non_chat_gguf_refusal(+ hf_repo = "owner/a", hf_variant = "Q8_0", hf_token = None, model_identifier = "owner/a"+ )+ assert calls == ["owner/a", "owner/b", "owner/a"]diff --git a/studio/backend/tests/test_llama_cpp_start_failure_classification.py b/studio/backend/tests/test_llama_cpp_start_failure_classification.pyindex 342368d182c..63bcb726286 100644--- a/studio/backend/tests/test_llama_cpp_start_failure_classification.py+++ b/studio/backend/tests/test_llama_cpp_start_failure_classification.py@@ -62,14 +62,55 @@ class TestDiffusionArchitectures:assert "enough memory" not in msg.lower()# Parametrize over the production set so new arches are auto-covered.- @pytest.mark.parametrize("arch", sorted(LlamaCppBackend._DIFFUSION_ARCHES))- def test_every_diffusion_arch_is_recognised(self, arch):+ @pytest.mark.parametrize("arch", sorted(LlamaCppBackend._IMAGE_ARCHES))+ def test_every_image_arch_is_recognised(self, arch):out = f"error loading model: unknown model architecture: '{arch}'"msg = _classify(out, f"/models/{arch}.gguf", f"local/{arch}")assert "diffusion" in msg.lower()assert "Images page" in msgassert arch in msg+ # A video arch must name the VIDEO page: Images cannot run it either.+ @pytest.mark.parametrize("arch", sorted(LlamaCppBackend._VIDEO_ARCHES))+ def test_every_video_arch_routes_to_the_video_page(self, arch):+ out = f"error loading model: unknown model architecture: '{arch}'"+ msg = _classify(out, f"/models/{arch}.gguf", f"local/{arch}")+ assert "text-to-video" in msg.lower()+ assert "Video page" in msg+ assert "Images page" not in msg+ assert arch in msg+ assert "enough memory" not in msg.lower()++ # An arch no page can run must promise NEITHER page: the picker tags these+ # ``image-diffusion-unsupported``, hiding them from the Images and Video lists alike.+ @pytest.mark.parametrize("arch", sorted(LlamaCppBackend._UNRUNNABLE_MEDIA_ARCHES))+ def test_unrunnable_media_arch_names_no_page(self, arch):+ out = f"error loading model: unknown model architecture: '{arch}'"+ msg = _classify(out, f"/models/{arch}.gguf", f"local/{arch}")+ assert arch in msg+ assert "neither the Images page nor the Video page" in msg+ assert "Use Unsloth's image generation page" not in msg+ assert "Open it from" not in msg+ assert "cannot run" in msg.lower()+ assert "enough memory" not in msg.lower()++ def test_media_arch_sets_are_disjoint_and_cover_the_union(self):+ sets = (+ LlamaCppBackend._IMAGE_ARCHES,+ LlamaCppBackend._AMBIGUOUS_IMAGE_ARCHES,+ LlamaCppBackend._VIDEO_ARCHES,+ LlamaCppBackend._UNRUNNABLE_MEDIA_ARCHES,+ )+ assert sum(len(s) for s in sets) == len(set().union(*sets))+ assert set().union(*sets) == LlamaCppBackend._DIFFUSION_ARCHES++ # The video set must stay inside what the Video picker offers: an arch routes.models+ # tags unsupported can never be picked on the page we name. Video only -- the image half+ # (sd1/sd3/sdxl/aura/hidream) predates the video split and is left to its own change.+ def test_no_runnable_video_arch_is_tagged_unsupported_by_the_picker(self):+ from routes.models import _UNSUPPORTED_DIFFUSION_GGUF_ARCHS+ assert not (LlamaCppBackend._VIDEO_ARCHES & _UNSUPPORTED_DIFFUSION_GGUF_ARCHS)+class TestUnsupportedNonDiffusionArchitecture:def test_unknown_llm_arch_says_unsupported_not_oom(self):diff --git a/studio/frontend/src/features/hub/hooks/use-selected-model-view.ts b/studio/frontend/src/features/hub/hooks/use-selected-model-view.tsindex cceac997539..287cdc5c940 100644--- a/studio/frontend/src/features/hub/hooks/use-selected-model-view.ts+++ b/studio/frontend/src/features/hub/hooks/use-selected-model-view.ts@@ -217,6 +217,10 @@ export function useSelectedModelView({capabilities: selectedDiscoverRow.capabilities,license: detectLicense(selectedDiscoverRow.result.tags),pipelineTag: selectedDiscoverRow.result.pipelineTag,+ // From the matched on-device row, like every field above: its inventory task is the+ // only record of the modality when the Hub metadata has no pipeline tag or only the+ // generic text-generation one.+ task: selectedCachedRow?.task ?? selectedLocalRow?.task ?? null,libraryName: selectedDiscoverRow.result.libraryName,gated: selectedDiscoverRow.result.gated,private: selectedDiscoverRow.result.private,@@ -287,6 +291,7 @@ export function useSelectedModelView({),license: detectLicense(mergedTags),pipelineTag: mergedPipelineTag,+ task: selectedCachedRow.task ?? null,libraryName: mergedLibraryName,gated: selectedHfResult?.gated,private: selectedHfResult?.private,@@ -363,6 +368,7 @@ export function useSelectedModelView({),license: detectLicense(mergedTags),pipelineTag: mergedPipelineTag,+ task: selectedLocalRow.task ?? null,libraryName: mergedLibraryName,gated: selectedHfResult?.gated,private: selectedHfResult?.private,@@ -415,6 +421,7 @@ export function useSelectedModelView({),license: detectLicense(mergedTags),pipelineTag: mergedPipelineTag,+ task: selectedLocalRow.task ?? null,libraryName: mergedLibraryName,gated: localHubMetadata?.gated,private: localHubMetadata?.private,diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsxindex d8ae7d682d9..68c5b3d69c3 100644--- a/studio/frontend/src/features/hub/hub-page.tsx+++ b/studio/frontend/src/features/hub/hub-page.tsx@@ -25,6 +25,8 @@ import {useActiveModelConfig,} from "@/features/model-picker";import { loadOpenAIAutoSwitchSettings } from "@/features/settings";+import { taskForMediaPick } from "@/features/model-picker/components/model-selector/audio-picker-policy";+import { diffusionRouteSearch } from "@/lib/diffusion-route-search";import { useDebouncedValue } from "@/hooks/use-debounced-value";import { useGpuInfo, useInferenceGpuInfo } from "@/hooks/use-gpu-info";import { toast } from "@/lib/toast";@@ -97,6 +99,7 @@ import {isHiddenModelId,} from "./lib/hidden-models";import { inventoryRowMatches, tokenizeQuery } from "./lib/inventory-search";+import { looksLikeLocalPath, routableToMediaPage } from "./lib/local-path";import {ggufVariantsMatch,modelIdsMatch,@@ -107,6 +110,7 @@ import {matchesModelType,} from "./lib/model-type-filter";import { resolveOwnerProviderLogo } from "./lib/provider-logos";+import { studioPageForTask } from "./lib/unsloth-support";import { fingerprintToken } from "./lib/token-fingerprint";import {buildDiscoverRows,@@ -1277,6 +1281,35 @@ export function ModelsPage() {(opts: ModelLoadOptions, isDownloaded: boolean) => {if (!selectedModel) return;const runId = selectedModel.resource.runId;+ // An image / video model is run by its own page, not by chat: loading it here evicted+ // the resident chat model for a llama.cpp load that could only fail. Same resolution+ // and destination the chat picker uses, so both surfaces route a pick identically.+ // `task` is not optional here: only CachedModelRepo carries pipelineTag, so every+ // cached GGUF repo (the reported MiniMax-H3 case) reports its modality on `task`.+ const mediaPage = studioPageForTask(+ taskForMediaPick(selectedModel.pipelineTag, selectedModel.task) ?? undefined,+ );+ // The target pages read a routed `model` as a Hub id, so a runId that is a PATH would+ // arrive as a repo that does not exist -- prefer the Hub id, which loads the same copy+ // since the loader reuses whichever cache root holds it. That covers a filesystem row+ // (left on today's route, and the backend preflight now refuses it by name) and a+ // cached repo the inventory pinned to its snapshot directory, whose symlinked entries+ // the pages' containment check rejects anyway.+ const routeId = runId && !looksLikeLocalPath(runId) ? runId : selectedModel.hubRepoId;+ if (+ mediaPage &&+ routableToMediaPage(selectedModel.kind, selectedModel.localSource) &&+ routeId+ ) {+ void navigate({+ to: `/${mediaPage}`,+ // `quant` is consumed verbatim as a gguf filename, so a label rides `ggufQuant`.+ search: diffusionRouteSearch(routeId, {+ ggufVariant: opts.ggufVariant ?? null,+ }),+ });+ return;+ }const configIdentity = modelConfigIdentity(selectedModel.kind,selectedModel.resource,@@ -1313,7 +1346,7 @@ export function ModelsPage() {.catch(() => undefined);openNewChat();},- [openNewChat, selectModel, selectedModel],+ [navigate, openNewChat, selectModel, selectedModel],);const handleLoad = useCallback((opts: ModelLoadOptions) =>diff --git a/studio/frontend/src/features/hub/lib/local-path.ts b/studio/frontend/src/features/hub/lib/local-path.tsindex 4511c4dfcc9..77cb67ed927 100644--- a/studio/frontend/src/features/hub/lib/local-path.ts+++ b/studio/frontend/src/features/hub/lib/local-path.ts@@ -13,3 +13,14 @@ export function localPathCacheKey(path: string | null | undefined): string {.replace(TRAILING_PATH_SEPARATOR_RE, "") ?? "");}++/** Whether a selected row can be routed to the Images / Video pages, which resolve a routed+ * `model` as a Hub id. Only a FILESYSTEM row cannot: an HF-cache row is a complete Hub+ * snapshot carrying the repo id, and inventory dedup can leave it as the only row for that+ * repo, so excluding it by kind alone dropped it into a chat the backend then refuses. */+export function routableToMediaPage(+ kind: "discover" | "cache" | "local",+ localSource: string | null | undefined,+): boolean {+ return kind !== "local" || localSource === "hf_cache";+}diff --git a/studio/frontend/src/features/hub/types.ts b/studio/frontend/src/features/hub/types.tsindex ae9ddf5d4bc..73173bf6247 100644--- a/studio/frontend/src/features/hub/types.ts+++ b/studio/frontend/src/features/hub/types.ts@@ -85,6 +85,9 @@ export interface SelectedModelView {capabilities: Capability[];license: string | null;pipelineTag?: string;+ /** The backend's inferred pipeline task for an on-device row. A cached GGUF repo carries+ * this and NOT `pipelineTag`, so deciding a GGUF row's modality needs both. */+ task?: string | null;libraryName?: string;gated?: false | "auto" | "manual";private?: boolean;diff --git a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.tsindex 93c4606b9fd..1e269bfd791 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts@@ -234,12 +234,20 @@ export function allowedHiddenModelIdMatches();}+/** Backend tag for a diffusion GGUF the Images backend cannot assemble; both pickers hide+ * these rows. */+const UNSUPPORTED_DIFFUSION_TASK = "image-diffusion-unsupported";+/** Fresh Hub rows carry their authoritative task in selection metadata, while* downloaded/local rows retain their inventory task as a fallback. */export function taskForMediaPick(pipelineTag: string | null | undefined,inventoryTask: string | null | undefined,): string | null {+ // Such a GGUF still carries an ordinary text-to-image tag on the Hub. The on-device+ // verdict is the one the loader enforces, so it outranks the tag: trusting the tag routes+ // the pick at a page whose picker omits the row and whose load would be refused.+ if (inventoryTask === UNSUPPORTED_DIFFUSION_TASK) return inventoryTask;// Cache inventory commonly reports Audio GGUFs as generic text-generation;// an exact catalog task is the stronger runtime contract in that case.return pipelineTag && pipelineTag !== "text-generation"diff --git a/studio/frontend/tests/audio-picker-policy.test.ts b/studio/frontend/tests/audio-picker-policy.test.tsindex 878b10b1ba0..f95dba88627 100644--- a/studio/frontend/tests/audio-picker-policy.test.ts+++ b/studio/frontend/tests/audio-picker-policy.test.ts@@ -130,6 +130,26 @@ test("fresh Hub pipeline metadata routes media picks before stale inventory", ()assert.equal(taskForMediaPick(null, "text-to-speech"), "text-to-speech");});+test("an unbuildable diffusion GGUF keeps its on-device verdict over its Hub tag", () => {+ // gguf-org/stable-diffusion-v1-5-GGUF and friends: tagged text-to-image on the Hub,+ // image-diffusion-unsupported on device. Routing on the tag sends Run at an Images picker+ // that omits the row.+ assert.equal(+ taskForMediaPick("text-to-image", "image-diffusion-unsupported"),+ "image-diffusion-unsupported",+ );+ assert.equal(+ taskForMediaPick("image-to-image", "image-diffusion-unsupported"),+ "image-diffusion-unsupported",+ );+ assert.equal(+ taskForMediaPick(null, "image-diffusion-unsupported"),+ "image-diffusion-unsupported",+ );+ // Buildable diffusion rows are untouched.+ assert.equal(taskForMediaPick("text-to-image", "text-to-image"), "text-to-image");+});+test("generic cached GGUF metadata yields to the curated Audio task", () => {assert.equal(taskForMediaPick("text-generation", "automatic-speech-recognition"),diff --git a/studio/frontend/tests/local-path.test.ts b/studio/frontend/tests/local-path.test.tsindex 61db3a2d90f..aefaf19405e 100644--- a/studio/frontend/tests/local-path.test.ts+++ b/studio/frontend/tests/local-path.test.ts@@ -3,7 +3,10 @@import assert from "node:assert/strict";import test from "node:test";-import { looksLikeLocalPath } from "../src/features/hub/lib/local-path.ts";+import {+ looksLikeLocalPath,+ routableToMediaPage,+} from "../src/features/hub/lib/local-path.ts";test("recognizes local paths across supported operating systems", () => {for (const path of [@@ -30,3 +33,16 @@ test("does not classify Hugging Face repository identifiers as paths", () => {assert.equal(looksLikeLocalPath("HuggingFaceH4/ultrachat_200k"), false);assert.equal(looksLikeLocalPath("unsloth/Qwen3-4B"), false);});++test("an HF-cache row routes to the media pages, a filesystem row does not", () => {+ // Inventory dedup can leave a complete hf_cache LOCAL row as the only row for a repo, and+ // it carries the Hub id. Excluding it by kind sent a diffusion GGUF to the chat loader,+ // where the backend refuses it, instead of to Images or Video.+ assert.equal(routableToMediaPage("local", "hf_cache"), true);+ assert.equal(routableToMediaPage("local", "models_dir"), false);+ assert.equal(routableToMediaPage("local", "lmstudio"), false);+ assert.equal(routableToMediaPage("local", "ollama"), false);+ assert.equal(routableToMediaPage("local", null), false);+ assert.equal(routableToMediaPage("cache", null), true);+ assert.equal(routableToMediaPage("discover", null), true);+});