Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: find models already on the device before downloading, and make the first download cancellable (#7379)

Michael Hanbea471a14605
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index b18ca16975e..94096010017 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -30,6 +30,7 @@ from hub.services.models.common import (
_gguf_variant_state_summary,
_is_adapter_weight_name,
_is_checkpoint_weight_name,
+ _local_transformers_can_chat,
_is_training_artefact_name,
_is_gguf_filename,
_is_main_gguf_filename,
@@ -364,11 +365,21 @@ def _cache_inventory_fields(
active_hub_cache = active_hub_cache,
payload_snapshots = payload_snapshots,
)
+ # The directory this row loads from: the non-GGUF scan passes only
+ # *identity*, so snapshot_path alone classified nothing.
+ classify_snapshot = identity.load_snapshot or snapshot_path
capabilities = _capabilities_for_format(
model_format,
"hf_cache",
partial = partial,
requires_variant = requires_variant,
+ # Same classification the scan-folder rows get: a cached BERT or CLIP
+ # repo is chat-capable on format alone, and small enough to be tried first.
+ can_chat_override = (
+ _local_transformers_can_chat(classify_snapshot)
+ if model_format in {"safetensors", "checkpoint"} and classify_snapshot is not None
+ else None
+ ),
).model_dump()
# The loader's companion search never leaves the quants' snapshot.
if model_format == "gguf" and (
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
index f7f694c7481..150f750924c 100644
--- a/studio/backend/hub/services/models/common.py
+++ b/studio/backend/hub/services/models/common.py
@@ -118,15 +118,241 @@ def _runtime_for_format(model_format: ModelFormat) -> ModelRuntime:
return "unknown"
+# Deliberately narrow: an unfamiliar class name must not read as non-chat.
+_GENERATIVE_ARCHITECTURE_SUFFIXES = (
+ "ForCausalLM",
+ "ForConditionalGeneration",
+ "ForSeq2SeqLM",
+ "LMHeadModel",
+)
+_NON_GENERATIVE_ARCHITECTURE_SUFFIXES = (
+ "ForAudioClassification",
+ "ForCTC",
+ "ForFeatureExtraction",
+ "ForImageClassification",
+ "ForImageTextRetrieval",
+ "ForMaskedLM",
+ "ForMultipleChoice",
+ "ForNextSentencePrediction",
+ "ForObjectDetection",
+ "ForPreTraining",
+ "ForQuestionAnswering",
+ "ForRetrieval",
+ "ForRewardModel",
+ "ForSemanticSegmentation",
+ "ForSequenceClassification",
+ "ForTextEncoding",
+ "ForTokenClassification",
+ "ForVideoClassification",
+ "ForZeroShotImageClassification",
+)
+# Generative, but not of a chat reply: they match a generative suffix below yet
+# cannot answer a text turn, and they are small enough to be tried first.
+_NON_CHAT_GENERATIVE_MODEL_TYPES = frozenset(
+ {
+ "blip",
+ "blip-2",
+ "blip_2",
+ "git",
+ "instructblip",
+ "musicgen",
+ "musicgen_melody",
+ "speech-encoder-decoder",
+ "speech_to_text",
+ "speech_to_text_2",
+ "trocr",
+ "vision-encoder-decoder",
+ "whisper",
+ }
+)
+_NON_CHAT_GENERATIVE_ARCHITECTURES = frozenset(
+ {
+ "Blip2ForConditionalGeneration",
+ "BlipForConditionalGeneration",
+ "GitForCausalLM",
+ "InstructBlipForConditionalGeneration",
+ "MusicgenForConditionalGeneration",
+ "SpeechEncoderDecoderModel",
+ "Speech2TextForConditionalGeneration",
+ "VisionEncoderDecoderModel",
+ "WhisperForConditionalGeneration",
+ }
+)
+_BARE_TEXT_BACKBONE_ARCHITECTURES = frozenset(
+ {
+ "BartModel",
+ "BloomModel",
+ "FalconModel",
+ "GPT2Model",
+ "GPTJModel",
+ "GPTNeoXModel",
+ "Gemma2Model",
+ "Gemma3Model",
+ "GemmaModel",
+ "LlamaModel",
+ "MistralModel",
+ "MixtralModel",
+ "MptModel",
+ "OPTModel",
+ "Phi3Model",
+ "PhiModel",
+ "Qwen2Model",
+ "Qwen3Model",
+ "T5Model",
+ }
+)
+_ENCODER_ONLY_MODEL_TYPES = frozenset(
+ {
+ "albert",
+ "bert",
+ "camembert",
+ "chinese_clip",
+ "clip",
+ "deberta",
+ "deberta-v2",
+ "distilbert",
+ "electra",
+ "funnel",
+ "ibert",
+ "layoutlm",
+ "layoutlmv2",
+ "layoutlmv3",
+ "longformer",
+ "megatron-bert",
+ "mobilebert",
+ "modernbert",
+ "mpnet",
+ "nystromformer",
+ "rembert",
+ "roberta",
+ "roformer",
+ "siglip",
+ "siglip2",
+ "squeezebert",
+ "vision-text-dual-encoder",
+ "xlm-roberta",
+ # Vision and audio backbones: their bare ``*Model`` names carry no task
+ # suffix, so only the model type identifies them.
+ "beit",
+ "convnext",
+ "convnextv2",
+ "data2vec-audio",
+ "data2vec-vision",
+ "deit",
+ "dinov2",
+ "dpt",
+ "efficientnet",
+ "hubert",
+ "mobilevit",
+ "regnet",
+ "resnet",
+ "segformer",
+ "swin",
+ "swinv2",
+ "videomae",
+ "vit",
+ "vit_mae",
+ "vit_msn",
+ "wav2vec2",
+ "wavlm",
+ "whisper",
+ }
+)
+
+
+# Real configs are a few KB; the cap keeps a huge or hostile file out of memory.
+_MAX_LOCAL_JSON_BYTES = 1 << 20
+
+
+def _read_local_json_object(path: Path) -> dict:
+ """Config metadata, or ``{}``. Never raises: one unreadable file must not
+ fail the whole scan."""
+ try:
+ # is_file() also skips a FIFO, whose read would block the scan forever.
+ if not path.is_file() or path.stat().st_size > _MAX_LOCAL_JSON_BYTES:
+ return {}
+ data = json.loads(path.read_text(encoding = "utf-8"))
+ return data if isinstance(data, dict) else {}
+ # ValueError covers JSONDecodeError and UnicodeDecodeError; deeply nested
+ # JSON raises RecursionError, which is neither.
+ except (ValueError, OSError, RecursionError):
+ return {}
+
+
+def _local_transformers_can_chat(path: Path) -> Optional[bool]:
+ """False for a locally identifiable non-generative Transformers row.
+
+ ``None`` means inconclusive and the format capability stands, so a custom
+ architecture is never hidden. Without this, an embedding export is
+ chat-capable on file format alone, and those are small enough that chat
+ auto-load spends its whole attempt budget on them.
+ """
+ if not _safe_is_dir(path):
+ return None
+
+ # SentenceTransformers exports carry this even when the config names a
+ # broadly reusable encoder class.
+ try:
+ if (path / "modules.json").is_file():
+ return False
+ except OSError:
+ return None
+
+ config = _read_local_json_object(path / "config.json")
+ if not config:
+ return None
+
+ auto_map = config.get("auto_map")
+ if isinstance(auto_map, dict) and any(
+ key in auto_map for key in ("AutoModelForCausalLM", "AutoModelForSeq2SeqLM")
+ ):
+ return True
+
+ architectures = config.get("architectures")
+ names = (
+ [name.strip() for name in architectures if isinstance(name, str) and name.strip()]
+ if isinstance(architectures, list)
+ else []
+ )
+ model_type_raw = config.get("model_type")
+ normalized_type = model_type_raw.strip().lower() if isinstance(model_type_raw, str) else ""
+ # Before the generative suffix: Whisper and friends end in
+ # ForConditionalGeneration but cannot answer a text turn.
+ if normalized_type in _NON_CHAT_GENERATIVE_MODEL_TYPES or any(
+ name in _NON_CHAT_GENERATIVE_ARCHITECTURES for name in names
+ ):
+ return False
+ if any(name.endswith(_GENERATIVE_ARCHITECTURE_SUFFIXES) for name in names):
+ return True
+ if names and all(name.endswith(_NON_GENERATIVE_ARCHITECTURE_SUFFIXES) for name in names):
+ return False
+ # AutoModel.save_pretrained on a chat family writes the backbone name, and a
+ # backbone has no LM head. Listed explicitly, not shape-matched, so an
+ # unfamiliar FooModel still fails open.
+ if names and all(name in _BARE_TEXT_BACKBONE_ARCHITECTURES for name in names):
+ return False
+
+ # The type alone decides: requiring the name shape too kept rows chat-capable
+ # when it did not fit, e.g. google/siglip2-* omits architectures entirely and
+ # CLIPTextModelWithProjection ends in neither Model nor a known suffix.
+ # Anything generative returned True above, so no chat row reaches here.
+ if normalized_type in _ENCODER_ONLY_MODEL_TYPES:
+ return False
+ return None
+
+
def _capabilities_for_format(
model_format: ModelFormat,
source: str,
*,
partial: bool = False,
requires_variant: bool = False,
+ can_chat_override: Optional[bool] = None,
) -> LocalModelCapabilities:
is_complete = not partial
can_chat = model_format in {"gguf", "safetensors", "adapter", "checkpoint"}
+ if can_chat_override is not None:
+ can_chat = can_chat and can_chat_override
can_train = model_format in {"safetensors", "checkpoint"} and is_complete
return LocalModelCapabilities(
can_train = can_train,
@@ -466,6 +692,7 @@ def _local_model_info(
adapter_type: Optional[str] = None,
training_method: Optional[str] = None,
active_cache: Optional[bool] = None,
+ can_chat_override: Optional[bool] = None,
) -> LocalModelInfo:
load_id = (
model_id
@@ -502,6 +729,7 @@ def _local_model_info(
source,
partial = partial,
requires_variant = requires_variant,
+ can_chat_override = can_chat_override,
),
)
@@ -616,6 +844,11 @@ def _classify_local_path(
adapter_type = adapter_type if model_format == "adapter" else None,
training_method = training_method if model_format == "adapter" else None,
active_cache = active_cache,
+ can_chat_override = (
+ _local_transformers_can_chat(scan_path)
+ if model_format in {"safetensors", "checkpoint"}
+ else None
+ ),
)
)
elif not rows:
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
index a5911de10d4..7c204520bf4 100644
--- a/studio/backend/hub/services/models/local_inventory.py
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -626,6 +626,10 @@ def _promote_to_custom_source(model: LocalModelInfo) -> LocalModelInfo:
"custom",
partial = model.partial,
requires_variant = model.capabilities.requires_variant,
+ # Rebuilding from the format alone restored can_chat on rows the
+ # classifier had ruled out. The format is unchanged here, so
+ # carrying the old verdict through is idempotent.
+ can_chat_override = model.capabilities.can_chat,
),
}
)
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 5b61a67f844..054f1395284 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -4467,6 +4467,311 @@ def test_dataset_status_includes_generation(monkeypatch):
assert result.generation == 4
+def _write_local_model(
+ root: Path,
+ name: str,
+ config: dict,
+ *,
+ modules: bool = False,
+) -> Path:
+ path = root / name
+ path.mkdir(parents = True)
+ (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+ (path / "model.safetensors").write_bytes(b"\0" * 16)
+ if modules:
+ (path / "modules.json").write_text("[]", encoding = "utf-8")
+ return path
+
+
+ "config, modules, expected",
+ [
+ ({"architectures": ["LlamaForCausalLM"], "model_type": "llama"}, False, True),
+ ({"architectures": ["T5ForConditionalGeneration"], "model_type": "t5"}, False, True),
+ ({"auto_map": {"AutoModelForCausalLM": "m.C"}, "model_type": "bert"}, False, True),
+ ({"architectures": ["BertModel"], "model_type": "bert"}, False, False),
+ ({"architectures": ["BertModel"], "model_type": "bert"}, True, False),
+ ({"architectures": ["RobertaForMaskedLM"], "model_type": "roberta"}, False, False),
+ ({"architectures": ["CLIPModel"], "model_type": "clip"}, False, False),
+ # Unknown architectures must fail OPEN: never hide a real chat model.
+ ({"architectures": ["SomeCustomNet"], "model_type": "custom"}, False, None),
+ ({}, False, None),
+ ],
+)
+def test_local_transformers_chat_classification(tmp_path, config, modules, expected):
+ """A safetensors dir is chat-capable on file format alone, so an embedding
+ export looked like a chat model, and auto-load tries the smallest first."""
+ path = _write_local_model(tmp_path, "row", config, modules = modules)
+ assert model_common._local_transformers_can_chat(path) is expected
+
+
+def test_local_embedding_model_is_not_chat_capable(tmp_path):
+ """End to end through the scanner: the row is still listed, since that is
+ how the user deletes it, but can_chat is false so auto-load skips it."""
+ _write_local_model(
+ tmp_path,
+ "all-MiniLM-L6-v2",
+ {"architectures": ["BertModel"], "model_type": "bert"},
+ modules = True,
+ )
+ _write_local_model(
+ tmp_path,
+ "tiny-llama",
+ {"architectures": ["LlamaForCausalLM"], "model_type": "llama"},
+ )
+ rows = {
+ row.display_name: row
+ for path in sorted(tmp_path.iterdir())
+ for row in model_common._classify_local_path(path, "models_dir")
+ }
+ assert rows["all-MiniLM-L6-v2"].capabilities.can_chat is False
+ assert rows["tiny-llama"].capabilities.can_chat is True
+ # Training and LoRA support are unchanged: this only gates chat.
+ assert rows["all-MiniLM-L6-v2"].capabilities.can_train is True
+
+
+def test_cached_encoder_repo_is_not_chat_capable(tmp_path):
+ """Cached rows build capabilities from file format too, so a cached BERT
+ looked like a chat model to auto-load."""
+ snapshot = _write_local_model(
+ tmp_path, "snap", {"architectures": ["BertModel"], "model_type": "bert"}
+ )
+ fields = cache_inventory._cache_inventory_fields(
+ "sentence-transformers/all-MiniLM-L6-v2",
+ "safetensors",
+ identity = cache_inventory._LoadIdentity(
+ load_id = str(snapshot), active_cache = False, load_snapshot = snapshot
+ ),
+ )
+ assert fields["capabilities"]["can_chat"] is False
+
+
+def test_cached_generative_repo_stays_chat_capable(tmp_path):
+ """Control for the gate above."""
+ snapshot = _write_local_model(
+ tmp_path, "snap", {"architectures": ["LlamaForCausalLM"], "model_type": "llama"}
+ )
+ fields = cache_inventory._cache_inventory_fields(
+ "unsloth/Llama-3.2-1B-Instruct",
+ "safetensors",
+ identity = cache_inventory._LoadIdentity(
+ load_id = str(snapshot), active_cache = False, load_snapshot = snapshot
+ ),
+ )
+ assert fields["capabilities"]["can_chat"] is True
+
+
+def test_cached_row_without_a_snapshot_keeps_its_format_capability(tmp_path):
+ """Fails open: no snapshot to inspect must not hide the row."""
+ fields = cache_inventory._cache_inventory_fields(
+ "unsloth/Llama-3.2-1B-Instruct",
+ "safetensors",
+ identity = cache_inventory._LoadIdentity(
+ load_id = "unsloth/Llama-3.2-1B-Instruct",
+ active_cache = True,
+ load_snapshot = None,
+ ),
+ )
+ assert fields["capabilities"]["can_chat"] is True
+
+
+ "config",
+ [
+ {"architectures": ["WhisperForConditionalGeneration"], "model_type": "whisper"},
+ {"architectures": ["SomeCustomHead"], "model_type": "whisper"},
+ {"architectures": ["VisionEncoderDecoderModel"], "model_type": "vision-encoder-decoder"},
+ {"architectures": ["MusicgenForConditionalGeneration"], "model_type": "musicgen"},
+ ],
+)
+def test_non_chat_conditional_generation_is_not_chat_capable(tmp_path, config):
+ """These end in ForConditionalGeneration but cannot answer a text turn, and
+ are small enough that the cascade would stop there. The managed cache
+ already hides Whisper; scan folders did not."""
+ path = _write_local_model(tmp_path, "row", config)
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+ "config",
+ [
+ {"architectures": ["T5ForConditionalGeneration"], "model_type": "t5"},
+ {"architectures": ["Gemma3ForConditionalGeneration"], "model_type": "gemma3"},
+ {"architectures": ["BartForConditionalGeneration"], "model_type": "bart"},
+ ],
+)
+def test_real_conditional_generation_chat_models_are_unaffected(tmp_path, config):
+ """Guard on the list above: multimodal and seq2seq chat models must stay."""
+ path = _write_local_model(tmp_path, "row", config)
+ assert model_common._local_transformers_can_chat(path) is True
+
+
+ "config",
+ [
+ {"architectures": ["ViTModel"], "model_type": "vit"},
+ {"architectures": ["Dinov2Model"], "model_type": "dinov2"},
+ {"architectures": ["SwinModel"], "model_type": "swin"},
+ {"architectures": ["Wav2Vec2Model"], "model_type": "wav2vec2"},
+ ],
+)
+def test_bare_vision_and_audio_backbones_are_not_chat_capable(tmp_path, config):
+ """Their class names carry no task suffix, so only the model type gives them
+ away."""
+ path = _write_local_model(tmp_path, "row", config)
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+def test_unreadable_config_never_fails_the_scan(tmp_path):
+ """One bad config.json must classify as unknown, not take the inventory
+ request down. Deep nesting raises RecursionError, which is neither
+ JSONDecodeError nor OSError."""
+ cases = {
+ "deep": "[" * 60000 + "]" * 60000,
+ "truncated": '{"architectures": ["Llam',
+ "not_an_object": '["a", "b"]',
+ "empty": "",
+ }
+ for name, body in cases.items():
+ path = tmp_path / name
+ path.mkdir()
+ (path / "config.json").write_text(body, encoding = "utf-8")
+ assert model_common._local_transformers_can_chat(path) is None, name
+
+
+def test_oversized_config_is_skipped_rather_than_read(tmp_path):
+ path = tmp_path / "huge"
+ path.mkdir()
+ (path / "config.json").write_text(
+ '{"architectures": ["LlamaForCausalLM"], "pad": "'
+ + "a" * (model_common._MAX_LOCAL_JSON_BYTES + 1)
+ + '"}',
+ encoding = "utf-8",
+ )
+ assert model_common._local_transformers_can_chat(path) is None
+
+
+def test_a_fifo_named_config_json_does_not_block_the_scan(tmp_path):
+ """read_text() on a FIFO with no writer blocks forever, hanging the scan."""
+ os = pytest.importorskip("os")
+ if not hasattr(os, "mkfifo"):
+ pytest.skip("no mkfifo on this platform")
+ path = tmp_path / "fifo"
+ path.mkdir()
+ os.mkfifo(path / "config.json")
+ assert model_common._local_transformers_can_chat(path) is None
+
+
+ "model_type",
+ ["siglip", "clip", "bert", "vit", "wav2vec2"],
+)
+def test_an_encoder_without_architectures_is_still_not_chat_capable(tmp_path, model_type):
+ """google/siglip2-* ships config.json with no architectures key, and the
+ encoder-only branch used to require one, so those rows stayed chat-capable
+ and sorted ahead of a real chat model."""
+ path = tmp_path / model_type
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps({"model_type": model_type}), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+def test_a_causal_lm_without_architectures_still_fails_open(tmp_path):
+ """Control: keyed on the encoder-only type list, so an unknown type with no
+ architectures stays inconclusive."""
+ path = tmp_path / "custom"
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps({"model_type": "some_new_llm"}), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is None
+
+
+ "config",
+ [
+ {"model_type": "blip", "architectures": ["BlipForConditionalGeneration"]},
+ {"model_type": "blip-2", "architectures": ["Blip2ForConditionalGeneration"]},
+ {"model_type": "instructblip", "architectures": ["InstructBlipForConditionalGeneration"]},
+ {"model_type": "git", "architectures": ["GitForCausalLM"]},
+ ],
+)
+def test_an_image_captioner_is_not_chat_capable(tmp_path, config):
+ """These generate text, but only about an image, so a plain text turn fails,
+ and the smallest-first cascade would load one and stop looking."""
+ path = tmp_path / "captioner"
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+ "architecture",
+ ["CLIPTextModelWithProjection", "CLIPVisionModelWithProjection", "CLIPTextModel"],
+)
+def test_a_projection_head_encoder_is_not_chat_capable(tmp_path, architecture):
+ """The encoder-only branch also required the name to end in Model, so a
+ projection variant fell through and kept its format capability."""
+ path = tmp_path / "proj"
+ path.mkdir()
+ (path / "config.json").write_text(
+ json.dumps({"model_type": "clip", "architectures": [architecture]}), encoding = "utf-8"
+ )
+
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+ "config",
+ [
+ {"model_type": "bert", "architectures": ["BertLMHeadModel"]},
+ {"model_type": "t5", "architectures": ["T5ForConditionalGeneration"]},
+ {"model_type": "qwen3", "architectures": ["Qwen3ForCausalLM"]},
+ ],
+)
+def test_a_generative_head_still_wins_over_the_encoder_type(tmp_path, config):
+ """Control for both gates above: a generative architecture is accepted
+ before the type list is consulted."""
+ path = tmp_path / "gen"
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is True
+
+
+ "config",
+ [
+ {"model_type": "llama", "architectures": ["LlamaModel"]},
+ {"model_type": "gpt2", "architectures": ["GPT2Model"]},
+ {"model_type": "t5", "architectures": ["T5Model"]},
+ {"model_type": "mistral", "architectures": ["MistralModel"]},
+ ],
+)
+def test_a_bare_text_backbone_is_not_chat_capable(tmp_path, config):
+ """AutoModel.save_pretrained writes the backbone name, and a backbone has no
+ LM head, so the cascade would stop on one before a usable chat model."""
+ path = tmp_path / "backbone"
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+def test_an_unfamiliar_backbone_still_fails_open(tmp_path):
+ """The list is explicit, not shape-matched, so a custom FooModel keeps its
+ format capability."""
+ path = tmp_path / "custom"
+ path.mkdir()
+ (path / "config.json").write_text(
+ json.dumps({"model_type": "brand_new_arch", "architectures": ["FooModel"]}),
+ encoding = "utf-8",
+ )
+
+ assert model_common._local_transformers_can_chat(path) is None
+
+
@pytest.mark.parametrize("layout", ["flat", "publisher_child"])
def test_lmstudio_scan_matches_gguf_suffix_case_insensitively(tmp_path, layout):
"""The custom and models-dir scans lower() the suffix; these two did not, so a
@@ -4481,3 +4786,27 @@ def test_lmstudio_scan_matches_gguf_suffix_case_insensitively(tmp_path, layout):
found = {Path(row.path).name for row in local_inventory._scan_lmstudio_dir(lm_dir)}
assert found == {"lower.gguf", "UPPER.GGUF", "Mixed.GguF"}
+
+
+ ("config", "expected"),
+ [
+ ({"model_type": "bert", "architectures": ["BertModel"]}, False),
+ ({"model_type": "clip", "architectures": ["CLIPModel"]}, False),
+ ({"model_type": "llama", "architectures": ["LlamaForCausalLM"]}, True),
+ ],
+)
+def test_custom_promotion_keeps_the_classifier_verdict(tmp_path, config, expected):
+ """Promotion rebuilt capabilities from the format alone, which restored
+ can_chat on rows the classifier had ruled out."""
+ model_dir = tmp_path / "scan" / "model"
+ model_dir.mkdir(parents = True)
+ (model_dir / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+ (model_dir / "model.safetensors").write_bytes(b"x" * 1024)
+
+ rows = local_inventory._scan_custom_folder(tmp_path / "scan")
+ assert rows, "the scan produced no row"
+ for row in rows:
+ promoted = local_inventory._promote_to_custom_source(row)
+ assert promoted.source == "custom"
+ assert promoted.capabilities.can_chat is expected
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 6796ae47b6b..54e0b58025a 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -4,7 +4,22 @@
import { mlxRuntimeStateFrom } from "../lib/mlx-runtime-state";
import { getAuthToken } from "@/features/auth";
import { prepareHfTokenForUse } from "@/features/hf-auth";
+import { DOWNLOAD_KIND } from "@/features/hub/download-manager/constants";
+import {
+ downloadManager,
+ jobKeyOf,
+ selectActiveJob,
+ subscribeJobListeners,
+ useDownloadManagerStore,
+} from "@/features/hub/download-manager/download-manager-controller";
+import {
+ type LocalModelInfo,
+ listLocalModels,
+} from "@/features/hub/inventory/api";
+import { isHiddenModelId } from "@/features/hub/lib/hidden-models";
import { resolveInitialConfig } from "@/features/model-picker";
+import { isMlxId } from "@/features/model-picker/components/model-selector/recommended-fit";
+import { usePlatformStore } from "@/config/env";
import { projectHasSources } from "@/features/rag/api/rag-api";
import { apiUrl } from "@/lib/api-base";
import { parseParamCountB } from "@/lib/model-size";
@@ -117,6 +132,7 @@ import {
lastReasoningGroupTextLength,
} from "../utils/reasoning-duration";
import { resolveLoadMaxSeqLength } from "../presets/preset-policy";
+import type { CachedGgufRepo, CachedModelRepo } from "./chat-api";
import {
budgetImpliesTruncation,
CONTINUE_INSTRUCTION,
@@ -1641,20 +1657,14 @@ type AutoLoadCandidate = {
successLabel: string;
};
+// Same case rules as autoLoadSourceKey: folding a POSIX target would let a
+// failed /models/Foo mark a distinct /models/foo as already tried.
function autoLoadCandidateKey(
kind: LastLocalModelKind,
id: string,
ggufVariant?: string | null,
): string {
- return `${kind}:${id.toLowerCase()}:${(ggufVariant ?? "").toLowerCase()}`;
-}
-
-function findCachedRepo<T extends { repo_id: string }>(
- repos: T[],
- id: string,
-): T | undefined {
- const normalized = id.toLowerCase();
- return repos.find((repo) => repo.repo_id.toLowerCase() === normalized);
+ return `${kind}:${normalizeTarget(id)}:${(ggufVariant ?? "").toLowerCase()}`;
}
function hasBigEndianGgufMarker(filename: string, quant?: string | null): boolean {
@@ -1868,12 +1878,442 @@ function applyAutoLoadRuntimeState(
}
}
-/** Whether a cache row is chattable. Both fields are optional so an older backend keeps trying. */
+/** Whether a cache row is chattable. Every field is optional so an older backend keeps trying. */
function isChattableCachedRepo(repo: {
partial?: boolean;
+ task?: string | null;
+ model_format?: string | null;
capabilities?: { can_chat?: boolean } | null;
}): boolean {
- return repo.partial !== true && repo.capabilities?.can_chat !== false;
+ return (
+ repo.partial !== true &&
+ repo.capabilities?.can_chat !== false &&
+ // Same rule isAutoLoadableLocalRow applies locally: an adapter has no base
+ // weights, so /load fetches the base from the Hub when it is not cached,
+ // and can_chat is reported true for the format on file layout alone.
+ repo.model_format !== "adapter" &&
+ // Cached diffusion repos report can_chat true on file format alone.
+ !IMAGE_OR_VIDEO_TASKS.has(repo.task ?? "")
+ );
+}
+
+// Chat models are tagged "text-generation" or left null, so this is a list
+// rather than a "has a task" test. The picker routes these rows to the
+// Images/Video page on click; a background load has no routing step, so
+// without this the chat turn goes to a diffusion runtime.
+const IMAGE_OR_VIDEO_TASKS: ReadonlySet<string> = new Set([
+ "text-to-image",
+ "text-to-video",
+ "image-diffusion-unsupported",
+]);
+
+// Scan folders the picker exposes. hf_cache is already in the cached lists,
+// and ollama links are not loadable.
+const AUTO_LOAD_LOCAL_SOURCES: ReadonlySet<string> = new Set([
+ "models_dir",
+ "lmstudio",
+ "custom",
+]);
+
+/**
+ * Picker policy for a background pick. Adapters and checkpoints are excluded:
+ * an adapter resolves its base model (a Hub fetch when the base is uncached),
+ * and a scan-folder checkpoint is a pickle with no Hub security scan.
+ */
+function isAutoLoadableLocalRow(
+ row: LocalModelInfo,
+ // Set when a cached lookup failed: the excluded hf_cache rows are then the
+ // only evidence of that cache, and dropping them left a device whose one
+ // model lives there with nothing to load.
+ admitHfCache = false,
+): boolean {
+ return (
+ (AUTO_LOAD_LOCAL_SOURCES.has(row.source) ||
+ (admitHfCache && row.source === "hf_cache")) &&
+ // Absent capabilities means unclassified, not "not chat": requiring true
+ // skipped the row and fell through to downloading the default.
+ row.capabilities?.can_chat !== false &&
+ row.partial !== true &&
+ // An allowlist, because an exclusion is only as good as the classification:
+ // the backend sends "unknown" when it cannot tell a format apart and an
+ // older one omits the field, so both slipped past a `!== "checkpoint"` test
+ // and made a pickle eligible. A checkpoint directory looks like a
+ // safetensors one, so this has to fail closed; GGUF is still recognised by
+ // suffix, so an unclassified .gguf row keeps loading.
+ (isGgufLocalRow(row) || row.model_format === "safetensors") &&
+ !IMAGE_OR_VIDEO_TASKS.has(row.task ?? "") &&
+ runsOnThisPlatform(row) &&
+ !isHiddenModelId(row.model_id, row.id, row.path)
+ );
+}
+
+// model_format is optional, so an older backend omits it on a direct .gguf row.
+// Reading only the field made such a row a Transformers source, which sends the
+// safetensors context length to /load and remembers the wrong kind.
+function isGgufLocalRow(row: LocalModelInfo): boolean {
+ return row.model_format === "gguf" || row.path.toLowerCase().endsWith(".gguf");
+}
+
+/** Chat-only installs run GGUF anywhere and MLX on a Mac; the picker hides
+ * every other local format there. */
+function runsOnThisPlatform(row: LocalModelInfo): boolean {
+ const platform = usePlatformStore.getState();
+ // Until the backend reports it, chatOnly is a BROWSER guess: a Mac browser on
+ // a remote Linux Studio would hide every local safetensors model and fetch
+ // the default. Failing open is safe: validation refuses an ineligible pick.
+ if (!platform.fetched || !platform.isChatOnly()) return true;
+ if (isGgufLocalRow(row)) {
+ return true;
+ }
+ return (
+ platform.deviceType === "mac" &&
+ (isMlxId(row.id) ||
+ isMlxId(row.display_name ?? "") ||
+ isMlxId(row.model_id ?? ""))
+ );
+}
+
+/** The picker hides cached non-GGUF rows outright on a chat-only install
+ * (visibleCachedModelRows). Same wait-for-the-server rule as above. */
+function cachedModelsRunOnThisPlatform(): boolean {
+ const platform = usePlatformStore.getState();
+ return !platform.fetched || !platform.isChatOnly();
+}
+
+/** One loadable thing on this device, from any inventory. `listVariants` is
+ * lazy, so only the repos the cascade reaches are scanned. */
+type AutoLoadSource = {
+ kind: LastLocalModelKind;
+ /** Catalog id: per-model settings, toasts, remembered-model matching. */
+ id: string;
+ /** Sent to /api/inference/load as model_path. */
+ loadId: string;
+ sizeBytes: number;
+ maxSeqLength: number;
+ /** null when the target is one file already (a local .gguf) or safetensors. */
+ listVariants: (() => Promise<GgufVariantDetail[]>) | null;
+};
+
+// Case-sensitive targets keep their case (Linux distinguishes /models/Foo from
+// /models/foo; \\wsl$\ reaches the same ext4). Repo ids and Windows paths fold,
+// separators included, so C:\a\m.gguf and C:/a/m.gguf are one key. NFC first:
+// macOS returns decomposed names for the same file.
+function normalizeTarget(value: string): string {
+ const target = value.trim().normalize("NFC");
+ if (/^[A-Za-z]:[\\/]/.test(target) || target.startsWith("\\\\")) {
+ const slashed = target.replace(/\\/g, "/");
+ return /^\/\/wsl[$.]/i.test(slashed) ? slashed : slashed.toLowerCase();
+ }
+ return /^[/~]/.test(target) ? target : target.toLowerCase();
+}
+
+// The load target alone, not the kind: a repo holding both GGUF and safetensors
+// yields a row in each list, but the backend resolves one target to one model,
+// so keeping both would spend a second attempt on the same files.
+function autoLoadSourceKey(source: AutoLoadSource): string {
+ return normalizeTarget(source.loadId);
+}
+
+function buildAutoLoadSources(
+ ggufRepos: CachedGgufRepo[],
+ modelRepos: CachedModelRepo[],
+ localRows: LocalModelInfo[],
+ safetensorsMaxSeqLength: number,
+ // Already timeout-bounded, but a stopped send should not wait one out.
+ signal?: AbortSignal,
+): AutoLoadSource[] {
+ const sources: AutoLoadSource[] = [];
+ for (const repo of ggufRepos) {
+ sources.push({
+ kind: "gguf",
+ id: repo.repo_id,
+ loadId: repo.load_id || repo.repo_id,
+ sizeBytes: repo.size_bytes,
+ maxSeqLength: 0,
+ listVariants: () =>
+ listGgufVariants(repo.repo_id, undefined, {
+ preferLocalCache: true,
+ localPath: repo.cache_path,
+ signal,
+ }).then((response) => response.variants),
+ });
+ }
+ for (const repo of modelRepos) {
+ sources.push({
+ kind: "model",
+ id: repo.repo_id,
+ loadId: repo.load_id || repo.repo_id,
+ sizeBytes: repo.size_bytes,
+ maxSeqLength: safetensorsMaxSeqLength,
+ listVariants: null,
+ });
+ }
+ for (const row of localRows) {
+ const isGguf = isGgufLocalRow(row);
+ // A quant folder needs one picked; a .gguf path is already the file.
+ const needsVariant = isGguf && row.capabilities?.requires_variant === true;
+ sources.push({
+ kind: isGguf ? "gguf" : "model",
+ id: row.id,
+ loadId: row.load_id || row.id,
+ sizeBytes: row.size_bytes ?? 0,
+ maxSeqLength: isGguf ? 0 : safetensorsMaxSeqLength,
+ listVariants: needsVariant
+ ? () =>
+ listGgufVariants(row.path, undefined, {
+ preferLocalCache: true,
+ localPath: row.path,
+ signal,
+ }).then((response) => response.variants)
+ : null,
+ });
+ }
+ return sources;
+}
+
+function isRememberedSource(
+ source: AutoLoadSource,
+ remembered: { id: string; kind: LastLocalModelKind },
+): boolean {
+ if (source.kind !== remembered.kind) return false;
+ // Same case rules as the dedupe key: folding a POSIX path would mark two
+ // models differing only by case as both being the remembered one.
+ const target = normalizeTarget(remembered.id);
+ return (
+ normalizeTarget(source.id) === target ||
+ normalizeTarget(source.loadId) === target
+ );
+}
+
+/** Last used first, then GGUF before safetensors, then smallest first. */
+function orderAutoLoadSources(
+ sources: AutoLoadSource[],
+ remembered: { id: string; kind: LastLocalModelKind } | null,
+): AutoLoadSource[] {
+ const rank = (source: AutoLoadSource): number => {
+ if (remembered && isRememberedSource(source, remembered)) return 0;
+ return source.kind === "gguf" ? 1 : 2;
+ };
+ // Unknown sizes sort last so a sizeless row cannot shadow a real one.
+ const size = (source: AutoLoadSource): number =>
+ source.sizeBytes > 0 ? source.sizeBytes : Number.MAX_SAFE_INTEGER;
+ // Same-target twins are kept, just ordered behind the preferred row: dropping
+ // them here lost a loadable safetensors row whenever its GGUF twin resolved
+ // no quant, so the cascade skips a twin at run time instead.
+ return [...sources].sort((a, b) => rank(a) - rank(b) || size(a) - size(b));
+}
+
+/** The candidate to attempt, resolving a GGUF quant when one is needed:
+ * remembered quant first, then smallest, skipping quants already tried so one
+ * bad file cannot sink a whole repo. null when nothing here is loadable. */
+async function resolveAutoLoadCandidate(
+ source: AutoLoadSource,
+ rememberedVariant: string | null,
+ isSkipped: (candidate: AutoLoadCandidate) => boolean,
+): Promise<AutoLoadCandidate | null> {
+ const build = (ggufVariant: string | null): AutoLoadCandidate => ({
+ id: source.id,
+ loadId: source.loadId,
+ kind: source.kind,
+ ggufVariant,
+ maxSeqLength: source.maxSeqLength,
+ successLabel: ggufVariant
+ ? `Loaded ${source.id} (${ggufVariant})`
+ : `Loaded ${source.id}`,
+ });
+ if (!source.listVariants) {
+ const candidate = build(null);
+ return isSkipped(candidate) ? null : candidate;
+ }
+ const downloaded = (await source.listVariants())
+ .filter(
+ (variant) =>
+ variant.downloaded &&
+ variant.partial !== true &&
+ isAutoLoadableGgufVariant(variant),
+ )
+ .sort((a, b) => a.size_bytes - b.size_bytes);
+ const wanted = rememberedVariant?.trim().toLowerCase();
+ const ordered = wanted
+ ? [
+ ...downloaded.filter((v) => v.quant?.toLowerCase() === wanted),
+ ...downloaded.filter((v) => v.quant?.toLowerCase() !== wanted),
+ ]
+ : downloaded;
+ for (const variant of ordered) {
+ const candidate = build(variant.quant);
+ if (!isSkipped(candidate)) return candidate;
+ }
+ return null;
+}
+
+// Fetched only when the device genuinely has nothing on it.
+const DEFAULT_CHAT_MODEL_REPO = "unsloth/gemma-4-E2B-it-GGUF";
+const DEFAULT_CHAT_MODEL_VARIANT = "UD-Q4_K_XL";
+const DEFAULT_CHAT_MODEL_LABEL = "Gemma 4 E2B";
+
+function formatDownloadBytes(bytes: number): string {
+ if (!(bytes > 0)) return "";
+ const gb = bytes / 1024 ** 3;
+ return gb >= 1
+ ? `${gb.toFixed(1)} GB`
+ : `${Math.max(1, Math.round(bytes / 1024 ** 2))} MB`;
+}
+
+/** Fetch the default through the Hub download manager rather than letting
+ * /api/inference/load pull it inline: the manager gives it a panel entry, live
+ * progress, and a working Cancel. "ready" means the bytes are on disk. */
+async function ensureDefaultModelDownloaded(
+ hfToken: string | null,
+ abortSignal: AbortSignal | undefined,
+ setToast: (title: string, description: string, cancel?: () => void) => void,
+): Promise<"ready" | "cancelled" | "failed"> {
+ const variantKey = DEFAULT_CHAT_MODEL_VARIANT.toLowerCase();
+ let expectedBytes = 0;
+ try {
+ const listing = await listGgufVariants(DEFAULT_CHAT_MODEL_REPO, undefined, {
+ signal: abortSignal,
+ });
+ const variant = listing.variants.find(
+ (entry) => entry.quant?.toLowerCase() === variantKey,
+ );
+ // Pulled by an earlier run: nothing to download.
+ if (variant?.downloaded && variant.partial !== true) return "ready";
+ expectedBytes = variant?.download_size_bytes || variant?.size_bytes || 0;
+ } catch {
+ // Sizing is cosmetic; the manager learns the real total from the server.
+ }
+ abortSignal?.throwIfAborted();
+
+ // startJob sends the stored token raw, with none of the recovery validateModel
+ // and loadModel get, so an expired one would fail the download of a public
+ // repo the lookup above just read anonymously. After the on-disk check, so
+ // nothing prompts when there is nothing to download.
+ const prepared = await prepareHfTokenForUse(hfToken);
+ abortSignal?.throwIfAborted();
+ if (!prepared.proceed) return "cancelled";
+
+ const request = {
+ kind: DOWNLOAD_KIND.MODEL,
+ repoId: DEFAULT_CHAT_MODEL_REPO,
+ variant: DEFAULT_CHAT_MODEL_VARIANT,
+ expectedBytes,
+ };
+ const jobKey = jobKeyOf(request.kind, request.repoId, request.variant);
+ // requestStart runs transport preflights before the job exists, and cancel()
+ // no-ops on a missing key, so remember the click and replay it once the job
+ // appears or the first Cancel is silently swallowed.
+ let cancelRequested = false;
+ let cancelInFlight = false;
+ let cancelEverIssued = false;
+ // Cancelling patches the job and wakes the subscription below, so this must
+ // not re-enter while a request is outstanding. The latch clears when the
+ // request settles, since a failed cancel leaves the job running for a retry.
+ const issueCancel = (): boolean => {
+ const active = selectActiveJob(
+ useDownloadManagerStore.getState(),
+ request.kind,
+ request.repoId,
+ request.variant,
+ );
+ if (!active) return false;
+ if (cancelInFlight || active.state === "cancelling") return true;
+ cancelInFlight = true;
+ cancelEverIssued = true;
+ void downloadManager.cancel(active.key).finally(() => {
+ cancelInFlight = false;
+ });
+ return true;
+ };
+ const cancelDownload = (): void => {
+ cancelRequested = true;
+ issueCancel();
+ };
+ const totalLabel = formatDownloadBytes(expectedBytes);
+ const description =
+ `Unsloth couldn’t find an existing model. Unsloth is now getting ` +
+ `${DEFAULT_CHAT_MODEL_LABEL} ready for use. You can stop the download or ` +
+ `manage models later in the 'Model hub'`;
+ setToast(
+ `Getting ${DEFAULT_CHAT_MODEL_LABEL} ready`,
+ description,
+ cancelDownload,
+ );
+
+ const isOurVariant = (variant: string | null): boolean =>
+ (variant ?? "").toLowerCase() === variantKey;
+
+ return await new Promise<"ready" | "cancelled" | "failed">((resolve) => {
+ let settled = false;
+ const cleanups: Array<() => void> = [];
+ const finish = (outcome: "ready" | "cancelled" | "failed"): void => {
+ if (settled) return;
+ settled = true;
+ for (const cleanup of cleanups) cleanup();
+ resolve(outcome);
+ };
+
+ // Before the start request, so a fast completion cannot be missed.
+ cleanups.push(
+ subscribeJobListeners(request.kind, request.repoId, {
+ // A cancel can fail and the transfer finish anyway; the user asked for
+ // it to stop, so the bytes are not handed to a load.
+ onComplete: (variant) =>
+ isOurVariant(variant) &&
+ finish(cancelRequested ? "cancelled" : "ready"),
+ onCancelled: (variant) => isOurVariant(variant) && finish("cancelled"),
+ onError: (variant) => isOurVariant(variant) && finish("failed"),
+ }),
+ );
+ // Live progress in the title; the panel shows the same job with its bar.
+ cleanups.push(
+ useDownloadManagerStore.subscribe((state) => {
+ const job = state.jobs[jobKey];
+ if (!job) return;
+ // Cancelled during the preflights: stop it as soon as it exists. The
+ // deferred first attempt only; a retry comes from another click, not
+ // from every store tick.
+ if (cancelRequested) {
+ if (!cancelEverIssued) issueCancel();
+ return;
+ }
+ if (job.state === "cancelling") return;
+ const done = formatDownloadBytes(job.downloadedBytes);
+ const total = formatDownloadBytes(job.expectedBytes) || totalLabel;
+ if (!done || !total) return;
+ setToast(
+ `Getting ${DEFAULT_CHAT_MODEL_LABEL} ready (${done} of ${total})`,
+ description,
+ cancelDownload,
+ );
+ }),
+ );
+ // Stopping the send stops the wait, not the transfer: it keeps running and
+ // stays cancellable in the panel.
+ if (abortSignal) {
+ const onAbort = () => finish("cancelled");
+ abortSignal.addEventListener("abort", onAbort, { once: true });
+ cleanups.push(() => abortSignal.removeEventListener("abort", onAbort));
+ }
+
+ void downloadManager.requestStart(request).then(
+ (outcome) => {
+ if (outcome === "started") {
+ // Cancelled while the start was still in flight.
+ if (cancelRequested && !issueCancel()) finish("cancelled");
+ return;
+ }
+ if (cancelRequested) {
+ finish("cancelled");
+ return;
+ }
+ // "conflict" and "busy" need the Hub download card; "error" already
+ // toasted.
+ finish("failed");
+ },
+ () => finish("failed"),
+ );
+ });
}
async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
@@ -1908,12 +2348,19 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
autoLoadToastDismissed = true;
},
});
- const updateAutoLoadToast = (message: string, description: string): void => {
+ const updateAutoLoadToast = (
+ message: string,
+ description: string,
+ onCancel?: () => void,
+ ): void => {
if (autoLoadToastDismissed) return;
toast.message(message, {
id: toastId,
description,
duration: Number.POSITIVE_INFINITY,
+ action: onCancel
+ ? { label: "Cancel", onClick: () => onCancel() }
+ : undefined,
});
};
const showAutoLoadSuccess = (message: string): void => {
@@ -2154,7 +2601,13 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
}))
) {
skippedAutoLoadCandidates.add(
- autoLoadCandidateKey(candidate.kind, candidate.id, candidate.ggufVariant),
+ autoLoadCandidateKey(
+ candidate.kind,
+ // A cached repo and a local row can alias the same files, so
+ // blocking one must block the other.
+ candidate.loadId ?? candidate.id,
+ candidate.ggufVariant,
+ ),
);
return false;
}
@@ -2337,164 +2790,111 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
return true;
}
try {
- const [allGgufRepos, allModelRepos] = await Promise.all([
- listCachedGguf().catch(() => []),
- listCachedModels().catch(() => []),
+ // Fail closed: these three lists are the only evidence of what is on the
+ // device, and `.catch(() => [])` turned one flaky request into "the user
+ // has nothing", downloading a model over a loadable local one. Both cached
+ // calls take the run signal because they are raw fetches with no timeout of
+ // their own; listLocalModels has its own 30s bound.
+ const inventory = await Promise.allSettled([
+ listCachedGguf(options?.abortSignal),
+ listCachedModels(hfToken, options?.abortSignal),
+ listLocalModels(),
]);
options?.abortSignal?.throwIfAborted();
- // Filtered once, so the last-used lookup sees the same set as the sweeps.
- const ggufRepos = allGgufRepos.filter(isChattableCachedRepo);
- const modelRepos = allModelRepos.filter(isChattableCachedRepo);
-
- if (lastLoaded) {
- if (lastLoaded.kind === "gguf") {
- const repo = findCachedRepo(ggufRepos, lastLoaded.id);
- if (repo && lastLoaded.ggufVariant) {
- try {
- const variants = await listGgufVariants(repo.repo_id, undefined, {
- preferLocalCache: true,
- localPath: repo.cache_path,
- });
- const variant = variants.variants.find(
- (entry) =>
- entry.downloaded &&
- entry.quant?.toLowerCase() ===
- lastLoaded.ggufVariant?.toLowerCase() &&
- isAutoLoadableGgufVariant(entry),
- );
- if (variant) {
- updateAutoLoadToast(
- "Loading last used model…",
- `${repo.repo_id} (${variant.quant})`,
- );
- if (
- await loadAutoLoadCandidate({
- id: repo.repo_id,
- loadId: repo.load_id,
- kind: "gguf",
- ggufVariant: variant.quant,
- maxSeqLength: 0,
- successLabel: `Loaded ${repo.repo_id} (${variant.quant})`,
- })
- ) {
- return { loaded: true, blockedByTrustRemoteCode: false };
- }
- }
- } catch {
- options?.abortSignal?.throwIfAborted();
- hadNonTrustFailure = true;
- skippedAutoLoadCandidates.add(
- autoLoadCandidateKey("gguf", repo.repo_id, lastLoaded.ggufVariant),
- );
- }
- }
- } else {
- const repo = findCachedRepo(modelRepos, lastLoaded.id);
- if (repo) {
+ // Settled, not all: a rejection is one unknown source, not an empty device.
+ // Failing the whole batch threw away the lists that did arrive, so a broken
+ // local scan skipped a loadable cached model. Keep what came back and let
+ // the gap block only the default download below.
+ const [ggufSettled, modelsSettled, localSettled] = inventory;
+ const allGgufRepos =
+ ggufSettled.status === "fulfilled" ? ggufSettled.value : [];
+ const allModelRepos =
+ modelsSettled.status === "fulfilled" ? modelsSettled.value : [];
+ const localRows =
+ localSettled.status === "fulfilled" ? localSettled.value.models : [];
+ const inventoryIncomplete = inventory.some((r) => r.status === "rejected");
+ // Only the two managed-cache lookups: /api/hub/local also reports hf_cache
+ // rows, so when either of these failed that response covers the gap.
+ const cachedInventoryFailed =
+ ggufSettled.status === "rejected" || modelsSettled.status === "rejected";
+ if (inventoryIncomplete) hadNonTrustFailure = true;
+
+ // Managed cache plus everything the picker indexes on disk. Reading only
+ // the cache lists is what made a local model invisible here.
+ const sources = orderAutoLoadSources(
+ buildAutoLoadSources(
+ allGgufRepos.filter(isChattableCachedRepo),
+ cachedModelsRunOnThisPlatform()
+ ? allModelRepos.filter(isChattableCachedRepo)
+ : [],
+ localRows.filter((row) => isAutoLoadableLocalRow(row, cachedInventoryFailed)),
+ store.params.maxSeqLength,
+ options?.abortSignal,
+ ),
+ lastLoaded,
+ );
+
+ // One load target can appear in more than one list. Once a row for it has
+ // produced a candidate its twin is the same files and must not spend a
+ // second attempt, so a twin is reached only if the preferred row resolved
+ // nothing at all.
+ const candidateResolvedFor = new Set<string>();
+ for (const source of sources) {
+ if (autoLoadCancelled || loadAttempts >= MAX_AUTO_LOAD_ATTEMPTS) break;
+ const sourceKey = autoLoadSourceKey(source);
+ if (candidateResolvedFor.has(sourceKey)) continue;
+ const isRemembered = lastLoaded
+ ? isRememberedSource(source, lastLoaded)
+ : false;
+ const isTried = (entry: AutoLoadCandidate): boolean =>
+ skippedAutoLoadCandidates.has(
+ autoLoadCandidateKey(
+ entry.kind,
+ entry.loadId ?? entry.id,
+ entry.ggufVariant,
+ ),
+ );
+ try {
+ // A repo can hold several downloaded quants: each failure marks that
+ // quant tried and comes back for the next, so one corrupt file does not
+ // cost the whole repo. The attempt cap bounds the loop.
+ while (!autoLoadCancelled && loadAttempts < MAX_AUTO_LOAD_ATTEMPTS) {
+ const candidate = await resolveAutoLoadCandidate(
+ source,
+ isRemembered ? lastLoaded?.ggufVariant ?? null : null,
+ isTried,
+ );
+ options?.abortSignal?.throwIfAborted();
+ if (!candidate) break;
+ candidateResolvedFor.add(sourceKey);
+ updateAutoLoadToast(
+ isRemembered ? "Loading last used model…" : "Loading a model…",
+ candidate.ggufVariant
+ ? `${candidate.id} (${candidate.ggufVariant})`
+ : candidate.id,
+ );
try {
- updateAutoLoadToast("Loading last used model…", repo.repo_id);
- if (
- await loadAutoLoadCandidate({
- id: repo.repo_id,
- loadId: repo.load_id,
- kind: "model",
- ggufVariant: null,
- maxSeqLength: store.params.maxSeqLength,
- successLabel: `Loaded ${repo.repo_id}`,
- })
- ) {
+ if (await loadAutoLoadCandidate(candidate)) {
return { loaded: true, blockedByTrustRemoteCode: false };
}
} catch {
options?.abortSignal?.throwIfAborted();
hadNonTrustFailure = true;
+ // loadAutoLoadCandidate records a refusal but not a rejection, so
+ // mark it here or the next pass resolves the same quant forever.
skippedAutoLoadCandidates.add(
- autoLoadCandidateKey("model", repo.repo_id),
+ autoLoadCandidateKey(
+ candidate.kind,
+ candidate.loadId ?? candidate.id,
+ candidate.ggufVariant,
+ ),
);
}
}
- }
- updateAutoLoadToast(
- "Loading a model…",
- "Auto-selecting the smallest downloaded model.",
- );
- }
-
- // GGUF first: smallest-total-size repo, then its smallest variant.
- if (ggufRepos.length > 0) {
- const sorted = [...ggufRepos].sort((a, b) => a.size_bytes - b.size_bytes);
- for (const repo of sorted) {
- if (loadAttempts >= MAX_AUTO_LOAD_ATTEMPTS) break;
- try {
- const variants = await listGgufVariants(repo.repo_id, undefined, {
- preferLocalCache: true,
- localPath: repo.cache_path,
- });
- const downloaded = variants.variants
- .filter((v) => v.downloaded && isAutoLoadableGgufVariant(v))
- .sort((a, b) => a.size_bytes - b.size_bytes);
- if (downloaded.length > 0) {
- const variant = downloaded[0];
- if (
- skippedAutoLoadCandidates.has(
- autoLoadCandidateKey("gguf", repo.repo_id, variant.quant),
- )
- ) {
- continue;
- }
- if (
- await loadAutoLoadCandidate({
- id: repo.repo_id,
- loadId: repo.load_id,
- kind: "gguf",
- ggufVariant: variant.quant,
- maxSeqLength: 0,
- successLabel: `Loaded ${repo.repo_id} (${variant.quant})`,
- })
- ) {
- return { loaded: true, blockedByTrustRemoteCode: false };
- }
- }
- } catch {
- options?.abortSignal?.throwIfAborted();
- hadNonTrustFailure = true;
- continue;
- }
- }
- }
-
- // Fall back to safetensors models.
- if (modelRepos.length > 0) {
- const sorted = [...modelRepos].sort(
- (a, b) => a.size_bytes - b.size_bytes,
- );
- for (const repo of sorted) {
- if (loadAttempts >= MAX_AUTO_LOAD_ATTEMPTS) break;
- try {
- if (
- skippedAutoLoadCandidates.has(
- autoLoadCandidateKey("model", repo.repo_id),
- )
- ) {
- continue;
- }
- if (
- await loadAutoLoadCandidate({
- id: repo.repo_id,
- loadId: repo.load_id,
- kind: "model",
- ggufVariant: null,
- maxSeqLength: 4096,
- successLabel: `Loaded ${repo.repo_id}`,
- })
- ) {
- return { loaded: true, blockedByTrustRemoteCode: false };
- }
- } catch {
- options?.abortSignal?.throwIfAborted();
- hadNonTrustFailure = true;
- continue;
- }
+ } catch {
+ options?.abortSignal?.throwIfAborted();
+ hadNonTrustFailure = true;
+ continue;
}
}
@@ -2526,11 +2926,15 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
};
}
- // No cached models — try downloading a small default GGUF.
- updateAutoLoadToast(
- "Downloading a small model…",
- "No downloaded models found. Fetching Qwen3.5-4B-MTP (UD-Q4_K_XL).",
- );
+ // Only an empty *complete* inventory means the device has nothing; with a
+ // source unknown, downloading risks duplicating a model already here.
+ if (inventoryIncomplete) {
+ toast.dismiss(toastId);
+ return { loaded: false, blockedByTrustRemoteCode: false };
+ }
+
+ // Nothing on the device: fetch the default as a managed download job, and
+ // only hand it to /api/inference/load once the bytes are here.
try {
const rt = useChatRuntimeStore.getState();
if (rt.selectedGpuIds != null) {
@@ -2540,12 +2944,16 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
rt.selectedGpuIds,
rt.selectedGpuIndexKind,
);
+ // Preflight BEFORE the transfer: active training or the GPU placement
+ // guard can refuse this model, and learning that after several gigabytes
+ // costs the user bandwidth and a long wait for nothing. The load below
+ // reuses this snapshot, so it sends exactly what was cleared here.
if (
!(await canAutoLoad({
- model_path: "unsloth/Qwen3.5-4B-MTP-GGUF",
+ model_path: DEFAULT_CHAT_MODEL_REPO,
max_seq_length: 0,
is_lora: false,
- gguf_variant: "UD-Q4_K_XL",
+ gguf_variant: DEFAULT_CHAT_MODEL_VARIANT,
// The same live-store GPU pick the load below sends (a fresh default
// model has no remembered settings to prefer).
gpu_ids: defaultGpuIds ?? undefined,
@@ -2557,10 +2965,36 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
toast.dismiss(toastId);
return { loaded: false, blockedByTrustRemoteCode };
}
+ const download = await ensureDefaultModelDownloaded(
+ hfToken,
+ options?.abortSignal,
+ updateAutoLoadToast,
+ );
+ options?.abortSignal?.throwIfAborted();
+ if (download !== "ready") {
+ toast.dismiss(toastId);
+ if (download === "cancelled") {
+ toast.message(`${DEFAULT_CHAT_MODEL_LABEL} download stopped`, {
+ description:
+ "No model is loaded. Pick one from the top bar, or download another from the Hub, then send again.",
+ duration: 8000,
+ closeButton: true,
+ });
+ }
+ return {
+ loaded: false,
+ blockedByTrustRemoteCode,
+ loadFailureReported: download === "cancelled",
+ };
+ }
+ updateAutoLoadToast(
+ `Loading ${DEFAULT_CHAT_MODEL_LABEL}…`,
+ `${DEFAULT_CHAT_MODEL_REPO} (${DEFAULT_CHAT_MODEL_VARIANT})`,
+ );
loadAttempts += 1;
options?.abortSignal?.throwIfAborted();
const loadResp = await loadModel({
- model_path: "unsloth/Qwen3.5-4B-MTP-GGUF",
+ model_path: DEFAULT_CHAT_MODEL_REPO,
hf_token: hfToken,
// Model default under both modes: Auto layers + no pin means
// resolveFitMaxSeqLength returns 0 for every mode (the canAutoLoad
@@ -2568,7 +3002,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
max_seq_length: 0,
load_in_4bit: true,
is_lora: false,
- gguf_variant: "UD-Q4_K_XL",
+ gguf_variant: DEFAULT_CHAT_MODEL_VARIANT,
trust_remote_code: trustRemoteCode,
speculative_type: specSettings.speculativeType,
spec_draft_n_max: specSettings.specDraftNMax,
@@ -2591,8 +3025,8 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
useChatRuntimeStore
.getState()
.setCheckpoint(
- "unsloth/Qwen3.5-4B-MTP-GGUF",
- "UD-Q4_K_XL",
+ DEFAULT_CHAT_MODEL_REPO,
+ DEFAULT_CHAT_MODEL_VARIANT,
{ trackQueuedSettings: !options?.preserveVisibleSettings },
);
const store = useChatRuntimeStore.getState();
@@ -2610,13 +3044,13 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
},
);
const defaultModel: ChatModelSummary = {
- id: "unsloth/Qwen3.5-4B-MTP-GGUF",
- name: loadResp.display_name ?? "Qwen3.5-4B-MTP-GGUF",
+ id: DEFAULT_CHAT_MODEL_REPO,
+ name: loadResp.display_name ?? DEFAULT_CHAT_MODEL_LABEL,
isVision: loadResp.is_vision ?? false,
isLora: false,
isGguf: true,
};
- if (!store.models.some((m) => m.id === "unsloth/Qwen3.5-4B-MTP-GGUF")) {
+ if (!store.models.some((m) => m.id === DEFAULT_CHAT_MODEL_REPO)) {
store.setModels([...store.models, defaultModel]);
}
useChatRuntimeStore.setState({
@@ -2650,11 +3084,13 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
...resolveLoadedSpeculativeSettings(loadResp),
});
recordLastLocalModelLoad({
- id: "unsloth/Qwen3.5-4B-MTP-GGUF",
+ id: DEFAULT_CHAT_MODEL_REPO,
kind: "gguf",
- ggufVariant: "UD-Q4_K_XL",
+ ggufVariant: DEFAULT_CHAT_MODEL_VARIANT,
});
- showAutoLoadSuccess("Loaded Qwen3.5-4B-MTP (UD-Q4_K_XL)");
+ showAutoLoadSuccess(
+ `Loaded ${DEFAULT_CHAT_MODEL_LABEL} (${DEFAULT_CHAT_MODEL_VARIANT})`,
+ );
});
return { loaded: true, blockedByTrustRemoteCode: false };
} catch {
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 195b8a0a5ef..b889942cea0 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -504,6 +504,9 @@ export interface CachedModelRepo {
repo_id: string;
load_id?: string | null;
size_bytes: number;
+ /** Weights format; "adapter" is a LoRA with no base weights of its own.
+ * Optional for older-backend compatibility. */
+ model_format?: string | null;
/** Epoch seconds of the newest downloaded weight file; sorts Downloaded
* newest-first. Optional for older-backend compatibility. */
last_modified?: number;
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index c7688ef64d2..8f921e130b1 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -1390,22 +1390,26 @@ export function useChatModelRuntime() {
(loadResponse.is_gguf || isGguf || ggufVariant) &&
!isExternalModelId(modelId),
);
+ // Remembered so auto-load re-picks what the user ran, not the
+ // smallest. Native file-picker paths need a signed, expiring lease,
+ // so they stay out.
+ const indexedLocalPick =
+ typeof selection !== "string" && selection.source === "local";
if (
!isLora &&
!(loadResponse.is_lora ?? false) &&
!nativePathToken &&
- !isLocalModelPath(modelId) &&
- !isExternalModelId(modelId)
+ !isExternalModelId(modelId) &&
+ (indexedLocalPick || !isLocalModelPath(modelId))
) {
- if (loadResponse.is_gguf || isGguf || ggufVariant) {
- recordLastLocalModelLoad({
- id: modelId,
- kind: "gguf",
- ggufVariant: ggufVariant ?? null,
- });
- } else {
- recordLastLocalModelLoad({ id: modelId, kind: "model" });
- }
+ recordLastLocalModelLoad({
+ id: modelId,
+ kind:
+ loadResponse.is_gguf || isGguf || ggufVariant
+ ? "gguf"
+ : "model",
+ ggufVariant: ggufVariant ?? null,
+ });
}
} catch (error) {
// Skip rollback if user cancelled -- model is already being unloaded.
diff --git a/studio/frontend/src/features/chat/utils/last-local-model-load.ts b/studio/frontend/src/features/chat/utils/last-local-model-load.ts
index 099386fbc74..2b1e4a8ea7b 100644
--- a/studio/frontend/src/features/chat/utils/last-local-model-load.ts
+++ b/studio/frontend/src/features/chat/utils/last-local-model-load.ts
@@ -3,6 +3,13 @@
export type LastLocalModelKind = "gguf" | "model";
+const PATH_LIKE_ID_RE = /^(?:[/~]|[A-Za-z]:[\\/]|\\\\)/;
+
+/** A filesystem target rather than a Hub repo id. */
+function isPathLikeId(id: string): boolean {
+ return PATH_LIKE_ID_RE.test(id);
+}
+
export type LastLocalModelLoad = {
id: string;
kind: LastLocalModelKind;
@@ -39,8 +46,10 @@ export function readLastLocalModelLoad(): LastLocalModelLoad | null {
) {
return null;
}
+ // A quant-less cached repo names no file; a local .gguf path is the file.
if (
parsed.kind === "gguf" &&
+ !isPathLikeId(parsed.id) &&
(typeof parsed.ggufVariant !== "string" || !parsed.ggufVariant.trim())
) {
return null;
@@ -67,7 +76,7 @@ export function recordLastLocalModelLoad(input: {
return;
}
const ggufVariant = input.ggufVariant?.trim() || null;
- if (input.kind === "gguf" && !ggufVariant) {
+ if (input.kind === "gguf" && !ggufVariant && !isPathLikeId(id)) {
return;
}
try {
diff --git a/studio/frontend/tests/auto-load-target-key.test.ts b/studio/frontend/tests/auto-load-target-key.test.ts
new file mode 100644
index 00000000000..95241416d2c
--- /dev/null
+++ b/studio/frontend/tests/auto-load-target-key.test.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import ts from "typescript";
+
+// The shipped helper is lifted out of chat-adapter.ts rather than copied, so
+// these assert against the real source. Importing the module would drag in the
+// stores and the toast layer for one pure string function.
+const adapterPath = fileURLToPath(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+);
+const source = readFileSync(adapterPath, "utf8");
+const start = source.indexOf("function normalizeTarget(");
+assert.ok(start >= 0, "normalizeTarget is no longer defined in chat-adapter.ts");
+const declaration = source.slice(start, source.indexOf("\n}", start) + 2);
+const normalizeTarget = new Function(
+ `${ts.transpileModule(declaration, {
+ compilerOptions: { target: ts.ScriptTarget.ES2020 },
+ }).outputText}; return normalizeTarget;`,
+)() as (value: string) => string;
+
+const sameKey = (a: string, b: string) => normalizeTarget(a) === normalizeTarget(b);
+
+test("one Windows file spelled with either separator is one candidate", () => {
+ // Two keys meant one spelling burned an attempt on the same file, and a
+ // remembered record written as C:\ never matched C:/.
+ assert.ok(sameKey("C:\\Users\\a\\models\\M.gguf", "C:/Users/a/models/M.gguf"));
+});
+
+test("Windows and UNC paths still fold case", () => {
+ assert.ok(sameKey("C:\\Users\\a\\M.gguf", "c:\\users\\a\\m.gguf"));
+ assert.ok(sameKey("\\\\srv\\share\\M.gguf", "\\\\SRV\\share\\m.gguf"));
+});
+
+test("WSL UNC paths keep their case, because they address ext4", () => {
+ // Folding merged two real files onto one key, so the second never loaded.
+ assert.ok(
+ !sameKey("\\\\wsl$\\Ubuntu\\home\\a\\M.gguf", "\\\\wsl$\\Ubuntu\\home\\a\\m.gguf"),
+ );
+ assert.ok(sameKey("\\\\wsl$\\Ubuntu\\home\\a\\M.gguf", "//wsl$/Ubuntu/home/a/M.gguf"));
+});
+
+test("POSIX paths keep their case", () => {
+ assert.ok(!sameKey("/home/a/M.gguf", "/home/a/m.gguf"));
+});
+
+test("a decomposed filename is the same candidate as its composed form", () => {
+ // macOS hands back NFD, so a remembered model was never re-attempted.
+ assert.ok(sameKey("/home/a/caf\u00e9.gguf", "/home/a/cafe\u0301.gguf"));
+});
+
+test("repo ids still fold case", () => {
+ assert.ok(sameKey("unsloth/Qwen3-0.6B-GGUF", "UNSLOTH/qwen3-0.6b-gguf"));
+});
diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.py
index 2729341b1aa..b2314d8451c 100644
--- a/tests/studio/test_chat_autoload_failure_gate.py
+++ b/tests/studio/test_chat_autoload_failure_gate.py
@@ -31,8 +31,9 @@ def _source_path(relative_path: str) -> Path:
ADAPTER = _source_path("studio/frontend/src/features/chat/api/chat-adapter.ts")
TEMP = WORKDIR / "temp" / "chat_autoload_failure_gate"
-DEFAULT_MODEL = "unsloth/Qwen3.5-4B-MTP-GGUF"
+DEFAULT_MODEL = "unsloth/gemma-4-E2B-it-GGUF"
GEMMA_REPO = "unsloth/gemma-4-26B-A4B-it-qat-GGUF"
+LOCAL_GGUF_PATH = "/home/john-doe/models/qwen3-1.7b-instruct-q4_k_m.gguf"
# Stubs for everything autoLoadSmallestModel imports; each scenario supplies the cache inventory
# and how /validate and /load answer per model_path.
@@ -49,10 +50,24 @@ type ChatModelSummary = Record<string, unknown>;
export type Scenario = {
ggufRepos: any[];
modelRepos: any[];
+ localModels: any[];
+ chatOnly: boolean;
+ deviceType: string;
+ /** Click the toast's Cancel while requestStart is still in its preflights. */
+ cancelDuringStart: boolean;
+ /** Cancellation request fails and the transfer keeps running. */
+ cancelFails: boolean;
+ /** "decline" or "anonymous" from the expired-token dialog. */
+ tokenDecision: string | null;
+ /** false = the backend platform probe has not landed yet. */
+ platformFetched: boolean;
variants: Record<string, any>;
lastLoaded: any;
validate: (payload: any) => any;
load: (payload: any) => any;
+ /** How the Hub download manager answers the default-model request:
+ * "complete" (default), "cancelled", "failed", "busy", or "conflict". */
+ download: (request: any) => string;
};
export const EVENTS: any[] = [];
@@ -61,6 +76,11 @@ export function setScenario(scenario: Scenario) {
SCENARIO = scenario;
EVENTS.length = 0;
STORE = makeStore();
+ DOWNLOAD_LISTENERS = [];
+ DOWNLOAD_STATE = { jobs: {} };
+ DOWNLOAD_SUBS = [];
+ CANCELLED_KEYS = new Set();
+ CANCEL_TOAST_ACTION = null;
}
const GPU_LAYERS_AUTO = -1;
@@ -133,6 +153,9 @@ function mlxRuntimeStateFrom(resp: any) {
};
}
async function prepareHfTokenForUse(token: any) {
+ EVENTS.push({ kind: "prepareHfToken" });
+ if (SCENARIO.tokenDecision === "decline") return { proceed: false, token };
+ if (SCENARIO.tokenDecision === "anonymous") return { proceed: true, token: null };
return { proceed: true, token };
}
async function fetchGgufStagedMetadata(_req: any) {
@@ -179,7 +202,13 @@ const toast: any = Object.assign(
(_msg: string, _opts?: any) => "toast-id",
{
message: (msg: string, opts?: any) => {
- EVENTS.push({ kind: "toast.message", msg, description: opts?.description });
+ EVENTS.push({
+ kind: "toast.message",
+ msg,
+ description: opts?.description,
+ hasCancel: Boolean(opts?.action),
+ });
+ if (opts?.action?.onClick) CANCEL_TOAST_ACTION = opts.action.onClick;
return "toast-id";
},
success: (msg: string) => EVENTS.push({ kind: "toast.success", msg }),
@@ -195,7 +224,9 @@ function resolveSpeculativeSettingsForLoad() {
return { speculativeType: null, specDraftNMax: 0 };
}
function readLastLocalModelLoad() { return SCENARIO.lastLoaded; }
-function recordLastLocalModelLoad(_x: any) {}
+function recordLastLocalModelLoad(x: any) {
+ EVENTS.push({ kind: "recordLastLocal", id: x.id, modelKind: x.kind });
+}
function resolveInitialConfig(_id: string, _variant: any) {
return { config: {
customContextLength: null, maxSeqLength: null, gpuMemoryMode: null,
@@ -217,9 +248,147 @@ function loadedGpuMemoryFields(_x: any) { return {}; }
function resolveLoadedSpeculativeSettings(_x: any) { return {}; }
function isMultimodalResponse(_x: any) { return false; }
-async function listCachedGguf() { return SCENARIO.ggufRepos as any; }
-async function listCachedModels() { return SCENARIO.modelRepos as any; }
-async function listGgufVariants(repoId: string, _b?: any, _c?: any) {
+async function listCachedGguf(signal?: any) {
+ EVENTS.push({ kind: "listCachedGguf", hasSignal: Boolean(signal) });
+ if (SCENARIO.ggufRepos === "throw") throw new Error("cached gguf listing failed");
+ return SCENARIO.ggufRepos as any;
+}
+async function listCachedModels(_token?: any, signal?: any) {
+ EVENTS.push({ kind: "listCachedModels", hasSignal: Boolean(signal) });
+ if (SCENARIO.modelRepos === "throw") throw new Error("cached model listing failed");
+ return SCENARIO.modelRepos as any;
+}
+// The unified on-device inventory (models dir, LM Studio, custom scan folders).
+// Before #7374 was fixed the cascade never asked for it, so a downloaded local
+// model was invisible and Send fetched an unrelated default instead.
+async function listLocalModels() {
+ if (SCENARIO.localModels === "throw") throw new Error("local inventory failed");
+ return { models: (SCENARIO.localModels ?? []) as any[] };
+}
+function isHiddenModelId(..._a: any[]) { return false; }
+// A chat-only install (Mac / AMD / CPU) runs GGUF, plus MLX on a Mac; the
+// picker hides every other local format there, so a background pick must too.
+const usePlatformStore = {
+ getState: () => ({
+ deviceType: SCENARIO.deviceType ?? "linux",
+ // Server-reported unless a scenario says the probe has not landed.
+ fetched: SCENARIO.platformFetched !== false,
+ isChatOnly: () => SCENARIO.chatOnly === true,
+ }),
+};
+function isMlxId(value: string) {
+ return typeof value === "string" && value.toLowerCase().includes("mlx");
+}
+
+// --- Hub download manager -------------------------------------------------
+// The default-model fetch is a managed job now, so the harness models its
+// surface: a start request, terminal listeners, and a cancel.
+const DOWNLOAD_KIND = { MODEL: "model", DATASET: "dataset" } as const;
+function jobKeyOf(kind: string, repoId: string, variant: string | null) {
+ return variant ? `${kind}:${repoId}#${variant}` : `${kind}:${repoId}`;
+}
+function selectActiveJob(state: any, kind: string, repoId: string, variant?: any) {
+ const job = state.jobs[jobKeyOf(kind, repoId, variant ?? null)];
+ return job && job.state !== "cancelled" ? job : null;
+}
+let DOWNLOAD_STATE: any = { jobs: {} };
+let DOWNLOAD_SUBS: any[] = [];
+let CANCELLED_KEYS = new Set<string>();
+let CANCEL_TOAST_ACTION: any = null;
+function notifyDownloadStore() {
+ for (const listener of [...DOWNLOAD_SUBS]) listener(DOWNLOAD_STATE);
+}
+const useDownloadManagerStore = {
+ getState: () => DOWNLOAD_STATE,
+ subscribe: (listener: any) => {
+ DOWNLOAD_SUBS.push(listener);
+ return () => {
+ DOWNLOAD_SUBS = DOWNLOAD_SUBS.filter((entry) => entry !== listener);
+ };
+ },
+};
+let DOWNLOAD_LISTENERS: any[] = [];
+function subscribeJobListeners(_kind: string, _repoId: string, handlers: any) {
+ DOWNLOAD_LISTENERS.push(handlers);
+ return () => {
+ DOWNLOAD_LISTENERS = DOWNLOAD_LISTENERS.filter((entry) => entry !== handlers);
+ };
+}
+const downloadManager = {
+ requestStart: async (request: any) => {
+ EVENTS.push({
+ kind: "download.start",
+ repoId: request.repoId,
+ variant: request.variant,
+ });
+ const behaviour = SCENARIO.download ? SCENARIO.download(request) : "complete";
+ if (behaviour === "busy" || behaviour === "conflict" || behaviour === "error") {
+ return behaviour;
+ }
+ // The real requestStart runs transport preflights before any job exists.
+ // A scenario can click the toast's Cancel inside that window.
+ if (SCENARIO.cancelDuringStart) CANCEL_TOAST_ACTION?.();
+ const key = jobKeyOf(request.kind, request.repoId, request.variant);
+ DOWNLOAD_STATE = {
+ jobs: {
+ ...DOWNLOAD_STATE.jobs,
+ [key]: {
+ key,
+ variant: request.variant,
+ state: "running",
+ downloadedBytes: 0,
+ expectedBytes: request.expectedBytes,
+ },
+ },
+ };
+ notifyDownloadStore();
+ // Terminal events land on a later turn, as the real poll loop's do.
+ queueMicrotask(() => {
+ if (CANCELLED_KEYS.has(key)) return;
+ for (const handlers of [...DOWNLOAD_LISTENERS]) {
+ if (behaviour === "complete") {
+ handlers.onComplete?.(request.variant, request.expectedBytes);
+ } else if (behaviour === "cancelled") {
+ handlers.onCancelled?.(request.variant);
+ } else {
+ handlers.onError?.(request.variant);
+ }
+ }
+ });
+ return "started";
+ },
+ cancel: async (key: string) => {
+ EVENTS.push({ kind: "download.cancel", key });
+ const job = DOWNLOAD_STATE.jobs[key];
+ // The real cancelJob can fail its request, probe the transfer as still
+ // running, and restore the job. Nothing is cancelled in that case.
+ if (SCENARIO.cancelFails) {
+ if (job) {
+ DOWNLOAD_STATE = {
+ jobs: { ...DOWNLOAD_STATE.jobs, [key]: { ...job, state: "running" } },
+ };
+ notifyDownloadStore();
+ }
+ return;
+ }
+ CANCELLED_KEYS.add(key);
+ if (job) {
+ DOWNLOAD_STATE = {
+ jobs: { ...DOWNLOAD_STATE.jobs, [key]: { ...job, state: "cancelled" } },
+ };
+ notifyDownloadStore();
+ }
+ for (const handlers of [...DOWNLOAD_LISTENERS]) {
+ handlers.onCancelled?.(job?.variant ?? null);
+ }
+ },
+};
+async function listGgufVariants(repoId: string, _b?: any, options?: any) {
+ EVENTS.push({
+ kind: "listGgufVariants",
+ repoId,
+ hasSignal: Boolean(options?.signal),
+ });
const entry = SCENARIO.variants[repoId];
if (entry === "throw") throw new Error("variant listing failed");
return entry ?? { variants: [] };
@@ -235,6 +404,8 @@ async function loadModel(payload: any) {
kind: "loadModel",
model_path: payload.model_path,
gguf_variant: payload.gguf_variant ?? null,
+ // GGUF sources send 0; a Transformers source sends the safetensors length.
+ max_seq_length: payload.max_seq_length,
rejected: result instanceof Error,
});
if (result instanceof Error) throw result;
@@ -271,13 +442,33 @@ SCENARIO_HELPERS = """
is_gguf: true,
context_length: 32768,
});
+ // A backend-indexed local GGUF: exactly the row the old cascade could not
+ // see, so Send downloaded a model the user already had a substitute for.
+ const LOCAL_GGUF = {
+ id: "/home/john-doe/models/qwen3-1.7b-instruct-q4_k_m.gguf",
+ load_id: "/home/john-doe/models/qwen3-1.7b-instruct-q4_k_m.gguf",
+ path: "/home/john-doe/models/qwen3-1.7b-instruct-q4_k_m.gguf",
+ display_name: "qwen3-1.7b-instruct-q4_k_m",
+ source: "models_dir",
+ model_format: "gguf",
+ size_bytes: 1_100_000_000,
+ capabilities: { can_chat: true, requires_variant: false },
+ };
const scenario = (over) => ({
ggufRepos: [],
modelRepos: [],
+ localModels: [],
+ chatOnly: false,
+ deviceType: "linux",
+ cancelDuringStart: false,
+ cancelFails: false,
+ tokenDecision: null,
+ platformFetched: true,
variants: {},
lastLoaded: null,
validate: VALIDATE_OK,
load: LOADED,
+ download: () => "complete",
...over,
});
"""
@@ -396,7 +587,11 @@ def _run(scenario_expr: str) -> dict:
+ textwrap.dedent(
f"""
setScenario({scenario_expr});
- const result = await autoLoadSmallestModel();
+ // The real send path always supplies one, so the signal plumbing is
+ // exercised by every scenario.
+ const result = await autoLoadSmallestModel({{
+ abortSignal: new AbortController().signal,
+ }});
console.log(JSON.stringify({{ result, events: EVENTS }}));
"""
)
@@ -407,6 +602,9 @@ def _run(scenario_expr: str) -> dict:
cwd = str(run_dir),
capture_output = True,
text = True,
+ # Explicit: text alone decodes with the Windows ANSI code page, which
+ # mangles the non-ASCII toast copy node emits as UTF-8.
+ encoding = "utf-8",
timeout = 60,
env = dict(os.environ, NODE_NO_WARNINGS = "1"),
)
@@ -423,6 +621,10 @@ def _toasts(out: dict, kind: str) -> list[dict]:
return [event for event in out["events"] if event["kind"] == kind]
+def _downloads_started(out: dict) -> list[str]:
+ return [event["repoId"] for event in out["events"] if event["kind"] == "download.start"]
+
+
def test_failed_cached_load_does_not_download_the_default_model():
"""The reported case: the only cached repo enumerates fine but its load OOMs, so auto-load stops
there rather than fetch a model the user never asked for."""
@@ -438,6 +640,7 @@ def test_failed_cached_load_does_not_download_the_default_model():
assert not any(
"Downloading a small model" in event["msg"] for event in _toasts(out, "toast.message")
)
+ assert _downloads_started(out) == []
def test_failed_cached_load_surfaces_the_backend_reason():
@@ -472,7 +675,7 @@ def test_empty_device_still_downloads_the_default_model():
assert out["result"]["loaded"] is True
assert _toasts(out, "toast.error") == []
assert [event["msg"] for event in _toasts(out, "toast.success")] == [
- "Loaded Qwen3.5-4B-MTP (UD-Q4_K_XL)"
+ "Loaded Gemma 4 E2B (UD-Q4_K_XL)"
]
@@ -624,3 +827,617 @@ def test_a_rejected_validation_still_lets_a_later_cached_model_load():
assert _loaded_paths(out) == ["r2"]
assert out["result"]["loaded"] is True
assert _toasts(out, "toast.error") == []
+
+
+# --- #7374: a model already on disk must be found before anything is fetched ---
+
+
+def test_an_indexed_local_gguf_loads_instead_of_downloading_the_default():
+ """The reported bug. The user has a GGUF in their models dir, but the cascade
+ only read the two managed-cache lists, so Send fetched a model instead."""
+ out = _run("scenario({ localModels: [LOCAL_GGUF] })")
+
+ assert _loaded_paths(out) == [LOCAL_GGUF_PATH]
+ assert _downloads_started(out) == []
+ assert out["result"]["loaded"] is True
+
+
+def test_a_local_model_wins_over_the_default_even_when_the_cache_is_empty():
+ """An empty managed cache is not an empty device."""
+ out = _run("scenario({ ggufRepos: [], modelRepos: [], localModels: [LOCAL_GGUF] })")
+
+ assert DEFAULT_MODEL not in _loaded_paths(out)
+ assert _downloads_started(out) == []
+
+
+def test_the_smallest_on_device_model_wins_across_inventories():
+ """Cached and local rows compete in one size-ordered cascade, not one list
+ then the other."""
+ out = _run(
+ "scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " localModels: [LOCAL_GGUF] })"
+ )
+
+ # LOCAL_GGUF is 1.1 GB, GEMMA is 15.8 GB.
+ assert _loaded_paths(out) == [LOCAL_GGUF_PATH]
+
+
+ "inventory",
+ ["ggufRepos", "modelRepos", "localModels"],
+)
+def test_an_inventory_failure_never_reads_as_an_empty_device(inventory):
+ """Both cached lookups used to be wrapped in `.catch(() => [])`, so one flaky
+ request looked exactly like "this user has no models" and started a download."""
+ out = _run(f"scenario({{ {inventory}: 'throw' }})")
+
+ assert _downloads_started(out) == []
+ assert _loaded_paths(out) == []
+ assert out["result"]["loaded"] is False
+
+
[email protected]("broken", ["ggufRepos", "modelRepos", "localModels"])
+def test_one_broken_inventory_still_loads_a_model_another_one_found(broken):
+ """A failure is one unknown source, not a verdict on the other two.
+ Promise.all rejected the batch, discarding lists that had already arrived,
+ so a broken local scan left a loadable model unused."""
+ # Put the model in a source that is not the one being broken.
+ holder = "localModels" if broken != "localModels" else "ggufRepos"
+ rows = "[LOCAL_GGUF]" if holder == "localModels" else "[GEMMA]"
+ extra = "" if holder == "localModels" else ", variants: { [GEMMA.repo_id]: GEMMA_VARIANTS }"
+ out = _run(f"scenario({{ {broken}: 'throw', {holder}: {rows}{extra} }})")
+
+ assert out["result"]["loaded"] is True
+ # Still fails closed on the part it cannot see: no default is fetched.
+ assert _downloads_started(out) == []
+ assert DEFAULT_MODEL not in _loaded_paths(out)
+
+
+def test_a_local_row_the_picker_would_hide_is_never_auto_loaded():
+ """A background pick must be something the user could have picked themselves."""
+ hidden = (
+ "{ ...LOCAL_GGUF, capabilities: { can_chat: false } },"
+ " { ...LOCAL_GGUF, id: 'p', load_id: 'p', path: 'p', partial: true },"
+ " { ...LOCAL_GGUF, id: 'a', load_id: 'a', path: 'a', model_format: 'adapter' },"
+ " { ...LOCAL_GGUF, id: 'c', load_id: 'c', path: 'c', model_format: 'checkpoint' },"
+ " { ...LOCAL_GGUF, id: 'o', load_id: 'o', path: 'o', source: 'ollama' }"
+ )
+ out = _run(f"scenario({{ localModels: [{hidden}] }})")
+
+ # Nothing loadable on device, so the default download is the correct answer.
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+ assert _downloads_started(out) == [DEFAULT_MODEL]
+
+
+def test_the_remembered_local_model_is_tried_before_a_smaller_one():
+ """Re-picking the model the user actually ran beats re-picking the smallest."""
+ out = _run(
+ "scenario({ localModels: [LOCAL_GGUF,"
+ " { ...LOCAL_GGUF, id: 'tiny', load_id: 'tiny', path: 'tiny', size_bytes: 1 }],"
+ " lastLoaded: { id: LOCAL_GGUF.load_id, kind: 'gguf', ggufVariant: null } })"
+ )
+
+ assert _loaded_paths(out) == [LOCAL_GGUF_PATH]
+
+
+# --- the default download is a managed, cancellable job ---
+
+
+def test_the_default_model_is_fetched_through_the_download_manager():
+ """Not inline inside /api/inference/load: the manager owns the transfer, so
+ it gets a panel entry, progress, and a Cancel that stops it."""
+ out = _run("scenario({})")
+
+ assert _downloads_started(out) == [DEFAULT_MODEL]
+ # The bytes land before the load is attempted.
+ kinds = [event["kind"] for event in out["events"]]
+ assert kinds.index("download.start") < kinds.index("loadModel")
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+
+
+def test_cancelling_the_first_download_loads_nothing_and_says_what_to_do():
+ out = _run("scenario({ download: () => 'cancelled' })")
+
+ assert _loaded_paths(out) == []
+ assert out["result"]["loaded"] is False
+ [notice] = [
+ event for event in _toasts(out, "toast.message") if "download stopped" in event["msg"]
+ ]
+ assert "Pick one from the top bar" in notice["description"]
+
+
+def test_a_failed_first_download_never_reaches_the_load():
+ """A dead transfer must not be handed to /load as if the file were there."""
+ for behaviour in ("failed", "error", "busy", "conflict"):
+ out = _run(f"scenario({{ download: () => '{behaviour}' }})")
+ assert _loaded_paths(out) == [], behaviour
+ assert out["result"]["loaded"] is False, behaviour
+
+
+def test_the_first_download_toast_explains_rather_than_alarms():
+ """The old copy read as a warning about the user's machine and named a raw
+ repo id and quant."""
+ out = _run("scenario({})")
+
+ messages = [event["msg"] for event in _toasts(out, "toast.message")]
+ descriptions = [event["description"] or "" for event in _toasts(out, "toast.message")]
+ assert any("Getting Gemma 4 E2B ready" in msg for msg in messages)
+ assert any(
+ "Unsloth couldn\u2019t find an existing model. Unsloth is now getting "
+ "Gemma 4 E2B ready for use. You can stop the download or manage models "
+ "later in the 'Model hub'" == text
+ for text in descriptions
+ )
+ assert not any("No downloaded models found" in text for text in descriptions)
+
+
+def test_a_chat_only_install_never_auto_loads_a_format_it_cannot_run():
+ """On chat-only builds the picker shows GGUF (and MLX on a Mac) only, so a
+ background pick must not spend an attempt on a safetensors row."""
+ safetensors = (
+ "{ ...LOCAL_GGUF, id: 'st', load_id: 'st', path: '/models/st',"
+ " model_format: 'safetensors' }"
+ )
+ out = _run(f"scenario({{ chatOnly: true, localModels: [{safetensors}] }})")
+ assert "st" not in _loaded_paths(out)
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+
+ # The same row is fair game on a full install.
+ out = _run(f"scenario({{ chatOnly: false, localModels: [{safetensors}] }})")
+ assert _loaded_paths(out) == ["st"]
+
+
+def test_a_mac_chat_only_install_still_auto_loads_a_local_mlx_model():
+ mlx = (
+ "{ ...LOCAL_GGUF, id: 'org/Qwen3-4B-mlx-4bit', load_id: '/models/mlx',"
+ " path: '/models/mlx', model_format: 'safetensors' }"
+ )
+ out = _run(f"scenario({{ chatOnly: true, deviceType: 'mac', localModels: [{mlx}] }})")
+ assert _loaded_paths(out) == ["/models/mlx"]
+
+
+# --- review fixes on the on-device cascade ---
+
+
+def test_an_image_generation_row_is_never_auto_loaded_for_chat():
+ """Diffusion rows carry an image/video task while can_chat stays true on
+ file format alone. The picker routes them to the Images page on click; a
+ background load has no routing step, so it has to skip them."""
+ for task in ("text-to-image", "text-to-video", "image-diffusion-unsupported"):
+ rows = (
+ f"{{ ...LOCAL_GGUF, id: 'img', load_id: 'img', path: 'img', task: '{task}',"
+ " size_bytes: 1 }, LOCAL_GGUF"
+ )
+ out = _run(f"scenario({{ localModels: [{rows}] }})")
+ # 'img' is the smaller row, so only the task gate can keep it out.
+ assert _loaded_paths(out) == [LOCAL_GGUF_PATH], task
+
+
+def test_a_chat_row_with_no_task_tag_still_auto_loads():
+ """Control for the gate above: the backend leaves task null for chat LLMs."""
+ out = _run("scenario({ localModels: [{ ...LOCAL_GGUF, task: null }] })")
+ assert _loaded_paths(out) == [LOCAL_GGUF_PATH]
+
+
+def test_a_failed_quant_falls_through_to_the_next_one_in_the_same_repo():
+ """One corrupt quant must not cost a repo that holds a valid one."""
+ variants = (
+ "{ variants: ["
+ "{ quant: 'Q2_K', filename: 'm-Q2_K.gguf', downloaded: true, size_bytes: 100 },"
+ "{ quant: 'Q4_K_M', filename: 'm-Q4_K_M.gguf', downloaded: true, size_bytes: 200 }"
+ "] }"
+ )
+ out = _run(
+ f"scenario({{ ggufRepos: [GEMMA], variants: {{ [GEMMA.repo_id]: {variants} }},"
+ " load: (p) => p.gguf_variant === 'Q2_K' ? new Error(OOM) : LOADED(p) })"
+ )
+
+ assert [event["gguf_variant"] for event in out["events"] if event["kind"] == "loadModel"] == [
+ "Q2_K",
+ "Q4_K_M",
+ ]
+ assert out["result"]["loaded"] is True
+ assert _downloads_started(out) == []
+
+
+def test_the_variant_retry_still_respects_the_attempt_cap():
+ """Guard on the loop above: a repo of broken quants must not spin."""
+ variants = (
+ "{ variants: [1,2,3,4,5,6].map((i) => ({ quant: `Q${i}`,"
+ " filename: `m-Q${i}.gguf`, downloaded: true, size_bytes: i })) }"
+ )
+ out = _run(
+ f"scenario({{ ggufRepos: [GEMMA], variants: {{ [GEMMA.repo_id]: {variants} }},"
+ " load: () => new Error(OOM) })"
+ )
+
+ assert len(_loaded_paths(out)) == 3
+ assert _downloads_started(out) == []
+
+
+def test_cached_inventory_lookups_carry_the_run_abort_signal():
+ """Both are raw fetches with no timeout of their own, so a stall would hold
+ the model-loading lease open after the user stops the send."""
+ out = _run("scenario({})")
+ for kind in ("listCachedGguf", "listCachedModels"):
+ [call] = [event for event in out["events"] if event["kind"] == kind]
+ assert call["hasSignal"] is True, kind
+
+
+def test_cancel_during_the_download_preflight_still_stops_it():
+ """requestStart runs transport preflights before the job exists and cancel
+ no-ops on a missing key, so the first Cancel click was swallowed."""
+ out = _run("scenario({ cancelDuringStart: true })")
+
+ assert [event["kind"] for event in out["events"]].count("download.cancel") >= 1
+ assert _loaded_paths(out) == []
+ assert out["result"]["loaded"] is False
+
+
+def test_the_download_toast_carries_a_cancel_action():
+ out = _run("scenario({})")
+ assert any(
+ event.get("hasCancel") and "Getting Gemma 4 E2B ready" in event["msg"]
+ for event in _toasts(out, "toast.message")
+ )
+
+
+def test_remembered_posix_paths_match_case_sensitively():
+ """Two local models on Linux can differ only by path casing; folding them
+ marks both as the remembered one and can auto-load the wrong model."""
+ rows = (
+ "{ ...LOCAL_GGUF, id: '/models/Foo.gguf', load_id: '/models/Foo.gguf',"
+ " path: '/models/Foo.gguf', size_bytes: 200 },"
+ " { ...LOCAL_GGUF, id: '/models/foo.gguf', load_id: '/models/foo.gguf',"
+ " path: '/models/foo.gguf', size_bytes: 100 }"
+ )
+ out = _run(
+ f"scenario({{ localModels: [{rows}],"
+ " lastLoaded: { id: '/models/Foo.gguf', kind: 'gguf', ggufVariant: null } })"
+ )
+
+ # Lowercasing would rank both as remembered and let the smaller one win.
+ assert _loaded_paths(out) == ["/models/Foo.gguf"]
+
+
+def test_a_mixed_cached_repo_is_attempted_once_not_twice():
+ """A repo holding both GGUF and safetensors appears in both cached lists,
+ but the backend resolves one load target to one model, so keeping both rows
+ spends a second attempt on the same files."""
+ out = _run(
+ "scenario({ ggufRepos: [GEMMA],"
+ " modelRepos: [{ repo_id: GEMMA.repo_id, load_id: GEMMA.load_id, size_bytes: 15800000000 }],"
+ " variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " load: () => new Error(OOM) })"
+ )
+
+ assert _loaded_paths(out) == [GEMMA_REPO]
+ # The GGUF row is the one the backend will actually resolve, so it survives.
+ assert [event["gguf_variant"] for event in out["events"] if event["kind"] == "loadModel"] == [
+ "UD-Q4_K_XL"
+ ]
+
+
+def test_a_mixed_cached_repo_still_loads_through_its_gguf_row():
+ """Control: deduping must not drop the repo altogether."""
+ out = _run(
+ "scenario({ ggufRepos: [GEMMA],"
+ " modelRepos: [{ repo_id: GEMMA.repo_id, load_id: GEMMA.load_id, size_bytes: 1 }],"
+ " variants: { [GEMMA.repo_id]: GEMMA_VARIANTS } })"
+ )
+ assert _loaded_paths(out) == [GEMMA_REPO]
+ assert out["result"]["loaded"] is True
+
+
+def test_distinct_repos_are_not_collapsed_by_the_dedupe():
+ """Guard on the key: only a shared load target may collapse."""
+ out = _run(
+ "scenario({ ggufRepos: [1, 2].map((i) => ({ ...GEMMA, repo_id: `r${i}`,"
+ " load_id: `r${i}`, size_bytes: i })),"
+ " variants: { r1: GEMMA_VARIANTS, r2: GEMMA_VARIANTS },"
+ " load: () => new Error(OOM) })"
+ )
+ assert _loaded_paths(out) == ["r1", "r2"]
+
+
+def test_variant_scans_carry_the_run_abort_signal():
+ """Bounded by their own timeout, but a stopped send should not wait it out."""
+ out = _run("scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: GEMMA_VARIANTS } })")
+ scans = [event for event in out["events"] if event["kind"] == "listGgufVariants"]
+ assert scans, "no variant scan ran"
+ assert all(scan["hasSignal"] for scan in scans)
+
+
+def test_a_failed_path_does_not_mark_a_case_distinct_sibling_as_tried():
+ """On Linux /models/Foo.gguf and /models/foo.gguf are two models, so folding
+ the tried-candidate key let one failure suppress the other."""
+ rows = (
+ "{ ...LOCAL_GGUF, id: '/models/Foo.gguf', load_id: '/models/Foo.gguf',"
+ " path: '/models/Foo.gguf', size_bytes: 1 },"
+ " { ...LOCAL_GGUF, id: '/models/foo.gguf', load_id: '/models/foo.gguf',"
+ " path: '/models/foo.gguf', size_bytes: 2 }"
+ )
+ out = _run(
+ f"scenario({{ localModels: [{rows}],"
+ " load: (p) => p.model_path === '/models/Foo.gguf' ? new Error(OOM) : LOADED(p) })"
+ )
+
+ assert _loaded_paths(out) == ["/models/Foo.gguf", "/models/foo.gguf"]
+ assert out["result"]["loaded"] is True
+ assert _downloads_started(out) == []
+
+
+def test_the_default_variant_lookup_carries_the_run_abort_signal():
+ """Bounded by its own 30s timeout, but a stopped send should not hold the
+ model-loading lease waiting it out before the download even starts."""
+ out = _run("scenario({})")
+ [lookup] = [
+ event
+ for event in out["events"]
+ if event["kind"] == "listGgufVariants" and event["repoId"] == DEFAULT_MODEL
+ ]
+ assert lookup["hasSignal"] is True
+
+
+def test_a_download_that_survives_a_failed_cancel_is_not_loaded():
+ """cancelJob can fail and the transfer keep running, but the user asked for
+ it to stop, so the bytes that arrive anyway must not reach a load."""
+ out = _run("scenario({ cancelDuringStart: true, cancelFails: true })")
+
+ assert _loaded_paths(out) == []
+ assert out["result"]["loaded"] is False
+
+
+def test_a_failed_cancel_does_not_latch_the_toast_action_off():
+ """The retry latch must clear once the request settles, or every later
+ Cancel click is swallowed."""
+ src = (WORKDIR / "studio/frontend/src/features/chat/api/chat-adapter.ts").read_text(
+ encoding = "utf-8"
+ )
+ helper = src.split("async function ensureDefaultModelDownloaded", 1)[1]
+ helper = helper.split("async function autoLoadSmallestModel", 1)[0]
+ # In flight only, cleared when the request settles.
+ assert 'if (cancelInFlight || active.state === "cancelling") return true;' in helper
+ assert "cancelInFlight = false;\n });" in helper
+ # The subscription fires the deferred attempt once; retries come from clicks.
+ assert "if (!cancelEverIssued) issueCancel();" in helper
+
+
+def test_an_expired_token_is_prepared_before_the_managed_start():
+ """startJob sends the stored token raw, with none of the recovery
+ validateModel and loadModel get, so an expired one would fail the download
+ of a public repo the lookup just read anonymously."""
+ out = _run("scenario({})")
+ kinds = [event["kind"] for event in out["events"]]
+ assert "prepareHfToken" in kinds
+ assert kinds.index("prepareHfToken") < kinds.index("download.start")
+
+
+def test_declining_the_token_dialog_starts_no_download():
+ out = _run("scenario({ tokenDecision: 'decline' })")
+ assert _downloads_started(out) == []
+ assert _loaded_paths(out) == []
+ assert out["result"]["loaded"] is False
+
+
+def test_the_token_is_not_prepared_when_the_default_is_already_on_disk():
+ """Nothing to download means nothing to prompt about."""
+ downloaded = (
+ "{ variants: [{ quant: 'UD-Q4_K_XL', filename: 'm-UD-Q4_K_XL.gguf',"
+ " downloaded: true, size_bytes: 100 }] }"
+ )
+ out = _run(f"scenario({{ variants: {{ 'unsloth/gemma-4-E2B-it-GGUF': {downloaded} }} }})")
+ kinds = [event["kind"] for event in out["events"]]
+ assert "prepareHfToken" not in kinds
+ assert _downloads_started(out) == []
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+
+
+def test_a_cached_image_repo_is_never_auto_loaded_for_chat():
+ """Cached diffusion repos report can_chat true on file format alone, and
+ carry their Images/Video task on the row."""
+ for task in ("text-to-image", "text-to-video", "image-diffusion-unsupported"):
+ out = _run(
+ f"scenario({{ ggufRepos: [{{ ...GEMMA, repo_id: 'img', load_id: 'img',"
+ f" size_bytes: 1, task: '{task}' }}, GEMMA],"
+ " variants: { img: GEMMA_VARIANTS, [GEMMA.repo_id]: GEMMA_VARIANTS } })"
+ )
+ assert _loaded_paths(out) == [GEMMA_REPO], task
+
+
+def test_a_cached_text_generation_repo_still_auto_loads():
+ """Chat GGUFs are tagged text-generation, not null, so the gate must be a
+ list of image/video tasks rather than "has a task"."""
+ out = _run(
+ "scenario({ ggufRepos: [{ ...GEMMA, task: 'text-generation' }],"
+ " variants: { [GEMMA.repo_id]: GEMMA_VARIANTS } })"
+ )
+ assert _loaded_paths(out) == [GEMMA_REPO]
+
+
+def test_a_provisional_mac_platform_does_not_hide_a_remote_backends_models():
+ """Before the probe lands chatOnly is a browser guess: a Mac browser on a
+ remote Linux Studio would hide every local safetensors model."""
+ safetensors = (
+ "{ ...LOCAL_GGUF, id: 'st', load_id: 'st', path: '/models/st',"
+ " model_format: 'safetensors' }"
+ )
+ out = _run(
+ f"scenario({{ chatOnly: true, deviceType: 'mac', platformFetched: false,"
+ f" localModels: [{safetensors}] }})"
+ )
+
+ assert _loaded_paths(out) == ["st"]
+ assert _downloads_started(out) == []
+
+
+def test_a_server_reported_chat_only_platform_still_gates():
+ """Control: once the backend has answered, the gate applies."""
+ safetensors = (
+ "{ ...LOCAL_GGUF, id: 'st', load_id: 'st', path: '/models/st',"
+ " model_format: 'safetensors' }"
+ )
+ out = _run(
+ f"scenario({{ chatOnly: true, platformFetched: true, localModels: [{safetensors}] }})"
+ )
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+
+
+def test_the_default_is_validated_before_its_download_starts():
+ """Active training or the GPU placement guard can refuse the default, and
+ learning that after several gigabytes costs a long wait for nothing."""
+ out = _run(
+ "scenario({ validate: () => ({ requires_trust_remote_code: false,"
+ " requires_security_review: false, requires_transformers_upgrade: true }) })"
+ )
+
+ assert _downloads_started(out) == []
+ assert _loaded_paths(out) == []
+ assert out["result"]["loaded"] is False
+
+
+def test_a_cleared_default_still_downloads_and_loads():
+ """Control: the preflight must not block the normal path."""
+ out = _run("scenario({})")
+ kinds = [event["kind"] for event in out["events"]]
+ assert kinds.index("download.start") < kinds.index("loadModel")
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+
+
+def test_a_chat_only_backend_skips_cached_non_gguf_rows():
+ """The picker hides cached non-GGUF rows outright in chat-only mode, so the
+ cascade must not auto-select a format the UI calls unrunnable."""
+ out = _run(
+ "scenario({ chatOnly: true, platformFetched: true,"
+ " modelRepos: [{ repo_id: 'org/st', load_id: 'org/st', size_bytes: 1 }] })"
+ )
+ assert "org/st" not in _loaded_paths(out)
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+
+
+def test_a_full_install_still_uses_cached_non_gguf_rows():
+ """Control for the gate above."""
+ out = _run(
+ "scenario({ chatOnly: false,"
+ " modelRepos: [{ repo_id: 'org/st', load_id: 'org/st', size_bytes: 1 }] })"
+ )
+ assert _loaded_paths(out) == ["org/st"]
+
+
+def test_a_provisional_platform_does_not_hide_cached_non_gguf_rows():
+ """Before the probe lands the chatOnly flag is a browser guess."""
+ out = _run(
+ "scenario({ chatOnly: true, platformFetched: false,"
+ " modelRepos: [{ repo_id: 'org/st', load_id: 'org/st', size_bytes: 1 }] })"
+ )
+ assert _loaded_paths(out) == ["org/st"]
+
+
+def test_a_cached_adapter_repo_is_never_auto_loaded():
+ """A cached LoRA has no weights of its own: /load fetches the base from the
+ Hub when it is not cached, which is why the local twin is dropped too.
+ Adapters are tiny, so the size order puts one first."""
+ out = _run(
+ "scenario({ modelRepos: [{ repo_id: 'org/lora', load_id: 'org/lora',"
+ " size_bytes: 40000000, model_format: 'adapter',"
+ " capabilities: { can_chat: true } }] })"
+ )
+
+ assert "org/lora" not in _loaded_paths(out)
+ # Nothing loadable on device, so the default download is the correct answer.
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+
+
+def test_a_cached_safetensors_repo_is_still_auto_loaded():
+ """Control for the gate above: only the adapter format is dropped."""
+ out = _run(
+ "scenario({ modelRepos: [{ repo_id: 'org/base', load_id: 'org/base',"
+ " size_bytes: 40000000, model_format: 'safetensors',"
+ " capabilities: { can_chat: true } }] })"
+ )
+
+ assert _loaded_paths(out) == ["org/base"]
+ assert _downloads_started(out) == []
+
+
[email protected]("broken", ["ggufRepos", "modelRepos"])
+def test_an_hf_cache_row_is_used_when_the_cached_lookup_fails(broken):
+ """/api/hub/local also reports hf_cache rows, which autoload normally skips
+ as duplicates. When a cached list fails they are the only evidence left, and
+ dropping them ended the send with no model at all, since the gap also blocks
+ the default."""
+ row = "{ ...LOCAL_GGUF, source: 'hf_cache' }"
+ out = _run(f"scenario({{ {broken}: 'throw', localModels: [{row}] }})")
+
+ assert _loaded_paths(out) == [LOCAL_GGUF_PATH]
+ assert _downloads_started(out) == []
+
+
+def test_an_hf_cache_row_stays_excluded_when_both_lookups_answer():
+ """Control: with the cached lists healthy the row is a duplicate of what they
+ already report, so autoload keeps skipping it."""
+ row = "{ ...LOCAL_GGUF, source: 'hf_cache' }"
+ out = _run(f"scenario({{ localModels: [{row}] }})")
+
+ assert LOCAL_GGUF_PATH not in _loaded_paths(out)
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+
+
+def test_an_admitted_hf_cache_row_is_not_attempted_twice():
+ """The surviving cached list may name the same model as the admitted
+ hf_cache row, so the load-target dedupe has to collapse them or the pair
+ spends two of the three attempts on one model."""
+ row = (
+ "{ ...LOCAL_GGUF, source: 'hf_cache', load_id: 'org/dup', path: 'org/dup', id: 'org/dup' }"
+ )
+ out = _run(
+ "scenario({ ggufRepos: 'throw',"
+ " modelRepos: [{ repo_id: 'org/dup', load_id: 'org/dup', size_bytes: 1 }],"
+ f" localModels: [{row}] }})"
+ )
+
+ assert _loaded_paths(out).count("org/dup") == 1
+ assert _downloads_started(out) == []
+
+
+def test_a_safetensors_twin_survives_a_gguf_row_with_no_loadable_quant():
+ """Dedupe keeps the GGUF row because the backend probes GGUF first, but when
+ that repo resolves no quant -- every variant big-endian, say -- the twin was
+ already discarded and a full inventory fell through to the default."""
+ out = _run(
+ "scenario({ ggufRepos: [{ ...GEMMA, repo_id: 'org/both', load_id: 'org/both' }],"
+ " variants: { 'org/both': [{ quant: 'Q4_K_M',"
+ " filename: 'gemma-4-26B-A4B-it-BE.Q4_K_M.gguf', downloaded: true,"
+ " size_bytes: 900000000 }] },"
+ " modelRepos: [{ repo_id: 'org/both', load_id: 'org/both', size_bytes: 2000000000 }] })"
+ )
+
+ assert _loaded_paths(out) == ["org/both"]
+ assert _downloads_started(out) == []
+
+
+def test_a_legacy_gguf_row_without_model_format_loads_as_gguf():
+ """model_format is optional, so an older backend omits it on a direct .gguf
+ row. The source builder did not fall back to the suffix, so the row became a
+ Transformers source: /load got the safetensors context length instead of 0
+ and the remembered kind was wrong."""
+ row = "{ ...LOCAL_GGUF, model_format: undefined }"
+ out = _run(f"scenario({{ localModels: [{row}] }})")
+
+ assert _loaded_paths(out) == [LOCAL_GGUF_PATH]
+ remembered = [e for e in out["events"] if e["kind"] == "recordLastLocal"]
+ assert remembered and remembered[0]["modelKind"] == "gguf", remembered
+
+
[email protected]("fmt", ["'unknown'", "undefined"])
+def test_an_unclassified_local_row_is_never_auto_loaded(fmt):
+ """The gate was a denylist, so a row the backend could not classify passed
+ it: "unknown" is what the backend sends when it cannot tell, and an older one
+ omits the field. Either way the row may be the pickle checkpoint the
+ exclusions exist to keep out, and a directory gives no suffix to tell them
+ apart, so this fails closed."""
+ row = f"{{ ...LOCAL_GGUF, id: 'x', load_id: '/models/x', path: '/models/x', model_format: {fmt} }}"
+ out = _run(f"scenario({{ localModels: [{row}] }})")
+
+ assert "/models/x" not in _loaded_paths(out)
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 49dffc7ac15..b9d9a8361af 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -88,8 +88,19 @@ def test_chat_autoload_toast_is_persistent_and_dismissible():
assert "toast.loading(" not in auto_load
assert "const updateAutoLoadToast =" in auto_load
assert "if (autoLoadToastDismissed) return;" in auto_load
- assert auto_load.count("toast.message(") == 2
- assert auto_load.count("updateAutoLoadToast(") >= 4
+ # Progress + the terminal "download stopped" notice; success/error use their
+ # own toast.success / toast.error helpers.
+ assert auto_load.count("toast.message(") == 3
+ # One progress toast re-titled through every phase: the cascade updates it
+ # directly, and the download keeps it live via the same updater.
+ assert auto_load.count("updateAutoLoadToast(") >= 2
+ assert (
+ "ensureDefaultModelDownloaded(\n hfToken,\n options?.abortSignal,\n updateAutoLoadToast,\n )"
+ in auto_load
+ )
+ download_helper = src.split("async function ensureDefaultModelDownloaded", 1)[1]
+ download_helper = download_helper.split("async function autoLoadSmallestModel", 1)[0]
+ assert download_helper.count("setToast(") >= 2
assert "duration: Number.POSITIVE_INFINITY" in auto_load
assert "closeButton: true" in auto_load
assert "icon: createLoadingToastIcon()" in auto_load
@@ -528,9 +539,13 @@ def test_chat_autoload_scopes_variant_lookup_to_cached_repo_path():
"""Autoload must probe the exact cache row it will load, including rows
retained from a previously selected Hugging Face cache."""
src = _read("features/chat/api/chat-adapter.ts")
- auto_load = src.split("async function autoLoadSmallestModel", 1)[1]
- assert auto_load.count("preferLocalCache: true") >= 2
- assert auto_load.count("localPath: repo.cache_path") >= 2
+ # Both cache-backed sources scan the exact path they will load from, not the
+ # bare repo id.
+ sources = src.split("function buildAutoLoadSources", 1)[1]
+ sources = sources.split("function isRememberedSource", 1)[0]
+ assert sources.count("preferLocalCache: true") == 2
+ assert "localPath: repo.cache_path" in sources
+ assert "localPath: row.path" in sources
# #7767 moved the query building out of chat-api into its own module, so the listing
# imports without the auth barrel. Both halves are pinned: the caller must still hand
@@ -1368,8 +1383,8 @@ def test_parallel_slots_control_cleared_when_the_load_never_sent_them():
assert "nParallel: null," in non_gguf_branch
assert "loadedNParallel: null," in non_gguf_branch
- fresh_default = adapter.split("No downloaded models found. Fetching", 1)[1].split(
- 'showAutoLoadSuccess("Loaded Qwen', 1
+ fresh_default = adapter.split("// Nothing on the device:", 1)[1].split(
+ "showAutoLoadSuccess(\n `Loaded ${DEFAULT_CHAT_MODEL_LABEL}", 1
)[0]
# The fresh-default download omits the slots, so its success state clears both,
# or the control reads as an unapplied edit against the seeded baseline.
@@ -2388,3 +2403,363 @@ def test_the_primary_action_keeps_its_four_labels():
for el in re.finditer(r"<Button\b.*?</Button>", page, re.S)
)
assert primary, "primaryActionLabel is no longer rendered inside the handleRun Button"
+
+
+def test_autoload_sees_every_on_device_inventory_and_fails_closed():
+ """#7374: Send downloaded a model over a loadable local one. The cascade read
+ only the two managed-cache lists, both wrapped in `.catch(() => [])`, so a
+ flaky request also read as "device is empty"."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ auto_load = src.split("async function autoLoadSmallestModel", 1)[1]
+ discovery = auto_load.split("for (const source of sources)", 1)[0]
+ # The backend-indexed on-device inventory is consulted, not just the cache.
+ assert "listLocalModels()" in discovery
+ assert "listCachedGguf(options?.abortSignal)" in discovery
+ assert "listCachedModels(hfToken, options?.abortSignal)" in discovery
+ # Fail closed: an inventory error must not read as an empty device.
+ assert "listCachedGguf().catch(" not in src
+ assert "listCachedModels().catch(" not in src
+ assert "listLocalModels().catch(" not in src
+
+
+def test_autoload_local_rows_follow_the_picker_policy():
+ """A background pick must be something the user could have picked, minus the
+ formats that must stay an explicit action."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ policy = src.split("function isAutoLoadableLocalRow", 1)[1]
+ policy = policy.split("\n}", 1)[0]
+ assert "AUTO_LOAD_LOCAL_SOURCES.has(row.source)" in policy
+ # Not `=== true`: normalizeCapabilities falls back to the format capability
+ # when the backend sends no can_chat, so the picker shows such a row while
+ # `=== true` skipped it and fell through to downloading the default.
+ assert "row.capabilities?.can_chat !== false" in policy
+ assert "row.partial !== true" in policy
+ # An adapter resolves its base model, a Hub fetch when that base is uncached;
+ # a scan-folder checkpoint is a pickle with no Hub security scan. Stated as
+ # an allowlist, which subsumes both: excluding them by name was only as good
+ # as the classification, and the backend sends "unknown" when it cannot tell.
+ # test_a_local_row_the_picker_would_hide_is_never_auto_loaded covers the
+ # behaviour.
+ assert '(isGgufLocalRow(row) || row.model_format === "safetensors")' in policy
+ assert "isHiddenModelId(row.model_id, row.id, row.path)" in policy
+
+ sources = src.split("const AUTO_LOAD_LOCAL_SOURCES", 1)[1].split("]", 1)[0]
+ assert '"models_dir"' in sources
+ assert '"lmstudio"' in sources
+ assert '"custom"' in sources
+ # hf_cache rows are the cached lists' job; ollama links are not loadable.
+ assert '"hf_cache"' not in sources
+ assert '"ollama"' not in sources
+
+
+def test_default_model_download_is_visible_and_cancellable():
+ """On a genuinely empty device Studio still fetches a model, but as a managed
+ download with progress and a Cancel, never an inline pull inside /load."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ helper = src.split("async function ensureDefaultModelDownloaded", 1)[1]
+ helper = helper.split("async function autoLoadSmallestModel", 1)[0]
+ assert "downloadManager.requestStart(request)" in helper
+ assert "downloadManager.cancel(" in helper
+ assert "subscribeJobListeners(" in helper
+ # The toast carries its own Cancel wired to the same job.
+ assert "cancelDownload," in helper
+ # Live byte progress, so the user is not staring at a static message.
+ assert "useDownloadManagerStore.subscribe(" in helper
+ # Already on disk from an earlier run: no download at all.
+ assert 'if (variant?.downloaded && variant.partial !== true) return "ready";' in helper
+ # The load only happens once the bytes are actually here.
+ assert "loadModel(" not in helper
+
+ auto_load = src.split("async function autoLoadSmallestModel", 1)[1]
+ fallback = auto_load.split("// Nothing on the device:", 1)[1]
+ assert 'if (download !== "ready") {' in fallback
+ # Cancelling leaves the user with actionable next steps, not a dead end.
+ assert "Pick one from the top bar" in fallback
+
+ updater = src.split("const updateAutoLoadToast =", 1)[1].split("\n };", 1)[0]
+ assert 'label: "Cancel"' in updater
+
+
+def test_default_chat_model_is_gemma_4_e2b():
+ """The empty-device default, in one place so it cannot drift."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ assert 'const DEFAULT_CHAT_MODEL_REPO = "unsloth/gemma-4-E2B-it-GGUF";' in src
+ assert 'const DEFAULT_CHAT_MODEL_VARIANT = "UD-Q4_K_XL";' in src
+ assert 'const DEFAULT_CHAT_MODEL_LABEL = "Gemma 4 E2B";' in src
+ # No hard-coded repo id or quant left anywhere on the send path.
+ assert "Qwen3.5-4B-MTP-GGUF" not in src
+ assert src.count('"UD-Q4_K_XL"') == 1
+
+
+def test_first_download_toast_is_informative_not_alarming():
+ """The old copy read as a warning about the user's machine ("No downloaded
+ models found") and named a raw repo/quant."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ assert "No downloaded models found" not in src
+ assert "Downloading a small model" not in src
+ helper = src.split("async function ensureDefaultModelDownloaded", 1)[1]
+ helper = helper.split("async function autoLoadSmallestModel", 1)[0]
+ assert "Getting ${DEFAULT_CHAT_MODEL_LABEL} ready" in helper
+ assert "Unsloth couldn\u2019t find an existing model." in helper
+ assert "You can stop the download or " in helper
+ assert "manage models later in the 'Model hub'" in helper
+
+
+def test_indexed_local_loads_are_remembered_without_bypassing_leases():
+ """A local model the user actually ran should be re-picked first, but a
+ native file-picker path must not be: reaching it needs a signed lease."""
+ runtime = _read("features/chat/hooks/use-chat-model-runtime.ts")
+ block = runtime.split("const indexedLocalPick =", 1)[1]
+ block = block.split("} catch (error) {", 1)[0]
+ assert 'selection.source === "local"' in block
+ assert "!nativePathToken &&" in block
+ assert "(indexedLocalPick || !isLocalModelPath(modelId))" in block
+
+ store = _read("features/chat/utils/last-local-model-load.ts")
+ # A cached Hub GGUF repo without a quant names no file; a local .gguf does.
+ assert 'input.kind === "gguf" && !ggufVariant && !isPathLikeId(id)' in store
+ # Identity only: no tokens, leases, or approvals are persisted.
+ assert "token" not in store.lower().replace("isPathLikeId", "")
+
+
+def test_autoload_skips_image_and_video_rows():
+ """The backend tags a row with a task only for image/video models, and the
+ picker routes those away on click. A background load has no routing step."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ tasks = src.split("const IMAGE_OR_VIDEO_TASKS", 1)[1].split("]", 1)[0]
+ assert '"text-to-image"' in tasks
+ assert '"text-to-video"' in tasks
+ assert '"image-diffusion-unsupported"' in tasks
+ policy = src.split("function isAutoLoadableLocalRow", 1)[1].split("\n}", 1)[0]
+ assert 'IMAGE_OR_VIDEO_TASKS.has(row.task ?? "")' in policy
+
+
+def test_remembered_matching_uses_the_same_case_rules_as_the_dedupe_key():
+ """Folding a POSIX path would mark two models differing only by case as
+ both being the remembered one."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ remembered = src.split("function isRememberedSource", 1)[1].split("\n}", 1)[0]
+ assert "normalizeTarget(remembered.id)" in remembered
+ assert "normalizeTarget(source.id)" in remembered
+ assert "normalizeTarget(source.loadId)" in remembered
+ assert ".toLowerCase()" not in remembered
+ key = src.split("function autoLoadSourceKey", 1)[1].split("\n}", 1)[0]
+ assert "normalizeTarget(source.loadId)" in key
+
+
+def test_cached_inventory_lookups_take_the_run_signal():
+ """Neither has a timeout of its own, unlike listLocalModels."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ assert "listCachedGguf(options?.abortSignal)" in src
+ assert "listCachedModels(hfToken, options?.abortSignal)" in src
+
+
+def test_download_cancel_survives_the_pending_start_window():
+ """cancel() no-ops on a key with no job, so a click during requestStart's
+ preflights is replayed once the job exists, and exactly once: cancelling
+ patches the job and wakes the subscription."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ helper = src.split("async function ensureDefaultModelDownloaded", 1)[1]
+ helper = helper.split("async function autoLoadSmallestModel", 1)[0]
+ assert "let cancelRequested = false;" in helper
+ assert "let cancelInFlight = false;" in helper
+ # In flight only: a failed cancel restores the job, so a later click retries.
+ assert 'if (cancelInFlight || active.state === "cancelling") return true;' in helper
+ assert "if (cancelRequested) {\n if (!cancelEverIssued) issueCancel();" in helper
+ assert 'if (cancelRequested && !issueCancel()) finish("cancelled");' in helper
+
+
+def test_a_failed_quant_is_marked_tried_so_the_repo_continues():
+ """One corrupt quant must not cost a repo that holds a valid one."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ cascade = src.split("for (const source of sources)", 1)[1]
+ cascade = cascade.split("// Nothing on the device:", 1)[0]
+ assert "while (!autoLoadCancelled && loadAttempts < MAX_AUTO_LOAD_ATTEMPTS)" in cascade
+ assert "skippedAutoLoadCandidates.add(" in cascade
+
+
+def test_local_safetensors_chat_capability_is_classified_not_assumed():
+ """An embedding export is config.json plus model.safetensors, which the
+ format-only rule marked chat-capable, and it is small enough to be tried
+ first."""
+ src = _read_backend("hub/services/models/common.py")
+ assert "def _local_transformers_can_chat(" in src
+ assert "can_chat_override" in src
+ call = src.split("adapter_type = adapter_type if model_format", 1)[1]
+ call = call.split("elif not rows:", 1)[0]
+ assert "_local_transformers_can_chat(scan_path)" in call
+ assert 'model_format in {"safetensors", "checkpoint"}' in call
+ # Fails open: an unfamiliar architecture must not be hidden.
+ classifier = src.split("def _local_transformers_can_chat(", 1)[1]
+ classifier = classifier.split("\ndef ", 1)[0]
+ assert classifier.rstrip().endswith("return None")
+
+
+def test_sources_dedupe_on_the_load_target_alone():
+ """A repo holding both GGUF and safetensors yields a row in each cached list,
+ but the backend resolves one target to one model, so keeping both spends a
+ second attempt on the same files. Skipped in the cascade rather than dropped
+ while ordering, because dropping the twin lost a loadable safetensors row
+ whenever its GGUF twin resolved no quant."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ key = src.split("function autoLoadSourceKey", 1)[1].split("\n}", 1)[0]
+ assert "return normalizeTarget(source.loadId);" in key
+ assert "source.kind" not in key
+ # Ordering keeps every row; the sort alone decides which twin is reached first.
+ order = src.split("function orderAutoLoadSources", 1)[1].split("\n}\n", 1)[0]
+ assert "[...sources].sort(" in order
+ assert "filter(" not in order
+ # The skip is keyed on a candidate having been resolved, not on merely visiting.
+ body = src.split("const candidateResolvedFor = new Set<string>();", 1)[1]
+ body = body.split("\n // Cap also gates", 1)[0]
+ assert body.index("if (candidateResolvedFor.has(sourceKey)) continue;") < body.index(
+ "candidateResolvedFor.add(sourceKey);"
+ )
+ assert "if (!candidate) break;\n candidateResolvedFor.add(sourceKey);" in body
+
+
+def test_variant_scans_take_the_run_signal():
+ src = _read("features/chat/api/chat-adapter.ts")
+ build = src.split("function buildAutoLoadSources", 1)[1]
+ build = build.split("function isRememberedSource", 1)[0]
+ assert build.count("signal,") == 2
+ assert "options?.abortSignal,\n )," in src
+
+
+def test_cached_rows_classify_chat_capability_too():
+ """The same encoder gate the scan-folder rows get; cached rows built their
+ capabilities from file format alone."""
+ src = _read_backend("hub/services/models/cache_inventory.py")
+ assert "_local_transformers_can_chat" in src
+ fields = src.split("def _cache_inventory_fields", 1)[1].split("\ndef ", 1)[0]
+ assert "can_chat_override" in fields
+ assert (
+ 'model_format in {"safetensors", "checkpoint"} and classify_snapshot is not None' in fields
+ )
+
+
+def test_every_load_target_comparison_uses_the_same_case_rules():
+ """Source dedupe, remembered matching, and tried-candidate keys all compare
+ load targets, so they must agree on POSIX case."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ for fn in ("autoLoadSourceKey", "isRememberedSource", "autoLoadCandidateKey"):
+ body = src.split(f"function {fn}(", 1)[1].split("\n}", 1)[0]
+ assert "normalizeTarget(" in body, fn
+ assert "id.toLowerCase()" not in body, fn
+
+
+def test_the_default_variant_lookup_takes_the_run_signal():
+ src = _read("features/chat/api/chat-adapter.ts")
+ helper = src.split("async function ensureDefaultModelDownloaded", 1)[1]
+ helper = helper.split("async function autoLoadSmallestModel", 1)[0]
+ assert (
+ "listGgufVariants(DEFAULT_CHAT_MODEL_REPO, undefined, {\n signal: abortSignal,\n })"
+ in helper
+ )
+ # The catch below swallows the abort rejection, so the guard after it is
+ # what actually stops the download from starting.
+ assert helper.index("} catch {") < helper.index("abortSignal?.throwIfAborted();")
+
+
+def test_cached_rows_get_the_same_image_and_video_gate_as_local_rows():
+ """Cached diffusion repos carry their task on the row and report can_chat
+ true on file format alone."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ cached = src.split("function isChattableCachedRepo", 1)[1].split("\n}\n", 1)[0]
+ assert 'IMAGE_OR_VIDEO_TASKS.has(repo.task ?? "")' in cached
+ local = src.split("function isAutoLoadableLocalRow", 1)[1].split("\n}", 1)[0]
+ assert 'IMAGE_OR_VIDEO_TASKS.has(row.task ?? "")' in local
+ # A chat GGUF is tagged text-generation, so the gate is a list, not "has a task".
+ tasks = src.split("const IMAGE_OR_VIDEO_TASKS", 1)[1].split("]", 1)[0]
+ assert '"text-generation"' not in tasks
+
+
+def test_the_default_download_prepares_the_token_first():
+ """startJob sends the stored token raw, with none of the recovery
+ validateModel and loadModel get."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ helper = src.split("async function ensureDefaultModelDownloaded", 1)[1]
+ helper = helper.split("async function autoLoadSmallestModel", 1)[0]
+ assert "prepareHfTokenForUse(hfToken)" in helper
+ assert 'if (!prepared.proceed) return "cancelled";' in helper
+ # After the on-disk check, so nothing prompts when there is no download,
+ # and before the managed start.
+ assert helper.index('return "ready"') < helper.index("prepareHfTokenForUse(hfToken)")
+ assert helper.index("prepareHfTokenForUse(hfToken)") < helper.index(
+ "downloadManager.requestStart(request)"
+ )
+
+
+def test_a_cancelled_download_is_never_handed_to_a_load():
+ """A cancel can fail and the transfer finish anyway."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ helper = src.split("async function ensureDefaultModelDownloaded", 1)[1]
+ helper = helper.split("async function autoLoadSmallestModel", 1)[0]
+ assert 'finish(cancelRequested ? "cancelled" : "ready")' in helper
+
+
+def test_cached_classification_reads_the_snapshot_the_row_loads():
+ """_scan_cached_models passes only `identity`, so snapshot_path alone
+ classified nothing and the gate was a no-op in production."""
+ src = _read_backend("hub/services/models/cache_inventory.py")
+ fields = src.split("def _cache_inventory_fields", 1)[1].split("\ndef ", 1)[0]
+ assert "classify_snapshot = identity.load_snapshot or snapshot_path" in fields
+ assert "_local_transformers_can_chat(classify_snapshot)" in fields
+ # The resolve must run before the classification reads it.
+ assert fields.index("identity = _resolve_load_identity(") < fields.index("classify_snapshot =")
+
+
+def test_non_chat_conditional_generation_is_excluded_before_the_suffix_check():
+ """Whisper ends in ForConditionalGeneration; the order decides the answer."""
+ src = _read_backend("hub/services/models/common.py")
+ classifier = src.split("def _local_transformers_can_chat(", 1)[1]
+ classifier = classifier.split("\ndef ", 1)[0]
+ assert classifier.index("_NON_CHAT_GENERATIVE_MODEL_TYPES") < classifier.index(
+ "_GENERATIVE_ARCHITECTURE_SUFFIXES"
+ )
+ assert '"whisper"' in src
+ # Real seq2seq and multimodal chat models must not be listed.
+ excluded = src.split("_NON_CHAT_GENERATIVE_ARCHITECTURES = frozenset(", 1)[1]
+ excluded = excluded.split(")", 1)[0]
+ assert "T5ForConditionalGeneration" not in excluded
+ assert "Gemma" not in excluded
+
+
+def test_format_gates_wait_for_the_server_reported_platform():
+ """The store's initial chatOnly is a browser guess: a Mac browser on a remote
+ Linux Studio would hide every local safetensors model."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ gate = src.split("function runsOnThisPlatform", 1)[1].split("\n}", 1)[0]
+ assert "if (!platform.fetched || !platform.isChatOnly()) return true;" in gate
+
+
+def test_the_default_is_preflighted_before_the_managed_download():
+ """A refusal from the training or placement guard must not cost gigabytes
+ first."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ fallback = src.split("// Nothing on the device:", 1)[1]
+ fallback = fallback.split("export function createOpenAIStreamAdapter", 1)[0]
+ assert fallback.index("canAutoLoad({") < fallback.index("ensureDefaultModelDownloaded(")
+ # One GPU snapshot feeds both, so the load sends what was cleared.
+ assert fallback.index("const rt = useChatRuntimeStore.getState();") < fallback.index(
+ "canAutoLoad({"
+ )
+
+
+def test_cached_non_gguf_rows_get_the_chat_only_platform_gate():
+ """The picker hides them outright there (visibleCachedModelRows)."""
+ src = _read("features/chat/api/chat-adapter.ts")
+ gate = src.split("function cachedModelsRunOnThisPlatform", 1)[1].split("\n}", 1)[0]
+ assert "return !platform.fetched || !platform.isChatOnly();" in gate
+ assert "cachedModelsRunOnThisPlatform()\n ? allModelRepos.filter(" in src
+ # GGUF runs everywhere, so those rows stay ungated.
+ assert "allGgufRepos.filter(isChattableCachedRepo)," in src
+
+
+def test_bare_vision_and_audio_backbones_are_classified_non_chat():
+ """A ViTModel name has no task suffix, so only the model type identifies it."""
+ src = _read_backend("hub/services/models/common.py")
+ encoders = src.split("_ENCODER_ONLY_MODEL_TYPES = frozenset(", 1)[1]
+ encoders = encoders.split(")", 1)[0]
+ for model_type in ('"vit"', '"dinov2"', '"swin"', '"wav2vec2"', '"resnet"'):
+ assert model_type in encoders, model_type