Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: show MTP companion download progress (#10243)
Lee Jackson1391fe6c96fe
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.ymlindex e3bc4a99084..b2281ed3543 100644--- a/.github/workflows/studio-ui-smoke.yml+++ b/.github/workflows/studio-ui-smoke.yml@@ -448,6 +448,20 @@ jobs:path: ~/.cache/ms-playwrightkey: ms-playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}-${{ matrix.engine_key }}-v2+ - name: Drive MTP companion download visibility+ if: matrix.shard == 'extra'+ env:+ PW_SIDE: AFTER+ PW_ART_DIR: logs/playwright_mtp+ run: |+ # A restored dist does not include the dependencies for the Vite fixture.+ if [ ! -x studio/frontend/node_modules/.bin/vite ]; then+ npm ci --prefix studio/frontend+ fi+ python -m pip install 'pillow>=10,<13'+ export PW_BACKEND_PYTHON="$HOME/.unsloth/studio/unsloth_studio/bin/python"+ python tests/studio/playwright_mtp_download_visibility.py+- name: Reset auth + boot Unslothif: matrix.shard == 'chat'run: |@@ -879,6 +893,7 @@ jobs:logs/install.loglogs/server-logs/logs/playwright+ logs/playwright_mtplogs/playwright-permissions-*logs/playwright_extralogs/playwright_mcp_argumentsdiff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.pyindex ce60b0b70b5..5f88a54afe9 100644--- a/studio/backend/hub/schemas/inventory.py+++ b/studio/backend/hub/schemas/inventory.py@@ -24,6 +24,17 @@ class GgufVariantDetail(BaseModel):)size_bytes: int = Field(0, description = "File size in bytes")download_size_bytes: int = Field(0, description = "Total bytes needed to download this variant")+ pending_drafter_filename: Optional[str] = Field(+ None,+ description = (+ "The sole missing MTP/DSpark/DFlash companion when the main GGUF and any "+ "vision projector are already cached. Lets the download UI name the artifact "+ "it is actually transferring instead of presenting it as the whole model."+ ),+ )+ pending_drafter_size_bytes: int = Field(+ 0, description = "Remote size of pending_drafter_filename"+ )shard_count: int = Field(0, description = "Part count for a complete canonical split GGUF")download_remaining_bytes: Optional[int] = Field(None,@@ -97,6 +108,10 @@ class GgufVariantsResponse(BaseModel):False,description = "Whether this answer came from resolving repo_id as a local path",)+ dependencies_resolved: bool = Field(+ False,+ description = "Whether Hub metadata was available to resolve the variant's required companion files",+ )loadable_variants: Optional[List[str]] = Field(None,description = (diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.pyindex b8a26168255..6524c1b7e56 100644--- a/studio/backend/hub/services/models/gguf_variants.py+++ b/studio/backend/hub/services/models/gguf_variants.py@@ -1426,8 +1426,7 @@ async def get_gguf_variants_answer(# Per-snapshot accounting: split GGUFs need every shard together, sizes are max across snapshots# so shared blobs are not double-counted, and keys are lowercased since cache casing can differ.- cached_filenames_by_snapshot: list[dict[str, int]] = []- cached_quant_bytes_by_snapshot: list[dict[str, int]] = []+ cached_snapshots: list[tuple[dict[str, int], dict[str, int]]] = []# A gated repo can list its files publicly, so reaching here is not authorization:# everything below reads the local caches, and would report `downloaded`, `partial`# and remaining bytes for the operator's copy to a caller the other paths refuse.@@ -1466,10 +1465,8 @@ async def get_gguf_variants_answer(continueq = q.lower()by_quant[q] = by_quant.get(q, 0) + size- if by_filename:- cached_filenames_by_snapshot.append(by_filename)- if by_quant:- cached_quant_bytes_by_snapshot.append(by_quant)+ if by_filename or by_quant:+ cached_snapshots.append((by_filename, by_quant))requirements_by_quant = {v.quant.lower(): _variant_requirement_cache_get(@@ -1486,54 +1483,134 @@ async def get_gguf_variants_answer(if requirements_by_quant.get(key) is None:requirements_by_quant[key] = fetched_requirements.get(key)- def _filenames_cached(filenames: frozenset[str], expected_size: int) -> bool:+ def _filenames_cached_in_snapshot(+ by_filename: dict[str, int], filenames: frozenset[str], expected_size: int+ ) -> bool:if not filenames:return Falsewanted = [name.lower() for name in filenames]+ cached = 0+ for name in wanted:+ size = by_filename.get(name)+ if size is None:+ return False+ cached += size+ return expected_size <= 0 or cached >= expected_size * 0.99++ def _filenames_cached(filenames: frozenset[str], expected_size: int) -> bool:# All files must live in a single snapshot, not spread across several.- for by_filename in cached_filenames_by_snapshot:- cached = 0- for name in wanted:- size = by_filename.get(name)- if size is None:- break- cached += size- else:- return expected_size <= 0 or cached >= expected_size * 0.99- return False+ return any(+ _filenames_cached_in_snapshot(by_filename, filenames, expected_size)+ for by_filename, _by_quant in cached_snapshots+ )def _any_mmproj_cached(filenames: frozenset[str]) -> bool:if any(by_filename.get(name.lower()) is not None- for by_filename in cached_filenames_by_snapshot+ for by_filename, _by_quant in cached_snapshotsfor name in filenames):return Truereturn any(_is_mmproj_filename(name.rsplit("/", 1)[-1])- for by_filename in cached_filenames_by_snapshot+ for by_filename, _by_quant in cached_snapshotsfor name in by_filename)- def _quant_bytes_present(quant: str, size_bytes: int) -> bool:- # Small rounding tolerance for symlinks vs real sizes.+ def _non_mmproj_companions(requirement: Optional[_GgufVariantRequirement]) -> tuple:+ if requirement is None:+ return ()+ return tuple(+ file+ for file in requirement.expected_files+ if _is_mtp_drafter_path(file.path) and not _is_mmproj_filename(file.path)+ )++ def _snapshot_has_companions(by_filename: dict[str, int], companions: tuple) -> bool:+ return all(+ _filenames_cached_in_snapshot(+ by_filename,+ frozenset({file.path}),+ max(0, int(file.size or 0)),+ )+ for file in companions+ )++ def _main_and_companions_ready(requirement: _GgufVariantRequirement) -> bool:+ companions = _non_mmproj_companions(requirement)+ return any(+ _filenames_cached_in_snapshot(+ by_filename,+ requirement.main_filenames,+ requirement.main_size_bytes,+ )+ and _snapshot_has_companions(by_filename, companions)+ for by_filename, _by_quant in cached_snapshots+ )++ def _quant_and_companions_ready(quant: str, size_bytes: int, companions: tuple) -> bool:if size_bytes <= 0:return Falsereturn any(by_quant.get(quant, 0) >= size_bytes * 0.99- for by_quant in cached_quant_bytes_by_snapshot+ and _snapshot_has_companions(by_filename, companions)+ for by_filename, by_quant in cached_snapshots)+ def _pending_drafter(requirement: Optional[_GgufVariantRequirement], quant: str):+ """Name one companion-only transfer without mislabelling a model pull."""+ if requirement is None:+ return None+ for by_filename, _by_quant in cached_snapshots:+ if not _filenames_cached_in_snapshot(+ by_filename, requirement.main_filenames, requirement.main_size_bytes+ ):+ continue+ missing = tuple(+ file+ for file in _non_mmproj_companions(requirement)+ if not _filenames_cached_in_snapshot(+ by_filename, frozenset({file.path}), max(0, int(file.size or 0))+ )+ )+ if len(missing) != 1:+ continue+ local_blobs = local_blobs_by_quant.get(quant.lower(), {})+ for expected in requirement.expected_files:+ if expected.path == missing[0].path:+ continue+ if not _filenames_cached_in_snapshot(+ by_filename, frozenset({expected.path}), expected.size+ ):+ break+ # Only subtract files the worker can reuse at the planned revision.+ identities = local_blobs.get(expected.path.replace("\\", "/"), set())+ if (+ expected.sha256+ and expected.sha256 not in identities+ and not _size_identity_matches(identities, expected.size)+ ):+ break+ else:+ return missing[0]+ return None+def _is_fully_downloaded(variant) -> bool:quant = variant.quant.lower()requirement = requirements_by_quant.get(quant)+ # The managed GGUF scope includes non-vision companions (MTP,+ # DSpark and DFlash) as well as the quant. A cached main file with a+ # newly-required drafter is loadable without speculation, but it is+ # not ready for the requested load: calling it downloaded makes the+ # picker bypass the manager and the loader fetches gigabytes inline+ # with no Downloads-panel row. Keep the existing any-precision+ # mmproj rule below; the loader can genuinely use any compatible+ # projector, while it selects one exact planned drafter.+ companions = _non_mmproj_companions(requirement)# Vision repos ship an mmproj adapter; any precision on disk suffices.if (requirement is not None- and _filenames_cached(- requirement.main_filenames,- requirement.main_size_bytes,- )+ and _main_and_companions_ready(requirement)and (not requirement.mmproj_filenamesor _any_mmproj_cached(requirement.mmproj_filenames)@@ -1542,7 +1619,7 @@ async def get_gguf_variants_answer(return True# Byte fallback so a present quant is not demoted by a filename mismatch; vision repos still need an# mmproj cached, at any precision.- if not _quant_bytes_present(quant, variant.size_bytes):+ if not _quant_and_companions_ready(quant, variant.size_bytes, companions):return Falseif (requirement is not None@@ -1661,6 +1738,7 @@ async def get_gguf_variants_answer(is_partial = v.quant in partial_quantsrequirement = requirements_by_quant.get(v.quant.lower())downloaded = _is_fully_downloaded(v) and not is_partial+ pending_drafter = _pending_drafter(requirement, v.quant)return GgufVariantDetail(filename = v.filename,quant = v.quant,@@ -1670,6 +1748,12 @@ async def get_gguf_variants_answer(download_size_bytes = (requirement.download_size_bytes if requirement is not None else v.size_bytes),+ pending_drafter_filename = (+ pending_drafter.path if pending_drafter is not None else None+ ),+ pending_drafter_size_bytes = (+ max(0, int(pending_drafter.size or 0)) if pending_drafter is not None else 0+ ),# Scanned per partial variant only: repos carry one, and the scan walks blobs/.download_remaining_bytes = (variant_remaining_bytes(repo_id, requirement, repo_cache_dir)@@ -1696,6 +1780,7 @@ async def get_gguf_variants_answer(variants = [_variant_detail(v) for v in variants],has_vision = has_vision,default_variant = default_variant,+ dependencies_resolved = siblings is not None,)def _compute_with_cleanables() -> VariantsAnswer:diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 62bfcd36b24..44b6e22da16 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -2616,6 +2616,68 @@ def test_gguf_variant_requirements_include_split_files_and_preferred_mmproj():)+def test_qwen38_flash_next_plan_includes_the_loaders_nested_mtp_choice():+ requirements = gguf_variants._build_gguf_variant_requirements(+ [+ _sibling("Qwen3.8-Flash-Next-UD-Q4_K_XL.gguf", 18_000, "main"),+ _sibling("MTP/mtp-Qwen3.8-Flash-Next-BF16.gguf", 7_700, "bf16"),+ _sibling("MTP/mtp-Qwen3.8-Flash-Next-Q8_0.gguf", 4_100, "q8"),+ _sibling("MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf", 2_600, "shared-q8"),+ # A real weight copy under MTP/ is hidden from the variant menu by the broad path+ # predicate, but the loader refuses it as a drafter because its basename is not published.+ _sibling("MTP/aaa-Q8_0.gguf", 900, "not-a-drafter"),+ ]+ )++ req = requirements["ud-q4_k_xl"]++ assert req.target_filenames == (+ "Qwen3.8-Flash-Next-UD-Q4_K_XL.gguf",+ "MTP/mtp-Qwen3.8-Flash-Next-Q8_0.gguf",+ )+ assert req.download_size_bytes == 22_100+ assert req.companion_hashes == frozenset({"q8"})+++def test_qwen38_flash_next_plan_skips_incomplete_preferred_mtp_family():+ requirements = gguf_variants._build_gguf_variant_requirements(+ [+ _sibling("Qwen3.8-Flash-Next-UD-Q4_K_XL.gguf", 18_000, "main"),+ # Q8_0 ranks first but cannot launch without shard 2. Planning must+ # select the complete BF16 fallback, as detect_mtp_file does.+ _sibling(+ "MTP/mtp-Qwen3.8-Flash-Next-Q8_0-00001-of-00002.gguf",+ 2_100,+ "q8-1",+ ),+ _sibling("MTP/mtp-Qwen3.8-Flash-Next-BF16.gguf", 7_700, "bf16"),+ ]+ )++ req = requirements["ud-q4_k_xl"]++ assert req.target_filenames == (+ "Qwen3.8-Flash-Next-UD-Q4_K_XL.gguf",+ "MTP/mtp-Qwen3.8-Flash-Next-BF16.gguf",+ )+ assert req.download_size_bytes == 25_700+ assert req.companion_hashes == frozenset({"bf16"})+++def test_qwen38_embedded_head_family_does_not_plan_its_nested_mtp_copy():+ requirements = gguf_variants._build_gguf_variant_requirements(+ [+ _sibling("Qwen3.8-27B-UD-Q4_K_XL.gguf", 18_000, "main"),+ _sibling("MTP/mtp-Qwen3.8-27B-Q4_0.gguf", 1_300, "nested"),+ ]+ )++ req = requirements["ud-q4_k_xl"]++ assert req.target_filenames == ("Qwen3.8-27B-UD-Q4_K_XL.gguf",)+ assert req.download_size_bytes == 18_000++def test_gguf_variant_requirements_skip_big_endian_sibling():requirements = gguf_variants._build_gguf_variant_requirements([@@ -4242,6 +4304,7 @@ def test_gguf_variants_partial_marker_overrides_size_only_downloaded(monkeypatchresult = asyncio.run(gguf_variants.get_gguf_variants_response("Org/PartialRepo"))+ assert result.dependencies_resolved is Falseassert result.variants[0].downloaded is Falseassert result.variants[0].partial is True@@ -4307,6 +4370,124 @@ def test_gguf_variants_scopes_partial_state_to_requested_cache(monkeypatch, tmp_assert result.variants[0].partial is False+ "cache_case",+ [+ "current",+ "partial-mtp",+ "alternate-projector",+ "stale-main",+ "planned-projector",+ "cross-snapshot",+ "undersized-mtp",+ ],+)+def test_cached_flash_next_quant_needs_managed_mtp_before_it_is_downloaded(+ monkeypatch, tmp_path, cache_case+):+ """A pre-MTP cache must enter the manager instead of downloading at load time."""+ with gguf_variants._VARIANT_HASH_LOCK:+ gguf_variants._VARIANT_REQUIREMENT_CACHE.clear()++ async def _run_inline(fn, *args, **kwargs):+ return fn(*args, **kwargs)++ repo_id = "unsloth/Qwen3.8-Flash-Next-GGUF"+ snapshot = (+ tmp_path / "cache" / "models--unsloth--Qwen3.8-Flash-Next-GGUF" / "snapshots" / "rev0"+ )+ snapshot.mkdir(parents = True)+ main_name = "Qwen3.8-Flash-Next-UD-Q4_K_XL.gguf"+ mtp_name = "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"+ (snapshot / main_name).write_bytes(b"m" * 100)+ siblings = [+ _sibling(main_name, 100, "main"),+ _sibling(mtp_name, 20, "mtp"),+ ]+ snapshots = [snapshot]+ if cache_case == "cross-snapshot":+ companion_snapshot = snapshot.parent / "rev1"+ companion = companion_snapshot / mtp_name+ companion.parent.mkdir(parents = True)+ companion.write_bytes(b"d" * 20)+ snapshots.append(companion_snapshot)+ elif cache_case == "undersized-mtp":+ companion = snapshot / mtp_name+ companion.parent.mkdir(parents = True)+ companion.write_bytes(b"d" * 10)+ local_blobs = {main_name: {"old-main" if cache_case == "stale-main" else "main"}}+ if cache_case in {"alternate-projector", "planned-projector"}:+ siblings.extend(+ [+ _sibling("mmproj-F16.gguf", 10, "projector-f16"),+ _sibling("mmproj-Q8_0.gguf", 8, "projector-q8"),+ ]+ )+ (snapshot / "mmproj-Q8_0.gguf").write_bytes(b"p" * 8)+ local_blobs["mmproj-Q8_0.gguf"] = {"projector-q8"}+ if cache_case == "planned-projector":+ (snapshot / "mmproj-F16.gguf").write_bytes(b"p" * 10)+ local_blobs["mmproj-F16.gguf"] = {"projector-f16"}+ monkeypatch.setattr(+ gguf_variants,+ "_local_main_gguf_blobs_by_quant",+ lambda *_args: {"ud-q4_k_xl": local_blobs},+ )+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")+ monkeypatch.setattr(gguf_variants.asyncio, "to_thread", _run_inline)+ monkeypatch.setattr(+ gguf_variants,+ "list_gguf_variants",+ lambda *_args, **_kwargs: (+ [+ SimpleNamespace(+ filename = main_name,+ quant = "UD-Q4_K_XL",+ display_label = None,+ size_bytes = 100,+ )+ ],+ False,+ siblings,+ ),+ )+ monkeypatch.setattr(+ gguf_variants,+ "iter_hf_cache_snapshots",+ lambda _repo_id, root = None: snapshots,+ )+ monkeypatch.setattr(+ gguf_variants.download_registry,+ "incomplete_blob_hashes",+ lambda *_args, **_kwargs: {"mtp"} if cache_case == "partial-mtp" else set(),+ )++ before = asyncio.run(gguf_variants.get_gguf_variants_response(repo_id))+ assert before.dependencies_resolved is True+ assert before.variants[0].downloaded is False+ assert before.variants[0].download_size_bytes == (130 if "projector" in cache_case else 120)+ assert before.variants[0].partial is (cache_case == "partial-mtp")+ if cache_case in {"alternate-projector", "stale-main"}:+ assert before.variants[0].pending_drafter_filename is None+ assert before.variants[0].pending_drafter_size_bytes == 0+ return+ assert before.variants[0].pending_drafter_filename == mtp_name+ assert before.variants[0].pending_drafter_size_bytes == 20++ companion = snapshot / mtp_name+ companion.parent.mkdir(exist_ok = True)+ companion.write_bytes(b"d" * 20)+ monkeypatch.setattr(+ gguf_variants.download_registry,+ "incomplete_blob_hashes",+ lambda *_args, **_kwargs: set(),+ )+ after = asyncio.run(gguf_variants.get_gguf_variants_response(repo_id))+ assert after.variants[0].downloaded is True+ assert after.variants[0].pending_drafter_filename is None+ assert after.variants[0].pending_drafter_size_bytes == 0++def test_download_registry_repo_keys_are_case_insensitive():registry = download_registry.DownloadRegistry()diff --git a/studio/backend/hub/utils/gguf_plan.py b/studio/backend/hub/utils/gguf_plan.pyindex 7daac80d60e..f7e3c3a6d8c 100644--- a/studio/backend/hub/utils/gguf_plan.py+++ b/studio/backend/hub/utils/gguf_plan.py@@ -3,6 +3,7 @@from __future__ import annotations+import refrom dataclasses import dataclassfrom typing import Optional, Sequence@@ -107,17 +108,97 @@ def preferred_mmproj_sibling(siblings: Sequence) -> Optional[object]:def preferred_mtp_sibling(siblings: Sequence) -> Optional[object]:- """The separate MTP drafter to fetch with every variant: the repo-root ``mtp-*.gguf`` copy unsloth ships for llama.cpp ``-hf`` auto-discovery (Gemma 4). Same pick as the loader's drafter resolution (root-level ``mtp-`` prefix, first in sort order) so download and load resolve the same file; the higher-precision ``MTP/`` subdir copies are for explicit selection and are not auto-fetched. None for repos with the head baked into the main GGUF (Qwen)."""+ """Choose the root MTP drafter used by normal llama.cpp discovery, or the loader-compatible nested sidecar required by Qwen3.8 Flash Next."""+ from utils.models.drafters import (+ is_published_drafter_filename,+ split_listing_is_complete,+ )++ gguf_names = [name for sibling in siblings if (name := _gguf_rfilename(sibling))]++ def _complete(name: str) -> bool:+ # Match detect_mtp_file's launchability gate. A half-published family+ # must step aside before preference ranking so a complete fallback can+ # be selected instead of making the plan omit MTP entirely.+ return split_listing_is_complete(gguf_names, name)+# Root-level only: the MTP/ subdir copies now share the mtp- prefix too.candidates = sorted((sfor s in siblings- if (name := _gguf_rfilename(s)) and "/" not in name and name.lower().startswith("mtp-")+ if (name := _gguf_rfilename(s))+ and "/" not in name+ and is_published_drafter_filename(name, kind = "mtp", allow_legacy_suffix = False)+ and _complete(name)),key = lambda s: getattr(s, "rfilename"),)- return candidates[0] if candidates else None+ if candidates:+ return candidates[0]++ # The remote planner cannot read an undownloaded GGUF header to prove+ # ``qwen4exp`` the way the loader can. This family token is part of every+ # main weight and every sidecar in the sole repo that needs the fallback,+ # and boundary matching keeps future names such as Flash-Next2 out.+ flash_next = any(+ re.search(r"(?:^|[/_-])qwen3\.8-flash-next(?:$|[/_.-])", name, re.IGNORECASE)+ for sibling in siblings+ if (name := _gguf_rfilename(sibling)) and not is_mtp_drafter_path(name)+ )+ if not flash_next:+ return None++ from utils.models.drafters.preference import mtp_preference_key++ nested = [+ sibling+ for sibling in siblings+ if (name := _gguf_rfilename(sibling))+ and "/" in name.replace("\\", "/")+ and is_mtp_drafter_path(name)+ and is_published_drafter_filename(name.replace("\\", "/").rsplit("/", 1)[-1], kind = "mtp")+ and _complete(name)+ ]+ return (+ min(nested, key = lambda sibling: mtp_preference_key(sibling.rfilename)) if nested else None+ )+++def mtp_plan_files(siblings: Sequence) -> tuple[ExpectedFile, ...]:+ """Every shard of the MTP sidecar selected by the loader-compatible preference rule."""+ from utils.models.drafters import (+ is_published_drafter_filename,+ split_listing_is_complete,+ )++ selected = preferred_mtp_sibling(siblings)+ selected_name = _gguf_rfilename(selected) if selected is not None else None+ if selected_name is None:+ return ()+ family = gguf_variant_family(selected_name)+ nested = "/" in selected_name.replace("\\", "/")+ files = tuple(+ sorted(+ (+ file+ for sibling in siblings+ if (name := _gguf_rfilename(sibling))+ and gguf_variant_family(name) == family+ and is_mtp_drafter_path(name)+ and is_published_drafter_filename(+ name.replace("\\", "/").rsplit("/", 1)[-1],+ kind = "mtp",+ allow_legacy_suffix = nested,+ )+ and (file := expected_file_from_sibling(sibling)) is not None+ ),+ key = lambda file: file.path,+ )+ )+ if not files or not split_listing_is_complete([file.path for file in files], selected_name):+ return ()+ return filesdef preferred_dflash_sibling(@@ -202,8 +283,7 @@ def build_gguf_variant_plans(siblings: Sequence) -> dict[str, GgufVariantPlan]:all_mmproj_hashes = frozenset(h for h in (sibling_sha256(s) for s in all_mmproj) if h)companion = preferred_mmproj_sibling(siblings)companion_expected = expected_file_from_sibling(companion) if companion is not None else None- mtp_sibling = preferred_mtp_sibling(siblings)- mtp_expected = expected_file_from_sibling(mtp_sibling) if mtp_sibling is not None else None+ mtp_expected = mtp_plan_files(siblings)common_companions_expected = (companion_expected,) if companion_expected is not None else ()for sibling in siblings:@@ -247,7 +327,7 @@ def build_gguf_variant_plans(siblings: Sequence) -> dict[str, GgufVariantPlan]:expected_files = (*main_expected,*common_companions_expected,- *((mtp_expected,) if mtp_expected is not None else ()),+ *mtp_expected,*dflash_expected,)plans[quant] = plan_from_expected_files(diff --git a/studio/backend/models/models.py b/studio/backend/models/models.pyindex ef6dca97e35..336347db21b 100644--- a/studio/backend/models/models.py+++ b/studio/backend/models/models.py@@ -161,6 +161,13 @@ class GgufVariantDetail(BaseModel):)size_bytes: int = Field(0, description = "File size in bytes")download_size_bytes: int = Field(0, description = "Total bytes needed to download this variant")+ # Mirrors hub.schemas.inventory.GgufVariantDetail; see display_label above.+ pending_drafter_filename: Optional[str] = Field(+ None, description = "Missing separate drafter when the main GGUF is already cached"+ )+ pending_drafter_size_bytes: int = Field(+ 0, description = "Remote size of pending_drafter_filename"+ )shard_count: int = Field(0, description = "Part count for a complete canonical split GGUF")downloaded: bool = Field(False, description = "Whether this variant is already in the local HF cache"@@ -202,6 +209,10 @@ class GgufVariantsResponse(BaseModel):False,description = "Whether this answer came from resolving repo_id as a local path",)+ dependencies_resolved: bool = Field(+ False,+ description = "Whether Hub metadata was available to resolve the variant's required companion files",+ )loadable_variants: Optional[List[str]] = Field(None,description = (diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 9fac18afea8..a0b0b660f1d 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -4480,6 +4480,10 @@ async def get_gguf_variants(download_size_bytes = int(getattr(v, "download_size_bytes", v.size_bytes) or v.size_bytes),+ pending_drafter_filename = getattr(v, "pending_drafter_filename", None),+ pending_drafter_size_bytes = int(+ getattr(v, "pending_drafter_size_bytes", 0) or 0+ ),downloaded = bool(v.downloaded),update_available = bool(getattr(v, "update_available", False)),partial = bool(getattr(v, "partial", False)),@@ -4495,6 +4499,7 @@ async def get_gguf_variants(else None),resolved_locally = bool(getattr(response, "resolved_locally", False)),+ dependencies_resolved = bool(getattr(response, "dependencies_resolved", False)),loadable_variants = getattr(response, "loadable_variants", None),loadable = getattr(response, "loadable", None),)diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex 285a23330bb..f93af1c7ba1 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -4144,6 +4144,7 @@ def test_gguf_variants_route_carries_local_resolution(monkeypatch, tmp_path):))assert result.resolved_locally is True+ assert result.dependencies_resolved is Falseassert [v.quant for v in result.variants] == ["Q4_K_M"]diff --git a/studio/backend/tests/test_mtp_drafter_companion.py b/studio/backend/tests/test_mtp_drafter_companion.pyindex f629ff48aba..87d8ea89e54 100644--- a/studio/backend/tests/test_mtp_drafter_companion.py+++ b/studio/backend/tests/test_mtp_drafter_companion.py@@ -176,6 +176,34 @@ def test_variant_plan_keeps_root_mtp_sidecar_until_metadata_is_available():assert plan.download_size_bytes == 4_600+def test_variant_plan_keeps_every_nested_mtp_shard_or_none():+ main = _sib("Qwen3.8-Flash-Next-Q4_K_M.gguf", 100, "main")+ first = _sib(+ "MTP/mtp-Qwen3.8-Flash-Next-Q8_0-00001-of-00002.gguf",+ 20,+ "mtp-1",+ )+ second = _sib(+ "MTP/mtp-Qwen3.8-Flash-Next-Q8_0-00002-of-00002.gguf",+ 20,+ "mtp-2",+ )++ complete = build_gguf_variant_plans([main, first, second])["q4_k_m"]+ assert complete.target_filenames == (+ "Qwen3.8-Flash-Next-Q4_K_M.gguf",+ "MTP/mtp-Qwen3.8-Flash-Next-Q8_0-00001-of-00002.gguf",+ "MTP/mtp-Qwen3.8-Flash-Next-Q8_0-00002-of-00002.gguf",+ )+ assert complete.companion_hashes == frozenset({"mtp-1", "mtp-2"})+ assert complete.download_size_bytes == 140++ incomplete = build_gguf_variant_plans([main, first])["q4_k_m"]+ assert incomplete.target_filenames == ("Qwen3.8-Flash-Next-Q4_K_M.gguf",)+ assert incomplete.companion_hashes == frozenset()+ assert incomplete.download_size_bytes == 100++def test_old_manifest_resume_reclassifies_drafter():# Pre-fix manifests could leak the drafter into a quant's expected# files; resume must classify it as a companion, not a main shard.diff --git a/studio/backend/utils/models/drafters/__init__.py b/studio/backend/utils/models/drafters/__init__.pyindex 3ca1840aae2..82b182671fc 100644--- a/studio/backend/utils/models/drafters/__init__.py+++ b/studio/backend/utils/models/drafters/__init__.py@@ -17,6 +17,7 @@ from utils.models.drafters.common import (split_listing_is_complete,_drafter_stem_rank,_drafter_total_size,+ is_published_drafter_filename,)from utils.models.drafters.preference import (dflash_precision_rank,@@ -40,6 +41,7 @@ __all__ = ["split_listing_is_complete","_drafter_stem_rank","_drafter_total_size",+ "is_published_drafter_filename","detect_dflash_file","dflash_budget_bytes","dflash_precision_rank",diff --git a/studio/backend/utils/models/drafters/common.py b/studio/backend/utils/models/drafters/common.pyindex 8ab22e31a8e..a94cef0aae5 100644--- a/studio/backend/utils/models/drafters/common.py+++ b/studio/backend/utils/models/drafters/common.py@@ -13,6 +13,20 @@ from typing import Iterable, Optional# model_config imports this module, so the naming helpers are pulled in per call rather than at import; they stay where they are because they are constants and pure functions shared with non-drafter code (gguf_variants, the auto download paths), so the GGUF naming rules keep one home.+def is_published_drafter_filename(+ name: str,+ *,+ kind: str,+ allow_legacy_suffix: bool = True,+) -> bool:+ """Whether *name* uses an allowed published sidecar form for this layout."""+ lower = Path(name).name.lower()+ if not lower.endswith(".gguf"):+ return False+ stem = re.sub(r"-[0-9]{5}-of-[0-9]{5}$", "", Path(lower).stem)+ return lower.startswith(f"{kind}-") or (allow_legacy_suffix and stem.endswith(f"-{kind}"))++def _drafter_pairing_stem(name: str, *, kind: str) -> str:"""The model family a drafter filename names, stripped of its own markers. Both published schemes are handled, ``<kind>-<model>`` and the older ``<model>-<KIND>``. The shard suffix sits outside the quant token, so it goes first or the anchored quant strip below cannot match. Full quant vocabulary, not a subset: K/IQ/UD/MXFP drafters pair too, and the optional bpw modifier goes with it, as _extract_quant_label does."""stem = Path(name).stem.lower()diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex f01bd265271..62c15bda804 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -2169,6 +2169,7 @@ from utils.models.drafters import ( # noqa: E402_drafter_total_size,detect_dflash_file,dspark_precision_rank,+ is_published_drafter_filename,)from utils.models.drafters import ( # noqa: E402dspark_preference_key as _drafters_dspark_preference_key,@@ -2265,8 +2266,7 @@ def detect_mtp_file(except OSError:continuefor f in entries:- name = f.name.lower()- if not (name.startswith("mtp-") and name.endswith(".gguf")):+ if not is_published_drafter_filename(f.name, kind = "mtp", allow_legacy_suffix = False):continueif not _matches_weight(f):continue@@ -2306,13 +2306,7 @@ def detect_mtp_file(# _is_mtp_drafter accepts everything under MTP/ by design (it excludes them from variant# menus). Too broad to include here: a weight copy would launch as --model-draft. Require# a published drafter name: mtp-<model> or <model>-MTP.- lower = f.name.lower()- if not lower.endswith(".gguf"):- continue- # Drop the shard suffix first: an old-scheme split copy is named- # <model>-Q8_0-MTP-00001-of-00002.gguf, whose stem does not end in -mtp.- stem = re.sub(r"-[0-9]{5}-of-[0-9]{5}$", "", Path(lower).stem)- if not (lower.startswith("mtp-") or stem.endswith("-mtp")):+ if not is_published_drafter_filename(f.name, kind = "mtp"):continueif not _matches_weight(f):continuediff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex c2466dc5a48..ded99595905 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -2896,6 +2896,7 @@ export function ChatPage({repoId: selection.id,variant: selection.ggufVariant ?? null,expectedBytes: selection.expectedBytes ?? 0,+ presentation: selection.downloadPresentation,// Handed over, not raised here, so one start makes one toast.callerToast: {title: "Downloading in the background",@@ -3022,6 +3023,7 @@ export function ChatPage({repoId: pending.selection.id,variant: pending.selection.ggufVariant ?? null,expectedBytes: pending.selection.expectedBytes ?? 0,+ presentation: pending.selection.downloadPresentation,// Notice-only: #9663 removed this surface's own toast, so it must not return on an HTTP start or// once the three notices are spent.callerToast: {@@ -3364,6 +3366,7 @@ export function ChatPage({ggufVariant: meta?.ggufVariant,isDownloaded: meta?.isDownloaded || isSameLoadedModel,expectedBytes: meta?.expectedBytes,+ downloadPresentation: meta?.downloadPresentation,isGguf: meta?.isGguf,isDiffusion: meta?.isDiffusion,config: meta?.config,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.tsindex 04a2ec3905c..e8333b2d8dd 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@@ -156,6 +156,11 @@ export type SelectedModelInput = {loadingDescription?: string;isDownloaded?: boolean;expectedBytes?: number;+ downloadPresentation?: {+ label: string;+ filename: string;+ expectedBytes: number;+ };forceReload?: boolean;nativePathToken?: string;nativePathExpiresAtMs?: number | null;diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 89f520d44fd..f3b1c5e2925 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -159,6 +159,9 @@ export interface GgufVariantDetail {display_label?: string | null;size_bytes: number;download_size_bytes?: number;+ /** The only missing artifact when the main GGUF is already cached. */+ pending_drafter_filename?: string | null;+ pending_drafter_size_bytes?: number;shard_count?: number;downloaded?: boolean;update_available?: boolean;@@ -175,6 +178,8 @@ export interface GgufVariantsResponse {variants: GgufVariantDetail[];has_vision: boolean;default_variant: string | null;+ /** True only when Hub metadata resolved every required companion. */+ dependencies_resolved?: boolean;/** Native max context from GGUF metadata; present once a variant is downloaded. */context_length?: number | null;}diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsxindex 42e38e9d952..d8c9f5b4376 100644--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx@@ -51,6 +51,7 @@ import {} from "react";import {downloadManager,+ pendingDrafterPresentation,useDownloadManagerStore,useHttpPartialsResumable,useRepoDownload,@@ -754,6 +755,7 @@ export function GgufDownloadCard({const selectedLiveState = selectedQuant? liveVariantStates.get(normalizeGgufVariantIdentity(selectedQuant)): undefined;+ const selectedPresentation = pendingDrafterPresentation(selected);const selectedLiveActive = activeDownloadState(selectedLiveState?.state);const downloadingThisVariant =progress !== null && ggufVariantsMatch(progress.variant, selectedQuant);@@ -803,6 +805,7 @@ export function GgufDownloadCard({job,variant: selectedQuant,expectedBytes: selected?.download_size_bytes ?? selected?.size_bytes ?? 0,+ presentation: selectedPresentation,downloading: downloadingThisVariant,cancelling,disabled: cancelling@@ -866,12 +869,14 @@ export function GgufDownloadCard({updateTargetVariant?.download_size_bytes ??updateTargetVariant?.size_bytes ??0;+ const presentation = pendingDrafterPresentation(updateTargetVariant);setUpdateTarget(null);void downloadManager.requestStart({kind: "model",repoId,variant,expectedBytes,+ ...(presentation ? { presentation } : {}),});}, [updateTarget, updateTargetVariant, repoId]);const variantListUnavailable = !sortedVariants || sortedVariants.length === 0;diff --git a/studio/frontend/src/features/hub/catalog/use-download-card-state.ts b/studio/frontend/src/features/hub/catalog/use-download-card-state.tsindex b10998da8b3..65baf782861 100644--- a/studio/frontend/src/features/hub/catalog/use-download-card-state.ts+++ b/studio/frontend/src/features/hub/catalog/use-download-card-state.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-import type { DownloadJob } from "../download-manager";+import type { DownloadJob, DownloadPresentation } from "../download-manager";import { useCallback, useEffect, useRef, useState } from "react";import type { DownloadStopMode } from "./download-cancel-indicator";@@ -71,6 +71,7 @@ export function useDownloadCardState({job,variant,expectedBytes,+ presentation,downloading,cancelling = job.cancelling,disabled,@@ -82,6 +83,7 @@ export function useDownloadCardState({job: DownloadJob;variant: string | null;expectedBytes: number;+ presentation?: DownloadPresentation;downloading: boolean;cancelling?: boolean;disabled: boolean;@@ -117,15 +119,18 @@ export function useDownloadCardState({return;}setStarting(true);- void job.requestStartDownload(variant, expectedBytes).finally(() => {- if (mountedRef.current) setStarting(false);- });+ void job+ .requestStartDownload(variant, expectedBytes, presentation)+ .finally(() => {+ if (mountedRef.current) setStarting(false);+ });}, [cancelling,disabled,downloading,expectedBytes,job,+ presentation,starting,variant,]);diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts b/studio/frontend/src/features/hub/download-manager/download-manager-controller.tsindex 172aee678ac..b0ce05aae6d 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-controller.ts@@ -35,6 +35,7 @@ export {useDownloadManagerStore,} from "./download-manager-state";export type {+ DownloadPresentation,DownloadRequest,JobListeners,ManagedDownload,diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsxindex 2a3bb0e6885..79fd93027b4 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx+++ b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx@@ -26,6 +26,7 @@ import {useDownloadManagerStore,} from "./download-manager-controller";import { DownloadProgressBar } from "./download-progress-bar";+import { presentedProgress } from "./download-presentation";function createOrderedJobKeysSelector(): (state: {jobs: Record<string, ManagedDownload>;@@ -115,12 +116,15 @@ function DownloadRow({ jobKey }: { jobKey: string }) {job.state === "complete" ||job.state === "cancelled" ||job.state === "error";+ const progress = presentedProgress(job);return (<li className="flex flex-col gap-1.5 py-2.5 pl-4 pr-3"><div className="flex items-center gap-2"><span className="min-w-0 flex-1 truncate text-ui-12p5 font-medium text-foreground">- {job.repoId}- <span className="text-muted-foreground">{variantSuffix(job)}</span>+ {job.presentation?.label ?? job.repoId}+ <span className="text-muted-foreground">+ {job.presentation ? ` · ${job.repoId}` : variantSuffix(job)}+ </span></span>{job.state === "complete" && (<HugeiconsIcon@@ -164,13 +168,14 @@ function DownloadRow({ jobKey }: { jobKey: string }) {</TooltipContent></Tooltip></div>+ {job.presentation ? (+ <div className="truncate text-ui-10p5 text-muted-foreground">+ {job.presentation.filename}+ </div>+ ) : null}{active ? (<DownloadProgressBar- progress={{- expectedBytes: job.expectedBytes,- downloadedBytes: job.downloadedBytes,- fraction: job.fraction,- }}+ progress={progress}bytesPerSec={job.bytesPerSec}cancelling={job.state === "cancelling"}etaSeconds={job.etaSeconds}diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts b/studio/frontend/src/features/hub/download-manager/download-manager-state.tsindex 30d6dc6b57d..5f03885643a 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts@@ -31,6 +31,7 @@ import {downloadInventoryHintKind,scopedDownloadInventoryKind,} from "./download-manager-types";+import { presentationForExpectedBytesUpdate } from "./download-presentation";import {clearRuntimeTimer,pruneSuppressedCompletedInventoryHints as pruneRuntimeSuppressedHints,@@ -56,6 +57,35 @@ function nonNegativeNumber(value: unknown, fallback = 0): number {return Math.max(0, finiteNumber(value, fallback));}+function presentationOfPersisted(value: Record<string, unknown>) {+ if (!isRecord(value.presentation)) return {};+ const { label, filename, expectedBytes, cachedPlanPrefixBytes } =+ value.presentation;+ if (+ typeof label !== "string" ||+ !label.trim() ||+ typeof filename !== "string" ||+ !filename.trim() ||+ typeof expectedBytes !== "number" ||+ !Number.isFinite(expectedBytes) ||+ expectedBytes <= 0+ ) {+ return {};+ }+ return {+ presentation: {+ label: label.trim(),+ filename: filename.trim(),+ expectedBytes,+ ...(typeof cachedPlanPrefixBytes === "number" &&+ Number.isFinite(cachedPlanPrefixBytes) &&+ cachedPlanPrefixBytes >= 0+ ? { cachedPlanPrefixBytes }+ : {}),+ },+ };+}+/*** Inventory kind of a persisted job. Records written before the field carry `scopedFiles`, the same evidence* `startJob` classifies a fresh scoped request from: without it a scoped GGUF download comes back as a model@@ -105,6 +135,7 @@ function sanitizePersistedJob(completedBytes: nonNegativeNumber(value.completedBytes),completeOnDisk: false,expectedBytes: nonNegativeNumber(value.expectedBytes),+ ...presentationOfPersisted(value),fraction: Math.min(Math.max(finiteNumber(value.fraction, 0), 0), 1),bytesPerSec: 0,etaSeconds: 0,@@ -167,6 +198,9 @@ function toPersistedJob(downloadedBytes: job.downloadedBytes,completedBytes: job.completedBytes,expectedBytes: job.expectedBytes,+ ...(job.presentation !== undefined+ ? { presentation: job.presentation }+ : {}),fraction: job.fraction,error: job.error,startedAt: job.startedAt,@@ -657,6 +691,11 @@ export function setExpectedBytesForJob(if (!job || job.state !== "running" || bytes <= job.expectedBytes) return;patchJob(job.key, {expectedBytes: bytes,+ presentation: presentationForExpectedBytesUpdate(+ job.presentation,+ job.expectedBytes,+ bytes,+ ),// Measured against the old, smaller total, so wrong the moment the total grows.etaSeconds: 0,fraction:diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.tsindex 51de5eaa535..7dc820ef044 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts@@ -22,6 +22,10 @@ export interface ManagedDownload {completedBytes: number;completeOnDisk: boolean;expectedBytes: number;+ /** Optional display scope when an atomic model plan is transferring only one+ * missing companion. Counters remain plan-wide; the panel subtracts the+ * already-cached prefix for an honest artifact-sized progress bar. */+ presentation?: DownloadPresentation;fraction: number;bytesPerSec: number;etaSeconds: number;@@ -45,12 +49,22 @@ export interface DownloadRequest {variant: string | null;inventoryKind?: Exclude<InventoryHint["kind"], "dataset">;expectedBytes: number;+ presentation?: DownloadPresentation;scopeId?: string | null;files?: string[];checkpoint?: boolean;callerToast?: CallerToast;}+export interface DownloadPresentation {+ label: string;+ filename: string;+ expectedBytes: number;+ /** Plan bytes already present before this sole artifact starts. Frozen when+ * the presentation is attached, because later metadata may grow the plan. */+ cachedPlanPrefixBytes?: number;+}+export interface CallerToast {title: string;description: string;diff --git a/studio/frontend/src/features/hub/download-manager/download-presentation.ts b/studio/frontend/src/features/hub/download-manager/download-presentation.tsnew file mode 100644index 00000000000..027e62461e6--- /dev/null+++ b/studio/frontend/src/features/hub/download-manager/download-presentation.ts@@ -0,0 +1,109 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { GgufVariantDetail } from "../inventory";+import type {+ DownloadPresentation,+ ManagedDownload,+} from "./download-manager-types";++/** Describe a sole missing drafter as the transfer, not as the cached model. */+export function pendingDrafterPresentation(+ variant: GgufVariantDetail | null | undefined,+): DownloadPresentation | undefined {+ const filename = variant?.pending_drafter_filename?.trim();+ const expectedBytes = variant?.pending_drafter_size_bytes ?? 0;+ if (!filename || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {+ return undefined;+ }+ const basename = filename.replaceAll("\\", "/").split("/").at(-1) ?? filename;+ const lower = basename.toLowerCase();+ const label = lower.startsWith("mtp-")+ ? "MTP companion"+ : lower.startsWith("dspark-") || lower.startsWith("dflash-")+ ? "Draft companion"+ : "Model companion";+ return { label, filename: basename, expectedBytes };+}++export function stabilizeDownloadPresentation(+ presentation: DownloadPresentation | undefined,+ planExpectedBytes: number,+): DownloadPresentation | undefined {+ if (+ !presentation ||+ presentation.cachedPlanPrefixBytes !== undefined ||+ !Number.isFinite(planExpectedBytes) ||+ planExpectedBytes < presentation.expectedBytes+ ) {+ return presentation;+ }+ return {+ ...presentation,+ cachedPlanPrefixBytes: Math.max(+ 0,+ planExpectedBytes - presentation.expectedBytes,+ ),+ };+}++/** A backend-active adoption has no UI metadata, so retain the persisted scope. */+export function presentationForJobStart(+ requested: DownloadPresentation | undefined,+ existing: DownloadPresentation | undefined,+ planExpectedBytes: number,+ adopt: boolean,+): DownloadPresentation | undefined {+ return stabilizeDownloadPresentation(+ requested ?? (adopt ? existing : undefined),+ planExpectedBytes,+ );+}++export function presentationForExpectedBytesUpdate(+ presentation: DownloadPresentation | undefined,+ previousPlanExpectedBytes: number,+ nextPlanExpectedBytes: number,+): DownloadPresentation | undefined {+ if (!presentation || presentation.cachedPlanPrefixBytes !== undefined) {+ return presentation;+ }+ const planExpectedBytes =+ previousPlanExpectedBytes >= presentation.expectedBytes+ ? previousPlanExpectedBytes+ : nextPlanExpectedBytes;+ return stabilizeDownloadPresentation(presentation, planExpectedBytes);+}++/** Project plan-wide cache counters onto the sole artifact still transferring. */+export function presentedProgress(+ job: Pick<+ ManagedDownload,+ "downloadedBytes" | "expectedBytes" | "fraction" | "presentation"+ >,+) {+ const presentation = job.presentation;+ if (!presentation) {+ return {+ expectedBytes: job.expectedBytes,+ downloadedBytes: job.downloadedBytes,+ fraction: job.fraction,+ };+ }+ const expectedBytes = presentation.expectedBytes;+ const cachedPlanPrefix =+ job.expectedBytes <= expectedBytes+ ? 0+ : (presentation.cachedPlanPrefixBytes ??+ Math.max(0, job.expectedBytes - expectedBytes));+ const downloadedBytes = Math.min(+ expectedBytes,+ Math.max(0, job.downloadedBytes - cachedPlanPrefix),+ );+ return {+ expectedBytes,+ downloadedBytes,+ fraction:+ expectedBytes > 0 ? downloadedBytes / expectedBytes : job.fraction,+ };+}diff --git a/studio/frontend/src/features/hub/download-manager/hydration.ts b/studio/frontend/src/features/hub/download-manager/hydration.tsindex e1c363088ce..a685bd25436 100644--- a/studio/frontend/src/features/hub/download-manager/hydration.ts+++ b/studio/frontend/src/features/hub/download-manager/hydration.ts@@ -298,6 +298,7 @@ export function hydrateDownloadManager(): void {...(job.inventoryKind ? { inventoryKind: job.inventoryKind } : {}),...(job.scopedFiles ? { files: job.scopedFiles } : {}),...(job.checkpoint !== undefined ? { checkpoint: job.checkpoint } : {}),+ ...(job.presentation ? { presentation: job.presentation } : {}),expectedBytes: job.expectedBytes,};void probeHydratedJob(job.key, req, 0);diff --git a/studio/frontend/src/features/hub/download-manager/index.ts b/studio/frontend/src/features/hub/download-manager/index.tsindex 23bf012005e..32eee34ab9c 100644--- a/studio/frontend/src/features/hub/download-manager/index.ts+++ b/studio/frontend/src/features/hub/download-manager/index.ts@@ -34,6 +34,7 @@ export {subscribeJobListeners,useDownloadManagerStore,type DownloadManagerController,+ type DownloadPresentation,type DownloadRequest,type JobListeners,type ManagedDownload,@@ -52,6 +53,10 @@ export {downloadInventoryHintKind,scopedVariant,} from "./download-manager-types";+export {+ pendingDrafterPresentation,+ presentedProgress,+} from "./download-presentation";export {dismissStartToast,dismissStartToasts,diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex 331b3f302ac..35cf59a3f3e 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -101,6 +101,10 @@ import {hasObservedExpectedBytes,resolveProgressUpdate,} from "./progress-reconcile";+import {+ presentationForExpectedBytesUpdate,+ presentationForJobStart,+} from "./download-presentation";import {clearWatchdog,runtimeRegistry,@@ -184,6 +188,11 @@ export function applyProgressUpdate(const resolved = resolveProgressUpdate(job, progressResp);patchJob(key, {expectedBytes: resolved.expected,+ presentation: presentationForExpectedBytesUpdate(+ job.presentation,+ job.expectedBytes,+ resolved.expected,+ ),downloadedBytes: resolved.downloadedBytes,measuredTransfer: resolved.measuredTransfer,completedBytes: resolved.completedBytes,@@ -647,7 +656,15 @@ export async function startJob(runtimeRegistry.runtimes.set(key, rt);const epoch = rt.epoch;- const expected = Math.max(existing?.expectedBytes ?? 0, req.expectedBytes);+ const carryOverSeed = carriesOverSeed(+ opts.adopt === true,+ existing?.serverGeneration,+ opts.generation,+ );+ const expected = Math.max(+ carryOverSeed ? (existing?.expectedBytes ?? 0) : 0,+ req.expectedBytes,+ );const hfToken = getHfToken() || null;// Carry the stored preference UNRESOLVED so "auto" survives to effectiveTransportMode(); collapsing it to a boolean sends every download over HTTP.// Never awaited for an adopted job: suspending here let a concurrent adoptJob replace this runtime, leaving duplicate timers and a leaked listener.@@ -667,11 +684,6 @@ export async function startJob(teardownRuntime(key);throw error;}- const carryOverSeed = carriesOverSeed(- opts.adopt === true,- existing?.serverGeneration,- opts.generation,- );const seedDownloaded = carryOverSeed ? (existing?.downloadedBytes ?? 0) : 0;const seedCompleted = carryOverSeed ? (existing?.completedBytes ?? 0) : 0;const seedFraction = carryOverSeed ? (existing?.fraction ?? 0) : 0;@@ -694,6 +706,12 @@ export async function startJob(: { transport: mode, cancelTransport: undefined };const activeTransport = adopted.transport;const inventoryKind = downloadRequestInventoryKind(req);+ const presentation = presentationForJobStart(+ req.presentation,+ existing?.presentation,+ expected,+ carryOverSeed,+ );if (!opts.adopt && hasActiveRepoPeer(req.kind, req.repoId, key, req.variant)) {teardownRuntime(key);return;@@ -709,6 +727,7 @@ export async function startJob(completedBytes: seedCompleted,completeOnDisk: false,expectedBytes: expected,+ ...(presentation ? { presentation } : {}),fraction: seedFraction,bytesPerSec: 0,error: null,diff --git a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts b/studio/frontend/src/features/hub/download-manager/use-repo-download.tsindex 94badc84134..22b8ff83501 100644--- a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts+++ b/studio/frontend/src/features/hub/download-manager/use-repo-download.ts@@ -8,6 +8,7 @@ import type { ResolvedTransport } from "./constants";import type { TransportConflictInfo } from "./types";import {type DownloadKind,+ type DownloadRequest,type JobListeners,downloadManager,jobKeyOf,@@ -39,6 +40,7 @@ export interface DownloadJob {requestStartDownload: (variant: string | null,expectedBytes: number,+ presentation?: DownloadRequest["presentation"],) => Promise<void>;cancelDownload: (variant: string | null) => void;setExpectedBytes: (bytes: number, variant?: string | null) => void;@@ -161,7 +163,11 @@ export function useRepoDownload(config: RepoDownloadConfig): DownloadJob {);const requestStartDownload = useCallback(- async (variant: string | null, expectedBytes: number) => {+ async (+ variant: string | null,+ expectedBytes: number,+ presentation?: DownloadRequest["presentation"],+ ) => {// This surface renders the conflict resolver (transportConflict), so the// start outcome is handled by the card UI; the awaited result is ignored.await downloadManager.requestStart({@@ -169,6 +175,7 @@ export function useRepoDownload(config: RepoDownloadConfig): DownloadJob {repoId,variant,expectedBytes,+ ...(presentation ? { presentation } : {}),});},[kind, repoId],diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.tsindex 70e557c2c59..e445f79ad84 100644--- a/studio/frontend/src/features/hub/index.ts+++ b/studio/frontend/src/features/hub/index.ts@@ -6,6 +6,7 @@ export {downloadManager,finishExternalJob,jobKeyOf,+ pendingDrafterPresentation,startExternalJob,subscribeJobListeners,type TransportMode,diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.tsindex 2a12c85c637..4cf8ee38965 100644--- a/studio/frontend/src/features/hub/inventory/api.ts+++ b/studio/frontend/src/features/hub/inventory/api.ts@@ -182,6 +182,9 @@ export interface GgufVariantDetail {display_label?: string | null;size_bytes: number;download_size_bytes?: number;+ /** The only missing artifact when the main GGUF is already cached. */+ pending_drafter_filename?: string | null;+ pending_drafter_size_bytes?: number;shard_count?: number;/** Bytes a resume still has to fetch. Set only on a partial variant. */download_remaining_bytes?: number | null;@@ -201,6 +204,8 @@ export interface GgufVariantsResponse {variants: GgufVariantDetail[];has_vision: boolean;default_variant: string | null;+ /** True only when Hub metadata resolved every required companion. */+ dependencies_resolved?: boolean;}async function parseJsonOrThrow<T>(diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex 3170cd9b91a..b16d5f4288a 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -62,6 +62,7 @@ import {useDownloadManagerStore,useHfTokenStore,useOnlineStatus,+ pendingDrafterPresentation,} from "@/features/hub";import type { HfTaskFilter } from "@/features/hub/hooks/use-hub-model-search";import {@@ -203,6 +204,7 @@ import {soleQuantFingerprint,soleQuantKey,takeDriftedRepos,+ verifiedSoleHubVariant,} from "./sole-quant-cache";import type {DeletedModelRef,@@ -1314,6 +1316,13 @@ function isValidGgufVariant(variant: unknown): variant is GgufVariantDetail {candidate.shard_count >= 0)) &&(candidate.downloaded === undefined ||typeof candidate.downloaded === "boolean") &&+ (candidate.pending_drafter_filename === undefined ||+ candidate.pending_drafter_filename === null ||+ typeof candidate.pending_drafter_filename === "string") &&+ (candidate.pending_drafter_size_bytes === undefined ||+ (typeof candidate.pending_drafter_size_bytes === "number" &&+ Number.isFinite(candidate.pending_drafter_size_bytes) &&+ candidate.pending_drafter_size_bytes >= 0)) &&// Carried through so each row can look up its own dependency group's footprint. Absent on an// older backend, which groups the repo as one, so it must never reject the row.(candidate.dependency_key === undefined ||@@ -1330,6 +1339,7 @@ function normalizeGgufVariantsResponse(has_vision?: unknown;context_length?: unknown;resolved_locally?: unknown;+ dependencies_resolved?: unknown;}| null| undefined,@@ -1339,6 +1349,7 @@ function normalizeGgufVariantsResponse(hasVision: boolean;contextLength: number | null;resolvedLocally: boolean;+ dependenciesResolved: boolean;} {const contextLength = res?.context_length;return {@@ -1359,6 +1370,9 @@ function normalizeGgufVariantsResponse(// The backend's own verdict, which resolves existence-first: a marker-less relative name that// exists on disk is a local model. A server predating the field leaves the prefix test.resolvedLocally: res?.resolved_locally === true,+ // Missing/false means the server used local or offline fallback metadata. That cannot prove+ // whether a cached main GGUF still needs a managed drafter companion.+ dependenciesResolved: res?.dependencies_resolved === true,};}@@ -1378,22 +1392,22 @@ interface SoleDownloadedQuant {hasVision: boolean;}-/** The repo's one complete quant, or null when it holds none, holds several, or could not be- * read. Disk-only and client-cached. */+/** The repo's one complete quant, or null when Hub metadata cannot verify its dependencies. */async function readSoleQuant(target: SoleQuantTarget,hfToken?: string,): Promise<SoleDownloadedQuant | null> {try {const res = await listGgufVariantsCached(target.repoId, hfToken, {- preferLocalCache: true,localPath: target.localSource,});const normalized = normalizeGgufVariantsResponse(res);- const local = normalized.variants;- // One file on disk and nothing torn beside it; a partial quant keeps the expander, where it can be resumed.- if (local.length !== 1 || local[0].downloaded !== true) return null;- return { variant: local[0], hasVision: normalized.hasVision };+ const variant = verifiedSoleHubVariant(+ normalized.variants,+ normalized.resolvedLocally,+ normalized.dependenciesResolved,+ );+ return variant ? { variant, hasVision: normalized.hasVision } : null;} catch {return null;}@@ -1650,6 +1664,7 @@ function GgufVariantExpander({filename: string,downloaded?: boolean,sizeBytes?: number,+ downloadPresentation?: ModelSelectorChangeMeta["downloadPresentation"],) => {const isAvailable = isLocalPath || downloaded === true;onSelect(repoId, {@@ -1661,6 +1676,7 @@ function GgufVariantExpander({ggufFilename: filename,isDownloaded: isLocalPath ? true : downloaded,expectedBytes: sizeBytes,+ downloadPresentation,contextLength: isAvailable ? nativeContext : undefined,isGguf: true,pipelineTag,@@ -2025,6 +2041,7 @@ function GgufVariantExpander({v.filename,v.downloaded,expectedBytes,+ pendingDrafterPresentation(v),)}className={cn(@@ -5182,16 +5199,17 @@ export function HubModelPicker({// Carried anyway: if that ever stops holding, the row states what is on disk instead of// handing a torn file to the loader.const isPartial = c.partial === true;+ const isDownloaded = variant.downloaded === true && !isPartial;const selectMeta: ModelSelectorChangeMeta = {source: "hub",isLora: false,// Only for a complete snapshot, as the variant select already does. A loadId names a// revision on disk, and the Audio route carries no isDownloaded field, so a forwarded// one is read there as proof the weights are present.- loadId: isPartial ? undefined : c.load_id,+ loadId: isDownloaded ? c.load_id : undefined,ggufVariant: variant.quant,ggufFilename: variant.filename,- isDownloaded: !isPartial,+ isDownloaded,expectedBytes,isGguf: true,pipelineTag: c.task ?? null,diff --git a/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.ts b/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.tsindex dbce2042f24..c9de320bcc4 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.ts@@ -21,6 +21,23 @@ export interface SoleQuantEntry<T> {quant: T | null;}+/** Collapse a Hub row only after a Hub-aware response verified every dependency. */+export function verifiedSoleHubVariant<T extends { downloaded?: boolean }>(+ variants: readonly T[],+ resolvedLocally: boolean,+ dependenciesResolved: boolean,+): T | null {+ if (+ resolvedLocally ||+ !dependenciesResolved ||+ variants.length !== 1 ||+ variants[0].downloaded !== true+ ) {+ return null;+ }+ return variants[0];+}+/** Identity of one repo's probe. Moves when that repo's variants cache is invalidated, the row* points at another directory, or the bytes on disk change under us. */export function soleQuantKey(diff --git a/studio/frontend/src/features/model-picker/components/model-selector/types.ts b/studio/frontend/src/features/model-picker/components/model-selector/types.tsindex afd14d825a9..38e79778247 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/types.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/types.ts@@ -50,6 +50,13 @@ export interface ModelSelectorChangeMeta {ggufFilename?: string;isDownloaded?: boolean;expectedBytes?: number;+ /** Presentation for a companion-only managed download. The manager still+ * owns one atomic GGUF job, but names the bytes actually crossing the wire. */+ downloadPresentation?: {+ label: string;+ filename: string;+ expectedBytes: number;+ };/** Native GGUF context, threaded so a staged pick can seed the slider. */contextLength?: number | null;/** Direct local .gguf file picked without a variant (custom folder / LM Unsloth). Marks it as adiff --git a/studio/frontend/tests/download-companion-presentation.test.ts b/studio/frontend/tests/download-companion-presentation.test.tsnew file mode 100644index 00000000000..2af79415169--- /dev/null+++ b/studio/frontend/tests/download-companion-presentation.test.ts@@ -0,0 +1,187 @@+// 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 test from "node:test";++import {+ pendingDrafterPresentation,+ presentationForExpectedBytesUpdate,+ presentationForJobStart,+ presentedProgress,+} from "../src/features/hub/download-manager/download-presentation.ts";+import { readSrc } from "./helpers/kit.ts";+import { carriesOverSeed } from "../src/features/hub/download-manager/adopt-rules.ts";++test("a pending MTP file becomes the download manager presentation", () => {+ assert.deepEqual(+ pendingDrafterPresentation({+ filename: "Qwen3.8-Flash-Next-Q4.gguf",+ quant: "Q4",+ size_bytes: 100,+ pending_drafter_filename: "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf",+ pending_drafter_size_bytes: 20,+ }),+ {+ label: "MTP companion",+ filename: "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf",+ expectedBytes: 20,+ },+ );+});++test("companion presentation subtracts the cached main model from progress", () => {+ const mainBytes = 112_238_658_784;+ const mtpBytes = 2_786_568_256;+ const mtpTransferred = 540_000_000;++ assert.deepEqual(+ presentedProgress({+ expectedBytes: mainBytes + mtpBytes,+ downloadedBytes: mainBytes + mtpTransferred,+ fraction: (mainBytes + mtpTransferred) / (mainBytes + mtpBytes),+ presentation: {+ label: "MTP companion",+ filename: "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf",+ expectedBytes: mtpBytes,+ },+ }),+ {+ expectedBytes: mtpBytes,+ downloadedBytes: mtpTransferred,+ fraction: mtpTransferred / mtpBytes,+ },+ );+});++test("companion presentation keeps backend baseline-adjusted progress", () => {+ const presentation = presentationForJobStart(+ {+ label: "MTP companion",+ filename: "mtp-shared-Q8_0.gguf",+ expectedBytes: 20,+ },+ undefined,+ 120,+ false,+ );++ assert.deepEqual(+ presentedProgress({+ // snapshot_progress has already removed the cached 100-byte main model.+ expectedBytes: 20,+ downloadedBytes: 5,+ fraction: 0.25,+ presentation,+ }),+ { expectedBytes: 20, downloadedBytes: 5, fraction: 0.25 },+ );+});++test("ordinary downloads retain their plan-wide counters", () => {+ assert.deepEqual(+ presentedProgress({+ expectedBytes: 100,+ downloadedBytes: 25,+ fraction: 0.25,+ }),+ { expectedBytes: 100, downloadedBytes: 25, fraction: 0.25 },+ );+});++test("backend-active adoption keeps and stabilizes persisted presentation", () => {+ const existing = {+ label: "MTP companion",+ filename: "mtp-shared-Q8_0.gguf",+ expectedBytes: 20,+ };+ assert.deepEqual(presentationForJobStart(undefined, existing, 120, true), {+ ...existing,+ cachedPlanPrefixBytes: 100,+ });+ assert.equal(+ presentationForJobStart(undefined, existing, 120, false),+ undefined,+ );+});++test("adoption defers stabilization while the backend total is unknown", () => {+ const existing = {+ label: "MTP companion",+ filename: "mtp-shared-Q8_0.gguf",+ expectedBytes: 20,+ };+ assert.deepEqual(presentationForJobStart(undefined, existing, 0, true), existing);+});++test("a different backend generation cannot inherit stale presentation", () => {+ const existing = {+ label: "MTP companion",+ filename: "old-mtp.gguf",+ expectedBytes: 20,+ };+ const carryExisting = carriesOverSeed(true, 1, 2);+ assert.equal(carryExisting, false);+ assert.equal(+ presentationForJobStart(undefined, existing, 120, carryExisting),+ undefined,+ );+ assert.match(+ readSrc("features/hub/download-manager/poll-loop.ts"),+ /presentationForJobStart\([\s\S]*?carryOverSeed,\s*\)/,+ );+});++test("a later plan-total increase cannot move companion progress backwards", () => {+ const presentation = presentationForJobStart(+ {+ label: "MTP companion",+ filename: "mtp-shared-Q8_0.gguf",+ expectedBytes: 20,+ },+ undefined,+ 120,+ false,+ );+ assert.deepEqual(+ presentedProgress({+ expectedBytes: 200,+ downloadedBytes: 105,+ fraction: 0.525,+ presentation,+ }),+ { expectedBytes: 20, downloadedBytes: 5, fraction: 0.25 },+ );+});++test("poll totals freeze the first authoritative prefix across later growth", () => {+ const initial = {+ label: "MTP companion",+ filename: "mtp-shared-Q8_0.gguf",+ expectedBytes: 20,+ };+ const first = presentationForExpectedBytesUpdate(initial, 0, 120);+ const grown = presentationForExpectedBytesUpdate(first, 120, 200);+ assert.deepEqual(first, { ...initial, cachedPlanPrefixBytes: 100 });+ assert.deepEqual(grown, first);+ assert.deepEqual(+ presentedProgress({+ expectedBytes: 200,+ downloadedBytes: 105,+ fraction: 0.525,+ presentation: grown,+ }),+ { expectedBytes: 20, downloadedBytes: 5, fraction: 0.25 },+ );+ assert.match(+ readSrc("features/hub/download-manager/poll-loop.ts"),+ /applyProgressUpdate[\s\S]*?presentationForExpectedBytesUpdate\(/,+ );+});++test("Models Hub forwards companion presentation on start and update", () => {+ const card = readSrc("features/hub/catalog/gguf-download-card.tsx");+ assert.match(card, /presentation:\s*selectedPresentation/);+ assert.match(card, /pendingDrafterPresentation\(updateTargetVariant\)/);+ assert.match(card, /presentation\s*\?\s*\{ presentation \}/);+});diff --git a/studio/frontend/tests/download-transport-persistence.test.ts b/studio/frontend/tests/download-transport-persistence.test.tsindex c8b1c6dd961..af88c9aaba1 100644--- a/studio/frontend/tests/download-transport-persistence.test.ts+++ b/studio/frontend/tests/download-transport-persistence.test.ts@@ -52,6 +52,14 @@ store.set(invalid: persistedJob("org/auto-model", "auto"),fallback: persistedJob("org/fallback-model", "http", "xet"),badMarker: persistedJob("org/bad-marker-model", "http", "auto"),+ presented: {+ ...persistedJob("org/presented-model", "http"),+ presentation: {+ label: "MTP companion",+ filename: "mtp-shared-Q8_0.gguf",+ expectedBytes: 20,+ },+ },},conflicts: {},},@@ -59,9 +67,18 @@ store.set(}),);-const { getState, hasActiveDownloadJob, jobKeyOf, putJob } = await import(+const {+ getState,+ hasActiveDownloadJob,+ jobKeyOf,+ putJob,+ setExpectedBytesForJob,+} = await import("../src/features/hub/download-manager/download-manager-state.ts");+const { presentedProgress } = await import(+ "../src/features/hub/download-manager/download-presentation.ts"+);test("reload hydration keeps only a resolved active transport", () => {const jobs = getState().jobs;@@ -120,6 +137,18 @@ test("an unresolved persisted marker is dropped, not trusted", () => {);});+test("reload hydration keeps a valid companion-only presentation", () => {+ assert.deepEqual(+ getState().jobs[jobKeyOf("model", "org/presented-model", null)]+ ?.presentation,+ {+ label: "MTP companion",+ filename: "mtp-shared-Q8_0.gguf",+ expectedBytes: 20,+ },+ );+});+test("the cancel marker is written with the persisted job", () => {const key = jobKeyOf("model", "org/retry-model", null);putJob({@@ -148,6 +177,99 @@ test("the cancel marker is written with the persisted job", () => {assert.equal(persisted.state.jobs[key].cancelTransport, "xet");});+test("a companion-only presentation is written for reload and Resume", () => {+ const key = jobKeyOf("model", "org/flash-next", "UD-Q4_K_XL");+ const presentation = {+ label: "MTP companion",+ filename: "mtp-Flash-Next-shared-Q8_0.gguf",+ expectedBytes: 2_786_568_256,+ };+ putJob({+ key,+ kind: "model",+ repoId: "org/flash-next",+ variant: "UD-Q4_K_XL",+ state: "running",+ downloadedBytes: 100,+ completedBytes: 0,+ completeOnDisk: false,+ expectedBytes: 120,+ presentation,+ fraction: 0.5,+ bytesPerSec: 0,+ etaSeconds: 0,+ error: null,+ startedAt: 4,+ transport: "http",+ });+ assert.ok(flushPersistedState);+ flushPersistedState();++ const persisted = JSON.parse(store.get(PERSIST_KEY) ?? "null");+ assert.deepEqual(persisted.state.jobs[key].presentation, presentation);+ assert.deepEqual(getState().jobs[key]?.presentation, presentation);+});++test("growing a plan freezes the old cached prefix before changing totals", () => {+ const key = jobKeyOf("model", "org/growing-plan", "Q4_K_M");+ putJob({+ key,+ kind: "model",+ repoId: "org/growing-plan",+ variant: "Q4_K_M",+ state: "running",+ downloadedBytes: 105,+ completedBytes: 100,+ completeOnDisk: false,+ expectedBytes: 120,+ presentation: {+ label: "MTP companion",+ filename: "mtp-shared-Q8_0.gguf",+ expectedBytes: 20,+ },+ fraction: 0.875,+ bytesPerSec: 0,+ etaSeconds: 0,+ error: null,+ startedAt: 5,+ });++ setExpectedBytesForJob("model", "org/growing-plan", "Q4_K_M", 200);+ const job = getState().jobs[key];+ assert.equal(job?.presentation?.cachedPlanPrefixBytes, 100);+ assert.equal(job && presentedProgress(job).downloadedBytes, 5);+});++test("the first known plan total stabilizes an adopted companion", () => {+ const key = jobKeyOf("model", "org/adopted-plan", "Q4_K_M");+ putJob({+ key,+ kind: "model",+ repoId: "org/adopted-plan",+ variant: "Q4_K_M",+ state: "running",+ downloadedBytes: 105,+ completedBytes: 100,+ completeOnDisk: false,+ expectedBytes: 0,+ presentation: {+ label: "MTP companion",+ filename: "mtp-shared-Q8_0.gguf",+ expectedBytes: 20,+ },+ fraction: 0,+ bytesPerSec: 0,+ etaSeconds: 0,+ error: null,+ startedAt: 6,+ });++ setExpectedBytesForJob("model", "org/adopted-plan", "Q4_K_M", 120);+ const job = getState().jobs[key];+ assert.equal(job?.presentation?.cachedPlanPrefixBytes, 100);+ assert.equal(job && presentedProgress(job).downloadedBytes, 5);+});+test("a running job is the activity the desktop quit path asks about", () => {// What set_renderer_activity mirrors into Rust, so the close button warns first.assert.equal(hasActiveDownloadJob(getState().jobs), true);diff --git a/studio/frontend/tests/fixtures/mtp-download/index.html b/studio/frontend/tests/fixtures/mtp-download/index.htmlnew file mode 100644index 00000000000..915ada43186--- /dev/null+++ b/studio/frontend/tests/fixtures/mtp-download/index.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <script src="/crypto-boot.js"></script>+ <title>MTP download visibility smoke</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/main.tsx"></script>+ </body>+</html>diff --git a/studio/frontend/tests/fixtures/mtp-download/main.tsx b/studio/frontend/tests/fixtures/mtp-download/main.tsxnew file mode 100644index 00000000000..1066e0e5d57--- /dev/null+++ b/studio/frontend/tests/fixtures/mtp-download/main.tsx@@ -0,0 +1,140 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Browser harness for tests/studio/playwright_mtp_download_visibility.py. It runs+// the same staging predicate as the chat model picker and renders the real+// bottom-right download manager without needing a GPU or a multi-gigabyte pull.+/* eslint-disable react-refresh/only-export-components -- standalone Playwright harness */++import { TooltipProvider } from "@/components/ui/tooltip";+/* eslint-disable no-restricted-imports -- the harness exercises these internal boundaries directly */+import { AUTH_TOKEN_KEY } from "@/features/auth/session";+import { wantsDownloadManagerStaging } from "@/features/chat/utils/model-download-staging";+import { pendingDrafterPresentation } from "../../../src/features/hub/download-manager/download-presentation";+import {+ DownloadManagerPanel,+ __resetDownloadManagerForTests,+ downloadManager,+ useDownloadManagerStore,+} from "@/features/hub/download-manager";+/* eslint-enable no-restricted-imports */+import {+ RouterProvider,+ createMemoryHistory,+ createRootRoute,+ createRoute,+ createRouter,+} from "@tanstack/react-router";+import { StrictMode } from "react";+import { createRoot } from "react-dom/client";+import "./styles.css";++const REPO_ID = "unsloth/Qwen3.8-Flash-Next-GGUF";++type Variant = {+ filename: string;+ size_bytes: number;+ quant: string;+ downloaded: boolean;+} & Record<"download_size_bytes", number> &+ Partial<Record<"pending_drafter_filename", string | null>> &+ Partial<Record<"pending_drafter_size_bytes", number>>;++declare global {+ interface Window {+ __mtpDownloadSmoke?: {+ reproduce: () => Promise<{+ backendDownloaded: boolean;+ staged: boolean;+ outcome: string | null;+ }>;+ jobs: () => ReturnType<typeof useDownloadManagerStore.getState>;+ };+ }+}++localStorage.setItem(AUTH_TOKEN_KEY, "mtp-download-smoke");+__resetDownloadManagerForTests();++window.__mtpDownloadSmoke = {+ reproduce: async () => {+ const response = await fetch(+ `/api/models/gguf-variants?repo_id=${encodeURIComponent(REPO_ID)}`,+ );+ if (!response.ok) {+ throw new Error(`Variant request failed: ${response.status}`);+ }+ const payload = (await response.json()) as { variants: Variant[] };+ const variant = payload.variants[0];+ if (!variant) {+ throw new Error("The deterministic backend returned no variant");+ }++ const staged = wantsDownloadManagerStaging({+ id: REPO_ID,+ source: "hub",+ isGguf: true,+ ggufVariant: variant.quant,+ isDownloaded: variant.downloaded,+ });+ let outcome: string | null = null;+ if (staged) {+ const presentation = pendingDrafterPresentation(variant);+ outcome = await downloadManager.requestStart({+ kind: "model",+ repoId: REPO_ID,+ variant: variant.quant,+ expectedBytes: variant.download_size_bytes,+ ...(presentation ? { presentation } : {}),+ });+ }+ return {+ backendDownloaded: variant.downloaded,+ staged,+ outcome,+ };+ },+ jobs: () => useDownloadManagerStore.getState(),+};++function Harness() {+ const side = new URLSearchParams(window.location.search).get("side") ?? "A/B";+ return (+ <TooltipProvider>+ <main className="min-h-dvh bg-background p-10 text-foreground">+ <div className="max-w-2xl rounded-2xl border border-border bg-card p-7 shadow-sm">+ <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">+ {side} · cached quant, missing MTP companion+ </p>+ <h1 className="mt-3 text-2xl font-semibold">Qwen3.8 Flash Next</h1>+ <p className="mt-2 text-sm text-muted-foreground">+ Selecting the already-cached model should stage its required 2.6 GiB+ MTP sidecar in Downloads before loading.+ </p>+ </div>+ <DownloadManagerPanel />+ </main>+ </TooltipProvider>+ );+}++const rootRoute = createRootRoute({ component: Harness });+const indexRoute = createRoute({+ getParentRoute: () => rootRoute,+ path: "/",+ component: () => null,+});+const router = createRouter({+ routeTree: rootRoute.addChildren([indexRoute]),+ history: createMemoryHistory({ initialEntries: ["/"] }),+});++const rootElement = document.getElementById("root");+if (!rootElement) {+ throw new Error("Root element not found");+}+createRoot(rootElement).render(+ <StrictMode>+ <RouterProvider router={router as unknown as never} />+ </StrictMode>,+);diff --git a/studio/frontend/tests/fixtures/mtp-download/styles.css b/studio/frontend/tests/fixtures/mtp-download/styles.cssnew file mode 100644index 00000000000..ac1bfbb216a--- /dev/null+++ b/studio/frontend/tests/fixtures/mtp-download/styles.css@@ -0,0 +1,6 @@+/* 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 "../../../src/index.css";+@source "../../../src";+@source "./";diff --git a/studio/frontend/tests/fixtures/mtp-download/vite.config.ts b/studio/frontend/tests/fixtures/mtp-download/vite.config.tsnew file mode 100644index 00000000000..ed6743f69c5--- /dev/null+++ b/studio/frontend/tests/fixtures/mtp-download/vite.config.ts@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A/B config for tests/studio/playwright_mtp_download_visibility.py. The+// harness and dependencies stay identical while @ resolves to the checkout+// named by PW_SOURCE_FRONTEND_DIR, so base and fix compile separate sources.++// biome-ignore lint/correctness/noNodejsModules: Vite configs execute in Node.+import path from "node:path";+import tailwindcss from "@tailwindcss/vite";+import react from "@vitejs/plugin-react";+import { defineConfig } from "vite";++const frontendRoot = path.resolve(__dirname, "../../..");+const sourceFrontend = path.resolve(+ process.env.PW_SOURCE_FRONTEND_DIR ?? frontendRoot,+);++// biome-ignore lint/style/noDefaultExport: Vite loads its config as a default export.+export default defineConfig({+ root: __dirname,+ publicDir: path.resolve(frontendRoot, "public"),+ plugins: [react(), tailwindcss()],+ css: { postcss: { plugins: [] } },+ server: {+ host: "127.0.0.1",+ fs: { allow: [frontendRoot, sourceFrontend] },+ },+ resolve: {+ // Source files live in a second worktree during the negative control. Keep+ // one React runtime even when that checkout has its own dependency tree.+ dedupe: ["react", "react-dom"],+ alias: {+ "@": path.resolve(sourceFrontend, "src"),+ "@dagrejs/dagre": path.resolve(+ frontendRoot,+ "node_modules/@dagrejs/dagre/dist/dagre.cjs.js",+ ),+ },+ },+ optimizeDeps: { include: ["@dagrejs/dagre", "@dagrejs/graphlib"] },+});diff --git a/studio/frontend/tests/model-picker-partial-downloads.test.ts b/studio/frontend/tests/model-picker-partial-downloads.test.tsindex e3b5c6ea51e..f8e2ed952dc 100644--- a/studio/frontend/tests/model-picker-partial-downloads.test.ts+++ b/studio/frontend/tests/model-picker-partial-downloads.test.ts@@ -430,8 +430,13 @@ test("a partial pick carries no load identity", () => {// snapshot told that page the weights were there and skipped the download.assert.equal(PICKERS.split("loadId: isPartial ? undefined : c.load_id,").length - 1,- 3,- "every cached-row pick drops it when the snapshot is torn",+ 2,+ "both multi-quant cached-row picks drop it when the snapshot is torn",+ );+ assert.equal(+ PICKERS.split("loadId: isDownloaded ? c.load_id : undefined,").length - 1,+ 1,+ "the sole-quant pick carries it only when that quant is complete",);// The GGUF variant select set this rule first; the two must not diverge.assert.ok(diff --git a/studio/frontend/tests/sole-quant-cache.test.ts b/studio/frontend/tests/sole-quant-cache.test.tsindex 1811ed38ef8..4a8c40a7c15 100644--- a/studio/frontend/tests/sole-quant-cache.test.ts+++ b/studio/frontend/tests/sole-quant-cache.test.ts@@ -12,11 +12,27 @@ import {soleQuantFingerprint,soleQuantKey,takeDriftedRepos,+ verifiedSoleHubVariant,} from "../src/features/model-picker/components/model-selector/sole-quant-cache.ts";const A = "unsloth/Qwen3-8B-GGUF";const B = "unsloth/Llama-3.1-8B-Instruct-GGUF";+test("a sole Hub quant collapses only after dependency-aware verification", () => {+ const complete = { quant: "Q4_K_M", downloaded: true };+ assert.equal(verifiedSoleHubVariant([complete], false, true), complete);+ assert.equal(verifiedSoleHubVariant([complete], true, true), null);+ assert.equal(verifiedSoleHubVariant([complete], false, false), null);+ assert.equal(+ verifiedSoleHubVariant(+ [{ quant: "Q4_K_M", downloaded: false }],+ false,+ true,+ ),+ null,+ );+});+/** Two listed repos, each at its own cache version. */const targetsAt = (versionA: string, versionB: string): SoleQuantTarget[] => [{diff --git a/tests/studio/playwright_mtp_download_visibility.py b/tests/studio/playwright_mtp_download_visibility.pynew file mode 100644index 00000000000..3dbc65d3bf3--- /dev/null+++ b/tests/studio/playwright_mtp_download_visibility.py@@ -0,0 +1,333 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A/B browser proof that Flash Next's missing MTP is a managed download.++Run this identical driver once with ``PW_REPO_DIR`` at the base checkout and+once at the fix checkout. The backend under test evaluates a real seeded HF+cache; the browser then runs the real picker predicate and Downloads panel.+No model bytes or GPU are required.++Install the frontend dependencies in both checkouts and run with a Python+environment containing the Studio backend dependencies, Playwright (including+Chromium), and Pillow. PW_BACKEND_PYTHON optionally selects a separate backend+interpreter; otherwise the running interpreter is used. Browser fixtures live+under studio/frontend/tests/fixtures/mtp-download.+"""++from __future__ import annotations++import asyncio+import json+import os+import shutil+import socket+import subprocess+import sys+import tempfile+import time+from pathlib import Path+from types import SimpleNamespace+from urllib.error import URLError+from urllib.parse import parse_qs, urlparse+from urllib.request import urlopen+++REPO_ID = "unsloth/Qwen3.8-Flash-Next-GGUF"+QUANT = "UD-Q4_K_XL"+MAIN_FILENAME = "Qwen3.8-Flash-Next-UD-Q4_K_XL.gguf"+MTP_FILENAME = "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"+MAIN_BYTES = 112_238_658_784+MTP_BYTES = 2_786_568_256+TOTAL_BYTES = MAIN_BYTES + MTP_BYTES++REPO_DIR = Path(os.environ.get("PW_REPO_DIR", Path(__file__).parents[2])).resolve()+FRONTEND_DIR = REPO_DIR / "studio" / "frontend"+HARNESS_FRONTEND_DIR = Path(__file__).parents[2].resolve() / "studio" / "frontend"+ART_DIR = Path(os.environ.get("PW_ART_DIR", "logs/playwright_mtp_download_visibility"))+SIDE = os.environ.get("PW_SIDE", "FIX").upper()+++def _free_port() -> int:+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++def _wait_for_vite(url: str, process: subprocess.Popen[str]) -> None:+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline:+ if process.poll() is not None:+ raise RuntimeError(f"Vite exited early with {process.returncode}")+ try:+ with urlopen(url, timeout = 1) as response:+ if response.status == 200:+ return+ except (OSError, URLError):+ time.sleep(0.1)+ raise RuntimeError(f"Timed out waiting for {url}")+++def _sibling(name: str, size: int, sha: str) -> SimpleNamespace:+ return SimpleNamespace(rfilename = name, size = size, lfs = {"sha256": sha})+++class _LogicalGgufPath:+ """A tiny physical fixture whose scan reports the model's real logical size."""++ def __init__(self, path: Path, size: int):+ self._path = path+ self._size = size++ @property+ def name(self) -> str:+ return self._path.name++ def relative_to(self, root: Path) -> Path:+ return self._path.relative_to(root)++ def stat(self) -> SimpleNamespace:+ return SimpleNamespace(st_size = self._size)+++def _backend_payload_here() -> dict[str, object]:+ """Ask this checkout's production inventory code about a main-only cache."""+ sys.path.insert(0, str(REPO_DIR / "studio" / "backend"))+ from hub.services.models import gguf_variants+ from hub.utils import state_dir++ async def _run_inline(fn, *args, **kwargs):+ return fn(*args, **kwargs)++ with tempfile.TemporaryDirectory(prefix = "mtp-download-ui-") as tmp:+ root = Path(tmp)+ snapshot = (+ root / "cache" / "models--unsloth--Qwen3.8-Flash-Next-GGUF" / "snapshots" / "rev0"+ )+ snapshot.mkdir(parents = True)+ cached_main = snapshot / MAIN_FILENAME+ cached_main.write_bytes(b"m")++ gguf_variants.asyncio.to_thread = _run_inline+ gguf_variants._iter_gguf_paths = lambda _snapshot: [+ _LogicalGgufPath(cached_main, MAIN_BYTES)+ ]+ gguf_variants.list_gguf_variants = lambda *_args, **_kwargs: (+ [+ SimpleNamespace(+ filename = MAIN_FILENAME,+ quant = QUANT,+ display_label = None,+ size_bytes = MAIN_BYTES,+ )+ ],+ False,+ [+ _sibling(MAIN_FILENAME, MAIN_BYTES, "main"),+ _sibling(MTP_FILENAME, MTP_BYTES, "mtp"),+ ],+ )+ gguf_variants.iter_hf_cache_snapshots = lambda *_args, **_kwargs: [snapshot]+ gguf_variants._local_main_gguf_blobs_by_quant = lambda *_args, **_kwargs: {+ QUANT.lower(): {MAIN_FILENAME: {"main"}}+ }+ gguf_variants.download_registry.incomplete_blob_hashes = lambda *_args, **_kwargs: set()+ state_dir.cache_root = lambda: root / "state"+ response = asyncio.run(gguf_variants.get_gguf_variants_response(REPO_ID))+ return response.model_dump(mode = "json")+++def _backend_payload() -> dict[str, object]:+ backend_python = os.environ.get(+ "PW_BACKEND_PYTHON",+ sys.executable,+ )+ output = subprocess.check_output(+ [backend_python, str(Path(__file__).resolve()), "--backend-payload"],+ env = {**os.environ, "PW_REPO_DIR": str(REPO_DIR)},+ text = True,+ )+ return json.loads(output.strip().splitlines()[-1])+++def _api_payload(path: str, query: dict[str, list[str]], variants: dict[str, object]):+ if path == "/api/models/gguf-variants":+ assert query.get("repo_id") == [REPO_ID], query+ return variants+ if path == "/api/studio/download-transport-capabilities":+ return {+ "http": {"available": True, "reason": None},+ "xet": {"available": False, "reason": "Deterministic UI fixture"},+ "auto_resolves_to": "http",+ "auto_reason": "Deterministic UI fixture",+ "partials_resumable": True,+ }+ if path == "/api/hub/transport-status":+ return {"has_partial": False, "last_transport": None, "resumable": True}+ if path == "/api/hub/active-downloads":+ return {"downloads": []}+ if path == "/api/hub/datasets/active-downloads":+ return {"downloads": []}+ if path == "/api/hub/download":+ return {"state": "running", "accepted": True, "generation": 1}+ if path == "/api/hub/download-status":+ return {"state": "running", "generation": 1}+ if path == "/api/hub/gguf-download-progress":+ return {+ "downloaded_bytes": MAIN_BYTES + 540_000_000,+ "completed_bytes": MAIN_BYTES,+ "complete_on_disk": False,+ "expected_bytes": TOTAL_BYTES,+ "progress": (MAIN_BYTES + 540_000_000) / TOTAL_BYTES,+ "cache_path": "/fixture/huggingface/cache",+ "target_present": True,+ "cache_measured": True,+ }+ return {}+++def main() -> None:+ from PIL import Image, ImageDraw, ImageFont+ from playwright.sync_api import Route, sync_playwright++ ART_DIR.mkdir(parents = True, exist_ok = True)+ variants = _backend_payload()+ variant = variants["variants"][0]+ port = _free_port()+ base_url = f"http://127.0.0.1:{port}"+ vite_log = (ART_DIR / f"{SIDE.lower()}-vite.log").open("w", encoding = "utf-8")+ npm = shutil.which("npm") or "npm"+ vite = subprocess.Popen(+ [+ npm,+ "run",+ "dev",+ "--",+ "--config",+ "tests/fixtures/mtp-download/vite.config.ts",+ "--host",+ "127.0.0.1",+ "--port",+ str(port),+ "--strictPort",+ ],+ cwd = HARNESS_FRONTEND_DIR,+ env = {**os.environ, "PW_SOURCE_FRONTEND_DIR": str(FRONTEND_DIR)},+ stdout = vite_log,+ stderr = subprocess.STDOUT,+ text = True,+ )+ page_errors: list[str] = []+ try:+ _wait_for_vite(f"{base_url}/", vite)+ with sync_playwright() as playwright:+ browser = playwright.chromium.launch(headless = True)+ context = browser.new_context(+ viewport = {"width": 1440, "height": 900},+ reduced_motion = "reduce",+ color_scheme = "dark",+ )++ def route_request(route: Route) -> None:+ parsed = urlparse(route.request.url)+ if parsed.path.startswith("/api/"):+ route.fulfill(+ status = 200,+ content_type = "application/json",+ json = _api_payload(parsed.path, parse_qs(parsed.query), variants),+ )+ return+ route.continue_()++ context.route("**/*", route_request)+ page = context.new_page()+ page.on("pageerror", lambda exc: page_errors.append(str(exc)))+ page.goto(+ f"{base_url}/?side={SIDE}",+ wait_until = "networkidle",+ )+ page.wait_for_function("window.__mtpDownloadSmoke !== undefined")+ result = page.evaluate("window.__mtpDownloadSmoke.reproduce()")++ if SIDE == "BEFORE":+ assert result == {+ "backendDownloaded": True,+ "staged": False,+ "outcome": None,+ }, result+ assert page.get_by_text("Downloading 1 item", exact = True).count() == 0+ assert page.locator(".hub-download-panel").count() == 0+ else:+ assert result == {+ "backendDownloaded": False,+ "staged": True,+ "outcome": "started",+ }, result+ page.get_by_text("Downloading 1 item", exact = True).wait_for()+ panel = page.locator(".hub-download-panel")+ panel.get_by_text("MTP companion", exact = False).wait_for()+ panel.get_by_text(MTP_FILENAME.rsplit("/", 1)[-1], exact = True).wait_for()+ panel.get_by_text("540 MB / 2.8 GB", exact = True).wait_for()+ progress_track = panel.locator("div.relative.overflow-hidden.rounded-full")+ assert progress_track.evaluate("el => el.getBoundingClientRect().height") == 3+ jobs = page.evaluate("window.__mtpDownloadSmoke.jobs()")+ assert len(jobs["jobs"]) == 1, jobs++ assert not page_errors, page_errors+ raw_path = ART_DIR / f"{SIDE.lower()}.png"+ # The effect lives in the bottom-right overlay. A fixed clip keeps+ # its filename and byte counters legible in a PR comment instead+ # of shrinking them into a mostly empty full-page comparison.+ page.screenshot(+ path = str(raw_path),+ clip = {"x": 740, "y": 520, "width": 700, "height": 380},+ )++ raw = Image.open(raw_path).convert("RGB")+ labelled = Image.new("RGB", (raw.width, raw.height + 64), "#101114")+ labelled.paste(raw, (0, 64))+ draw = ImageDraw.Draw(labelled)+ font = ImageFont.load_default(size = 24)+ label = (+ "BEFORE - no active MTP download is shown"+ if SIDE == "BEFORE"+ else "AFTER - MTP file and its own progress are explicit"+ )+ draw.text((24, 20), label, fill = "white", font = font)+ labelled.save(ART_DIR / f"{SIDE.lower()}-labelled.png")++ facts = {+ "side": SIDE,+ "repo_dir": str(REPO_DIR),+ "backend_downloaded": variant["downloaded"],+ "download_size_bytes": variant["download_size_bytes"],+ "pending_drafter_filename": variant.get("pending_drafter_filename"),+ "pending_drafter_size_bytes": variant.get("pending_drafter_size_bytes", 0),+ "main_bytes_cached": MAIN_BYTES,+ "mtp_bytes_missing": MTP_BYTES,+ "staged": result["staged"],+ "manager_outcome": result["outcome"],+ "page_errors": page_errors,+ }+ (ART_DIR / f"{SIDE.lower()}-facts.json").write_text(+ json.dumps(facts, indent = 2) + "\n",+ encoding = "utf-8",+ )+ browser.close()+ finally:+ vite.terminate()+ try:+ vite.wait(timeout = 5)+ except subprocess.TimeoutExpired:+ vite.kill()+ vite.wait(timeout = 5)+ vite_log.close()++ print(json.dumps({"side": SIDE, "variant": variant, "artifacts": str(ART_DIR)}))+++if __name__ == "__main__":+ if "--backend-payload" in sys.argv:+ print(json.dumps(_backend_payload_here()))+ else:+ main()diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 323aab79f24..512777f5baf 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -683,19 +683,24 @@ def test_a_pinned_cached_row_loads_from_the_id_the_backend_pinned():# that silently follows the default ref. #7736 added the third: the collapsed# single-quant GGUF row. #7880 added the fourth: the per-quant VRAM bar, which# has to price the pinned snapshot rather than the default ref. #10128 put three of- # them behind a torn-snapshot guard, so the guard is matched rather than one spelling.+ # them behind a torn-snapshot guard. The sole-quant row uses the stronger downloaded+ # verdict; the other two guard directly on partial state.pins = re.findall(r"loadId:\s*(?:(\w+)\s*\?\s*undefined\s*:\s*)?c\.load_id", picker)- assert len(pins) == 4, (+ downloaded_pins = re.findall(r"loadId:\s*(\w+)\s*\?\s*c\.load_id\s*:\s*undefined", picker)+ assert len(pins) + len(downloaded_pins) == 4, ("a row or gear that can start a load is missing the pin, or a new one was ""added and this count needs to follow it")# #10128: the three that can START a load withhold the pin for a part-downloaded# snapshot, since audio-page.tsx reads a forwarded loadId as proof the weights are# on disk. The VRAM bar only prices what is there, so it pins unconditionally.- assert sorted(pins) == ["", "isPartial", "isPartial", "isPartial"], (- "a row that can start a load lost its partial-snapshot guard, or the VRAM bar "+ assert sorted(pins) == ["", "isPartial", "isPartial"], (+ "a multi-quant row that can start a load lost its partial-snapshot guard, or the VRAM bar "f"gained one: {sorted(pins)}")+ assert downloaded_pins == [+ "isDownloaded"+ ], "the sole-quant row must carry the pin only after that quant is known complete"block = re.search(r"onConfigure\(repoId, \{.*?\n\s*\}", picker, re.S)assert block and "loadId," in block.group(0), "the GGUF gear drops the pin"# The variant click withholds it: a quant outside the pinned snapshot lands in a different one.diff --git a/tests/studio/test_playwright_mtp_download_visibility_fixture.py b/tests/studio/test_playwright_mtp_download_visibility_fixture.pynew file mode 100644index 00000000000..0e5be9dc4a2--- /dev/null+++ b/tests/studio/test_playwright_mtp_download_visibility_fixture.py@@ -0,0 +1,36 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import importlib.util+from pathlib import Path+++SCRIPT = Path(__file__).with_name("playwright_mtp_download_visibility.py")+++def _fixture_module():+ spec = importlib.util.spec_from_file_location("playwright_mtp_download_visibility", SCRIPT)+ assert spec and spec.loader+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_large_cache_fixture_reports_size_without_allocating_it(tmp_path):+ module = _fixture_module()+ target = tmp_path / "main.gguf"+ target.write_bytes(b"m")+ logical = module._LogicalGgufPath(target, module.MAIN_BYTES)++ assert target.stat().st_size == 1+ assert logical.stat().st_size == module.MAIN_BYTES+ assert logical.relative_to(tmp_path) == Path("main.gguf")+++def test_vite_launch_resolves_the_platform_npm_executable():+ source = SCRIPT.read_text(encoding = "utf-8")++ assert 'npm = shutil.which("npm") or "npm"' in source+ assert '[\n "npm",' not in source