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
Make startup ML warmup opt-in by feature (#16469)
Lee Jacksonb5c1396baae1
diff --git a/studio/backend/core/inference/defaults.py b/studio/backend/core/inference/defaults.pyindex 7d24af272cf..918a0959f28 100644--- a/studio/backend/core/inference/defaults.py+++ b/studio/backend/core/inference/defaults.py@@ -69,8 +69,21 @@ def suggestions_for_host(models: Iterable[str], device) -> list[str]:return list(dict.fromkeys(_named(model) for model in models))-def get_default_models() -> list[str]:- device = hw.get_device() # ensures detect_hardware() has run- if hw.CHAT_ONLY:+def get_default_models(*, detect_hardware: bool = True) -> list[str]:+ """Curated suggestions; read-only discovery can use the existing hardware verdict."""+ if detect_hardware:+ device = hw.get_device()+ chat_only = hw.CHAT_ONLY+ else:+ generation = hw.DETECTION_GENERATION+ device, chat_only = hw.DEVICE, hw.CHAT_ONLY+ if (+ device is None+ or not hw.DETECTION_COMPLETE.is_set()+ or generation != hw.DETECTION_GENERATION+ ):+ # Unknown is not a CPU verdict. The picker resolves compatibility on first use.+ return list(DEFAULT_MODELS_STANDARD)+ if chat_only:return list(DEFAULT_MODELS_GGUF)return suggestions_for_host(DEFAULT_MODELS_STANDARD, device)diff --git a/studio/backend/core/inference/engine_install.py b/studio/backend/core/inference/engine_install.pyindex 7f9d63068a3..443591f89b4 100644--- a/studio/backend/core/inference/engine_install.py+++ b/studio/backend/core/inference/engine_install.py@@ -152,10 +152,19 @@ def gpu_platform() -> str:global _kfd_has_amd_gpufrom utils.hardware import hardware- # IS_ROCM reads False until background detection settles; never pick CUDA meanwhile.- if not hardware.DETECTION_COMPLETE.is_set():- hardware.ensure_hardware_detected()- if hardware.IS_ROCM:+ # Status is read by idle Chat. The wheel's build family is enough to choose+ # an engine profile; discovering it must not initialize the ML runtime.+ if hardware.DETECTION_COMPLETE.is_set():+ is_rocm = hardware.IS_ROCM+ else:+ from core._torchao_stub import _installed_torch_is_rocm, _module_is_rocm+ torch = sys.modules.get("torch")+ is_rocm = (+ _module_is_rocm(torch)+ if getattr(torch, "__version__", None) is not None+ else _installed_torch_is_rocm()+ )+ if is_rocm:return "rocm"if platform.system() != "Linux" or os.path.exists("/proc/driver/nvidia/version"):return "cuda"@@ -785,6 +794,17 @@ def _rocm_gpu_arches() -> dict[int, str]:return _rocm_arches+def _known_rocm_gpu_arches(*, wait: bool) -> dict[int, str]:+ """Status uses existing runtime information or sysfs; a load may initialize torch.++ Do not cache an empty provisional answer: first use must still run the real+ probe, including GPU masks and HSA_OVERRIDE_GFX_VERSION.+ """+ if wait or "torch" in sys.modules:+ return _rocm_gpu_arches()+ return _rocm_arches or {}++def _unsupported_amd_gpu(found: list[str]) -> str:return ("Requires an AMD Instinct MI200, MI300 or MI350, Radeon RX 7700 to 7900, Radeon RX 9000, or Ryzen AI Max or AI 300 GPU"@@ -804,7 +824,7 @@ def _rocm_reason(wanted = profile(engine)if wsl_host.active():# ROCm is checked inside WSL; a target torch or the driver already names (the selected GPU's) refuses first.- arches = _rocm_gpu_arches() if gpu_id is not None else {}+ arches = _known_rocm_gpu_arches(wait = wait) if gpu_id is not None else {}if gpu_id in arches:known = [arches[gpu_id]]else:@@ -860,7 +880,17 @@ def _rocm_reason()# Each GPU's target as the engine sees it (HSA_OVERRIDE_GFX_VERSION included), else the kernel's.- arches = _rocm_gpu_arches()+ arches = _known_rocm_gpu_arches(wait = wait)+ if (+ not arches+ and _rocm_arches is None+ and (+ os.environ.get("HSA_OVERRIDE_GFX_VERSION", "").strip()+ or amd_kfd_gpu_gfx_targets() is None+ )+ ):+ # The kernel's target ignores the override, or is unreadable; stay provisional until torch reports one.+ return "Checking for a supported AMD GPU."if gpu_id is None:selected = list(arches.values()) or amd_kfd_gpu_gfx_targets() or []elif gpu_id in arches:diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex b9317f62ff6..e9a92ef312c 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -4870,9 +4870,13 @@ def _probe_target(request_shape: dict[str, Any]) -> Any:@functools.cache-def _video_family_capabilities() -> tuple[tuple[str, ...], tuple[str, ...]]:- # Once per process: on Metal the device probe allocates and syncs, which a status poll must not repeat.- available = pipeline_available_video_families(device = resolve_diffusion_device_target().device)+def _video_family_capabilities(+ *, detect_device: bool = True+) -> tuple[tuple[str, ...], tuple[str, ...]]:+ # Cache provisional and measured catalogs separately: idle status must not import torch,+ # and on Metal the actual device probe allocates and syncs, so later polls reuse its answer.+ device = resolve_diffusion_device_target().device if detect_device else None+ available = pipeline_available_video_families(device = device)return (tuple(fam.name for fam in available),tuple(fam.name for fam in available if fam.modular_workflow),@@ -14062,8 +14066,13 @@ class VideoBackend:return self.status()def status(self) -> dict[str, Any]:+ from utils.hardware import hardware as hw+state = self._state- supported, modular = _video_family_capabilities()+ supported, modular = _video_family_capabilities(+ detect_device = state is not None+ or (hw.DEVICE is not None and hw.DETECTION_COMPLETE.is_set())+ )if state is None:return {"loaded": False,diff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.pyindex 2222f0651c9..4327ba4c637 100644--- a/studio/backend/hub/services/models/catalog_classification.py+++ b/studio/backend/hub/services/models/catalog_classification.py@@ -98,16 +98,25 @@ def _gguf_architecture(path: str) -> Optional[str]:return read_gguf_architecture(path)+def _family_buildable_for_listing(family, *, model_kind: str) -> bool:+ from core.inference.diffusion_engine_router import family_buildable_here+ from utils.hardware import hardware as hw++ # Listing must not run hardware detection; the load re-checks buildability.+ if not hw.DETECTION_COMPLETE.is_set():+ return family is not None+ return family_buildable_here(family, model_kind = model_kind)++def _gguf_family_buildable(name_hints: tuple[Optional[str], ...]) -> bool:try:- from core.inference.diffusion_engine_router import family_buildable_herefrom core.inference.diffusion_families import detect_family_for_pickfor hint in name_hints:if not hint:continuefamily = detect_family_for_pick(hint)if family is not None:- return family_buildable_here(family, model_kind = "gguf")+ return _family_buildable_for_listing(family, model_kind = "gguf")except Exception:return Truereturn True@@ -265,10 +274,11 @@ def _whole_pipeline_gguf_task(path: str | Path) -> Optional[str]:family = whole_pipeline_gguf_family(str(path))if family is None:return None- from core.inference.diffusion_engine_router import family_buildable_herefrom core.inference.diffusion_families import detect_family- buildable = family_buildable_here(detect_family("", override = family), model_kind = "gguf")+ buildable = _family_buildable_for_listing(+ detect_family("", override = family), model_kind = "gguf"+ )except Exception:return Nonereturn "text-to-image" if buildable else _UNSUPPORTED_DIFFUSION_TASK@@ -322,15 +332,13 @@ def _arch_to_task(arch: Optional[str], name_hints: tuple[Optional[str], ...] = (return _VIDEO_GEN_TASKreturn _UNSUPPORTED_DIFFUSION_TASKif normalized in _AMBIGUOUS_DIFFUSION_GGUF_ARCHS:- from core.inference.diffusion_engine_router import family_buildable_herefrom core.inference.diffusion_families import detect_family_for_pick, family_gguf_loadable-for hint in name_hints:if not hint:continuefamily = detect_family_for_pick(hint)if family is not None:- loadable = family_gguf_loadable(family) and family_buildable_here(+ loadable = family_gguf_loadable(family) and _family_buildable_for_listing(family, model_kind = "gguf")return "text-to-image" if loadable else _UNSUPPORTED_DIFFUSION_TASK@@ -582,7 +590,6 @@ def _local_model_task(model) -> Optional[str]:except Exception:passtry:- from core.inference.diffusion_engine_router import family_buildable_herefrom core.inference.diffusion_families import (detect_family,detect_family_by_pipeline_index,@@ -599,7 +606,7 @@ def _local_model_task(model) -> Optional[str]:if family is not None:return ("text-to-image"- if family_buildable_here(family, model_kind = "pipeline")+ if _family_buildable_for_listing(family, model_kind = "pipeline")else None)return Nonediff --git a/studio/backend/main.py b/studio/backend/main.pyindex 28157aea2e3..5c20404ebf9 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -452,8 +452,10 @@ import utils.hardware.hardware as _hw_modulefrom utils.torch_warmup import (DISABLE_ENV_VAR,background_media_import,+ gate_torch_stack_import,join_background_warm,prewarm_diffusers_if_image_models_exist,+ prewarm_quant_probe_if_image_models_exist,reset_background_warm,start_background_warm,warm_status,@@ -616,6 +618,25 @@ def _start_llama_cpp_probes_if_enabled(app: FastAPI) -> None:_first_response_sent = threading.Event()+# Snapshot once per lifespan: saving the setting changes the next launch only.+_startup_ml_warmup_features: frozenset[str] = frozenset()+_hardware_detection_requested = False+++def _ml_warmup_enabled(feature: Optional[str] = None) -> bool:+ if os.environ.get(DISABLE_ENV_VAR) == "1":+ return False+ return (+ bool(_startup_ml_warmup_features)+ if feature is None+ else feature in _startup_ml_warmup_features+ )+++def _hardware_detection_deferred() -> bool:+ return not (_ml_warmup_enabled("hardware") or _hardware_detection_requested)++_post_warm_thread: Optional[threading.Thread] = None_post_warm_lock = threading.Lock()# Bumped every start/stop so a worker parked in join_background_warm() cannot act after shutdown.@@ -694,22 +715,36 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:if _post_warm_retired(generation):return- # Apple Silicon without MLX: reinstall and re-detect (UNSLOTH_DISABLE_MLX_AUTOREPAIR=1 opts out).- try:- from utils.mlx_repair import start_mlx_autorepair_if_needed- if _post_warm_retired(generation):- return- start_mlx_autorepair_if_needed()- except Exception as _mlx_exc:- import structlog as _structlog+ # Repair only after hardware is needed. A cold Apple Silicon launch must not+ # import mlx_lm/transformers merely to check whether they need repairing.+ def repair_mlx() -> None:+ try:+ from utils.mlx_repair import start_mlx_autorepair_if_needed+ if _post_warm_retired(generation):+ return+ start_mlx_autorepair_if_needed()+ except Exception as exc:+ import structlog as _structlog+ _structlog.get_logger(__name__).warning("mlx autorepair skipped: %s", exc)- # Warning, not debug: a half-applied update here silently greys out Train/Export.- _structlog.get_logger(__name__).warning("mlx autorepair skipped: %s", _mlx_exc)+ if _ml_warmup_enabled("hardware") or _hw_module.DETECTION_COMPLETE.is_set():+ repair_mlx()+ elif _hw_module.is_apple_silicon() and generation is not None:++ def repair_after_detection() -> None:+ while not _post_warm_retired(generation):+ if _hw_module.DETECTION_COMPLETE.wait(0.5):+ repair_mlx()+ return++ threading.Thread(+ target = repair_after_detection, name = "mlx-repair-on-demand", daemon = True+ ).start()if _post_warm_retired(generation):return# Off the polled path: /api/system must not import torchao itself.- if "torch" in sys.modules:+ if _ml_warmup_enabled("media") and "torch" in sys.modules:# Inside the media import window: skipped once a load claimed it; /api/system resolves both later.with background_media_import() as _window_open:if _window_open:@@ -744,14 +779,21 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:except Exception: # noqa: BLE001pass- # Last: pure latency work (~5s diffusers import), only with image/video models.+ # Last: optional latency work, only with image/video models.if _post_warm_retired(generation):return- try:- prewarm_diffusers_if_image_models_exist()- except Exception as _prewarm_exc: # noqa: BLE001 -- latency work must never end the worker- import structlog as _structlog- _structlog.get_logger(__name__).debug("diffusers prewarm skipped: %s", _prewarm_exc)+ if _ml_warmup_enabled("media"):+ try:+ # The allocating smoke test has its own selection, separate from library imports.+ prewarm_diffusers_if_image_models_exist(warm_quantization = False)+ except Exception as _prewarm_exc: # noqa: BLE001 -- latency work must never end the worker+ import structlog as _structlog+ _structlog.get_logger(__name__).debug("diffusers prewarm skipped: %s", _prewarm_exc)++ if _post_warm_retired(generation):+ return+ if _ml_warmup_enabled("quantization"):+ prewarm_quant_probe_if_image_models_exist()def clear_compiled_cache_unless_shared(app: FastAPI) -> None:@@ -789,10 +831,15 @@ def bootstrap_banner_lines(@asynccontextmanagerasync def lifespan(app: FastAPI):- """Startup: detect hardware, seed default admin if needed. Shutdown: clean up compiled cache."""+ """Startup: seed defaults, run maintenance and selected warmups. Shutdown: clean up compiled cache."""import time as _time+ global _startup_ml_warmup_features, _hardware_detection_requested+ from utils.ml_warmup_settings import get_startup_ml_warmup_features++ _startup_ml_warmup_features = get_startup_ml_warmup_features()+ _hardware_detection_requested = False_lifespan_started = _time.perf_counter()import structlog as _structlog@@ -987,7 +1034,11 @@ async def lifespan(app: FastAPI):# Stall thread-dump watchdog (#9712), only with UNSLOTH_STUDIO_STALL_WATCHDOG=1.from utils.stall_watchdog import stand_down_for_the_warm, start_stall_watchdog- start_stall_watchdog(asyncio.get_running_loop(), suppress = stand_down_for_the_warm)+ _startup_warm_expected = _ml_warmup_enabled()+ start_stall_watchdog(+ asyncio.get_running_loop(),+ suppress = lambda: stand_down_for_the_warm(warm_expected = _startup_warm_expected),+ )_lifespan_log.info("lifespan pre-auth setup completed in %.1fms",@@ -1024,7 +1075,8 @@ async def lifespan(app: FastAPI):# Last, so it never contends for the GIL before the socket binds; its stages wait for the first response._first_response_sent.clear()- start_background_warm(gate = _first_response_sent)+ if _ml_warmup_enabled():+ start_background_warm(gate = _first_response_sent, features = _startup_ml_warmup_features)_start_post_warm_thread()_lifespan_log.info(@@ -1985,7 +2037,7 @@ _HEALTH_DETECT_BUDGET_S = 1.0async def _await_hardware_detection(budget: float) -> bool:"""Poll instead of awaiting a thread: a timed-out to_thread keeps its executor slot for the import."""- if os.environ.get(DISABLE_ENV_VAR) == "1":+ if _hardware_detection_deferred():return _hw_module.DETECTION_COMPLETE.is_set() and _hw_module.DEVICE is not None# Check event AND DEVICE: shutdown clears DEVICE before the event.if _hw_module.DETECTION_COMPLETE.is_set() and _hw_module.DEVICE is not None:@@ -2140,7 +2192,7 @@ async def liveness_check():alive["inference_active"] = Trueif _hardware_snapshot() is None:alive["hardware_detecting"] = True- if os.environ.get(DISABLE_ENV_VAR) == "1":+ if _hardware_detection_deferred():# With the warm off nothing detects; mark hardware_detection_deferred or the watchdog waits in vain.alive["hardware_detection_deferred"] = Truereturn alive@@ -2158,8 +2210,29 @@ async def _desktop_shell_subject(request: Request) -> Optional[str]:return storage.DEFAULT_ADMIN_USERNAME+async def _health_subject(request: Request) -> Optional[str]:+ subject = await _desktop_shell_subject(request)+ auth = request.headers.get("authorization", "")+ bearer = auth.split(" ", 1)[1] if auth.lower().startswith("bearer ") else None+ if subject is None:+ try:+ from auth.authentication import credentials_for_token+ from auth.authentication import get_current_subject as _gcs++ creds = await credentials_for_token(request, bearer)+ if creds is None:+ return None+ # Must await: a bare coroutine is truthy and would skip the auth check+ subject = await _gcs(creds)+ except HTTPException:+ return None+ except Exception:+ return None+ return subject++@app.get("/api/health")-async def health_check(request: Request):+async def health_check(request: Request, detect_hardware: bool = False):"""Liveness plus launcher capability bits; host fingerprint gated on authentication.Unauthenticated callers get non-sensitive fields (service, studio_root_id,@@ -2167,6 +2240,13 @@ async def health_check(request: Request):backend and gate UI before a token exists. version / studio_version /device_type require authentication, including a valid desktop secret."""+ global _hardware_detection_requested+ subject = None+ if detect_hardware:+ subject = await _health_subject(request)+ if not subject:+ raise HTTPException(status_code = 401, detail = "Authentication required")+ _hardware_detection_requested = Trueawait _await_hardware_detection(_HEALTH_DETECT_BUDGET_S)# Snapshot, not a bare global read: a forced re-detect can start at any moment.snapshot = _hardware_snapshot()@@ -2213,26 +2293,11 @@ async def health_check(request: Request):# chat_only above is the pre-detection default, not a measurement; clients should re-read.base["hardware_detecting"] = True# Not when a repair is pending, since it settles the verdict; deferred would mean never.- if os.environ.get(DISABLE_ENV_VAR) == "1" and not mlx_repairing:+ if _hardware_detection_deferred() and not mlx_repairing:# Nothing is detecting until a hardware-dependent operation runs; say so instead of making clients poll.base["hardware_detection_deferred"] = True- subject = await _desktop_shell_subject(request)- auth = request.headers.get("authorization", "")- bearer = auth.split(" ", 1)[1] if auth.lower().startswith("bearer ") else Noneif subject is None:- try:- from auth.authentication import credentials_for_token- from auth.authentication import get_current_subject as _gcs-- creds = await credentials_for_token(request, bearer)- if creds is None:- return base- # Must await: a bare coroutine is truthy and would skip the auth check- subject = await _gcs(creds)- except HTTPException:- return base- except Exception:- return base+ subject = await _health_subject(request)if not subject:return base@@ -2246,6 +2311,7 @@ async def health_check(request: Request):device_type = platform_map.get(sys.platform, sys.platform)# Separate from device_type: Intel Macs spill to system RAM; Apple Silicon has one pool.from utils.hardware import is_apple_silicon+ from utils.paths.file_manager import file_manager_kindauthed = {**base,@@ -2286,8 +2352,6 @@ async def health_check(request: Request):authed["chat_only_hint"] = Noneauthed["device_type"] = device_typeauthed["apple_silicon"] = is_apple_silicon()- from utils.paths.file_manager import file_manager_kind-authed["file_manager"] = file_manager_kind()# base predates the bearer await; never ship "detecting" beside a measurement.authed.pop("hardware_detecting", None)@@ -2300,6 +2364,11 @@ async def health_check(request: Request):if mlx_repairing:# base predates the repair, so drop a now-contradicting deferred marker; the repair settles it.authed.pop("hardware_detection_deferred", None)+ elif authed.get("hardware_detection_deferred"):+ # Nothing will detect until asked, so the host platform cannot wait for a verdict.+ authed["device_type"] = device_type+ authed["apple_silicon"] = is_apple_silicon()+ authed["file_manager"] = file_manager_kind()return authed@@ -2709,7 +2778,9 @@ def _dense_quant_schemes() -> list[str]:@app.get("/api/system")def get_system_info(- current_subject: str = Depends(get_current_subject), refresh_memory: bool = False+ current_subject: str = Depends(get_current_subject),+ refresh_memory: bool = False,+ probe_media: bool = False,):"""Get system information.@@ -2732,6 +2803,22 @@ def get_system_info(logger = logging.getLogger(__name__)+ # The image/video picker explicitly asks on first use; ordinary system polls+ # must not import torchao or diffusers just to populate optional picker tiers.+ if probe_media:+ # Like an image or video load: the probes import torchao and diffusers, which must not race Dynamo.+ gate_torch_stack_import("media capability probe", logger)+ with background_media_import() as window_open:+ if window_open:+ try:+ _refresh_dense_quant_capability()+ except Exception as exc:+ logger.debug("dense quant capability unavailable: %s", exc)+ try:+ _refresh_quantised_streaming_capability()+ except Exception as exc:+ logger.debug("quantised streaming capability unavailable: %s", exc)+gpu_info, inference_gpu_info = _get_cached_system_gpu_info(logger, refresh_memory = refresh_memory)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 4d8d9eb37b8..f7fa91a6370 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -36469,6 +36469,10 @@ def _servable_catalog_scan(catalog, catalog_at: Optional[float]):hit = _fresh()if hit is not None:return hit+ from utils.hardware import hardware as hw++ # Non-GGUF servability needs the device; undetected hardware would list GGUF only.+ hw.ensure_hardware_detected()# Captured before the scan so an invalidation during it leaves the entry stale.generation = _servability_generation()scanned = []diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 3a53909687b..fced3d63a9c 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -246,7 +246,7 @@ try:decision_layout,is_decision_model,)- from core.inference import get_inference_backend+ from core.inference.orchestrator import peek_inference_backendfrom utils.paths import (is_local_path,normalize_path,@@ -280,7 +280,7 @@ except ImportError:decision_layout,is_decision_model,)- from core.inference import get_inference_backend+ from core.inference.orchestrator import peek_inference_backendfrom utils.paths import (is_local_path,normalize_path,@@ -2110,10 +2110,15 @@ def _looks_like_mlx_repo(model_id: str) -> bool:async def list_models(current_subject: str = Depends(get_current_subject)):"""List available models: default plus currently loaded."""try:- # Off-loop: building the singleton calls get_device(), which would freeze on the torch import.- inference_backend = await asyncio.to_thread(get_inference_backend)-- default_models = inference_backend.default_models+ from core.inference.defaults import get_default_models++ # Chat reads this on first paint: listing suggestions must not construct the runtime or probe hardware.+ inference_backend = peek_inference_backend()+ default_models = await asyncio.to_thread(+ lambda: inference_backend.default_models+ if inference_backend is not None+ else get_default_models(detect_hardware = False)+ )if account_access.managed_account():default_models = [m@@ -2163,7 +2168,7 @@ async def list_models(current_subject: str = Depends(get_current_subject)):hide_resident = account_access.resident_hidden("chat", getattr(inference_backend, "active_model_name", None))- if not hide_resident:+ if not hide_resident and inference_backend is not None:loaded_models += _orchestrator_models(inference_backend)llama_backend = get_llama_cpp_backend()diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 42ddca40ca3..0b95c35bf49 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -96,6 +96,14 @@ from utils.chat_preferences_settings import (migrate_show_model_disclaimer,set_show_model_disclaimer,)+from utils.ml_warmup_settings import (+ ML_WARMUP_FEATURES,+ MlWarmupFeature,+ effective_ml_warmup_features,+ get_ml_warmup_features,+ ml_warmup_disabled_by_env,+ set_ml_warmup_features,+)from utils.helper_precache_settings import (DEFAULT_HELPER_PRECACHE_ENABLED,get_helper_precache_enabled,@@ -760,6 +768,16 @@ class SystemOneDownloadPlan(BaseModel):error: Optional[str] = None+class MlWarmupPayload(BaseModel):+ features: list[MlWarmupFeature]+++class MlWarmupResponse(BaseModel):+ features: list[MlWarmupFeature]+ effective_features: list[MlWarmupFeature]+ disabled_by_env: bool++class HelperPrecachePayload(BaseModel):enabled: bool@@ -1188,6 +1206,16 @@ def _upload_limit_response(limit_mb: int) -> UploadLimitResponse:)+def _ml_warmup_response(features: frozenset[str] | None = None) -> MlWarmupResponse:+ selected = get_ml_warmup_features() if features is None else features+ effective = effective_ml_warmup_features(selected)+ return MlWarmupResponse(+ features = [feature for feature in ML_WARMUP_FEATURES if feature in selected],+ effective_features = [feature for feature in ML_WARMUP_FEATURES if feature in effective],+ disabled_by_env = ml_warmup_disabled_by_env(),+ )++def _helper_precache_response(enabled: bool | None = None) -> HelperPrecacheResponse:return HelperPrecacheResponse(enabled = get_helper_precache_enabled() if enabled is None else enabled,@@ -1612,6 +1640,19 @@ def update_tool_result_limit(return _tool_result_limit_response()+@_shared_settings_router.get("/ml-warmup", response_model = MlWarmupResponse)+def get_ml_warmup(current_subject: str = Depends(get_current_subject)) -> MlWarmupResponse:+ return _ml_warmup_response()+++@_owner_settings_router.put("/ml-warmup", response_model = MlWarmupResponse)+def update_ml_warmup(+ payload: MlWarmupPayload, current_subject: str = Depends(get_current_subject)+) -> MlWarmupResponse:+ """Save the selected ML warmup features for the next Unsloth startup."""+ return _ml_warmup_response(set_ml_warmup_features(payload.features))++@_shared_settings_router.get("/helper-precache", response_model = HelperPrecacheResponse)def get_helper_precache(current_subject: str = Depends(get_current_subject),diff --git a/studio/backend/tests/test_account_chat_settings.py b/studio/backend/tests/test_account_chat_settings.pyindex 79c5e787ccb..fa702cbfa60 100644--- a/studio/backend/tests/test_account_chat_settings.py+++ b/studio/backend/tests/test_account_chat_settings.py@@ -361,6 +361,7 @@ OWNER_PATHS = ["/llama-cpp-path": ("GET", "PUT"),"/upload-limit": ("PUT",),"/tool-result-limit": ("PUT",),+ "/ml-warmup": ("PUT",),"/helper-precache": ("PUT",),"/developer-mode": ("PUT",),"/download-transport": ("PUT",),@@ -803,3 +804,74 @@ def test_chat_memory_is_per_account(client):assert bob["text"] == "" and bob["enabled"] is Truealice = client.get("/settings/chat-memory").json()assert alice["text"] == "Alice uses uv.\n" and alice["enabled"] is False+++def test_ml_warmup_is_saved_for_owner_and_shared_with_managed_accounts(client, monkeypatch):+ from utils.ml_warmup_settings import ML_WARMUP_FEATURES_SETTING_KEY++ monkeypatch.delenv("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", raising = False)+ assert client.get("/settings/ml-warmup").json() == {+ "features": [],+ "effective_features": [],+ "disabled_by_env": False,+ }+ response = client.put(+ "/settings/ml-warmup",+ headers = {"x-test-account": OWNER.username},+ json = {"features": ["text"]},+ )+ assert response.status_code == 200, response.text+ assert response.json() == {+ "features": ["text"],+ "effective_features": ["hardware", "text"],+ "disabled_by_env": False,+ }+ assert run_as(OWNER, studio_db.get_app_setting, ML_WARMUP_FEATURES_SETTING_KEY) == ["text"]+ assert run_as(ALICE, studio_db.get_app_setting, ML_WARMUP_FEATURES_SETTING_KEY, None) is None+ assert client.get("/settings/ml-warmup").json()["features"] == ["text"]++ monkeypatch.setenv("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", "1")+ assert client.get("/settings/ml-warmup").json() == {+ "features": ["text"],+ "effective_features": ["hardware", "text"],+ "disabled_by_env": True,+ }++[email protected]("invalid", ["text", True, 1, None, ["unknown"], ["text", 1]])+def test_ml_warmup_api_requires_a_list_of_supported_features(client, invalid):+ response = client.put(+ "/settings/ml-warmup",+ headers = {"x-test-account": OWNER.username},+ json = {"features": invalid},+ )+ assert response.status_code == 422, response.text++[email protected]("mask", range(32))+def test_every_ml_warmup_selection_round_trips_without_persisting_dependencies(+ client, monkeypatch, mask+):+ from utils.ml_warmup_settings import ML_WARMUP_FEATURES_SETTING_KEY++ monkeypatch.delenv("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", raising = False)+ names = ("hardware", "text", "datasets", "media", "quantization")+ selected = [feature for bit, feature in enumerate(names) if mask & (1 << bit)]+ effective = set(selected)+ if effective & {"text", "media", "quantization"}:+ effective.add("hardware")+ expected = {+ "features": selected,+ "effective_features": [name for name in names if name in effective],+ "disabled_by_env": False,+ }+ response = client.put(+ "/settings/ml-warmup",+ headers = {"x-test-account": OWNER.username},+ json = {"features": list(reversed(selected)) + selected},+ )+ assert response.status_code == 200, response.text+ assert response.json() == expected+ assert client.get("/settings/ml-warmup").json() == expected+ assert run_as(OWNER, studio_db.get_app_setting, ML_WARMUP_FEATURES_SETTING_KEY) == selected+ assert run_as(ALICE, studio_db.get_app_setting, ML_WARMUP_FEATURES_SETTING_KEY, None) is Nonediff --git a/studio/backend/tests/test_cold_model_catalog.py b/studio/backend/tests/test_cold_model_catalog.pynew file mode 100644index 00000000000..8d6bbfb41bb--- /dev/null+++ b/studio/backend/tests/test_cold_model_catalog.py@@ -0,0 +1,181 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""First-paint catalogs use existing state without starting hardware or model runtimes."""++import asyncio+import threading+from types import SimpleNamespace++import pytest+++def catalog(monkeypatch):+ from core.inference import defaults, model_slots+ from routes import inference, models+ from utils.hardware import hardware as hw++ event = threading.Event()+ monkeypatch.setattr(hw, "DETECTION_COMPLETE", event)+ monkeypatch.setattr(hw, "DEVICE", None)+ monkeypatch.setattr(hw, "CHAT_ONLY", True)+ monkeypatch.setattr(hw, "get_device", lambda: pytest.fail("catalog started hardware detection"))+ monkeypatch.setattr(models, "peek_inference_backend", lambda: None)+ monkeypatch.setattr(+ models,+ "get_inference_backend",+ lambda: pytest.fail("catalog created a runtime"),+ raising = False, # Tripwire if the removed eager factory is called again.+ )+ monkeypatch.setattr(+ inference,+ "get_llama_cpp_backend",+ lambda: SimpleNamespace(is_loaded = False, model_identifier = None),+ )+ monkeypatch.setattr(model_slots, "visible", lambda: [])+ monkeypatch.setattr(models.account_access, "managed_account", lambda: False)+ monkeypatch.setattr(models.account_access, "resident_hidden", lambda *args: False)+ return defaults, models, hw, event+++def test_unknown_hardware_keeps_the_standard_catalog_without_a_cpu_verdict(catalog):+ defaults, models, _, _ = catalog+ response = asyncio.run(models.list_models(current_subject = "owner"))+ assert response.default_models == defaults.DEFAULT_MODELS_STANDARD+ assert [model.id for model in response.models] == defaults.DEFAULT_MODELS_STANDARD++[email protected]("device,chat_only", [("cpu", True), ("cuda", False), ("mlx", False)])+def test_read_only_catalog_uses_a_measured_host_without_reprobing(+ catalog, monkeypatch, device, chat_only+):+ defaults, models, hw, event = catalog+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType(device))+ monkeypatch.setattr(hw, "CHAT_ONLY", chat_only)+ event.set()+ response = asyncio.run(models.list_models(current_subject = "owner"))+ if chat_only:+ expected = defaults.DEFAULT_MODELS_GGUF+ elif device == "mlx":+ expected = defaults.suggestions_for_host(+ defaults.DEFAULT_MODELS_STANDARD, hw.DeviceType.MLX+ )+ assert all(not name.endswith("bnb-4bit") for name in expected)+ else:+ expected = defaults.DEFAULT_MODELS_STANDARD+ assert response.default_models == expected+++def test_catalog_updates_after_first_hardware_detection(catalog, monkeypatch):+ defaults, models, hw, event = catalog+ before = asyncio.run(models.list_models(current_subject = "owner"))+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU)+ event.set()+ after = asyncio.run(models.list_models(current_subject = "owner"))+ assert before.default_models == defaults.DEFAULT_MODELS_STANDARD+ assert after.default_models == defaults.DEFAULT_MODELS_GGUF+++def test_existing_runtime_keeps_its_ranked_catalog_and_loaded_models(catalog, monkeypatch):+ _, models, _, _ = catalog+ backend = SimpleNamespace(+ default_models = ["org/ranked", "org/curated"],+ models = {"org/loaded": {"is_vision": True}},+ active_model_name = "org/loaded",+ )+ monkeypatch.setattr(models, "peek_inference_backend", lambda: backend)+ response = asyncio.run(models.list_models(current_subject = "owner"))+ assert response.default_models == ["org/ranked", "org/curated"]+ assert [model.id for model in response.models] == ["org/ranked", "org/curated", "org/loaded"]+ assert response.models[-1].is_vision+++def test_managed_account_catalog_filter_and_hidden_resident_are_preserved(catalog, monkeypatch):+ _, models, _, _ = catalog+ backend = SimpleNamespace(+ default_models = ["org/private", "org/shared"],+ models = {"org/resident": {}},+ active_model_name = "org/resident",+ )+ monkeypatch.setattr(models, "peek_inference_backend", lambda: backend)+ monkeypatch.setattr(models.account_access, "managed_account", lambda: True)+ monkeypatch.setattr(models.account_access, "model_visible", lambda name: name == "org/shared")+ monkeypatch.setattr(models.account_access, "resident_hidden", lambda *args: True)+ response = asyncio.run(models.list_models(current_subject = "managed"))+ assert response.default_models == ["org/shared"]+ assert [model.id for model in response.models] == ["org/shared"]++[email protected]("device", ["cpu", "mps"])+def test_video_status_provisional_catalog_refreshes_after_explicit_detection(monkeypatch, device):+ from core.inference import video+ from utils.hardware import hardware as hw++ event = threading.Event()+ monkeypatch.setattr(hw, "DETECTION_COMPLETE", event)+ monkeypatch.setattr(hw, "DEVICE", None)+ calls, resolves = [], []+ ordinary = SimpleNamespace(name = "ordinary", modular_workflow = False)+ modular = SimpleNamespace(name = "modular", modular_workflow = True)++ def available(*, device):+ calls.append(device)+ return (ordinary,) if device == "mps" else (ordinary, modular)++ def resolve():+ resolves.append(device)+ assert event.is_set(), "idle status initialized the device"+ return SimpleNamespace(device = device)++ monkeypatch.setattr(video, "pipeline_available_video_families", available)+ monkeypatch.setattr(video, "resolve_diffusion_device_target", resolve)+ video._video_family_capabilities.cache_clear()+ try:+ backend = video.VideoBackend()+ assert backend.status()["supported_families"] == ["ordinary", "modular"]+ assert backend.status()["modular_families"] == ["modular"]+ assert resolves == [] and calls == [None]+ event.set()+ assert backend.status()["supported_families"] == ["ordinary", "modular"]+ assert resolves == [], "a torn-down device is not a settled snapshot"+ monkeypatch.setattr(+ hw, "DEVICE", hw.DeviceType.MLX if device == "mps" else hw.DeviceType.CPU+ )+ expected = ["ordinary"] if device == "mps" else ["ordinary", "modular"]+ assert backend.status()["supported_families"] == expected+ assert backend.status()["supported_families"] == expected+ assert resolves == [device] and calls == [None, device]+ finally:+ video._video_family_capabilities.cache_clear()+++def test_an_event_without_a_device_is_not_a_measured_catalog(catalog):+ defaults, models, _, event = catalog+ event.set()+ response = asyncio.run(models.list_models(current_subject = "owner"))+ assert response.default_models == defaults.DEFAULT_MODELS_STANDARD++[email protected]("arch", ["flux", "lumina2"])+def test_local_gguf_listing_defers_the_device_probe_until_hardware_is_known(+ catalog, monkeypatch, arch+):+ from core.inference import diffusion_engine_router, diffusion_families+ from hub.services.models import catalog_classification++ _, _, _, event = catalog+ probed = []+ monkeypatch.setattr(diffusion_families, "detect_family_for_pick", lambda hint: hint)+ monkeypatch.setattr(diffusion_families, "family_gguf_loadable", lambda family: True)+ monkeypatch.setattr(+ diffusion_engine_router,+ "family_buildable_here",+ lambda family, **kwargs: probed.append(family) or False,+ )+ classify = lambda: catalog_classification._arch_to_task(arch, ("model",))+ assert classify() == "text-to-image"+ assert probed == []+ event.set()+ assert classify() == catalog_classification._UNSUPPORTED_DIFFUSION_TASK+ assert probed == ["model"]diff --git a/studio/backend/tests/test_consent_gate.py b/studio/backend/tests/test_consent_gate.pyindex 8f5a5c24e3c..3c8d800878a 100644--- a/studio/backend/tests/test_consent_gate.py+++ b/studio/backend/tests/test_consent_gate.py@@ -1981,16 +1981,21 @@ class TestDiscardRemoteCodeDownload:repo = SimpleNamespace(repo_type = "model", repo_id = "evil/repo", revisions = [rev])return SimpleNamespace(repos = [repo], delete_revisions = MagicMock())- def _run(self, model_name, cache_scans):+ def _run(+ self,+ model_name,+ cache_scans,+ active_model_name = None,+ ):import asyncioimport routes.models as M- not_loaded = SimpleNamespace(active_model_name = None)+ backend = SimpleNamespace(active_model_name = active_model_name)with (patch.object(M, "is_local_path", return_value = model_name.startswith("/")),patch.object(M, "_all_hf_cache_scans", return_value = cache_scans),- patch.object(M, "get_inference_backend", return_value = not_loaded),+ patch("core.inference.orchestrator.peek_inference_backend", return_value = backend),patch("routes.inference.get_llama_cpp_backend",return_value = SimpleNamespace(is_loaded = False, model_identifier = None),@@ -2004,6 +2009,12 @@ class TestDiscardRemoteCodeDownload:assert res["deleted"] is Truecache.delete_revisions.assert_called_once_with("deadbeef")+ def test_refuses_loaded_model(self):+ cache = self._fake_cache(["config.json", "modeling_evil.py"])+ res = self._run("evil/repo", [cache], active_model_name = "evil/repo")+ assert res == {"deleted": False, "reason": "loaded"}+ cache.delete_revisions.assert_not_called()+def test_refuses_when_weights_present(self):cache = self._fake_cache(["config.json", "model.safetensors"])res = self._run("evil/repo", [cache])diff --git a/studio/backend/tests/test_delete_finetuned_diffusion_guard.py b/studio/backend/tests/test_delete_finetuned_diffusion_guard.pyindex ecdd428b060..b26a95d6016 100644--- a/studio/backend/tests/test_delete_finetuned_diffusion_guard.py+++ b/studio/backend/tests/test_delete_finetuned_diffusion_guard.py@@ -60,7 +60,6 @@ def client(tmp_path, monkeypatch):monkeypatch.setattr(models_module, "exports_root", lambda: tmp_path / "exports")entries = {f"model:training:{outputs / 'my-diffusion-model'}": {}, "upload:abc": {}}monkeypatch.setattr(library_db, "list_entries", lambda: entries)- monkeypatch.setattr(models_module, "get_inference_backend", lambda: _NoChat())app = FastAPI()app.include_router(models_router, prefix = "/api/models")@@ -68,11 +67,6 @@ def client(tmp_path, monkeypatch):return TestClient(app), outputs-class _NoChat:- active_model_name = None- loading_models: set = set()--def _model_dir(outputs):d = outputs / "my-diffusion-model"d.mkdir()diff --git a/studio/backend/tests/test_diffusers_prewarm.py b/studio/backend/tests/test_diffusers_prewarm.pyindex 5d51fb7a622..bf22fab87ba 100644--- a/studio/backend/tests/test_diffusers_prewarm.py+++ b/studio/backend/tests/test_diffusers_prewarm.py@@ -677,3 +677,16 @@ def test_the_coordinated_warm_stages_do_not_import_diffusers():for name, fn in torch_warmup._STAGES:body = inspect.getsource(fn)assert "diffusers" not in body, f"warm stage {name!r} imports diffusers"++[email protected]("warm_quantization", [False, True])+def test_diffusers_imports_do_not_require_the_allocating_quantization_probe(+ warm, monkeypatch, warm_quantization+):+ _stub_gate(monkeypatch, {"text-to-image": ["unsloth/Z-Image-GGUF"], "text-to-video": []})+ _stub_diffusers(monkeypatch)+ calls = []+ monkeypatch.setattr(warm, "_prewarm_quant_probe", lambda: calls.append("probe"))++ assert warm.prewarm_diffusers_if_image_models_exist(warm_quantization = warm_quantization) is True+ assert calls == (["probe"] if warm_quantization else [])diff --git a/studio/backend/tests/test_engine_status_stays_cold.py b/studio/backend/tests/test_engine_status_stays_cold.pynew file mode 100644index 00000000000..18ee3394464--- /dev/null+++ b/studio/backend/tests/test_engine_status_stays_cold.py@@ -0,0 +1,70 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Idle engine discovery must not import the runtime it merely describes."""++import threading+from types import SimpleNamespace++import pytest++from core import _torchao_stub+from core.inference import engine_install as install+from utils.hardware import hardware++[email protected]("system", ["Linux", "Windows"])[email protected]("rocm", [False, True, None])+def test_cold_engine_profiles_use_build_metadata_without_detecting(monkeypatch, system, rocm):+ monkeypatch.setattr(install.platform, "system", lambda: system)+ monkeypatch.setattr(+ install.os.path, "exists", lambda path: path == "/proc/driver/nvidia/version"+ )+ monkeypatch.setattr(hardware, "DETECTION_COMPLETE", threading.Event())+ monkeypatch.delitem(install.sys.modules, "torch", raising = False)+ monkeypatch.setattr(_torchao_stub, "_installed_torch_is_rocm", lambda: rocm)+ monkeypatch.setattr(+ hardware, "ensure_hardware_detected", lambda: pytest.fail("idle profile detected hardware")+ )+ assert install.gpu_platform() == ("rocm" if rocm else "cuda")+++def test_loaded_build_and_settled_verdict_take_precedence_over_disk(monkeypatch):+ monkeypatch.setattr(install.platform, "system", lambda: "Windows")+ complete = threading.Event()+ monkeypatch.setattr(hardware, "DETECTION_COMPLETE", complete)+ monkeypatch.setattr(_torchao_stub, "_installed_torch_is_rocm", lambda: False)+ monkeypatch.setitem(+ install.sys.modules,+ "torch",+ SimpleNamespace(__version__ = "2.12.0+rocm7.2", version = SimpleNamespace(hip = "7.2")),+ )+ assert install.gpu_platform() == "rocm"+ monkeypatch.setattr(hardware, "IS_ROCM", False)+ complete.set()+ assert install.gpu_platform() == "cuda"+++def test_cold_rocm_architecture_read_does_not_cache_a_provisional_empty_result(monkeypatch):+ monkeypatch.delitem(install.sys.modules, "torch", raising = False)+ monkeypatch.setattr(install, "_rocm_arches", None)+ probes = []+ monkeypatch.setattr(install, "_rocm_gpu_arches", lambda: probes.append(True) or {0: "gfx1100"})+ assert install._known_rocm_gpu_arches(wait = False) == {}+ assert install._rocm_arches is None+ assert probes == []+ assert install._known_rocm_gpu_arches(wait = True) == {0: "gfx1100"}+ assert probes == [True]+++def test_cold_rocm_status_reuses_measured_architectures(monkeypatch):+ monkeypatch.delitem(install.sys.modules, "torch", raising = False)+ monkeypatch.setattr(install, "_rocm_arches", {0: "gfx1100"})+ monkeypatch.setattr(install, "_rocm_gpu_arches", lambda: pytest.fail("status imported torch"))+ assert install._known_rocm_gpu_arches(wait = False) == {0: "gfx1100"}+++def test_rocm_status_can_resolve_architectures_after_explicit_hardware_use(monkeypatch):+ monkeypatch.setitem(install.sys.modules, "torch", SimpleNamespace())+ monkeypatch.setattr(install, "_rocm_gpu_arches", lambda: {1: "gfx1200"})+ assert install._known_rocm_gpu_arches(wait = False) == {1: "gfx1200"}diff --git a/studio/backend/tests/test_health_answers_within_probe_budget.py b/studio/backend/tests/test_health_answers_within_probe_budget.pyindex b9cd8a9deaa..f752fff7250 100644--- a/studio/backend/tests/test_health_answers_within_probe_budget.py+++ b/studio/backend/tests/test_health_answers_within_probe_budget.py@@ -87,6 +87,7 @@ import asyncio, contextlib, json, os, sys, threading, timeos.environ.pop("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", None)import main+main._startup_ml_warmup_features = frozenset({"hardware"})from fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -206,6 +207,7 @@ import json, os, threading, timeos.environ.pop("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", None)import main+main._startup_ml_warmup_features = frozenset({"hardware"})from fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -305,6 +307,7 @@ import asyncio, json, os, timeos.environ.pop("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", None)import main+main._startup_ml_warmup_features = frozenset({"hardware"})from fastapi import FastAPIfrom fastapi.testclient import TestClientdiff --git a/studio/backend/tests/test_liveness_reports_warmup_state.py b/studio/backend/tests/test_liveness_reports_warmup_state.pyindex 08cd04617b5..3c4608e1401 100644--- a/studio/backend/tests/test_liveness_reports_warmup_state.py+++ b/studio/backend/tests/test_liveness_reports_warmup_state.py@@ -26,6 +26,7 @@ else:os.environ.pop("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", None)import main+main._startup_ml_warmup_features = frozenset() if %(deferred)s else frozenset({"hardware"})from fastapi import FastAPIfrom fastapi.testclient import TestClientdiff --git a/studio/backend/tests/test_managed_engines_rocm.py b/studio/backend/tests/test_managed_engines_rocm.pyindex f56caa52bac..4527fbd95da 100644--- a/studio/backend/tests/test_managed_engines_rocm.py+++ b/studio/backend/tests/test_managed_engines_rocm.py@@ -99,19 +99,19 @@ def test_rocm_engine_stays_isolated_even_when_studio_matches_its_lock(rocm, monkassert not plan["shared"] and not plan["provided"]-def test_windows_waits_for_hardware_detection_before_choosing_the_profile(monkeypatch):+def test_windows_uses_installed_build_metadata_before_hardware_detection(monkeypatch):# IS_ROCM is False until detection settles; Windows has no KFD to fall back on.+ from core import _torchao_stubfrom utils.hardware import hardwaremonkeypatch.setattr(install.platform, "system", lambda: "Windows")monkeypatch.setattr(hardware, "IS_ROCM", False)monkeypatch.setattr(hardware, "DETECTION_COMPLETE", threading.Event())-- def detect(*_a, **_k):- hardware.IS_ROCM = True- hardware.DETECTION_COMPLETE.set()-- monkeypatch.setattr(hardware, "ensure_hardware_detected", detect)+ monkeypatch.delitem(install.sys.modules, "torch", raising = False)+ monkeypatch.setattr(_torchao_stub, "_installed_torch_is_rocm", lambda: True)+ monkeypatch.setattr(+ hardware, "ensure_hardware_detected", lambda: pytest.fail("profile imported torch")+ )assert install.gpu_platform() == "rocm"assert install.profile("vllm")["lock"] == "vllm-linux-rocm723"@@ -282,6 +282,18 @@ def test_sdk_rocm_torch_still_maps_each_gpu_to_its_target(monkeypatch):assert install._rocm_gpu_arches() == {0: "gfx1100", 1: "gfx1030"}+def test_cold_status_does_not_judge_an_overridden_gpu_by_its_kernel_target(amd_host, monkeypatch):+ amd_host.targets["value"] = ["gfx1102"]+ monkeypatch.setenv("HSA_OVERRIDE_GFX_VERSION", "11.0.0")+ monkeypatch.setattr(install, "_rocm_arches", None)+ monkeypatch.delitem(install.sys.modules, "torch", raising = False)+ assert install.support_reason("vllm", wait = False) == "Checking for a supported AMD GPU."+ monkeypatch.delenv("HSA_OVERRIDE_GFX_VERSION")+ assert install.support_reason("vllm", wait = False).startswith("Requires an AMD Instinct")+ amd_host.targets["value"] = None+ assert install.support_reason("vllm", wait = False) == "Checking for a supported AMD GPU."++def test_sglang_on_amd_points_to_vllm(amd_host):assert install.support_reason("sglang", wait = False) == ("SGLang requires an NVIDIA GPU. Use vLLM on AMD GPUs."diff --git a/studio/backend/tests/test_ml_warmup_idle_runtime.py b/studio/backend/tests/test_ml_warmup_idle_runtime.pynew file mode 100644index 00000000000..fdf09919e73--- /dev/null+++ b/studio/backend/tests/test_ml_warmup_idle_runtime.py@@ -0,0 +1,325 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Exercise the full idle lifespan in a fresh interpreter, including its maintenance worker."""++from __future__ import annotations++import importlib.util+import os+from pathlib import Path+import subprocess+import sys++import pytest++_BACKEND_DIR = Path(__file__).resolve().parent.parent++_COLD_START = r"""+import sys+import main+from fastapi.testclient import TestClient+from utils.torch_warmup import warm_status++main.app.state.suppress_bootstrap_injection = True+with TestClient(main.app) as client:+ # The first response releases startup's import gate if a warm was accidentally started.+ assert client.get('/api/liveness').status_code == 200+ for _ in range(2):+ response = client.get('/api/health')+ assert response.status_code == 200+ assert response.json()['hardware_detection_deferred'] is True+ assert client.get('/api/health?detect_hardware=true').status_code == 401+ assert client.get('/api/settings/ml-warmup').status_code == 401+ assert client.put('/api/settings/ml-warmup', json={'features': ['text']}).status_code == 401+ assert client.get('/api/system?probe_media=true').status_code == 401+ # Authenticated settings reads must not import ML libraries.+ from auth.authentication import get_current_subject+ main.app.dependency_overrides[get_current_subject] = lambda: 'owner'+ try:+ for _ in range(2):+ assert client.get('/api/settings/ml-warmup').json()['features'] == []+ finally:+ main.app.dependency_overrides.clear()+ worker = main._post_warm_thread+ assert worker is not None, 'startup maintenance must still run'+ worker.join(20)+ assert not worker.is_alive(), 'cold startup maintenance did not finish'+ assert warm_status()['started'] is False+ heavy = ('torch', 'transformers', 'datasets', 'diffusers', 'torchao', 'pandas', 'pyarrow')+ loaded = [name for name in heavy if name in sys.modules]+ assert not loaded, loaded+print('IDLE_STARTUP_STAYS_COLD')+"""+++_TEXT_START = r"""+import sys+from multiprocessing.process import BaseProcess+import main+from fastapi.testclient import TestClient+from utils.ml_warmup_settings import set_ml_warmup_features+from utils import torch_warmup++set_ml_warmup_features(['text'])+# Model availability must not turn a text-only preference into media or quant warmup.+torch_warmup._a_local_model_would_load_through_diffusers = lambda: True+spawned = []+original_start = BaseProcess.start+def record_start(process, *args, **kwargs):+ spawned.append(process._args[1] if len(process._args) > 1 else None)+ return original_start(process, *args, **kwargs)+BaseProcess.start = record_start++main.app.state.suppress_bootstrap_injection = True+with TestClient(main.app) as client:+ assert client.get('/api/liveness').status_code == 200+ assert client.get('/api/health').status_code == 200+ assert torch_warmup.join_background_warm(60), 'text warmup did not finish'+ main._post_warm_thread.join(20)+ assert not main._post_warm_thread.is_alive()+ state = torch_warmup.warm_status()+ assert list(state['stages']) == ['hardware', 'inference_backend', 'transformers']+ assert all(stage['ok'] for stage in state['stages'].values()), state+ for name in ('torch', 'torch._dynamo', 'transformers.models.auto.modeling_auto'):+ assert name in sys.modules, name+ for name in ('datasets', 'diffusers', 'torchao'):+ assert name not in sys.modules, name+ assert '_child_probe_entry' not in spawned, spawned+print('TEXT_WARMUP_STAYS_SCOPED')+"""+++def _run_startup(+ snippet,+ tmp_path,+ timeout = 120,+):+ env = os.environ.copy()+ env.pop("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", None)+ env.pop("UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM", None)+ env.update(+ {+ "UNSLOTH_HOME": str(tmp_path / "unsloth"),+ "UNSLOTH_STUDIO_HOME": str(tmp_path / "unsloth" / "studio"),+ "UNSLOTH_STUDIO_SANDBOX_HOME": str(tmp_path / "sandbox"),+ "HF_HOME": str(tmp_path / "hf"),+ "HF_HUB_CACHE": str(tmp_path / "hf" / "hub"),+ "HF_XET_CACHE": str(tmp_path / "hf" / "xet"),+ "XDG_CACHE_HOME": str(tmp_path / "cache"),+ "UNSLOTH_DISABLE_UPDATE_CHECK": "1",+ "UNSLOTH_DISABLE_MLX_AUTOREPAIR": "1",+ "HF_HUB_OFFLINE": "1",+ "HF_DATASETS_OFFLINE": "1",+ "UNSLOTH_STUDIO_STALL_WATCHDOG": "0",+ }+ )+ result = subprocess.run(+ [sys.executable, "-c", snippet],+ cwd = _BACKEND_DIR,+ env = env,+ capture_output = True,+ text = True,+ timeout = timeout,+ )+ assert result.returncode == 0, f"{result.stdout}\n{result.stderr[-5000:]}"+ return result.stdout+++def test_idle_startup_and_health_leave_ml_libraries_cold(tmp_path):+ output = _run_startup(_COLD_START, tmp_path)+ assert "IDLE_STARTUP_STAYS_COLD" in output+++def test_text_only_startup_imports_text_stack_without_media_or_quant_probe(tmp_path):+ for package in ("torch", "transformers"):+ if importlib.util.find_spec(package) is None:+ pytest.skip(f"{package} is not installed")+ output = _run_startup(_TEXT_START, tmp_path)+ assert "TEXT_WARMUP_STAYS_SCOPED" in output+++_RESTART_SELECTION = r"""+import sys+import main+from fastapi.testclient import TestClient+from auth.authentication import get_current_subject+from utils.ml_warmup_settings import get_ml_warmup_features+from utils import torch_warmup, stall_watchdog++main.app.state.suppress_bootstrap_injection = True+main.app.dependency_overrides[get_current_subject] = lambda: 'owner'+# Record scheduling while avoiding ML imports: this test isolates full-lifespan snapshot wiring.+scheduled = []+watchdog_gates = []+# Check the actual callback main supplies, including preferences saved during this lifespan.+stall_watchdog.start_stall_watchdog = lambda loop, suppress: watchdog_gates.append(suppress)+def record_start(*, gate, features):+ scheduled.append(frozenset(features))+ return True+main.start_background_warm = record_start+main.prewarm_diffusers_if_image_models_exist = lambda **kwargs: None+main.prewarm_quant_probe_if_image_models_exist = lambda: None+for previous, saved, expected in (([], ['text'], []), (['text'], ['datasets'], ['hardware', 'text']), (['datasets'], [], ['datasets']), ([], [], [])):+ with TestClient(main.app) as client:+ assert client.get('/api/liveness').status_code == 200+ assert main._startup_ml_warmup_features == frozenset(expected)+ assert watchdog_gates[-1]() is bool(expected)+ assert client.get('/api/settings/ml-warmup').json()['features'] == previous+ response = client.put('/api/settings/ml-warmup', json={'features': saved})+ assert response.status_code == 200, response.text+ assert response.json()['features'] == saved+ assert get_ml_warmup_features() == frozenset(saved)+ assert main._startup_ml_warmup_features == frozenset(expected)+ assert watchdog_gates[-1]() is bool(expected)+ main._post_warm_thread.join(20)+ assert not main._post_warm_thread.is_alive()+assert scheduled == [frozenset({'hardware', 'text'}), frozenset({'datasets'})], scheduled+print('SAVING_APPLIES_ONLY_TO_NEXT_LIFESPAN')+"""+++def test_saving_changes_only_the_next_lifespan_and_turning_off_stops_scheduling(tmp_path):+ output = _run_startup(_RESTART_SELECTION, tmp_path)+ assert "SAVING_APPLIES_ONLY_TO_NEXT_LIFESPAN" in output+++_SYSTEM_DEMAND = r"""+import sys+from multiprocessing.process import BaseProcess+import main+from fastapi.testclient import TestClient+from auth.authentication import get_current_subject+from utils.torch_warmup import warm_status++main.app.state.suppress_bootstrap_injection = True+main.app.dependency_overrides[get_current_subject] = lambda: 'owner'+spawned = []+original_start = BaseProcess.start+def record_start(process, *args, **kwargs):+ spawned.append(process._args[1] if len(process._args) > 1 else None)+ return original_start(process, *args, **kwargs)+BaseProcess.start = record_start++with TestClient(main.app) as client:+ assert client.get('/api/liveness').status_code == 200+ main._post_warm_thread.join(20)+ assert not main._post_warm_thread.is_alive()+ assert 'torch' not in sys.modules+ # Opening Resources/monitoring is explicit demand for real hardware information.+ for path in ('/api/system', '/api/system?refresh_memory=true'):+ reply = client.get(path)+ assert reply.status_code == 200, reply.text+ assert 'memory' in reply.json() and 'gpu' in reply.json()+ assert main._hw_module.DETECTION_COMPLETE.is_set()+ assert 'torch' in sys.modules+ unselected = ['datasets', 'diffusers', 'torchao']+ # Apple Silicon detection imports mlx_lm, which pulls in transformers.+ if not main._hw_module.is_apple_silicon():+ unselected += ['torch._dynamo', 'transformers']+ for name in unselected:+ assert name not in sys.modules, name+ assert warm_status()['started'] is False+ assert '_child_probe_entry' not in spawned, spawned+ assert 'hardware_detection_deferred' not in client.get('/api/health').json()+print('SYSTEM_DEMAND_LOADS_HARDWARE_ONLY')+"""+++def test_system_information_on_first_use_detects_hardware_without_unselected_ml_stacks(tmp_path):+ if importlib.util.find_spec("torch") is None:+ pytest.skip("torch is not installed")+ output = _run_startup(_SYSTEM_DEMAND, tmp_path)+ assert "SYSTEM_DEMAND_LOADS_HARDWARE_ONLY" in output+++_IDLE_CHAT = r"""+import json+import sys+import time+import psutil+import main+from fastapi.testclient import TestClient+from auth.authentication import get_current_subject, authenticated_via_api_key+from utils.torch_warmup import warm_status+from core.inference.orchestrator import peek_inference_backend++main.app.state.suppress_bootstrap_injection = True+main.app.dependency_overrides[get_current_subject] = lambda: 'owner'+main.app.dependency_overrides[authenticated_via_api_key] = lambda: False+heavy = ('torch', 'transformers', 'datasets', 'diffusers', 'torchao', 'pandas', 'pyarrow')+rows = []+# Read-only first-paint requests captured from the actual Chat page in Playwright.+paths = (+ '/api/health',+ '/api/auth/status',+ '/api/providers/registry?include_hidden=true&include_oauth=true',+ '/api/providers/',+ '/api/engines',+ '/api/hub/active-downloads',+ '/api/hub/datasets/active-downloads',+ '/api/export/status',+ '/api/settings/hugging-face-token',+ '/api/settings/pinned-models',+ '/api/settings/personalization',+ '/api/chat/settings',+ '/api/system/disk',+ '/api/inference/monitor',+ '/api/chat/projects?include_archived=false',+ '/api/skills',+ '/api/rag/knowledge-bases',+ '/api/settings/multi-model',+ '/api/inference/images/status',+ '/api/inference/video/status',+ '/api/hub/hidden-models',+ '/api/models/list',+ '/api/inference/status',+ '/api/scheduled-tasks/runs',+ '/api/hub/local',+ '/api/llama/update-status?force_refresh=true',+ '/api/chat/pins',+ '/api/models/loras',+ '/api/studio/update-status',+)+requests = [('GET', path, None) for path in paths]+for archived, unfiled, limit in ((False, True, 20), (False, False, 1), (True, False, 1)):+ requests.append(('POST', '/api/chat/sidebar/rows', {+ 'archived': archived, 'projectId': None, 'unfiledOnly': unfiled,+ 'includeIds': None, 'excludeIds': [], 'sort': 'updated',+ 'manualOrder': None, 'limit': limit, 'cursor': None,+ }))+with TestClient(main.app) as client:+ assert client.get('/api/liveness').status_code == 200+ main._post_warm_thread.join(20)+ assert not main._post_warm_thread.is_alive()+ assert not any(name in sys.modules for name in heavy)+ for pass_index in range(2):+ for method, path, body in requests:+ started = time.monotonic()+ response = client.request(method, path, **({'json': body} if body is not None else {}))+ row = {+ 'pass': pass_index + 1,+ 'method': method,+ 'path': path,+ 'status': response.status_code,+ 'elapsed_s': round(time.monotonic() - started, 3),+ 'rss_mib': round(psutil.Process().memory_info().rss / 1024**2, 1),+ 'imports': [name for name in heavy if name in sys.modules],+ }+ rows.append(row)+ print('IDLE_CHAT_ROUTE ' + json.dumps(row), flush=True)+ assert response.status_code == 200, response.text+ if path == '/api/models/list':+ assert response.json()['models'], 'cold catalog must keep model suggestions'+ assert not any(row['imports'] for row in rows), rows+ assert not main._hw_module.DETECTION_COMPLETE.is_set()+ assert peek_inference_backend() is None+ assert warm_status()['started'] is False+print('IDLE_CHAT_REQUESTS_STAY_COLD')+"""+++def test_idle_chat_model_status_inventory_and_monitor_requests_leave_ml_cold(tmp_path):+ # 65 sequential requests; TestClient adds seconds per request on some hosts.+ output = _run_startup(_IDLE_CHAT, tmp_path, timeout = 600)+ assert "IDLE_CHAT_REQUESTS_STAY_COLD" in outputdiff --git a/studio/backend/tests/test_ml_warmup_settings.py b/studio/backend/tests/test_ml_warmup_settings.pynew file mode 100644index 00000000000..0c9252f5e2d--- /dev/null+++ b/studio/backend/tests/test_ml_warmup_settings.py@@ -0,0 +1,100 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Selective startup warmup stays opt-in and preserves explicit dependency choices."""++from __future__ import annotations++import sys+import types+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from utils import ml_warmup_settings as settings+++def preferences(monkeypatch):+ values = {}+ database = types.ModuleType("storage.studio_db")+ database.get_app_setting = lambda key, default = None: values.get(key, default)+ database.upsert_app_settings = values.update+ monkeypatch.setitem(sys.modules, "storage.studio_db", database)+ monkeypatch.delenv("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", raising = False)+ return values+++def test_missing_preferences_default_to_no_features(preferences):+ assert settings.get_ml_warmup_features() == frozenset()+ assert settings.get_startup_ml_warmup_features() == frozenset()+++ "stored", [None, "", "text", True, False, 0, 1, {}, ["unknown"], ["text", 1]]+)+def test_invalid_preferences_default_off(preferences, stored):+ preferences[settings.ML_WARMUP_FEATURES_SETTING_KEY] = stored+ assert settings.get_ml_warmup_features() == frozenset()+++def test_unreadable_preferences_default_off(preferences, monkeypatch):+ def fail(*args):+ raise OSError("database unavailable")++ monkeypatch.setattr(sys.modules["storage.studio_db"], "get_app_setting", fail)+ assert settings.get_startup_ml_warmup_features() == frozenset()+++def test_selections_are_persisted_deduplicated_in_canonical_order(preferences):+ selected = settings.set_ml_warmup_features(["media", "text", "media", "datasets"])+ assert selected == frozenset({"text", "datasets", "media"})+ assert preferences[settings.ML_WARMUP_FEATURES_SETTING_KEY] == ["text", "datasets", "media"]+ # Required hardware is effective, not an explicit saved choice.+ assert settings.get_startup_ml_warmup_features() == selected | {"hardware"}+ assert "hardware" not in settings.get_ml_warmup_features()+++ "selected,effective",+ [+ ([], []),+ (["hardware"], ["hardware"]),+ (["datasets"], ["datasets"]),+ (["text"], ["hardware", "text"]),+ (["media"], ["hardware", "media"]),+ (["quantization"], ["hardware", "quantization"]),+ (["media", "quantization"], ["hardware", "media", "quantization"]),+ ],+)+def test_dependencies_add_only_hardware(selected, effective):+ assert settings.effective_ml_warmup_features(selected) == frozenset(effective)+++def test_removing_dependent_features_preserves_only_explicit_hardware(preferences):+ settings.set_ml_warmup_features(["text"])+ settings.set_ml_warmup_features([])+ assert settings.get_startup_ml_warmup_features() == frozenset()+ settings.set_ml_warmup_features(["hardware", "text"])+ settings.set_ml_warmup_features(["hardware"])+ assert settings.get_startup_ml_warmup_features() == frozenset({"hardware"})+++def test_operator_disable_wins_without_changing_saved_preference(preferences, monkeypatch):+ settings.set_ml_warmup_features(["text", "datasets"])+ monkeypatch.setenv("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", "1")+ assert settings.get_ml_warmup_features() == frozenset({"text", "datasets"})+ assert settings.ml_warmup_disabled_by_env() is True+ assert settings.get_startup_ml_warmup_features() == frozenset()++[email protected]("invalid", [None, True, "text", 0, 1, {}, ["unknown"], ["text", 1]])+def test_invalid_writes_do_not_change_preference(preferences, invalid):+ settings.set_ml_warmup_features(["datasets"])+ with pytest.raises(ValueError):+ settings.set_ml_warmup_features(invalid)+ assert settings.get_ml_warmup_features() == frozenset({"datasets"})diff --git a/studio/backend/tests/test_models_list_resident_gguf_label.py b/studio/backend/tests/test_models_list_resident_gguf_label.pyindex 411ecdee751..ed846b52225 100644--- a/studio/backend/tests/test_models_list_resident_gguf_label.py+++ b/studio/backend/tests/test_models_list_resident_gguf_label.py@@ -47,7 +47,7 @@ class _FakeUnsloth:def _list_models(monkeypatch, llama):- monkeypatch.setattr(models_route, "get_inference_backend", lambda: _FakeUnsloth())+ monkeypatch.setattr(models_route, "peek_inference_backend", lambda: _FakeUnsloth())monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: llama)return asyncio.run(models_route.list_models(current_subject = "unsloth")).models@@ -87,7 +87,7 @@ def test_plain_repo_ids_are_unchanged(monkeypatch):class _Backend(_FakeUnsloth):default_models = ["unsloth/Qwen3-4B-Instruct-2507", "Qwen3-4B"]- monkeypatch.setattr(models_route, "get_inference_backend", lambda: _Backend())+ monkeypatch.setattr(models_route, "peek_inference_backend", lambda: _Backend())monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama(None))entries = asyncio.run(models_route.list_models(current_subject = "unsloth")).models@@ -136,7 +136,7 @@ def test_a_hub_repo_id_ending_in_gguf_keeps_its_suffix(monkeypatch):class _Backend(_FakeUnsloth):default_models = ["lex-au/Orpheus-3b-FT-Q8_0.gguf"]- monkeypatch.setattr(models_route, "get_inference_backend", lambda: _Backend())+ monkeypatch.setattr(models_route, "peek_inference_backend", lambda: _Backend())monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama(None))entries = asyncio.run(models_route.list_models(current_subject = "unsloth")).modelsdiff --git a/studio/backend/tests/test_multi_model_serving.py b/studio/backend/tests/test_multi_model_serving.pyindex 7bca84ee3a4..fda5d225111 100644--- a/studio/backend/tests/test_multi_model_serving.py+++ b/studio/backend/tests/test_multi_model_serving.py@@ -1056,7 +1056,7 @@ def test_the_model_list_marks_kept_models_loaded(backends, monkeypatch):_, extra = backendsfake = FakeOrchestrator()fake.default_models = []- monkeypatch.setattr(models_routes, "get_inference_backend", lambda: fake)+ monkeypatch.setattr(models_routes, "peek_inference_backend", lambda: fake)model_slots.slots.append(model_slots.ExtraSlot(FakeLlama(), FakeOrchestrator("org/C"), "owner"))app = FastAPI()app.include_router(models_routes.router, prefix = "/api/models")diff --git a/studio/backend/tests/test_openai_models_servable_cache.py b/studio/backend/tests/test_openai_models_servable_cache.pyindex 036cb70be6e..5d0b46ad88f 100644--- a/studio/backend/tests/test_openai_models_servable_cache.py+++ b/studio/backend/tests/test_openai_models_servable_cache.py@@ -110,3 +110,16 @@ def test_a_managed_account_scans_the_shared_catalog_object(monkeypatch):monkeypatch.setattr(inf, "_servable_catalog_rows", lambda rows, at: seen.append(rows) or [])asyncio.run(inf._openai_catalog_objects())assert seen[0] is catalog+++def test_scan_detects_hardware_before_judging_servability(_stub, monkeypatch):+ from utils.hardware import hardware as hw++ order = []+ monkeypatch.setattr(hw, "ensure_hardware_detected", lambda: order.append("detect"))+ monkeypatch.setattr(+ "core.inference.local_model_resolver.local_servable_model",+ lambda info: order.append("scan") or (True, ()),+ )+ inf._servable_catalog_rows(_catalog(1), 111.0)+ assert order == ["detect", "scan"]diff --git a/studio/backend/tests/test_quantised_streaming_capability.py b/studio/backend/tests/test_quantised_streaming_capability.pyindex b6546c42c39..ad963af97b7 100644--- a/studio/backend/tests/test_quantised_streaming_capability.py+++ b/studio/backend/tests/test_quantised_streaming_capability.py@@ -137,7 +137,7 @@ def test_a_mixed_host_offers_the_tier_only_when_every_card_qualifies(monkeypatchdef test_the_post_warm_worker_resolves_it_behind_the_torch_guard():warm = _src("_post_warm_background_work")assert "_refresh_quantised_streaming_capability()" in warm- guard = warm.index('if "torch" in sys.modules:')+ guard = warm.index('if _ml_warmup_enabled("media") and "torch" in sys.modules:')assert guard < warm.index("_refresh_quantised_streaming_capability()")diff --git a/studio/backend/tests/test_selective_ml_warmup.py b/studio/backend/tests/test_selective_ml_warmup.pynew file mode 100644index 00000000000..ff0d85c32fa--- /dev/null+++ b/studio/backend/tests/test_selective_ml_warmup.py@@ -0,0 +1,179 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Selected warmup groups run only their stages and required shared prerequisites."""++from contextlib import nullcontext+import threading++import pytest+++def selected_warm(monkeypatch):+ from utils import torch_warmup as warm++ calls = []+ monkeypatch.delenv(warm.DISABLE_ENV_VAR, raising = False)+ monkeypatch.setattr(warm, "_thread", None)+ monkeypatch.setattr(warm, "_thread_epoch", None)+ monkeypatch.setattr(warm, "_status", {"started": False, "finished": False, "stages": {}})+ monkeypatch.setattr(warm, "_detection_epoch", lambda: 7)+ monkeypatch.setattr(warm, "_owning_epoch", lambda epoch: nullcontext())+ monkeypatch.setattr(+ warm,+ "_STAGES",+ tuple(+ (name, lambda name = name: calls.append(name))+ for name in ("hardware", "inference_backend", "transformers", "datasets")+ ),+ )+ monkeypatch.setattr(warm, "_kick_early_quant_probe", lambda: calls.append("quantization"))+ yield warm, calls+ warm.join_background_warm(5)+++_FEATURES = ("hardware", "text", "datasets", "media", "quantization")+_ALL_SELECTIONS = [+ frozenset(feature for bit, feature in enumerate(_FEATURES) if mask & (1 << bit))+ for mask in range(32)+]+++ "features",+ _ALL_SELECTIONS,+ ids = lambda features: "+".join(feature for feature in _FEATURES if feature in features)+ or "none",+)+def test_every_selection_runs_only_its_stages_and_dependencies(selected_warm, features):+ warm, calls = selected_warm+ expected = []+ if features & {"hardware", "text", "media", "quantization"}:+ expected.append("hardware")+ if features & {"text", "media", "quantization"}:+ expected.append("inference_backend")+ if "quantization" in features:+ expected.append("quantization")+ if "text" in features:+ expected.append("transformers")+ if "datasets" in features:+ expected.append("datasets")+ assert warm.start_background_warm(features = features) is bool(features)+ assert warm.join_background_warm(5) is True+ assert calls == expected+ assert warm.warm_status()["finished"] is bool(features)+++def test_empty_selection_starts_no_worker(selected_warm):+ warm, calls = selected_warm+ assert warm.start_background_warm(features = set()) is False+ assert warm.warm_status()["started"] is False+ assert warm._thread is None+ assert not calls+++def test_selection_is_captured_before_waiting_for_the_first_response(selected_warm, monkeypatch):+ warm, calls = selected_warm+ monkeypatch.setattr(warm, "START_GATE_MAX_WAIT_S", 10)+ gate = threading.Event()+ selection = {"text"}+ assert warm.start_background_warm(gate = gate, features = selection) is True+ selection.update({"datasets", "media", "quantization"})+ gate.set()+ assert warm.join_background_warm(5) is True+ assert calls == ["hardware", "inference_backend", "transformers"]+++def test_legacy_explicit_call_keeps_the_full_warm(selected_warm):+ warm, calls = selected_warm+ assert warm.start_background_warm() is True+ assert warm.join_background_warm(5) is True+ assert calls == ["hardware", "inference_backend", "quantization", "transformers", "datasets"]+++def test_legacy_operator_disable_overrides_every_selection(selected_warm, monkeypatch):+ warm, calls = selected_warm+ monkeypatch.setenv(warm.DISABLE_ENV_VAR, "1")+ assert warm.start_background_warm(features = {"text", "quantization", "datasets"}) is False+ assert not calls++[email protected]("has_model", [False, True])+def test_quantization_fallback_is_independent_of_early_timing_and_diffusers(+ selected_warm, monkeypatch, has_model+):+ warm, calls = selected_warm+ monkeypatch.setenv(warm.EARLY_PROBE_ENV_VAR, "0")+ monkeypatch.setenv(warm.DIFFUSERS_PREWARM_DISABLE_ENV_VAR, "1")+ monkeypatch.setattr(warm, "_a_local_model_would_load_through_diffusers", lambda: has_model)+ monkeypatch.setattr(warm, "_prewarm_quant_probe", lambda: calls.append("probe"))+ warm.prewarm_quant_probe_if_image_models_exist()+ assert calls == (["probe"] if has_model else [])+++def test_quantization_fallback_honors_global_disable(selected_warm, monkeypatch):+ warm, calls = selected_warm+ monkeypatch.setenv(warm.DISABLE_ENV_VAR, "1")+ monkeypatch.setattr(+ warm,+ "_a_local_model_would_load_through_diffusers",+ lambda: pytest.fail("disabled quantization scanned local models"),+ )+ monkeypatch.setattr(warm, "_prewarm_quant_probe", lambda: calls.append("probe"))+ warm.prewarm_quant_probe_if_image_models_exist()+ assert not calls+++def test_restart_hands_the_new_selection_to_the_successor(selected_warm, monkeypatch):+ warm, calls = selected_warm+ epoch = [7]+ entered = threading.Event()+ release = threading.Event()++ def hardware():+ calls.append("hardware")+ entered.set()+ assert release.wait(5)++ monkeypatch.setattr(warm, "_detection_epoch", lambda: epoch[0])+ monkeypatch.setattr(+ warm,+ "_STAGES",+ (+ ("hardware", hardware),+ ("transformers", lambda: calls.append("transformers")),+ ("datasets", lambda: calls.append("datasets")),+ ),+ )+ assert warm.start_background_warm(features = {"text"})+ try:+ assert entered.wait(5)+ epoch[0] = 8+ assert warm.start_background_warm(features = {"datasets"})+ finally:+ release.set()+ assert warm.join_background_warm(5)+ assert calls == ["hardware", "datasets"]+++def test_a_retired_warm_does_not_launch_its_selected_quantization_check(selected_warm, monkeypatch):+ warm, calls = selected_warm+ epoch = [7]+ monkeypatch.setattr(warm, "_detection_epoch", lambda: epoch[0])++ def retire_during_import():+ calls.append("inference_backend")+ epoch[0] += 1++ monkeypatch.setattr(+ warm,+ "_STAGES",+ (+ ("hardware", lambda: calls.append("hardware")),+ ("inference_backend", retire_during_import),+ ),+ )+ assert warm.start_background_warm(features = {"quantization"})+ assert warm.join_background_warm(5)+ assert calls == ["hardware", "inference_backend"]diff --git a/studio/backend/tests/test_stall_watchdog.py b/studio/backend/tests/test_stall_watchdog.pyindex 4bb5075aecc..de3b160fa80 100644--- a/studio/backend/tests/test_stall_watchdog.py+++ b/studio/backend/tests/test_stall_watchdog.py@@ -313,9 +313,9 @@ def test_the_lifespan_wires_it_in():startup and retires it at shutdown entry, and either side can be edited alone."""source = (_BACKEND_DIR / "main.py").read_text(encoding = "utf-8")assert (- "start_stall_watchdog(asyncio.get_running_loop()" in source+ "start_stall_watchdog(" in source and "asyncio.get_running_loop()" in source), "main.py no longer starts the stall watchdog; the next #9712 stall leaves no dump behind"- assert "suppress = stand_down_for_the_warm" in source, (+ assert "stand_down_for_the_warm(warm_expected = _startup_warm_expected)" in source, ("the watchdog no longer stands down for the warm; every cold start would ""dump over the torch import")@@ -330,3 +330,25 @@ def test_the_lifespan_wires_it_in():"the watchdog is opt-in and the mac smoke workflow no longer opts in; the ""one place #9712 stalls have been seen runs without it")++[email protected]("warm_expected", [False, True])+def test_watchdog_uses_lifespan_warm_expectation_before_a_worker_starts(monkeypatch, warm_expected):+ import utils.stall_watchdog as sw+ import utils.torch_warmup as tw++ monkeypatch.delenv(tw.DISABLE_ENV_VAR, raising = False)+ monkeypatch.setattr(+ tw, "warm_status", lambda: {"started": False, "finished": False, "alive": False}+ )+ assert sw.stand_down_for_the_warm(warm_expected = warm_expected) is warm_expected+++def test_an_active_warm_still_suppresses_the_watchdog_without_a_planned_warm(monkeypatch):+ import utils.stall_watchdog as sw+ import utils.torch_warmup as tw++ monkeypatch.setattr(+ tw, "warm_status", lambda: {"started": True, "finished": False, "alive": True}+ )+ assert sw.stand_down_for_the_warm(warm_expected = False)diff --git a/studio/backend/tests/test_startup_defers_stack_dependent_work.py b/studio/backend/tests/test_startup_defers_stack_dependent_work.pyindex 7dea927b8e7..e6b18e381a2 100644--- a/studio/backend/tests/test_startup_defers_stack_dependent_work.py+++ b/studio/backend/tests/test_startup_defers_stack_dependent_work.py@@ -114,6 +114,12 @@ def test_post_warm_thread_is_started_by_the_lifespan():def test_post_warm_runs_repair_and_linked_folder_lifecycle(monkeypatch):import main as main_mod++ monkeypatch.setattr(+ main_mod,+ "_startup_ml_warmup_features",+ frozenset({"hardware", "text", "datasets", "media", "quantization"}),+ )import utils.mlx_repair as mlx_modorder: list[str] = []@@ -134,6 +140,12 @@ def test_post_warm_runs_repair_and_linked_folder_lifecycle(monkeypatch):def test_a_failing_mlx_probe_does_not_strand_linked_folder_startup(monkeypatch):import main as main_mod++ monkeypatch.setattr(+ main_mod,+ "_startup_ml_warmup_features",+ frozenset({"hardware", "text", "datasets", "media", "quantization"}),+ )import utils.mlx_repair as mlx_modran: list[str] = []diff --git a/studio/backend/tests/test_startup_defers_torch.py b/studio/backend/tests/test_startup_defers_torch.pyindex 6802c5d2fc8..715b05fc7f5 100644--- a/studio/backend/tests/test_startup_defers_torch.py+++ b/studio/backend/tests/test_startup_defers_torch.py@@ -268,7 +268,7 @@ _OFFLOAD_REQUIRED = [("routes/training.py", "get_hardware_utilization", "get_gpu_utilization"),("routes/training.py", "_admit_training_request", "ensure_hardware_detected"),("routes/export.py", "_ensure_export_supported", "export_capability"),- ("routes/models.py", "list_models", "get_inference_backend"),+ # list_models only peeks now; test_ml_warmup_idle_runtime.py covers cold first paint.# get_status only peeks now; test_async_singleton_access.py guards it.("routes/inference.py", "get_api_monitor", "_monitor_active_model"),("routes/inference.py", "get_api_monitor", "_monitor_context_length"),diff --git a/studio/backend/tests/test_startup_ml_warmup.py b/studio/backend/tests/test_startup_ml_warmup.pynew file mode 100644index 00000000000..c14ce27b6c8--- /dev/null+++ b/studio/backend/tests/test_startup_ml_warmup.py@@ -0,0 +1,259 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Cold startup must stay cold until an authenticated feature needs hardware."""++import asyncio+import threading+import types+from contextlib import nullcontext++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+++def cold(monkeypatch):+ import main++ monkeypatch.setattr(main, "_startup_ml_warmup_features", frozenset())+ monkeypatch.setattr(main, "_hardware_detection_requested", False)+ monkeypatch.setattr(main._hw_module, "DEVICE", None)+ monkeypatch.setattr(main._hw_module, "DETECTION_COMPLETE", threading.Event())+ monkeypatch.setattr(main, "_superseded_by_mlx_repair", lambda snapshot: False)+ monkeypatch.delenv(main.DISABLE_ENV_VAR, raising = False)+ return main+++def test_cold_health_and_liveness_do_not_start_detection(cold, monkeypatch):+ starts = []+ monkeypatch.setattr(cold, "start_background_detection", lambda: starts.append(True))+ app = FastAPI()+ app.add_api_route("/api/health", cold.health_check)+ app.add_api_route("/api/liveness", cold.liveness_check)+ with TestClient(app) as client:+ for _ in range(3):+ for path in ("/api/health", "/api/liveness"):+ reply = client.get(path)+ assert reply.status_code == 200+ assert reply.json()["hardware_detection_deferred"] is True+ assert starts == []+++def test_deferred_authed_health_still_names_the_host_platform(cold, monkeypatch):+ async def subject(request):+ return "owner"++ monkeypatch.setattr(cold, "_health_subject", subject)+ app = FastAPI()+ app.add_api_route("/api/health", cold.health_check)+ with TestClient(app) as client:+ reply = client.get("/api/health").json()+ assert reply["hardware_detection_deferred"] is True+ assert reply["device_type"] == {"darwin": "mac", "win32": "windows"}.get(+ cold.sys.platform, "linux"+ )+ assert "apple_silicon" in reply and "file_manager" in reply+++def test_anonymous_request_cannot_trigger_hardware_detection(cold, monkeypatch):+ starts = []+ monkeypatch.setattr(cold, "start_background_detection", lambda: starts.append(True))+ app = FastAPI()+ app.add_api_route("/api/health", cold.health_check)+ with TestClient(app) as client:+ reply = client.get("/api/health?detect_hardware=true")+ assert reply.status_code == 401+ assert not cold._hardware_detection_requested+ assert starts == []+++def test_authenticated_demand_resolves_and_keeps_the_hardware_verdict(cold, monkeypatch):+ starts = []++ async def subject(request):+ return "owner"++ def detect():+ starts.append(True)+ cold._hw_module.DEVICE = cold._hw_module.DeviceType.CUDA+ cold._hw_module.DETECTION_COMPLETE.set()++ monkeypatch.setattr(cold, "_health_subject", subject)+ monkeypatch.setattr(cold, "start_background_detection", detect)+ monkeypatch.setattr(+ cold,+ "_hardware_snapshot",+ lambda: (False, None, None) if cold._hw_module.DETECTION_COMPLETE.is_set() else None,+ )+ app = FastAPI()+ app.add_api_route("/api/health", cold.health_check)+ with TestClient(app) as client:+ for path in ("/api/health?detect_hardware=true", "/api/health"):+ reply = client.get(path)+ assert reply.status_code == 200+ assert reply.json()["chat_only"] is False+ assert "hardware_detection_deferred" not in reply.json()+ assert "hardware_detecting" not in reply.json()+ assert starts == [True]+++def test_opt_in_starts_detection_but_legacy_disable_still_wins(cold, monkeypatch):+ starts = []+ monkeypatch.setattr(cold, "start_background_detection", lambda: starts.append(True))+ monkeypatch.setattr(+ cold,+ "_startup_ml_warmup_features",+ frozenset({"hardware", "text", "datasets", "media", "quantization"}),+ )+ asyncio.run(cold._await_hardware_detection(0))+ assert starts == [True]+ monkeypatch.setenv(cold.DISABLE_ENV_VAR, "1")+ asyncio.run(cold._await_hardware_detection(0))+ assert starts == [True]+ assert cold._hardware_detection_deferred()+++def maintenance(cold, monkeypatch):+ from core.training import account_jobs+ from utils import mlx_repair++ calls = []+ monkeypatch.setattr(cold, "join_background_warm", lambda: calls.append("join"))+ monkeypatch.setattr(cold._hw_module, "is_apple_silicon", lambda: False)+ monkeypatch.setattr(+ cold, "_start_linked_folder_auto_sync", lambda generation: calls.append("folders")+ )+ monkeypatch.setattr(account_jobs, "startup_reconciliation_accounts", lambda: [])+ monkeypatch.setattr(mlx_repair, "start_mlx_autorepair_if_needed", lambda: calls.append("mlx"))+ monkeypatch.setattr(cold, "_refresh_dense_quant_capability", lambda: calls.append("dense"))+ monkeypatch.setattr(+ cold, "_refresh_quantised_streaming_capability", lambda: calls.append("streaming")+ )+ monkeypatch.setattr(+ cold,+ "prewarm_diffusers_if_image_models_exist",+ lambda **kwargs: calls.append(("diffusers", kwargs)),+ )+ monkeypatch.setattr(+ cold, "prewarm_quant_probe_if_image_models_exist", lambda: calls.append("quantization")+ )+ monkeypatch.setattr(cold, "background_media_import", lambda: nullcontext(True))+ # Even an unrelated request importing torch must not authorize speculative imports.+ monkeypatch.setitem(cold.sys.modules, "torch", types.ModuleType("torch"))+ return cold, calls+++def test_default_keeps_maintenance_without_speculative_ml_imports(maintenance):+ main, calls = maintenance+ main._post_warm_background_work()+ assert calls == ["join", "folders"]+++def test_opt_in_keeps_all_warmup_stages(maintenance, monkeypatch):+ main, calls = maintenance+ monkeypatch.setattr(+ main,+ "_startup_ml_warmup_features",+ frozenset({"hardware", "text", "datasets", "media", "quantization"}),+ )+ main._post_warm_background_work()+ assert calls == [+ "join",+ "mlx",+ "dense",+ "streaming",+ "folders",+ ("diffusers", {"warm_quantization": False}),+ "quantization",+ ]++[email protected]("retired", [False, True])+def test_cold_mlx_repair_waits_for_demand_and_honors_shutdown(maintenance, monkeypatch, retired):+ main, calls = maintenance+ from utils import mlx_repair++ repaired = threading.Event()+ workers = []++ def worker(**kwargs):+ thread = threading.Thread(**kwargs)+ workers.append(thread)+ return thread++ monkeypatch.setattr(main, "threading", types.SimpleNamespace(Thread = worker))+ monkeypatch.setattr(main, "_post_warm_generation", 123)+ monkeypatch.setattr(main._hw_module, "is_apple_silicon", lambda: True)+ monkeypatch.setattr(mlx_repair, "start_mlx_autorepair_if_needed", repaired.set)+ main._post_warm_background_work(123)+ assert calls == ["join", "folders"]+ assert not repaired.is_set()+ if retired:+ main._stop_post_warm_thread()+ main._hw_module.DETECTION_COMPLETE.set()+ for thread in workers:+ thread.join(2)+ assert not thread.is_alive()+ assert repaired.is_set() is (not retired)++[email protected]("probe,window_open", [(False, True), (True, True), (True, False)])+def test_media_capabilities_are_probed_only_for_the_picker(cold, monkeypatch, probe, window_open):+ calls = []++ class HardwareSnapshotReached(Exception):+ pass++ def snapshot(*args, **kwargs):+ raise HardwareSnapshotReached++ monkeypatch.setattr(cold, "_get_cached_system_gpu_info", snapshot)+ monkeypatch.setattr(cold, "background_media_import", lambda: nullcontext(window_open))+ monkeypatch.setattr(cold, "gate_torch_stack_import", lambda *args: calls.append("gate"))+ monkeypatch.setattr(cold, "_refresh_dense_quant_capability", lambda: calls.append("dense"))+ monkeypatch.setattr(+ cold, "_refresh_quantised_streaming_capability", lambda: calls.append("streaming")+ )+ with pytest.raises(HardwareSnapshotReached):+ cold.get_system_info(current_subject = "owner", probe_media = probe)+ assert calls == (["gate"] if probe else []) + (+ ["dense", "streaming"] if probe and window_open else []+ )++[email protected]("mask", range(32))+def test_post_warm_respects_every_feature_combination(maintenance, monkeypatch, mask):+ from utils.ml_warmup_settings import effective_ml_warmup_features++ main, calls = maintenance+ names = ("hardware", "text", "datasets", "media", "quantization")+ selected = {feature for bit, feature in enumerate(names) if mask & (1 << bit)}+ effective = effective_ml_warmup_features(selected)+ monkeypatch.setattr(main, "_startup_ml_warmup_features", effective)+ main._post_warm_background_work()+ expected = ["join"]+ if selected & {"hardware", "text", "media", "quantization"}:+ expected.append("mlx")+ if "media" in selected:+ expected.extend(["dense", "streaming"])+ expected.append("folders")+ if "media" in selected:+ expected.append(("diffusers", {"warm_quantization": False}))+ if "quantization" in selected:+ expected.append("quantization")+ assert calls == expected+++def test_datasets_only_keeps_automatic_hardware_detection_deferred(cold, monkeypatch):+ monkeypatch.setattr(cold, "_startup_ml_warmup_features", frozenset({"datasets"}))+ monkeypatch.setattr(+ cold,+ "start_background_detection",+ lambda: pytest.fail("datasets-only warm started a hardware probe"),+ )+ assert cold._ml_warmup_enabled()+ assert cold._hardware_detection_deferred()+ assert asyncio.run(cold._await_hardware_detection(0)) is Falsediff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex 45ba36086f8..40dfdf334d6 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -2206,6 +2206,12 @@ def test_video_gguf_status_reports_selected_quant_instead_of_only_compute_dtype(def test_video_status_family_capabilities_are_probed_once(monkeypatch):+ from utils.hardware import hardware as hw++ detection = threading.Event()+ detection.set()+ monkeypatch.setattr(hw, "DETECTION_COMPLETE", detection)+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU)calls = []available = (types.SimpleNamespace(name = "ltx-2", modular_workflow = False),diff --git a/studio/backend/tests/test_warm_window_review_fixes.py b/studio/backend/tests/test_warm_window_review_fixes.pyindex 94135cadbcc..61774efbe01 100644--- a/studio/backend/tests/test_warm_window_review_fixes.py+++ b/studio/backend/tests/test_warm_window_review_fixes.py@@ -813,6 +813,12 @@ def test_health_still_kicks_detection_when_the_warm_is_on(monkeypatch):import main as main_mod+ monkeypatch.setattr(+ main_mod,+ "_startup_ml_warmup_features",+ frozenset({"hardware", "text", "datasets", "media", "quantization"}),+ )+kicks = []monkeypatch.setattr(main_mod, "start_background_detection", lambda: kicks.append(1), raising = Truediff --git a/studio/backend/utils/ml_warmup_settings.py b/studio/backend/utils/ml_warmup_settings.pynew file mode 100644index 00000000000..8e5c06d4503--- /dev/null+++ b/studio/backend/utils/ml_warmup_settings.py@@ -0,0 +1,83 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Persisted, feature-specific opt-ins for loading ML libraries during startup."""++from __future__ import annotations++import os+from collections.abc import Iterable+from typing import Literal++MlWarmupFeature = Literal["hardware", "text", "datasets", "media", "quantization"]+ML_WARMUP_FEATURES: tuple[MlWarmupFeature, ...] = (+ "hardware",+ "text",+ "datasets",+ "media",+ "quantization",+)+ML_WARMUP_FEATURES_SETTING_KEY = "ml_library_warmup_features"+_HARDWARE_DEPENDENTS = frozenset({"text", "media", "quantization"})+++def ml_warmup_disabled_by_env() -> bool:+ """Preserve the existing operator override for every optional warmup stage."""+ return os.environ.get("UNSLOTH_STUDIO_DISABLE_TORCH_WARM") == "1"+++def _validate_features(features: Iterable[str]) -> frozenset[str]:+ if isinstance(features, (str, bytes, dict)):+ raise ValueError("Startup warmup features must be a list of supported features.")+ try:+ selected = list(features)+ except TypeError as exc:+ raise ValueError("Startup warmup features must be a list of supported features.") from exc+ if any(+ not isinstance(feature, str) or feature not in ML_WARMUP_FEATURES for feature in selected+ ):+ raise ValueError("Unknown startup warmup feature.")+ return frozenset(selected)+++def get_ml_warmup_features() -> frozenset[str]:+ """Missing, invalid or unreadable preferences keep optional imports cold."""+ try:+ from storage.studio_db import get_app_setting++ stored = get_app_setting(ML_WARMUP_FEATURES_SETTING_KEY, None)+ if not isinstance(stored, list):+ return frozenset()+ return _validate_features(stored)+ except Exception:+ return frozenset()+++def set_ml_warmup_features(features: Iterable[str]) -> frozenset[str]:+ """Save explicit selections in canonical order; dependencies stay implicit."""+ selected = _validate_features(features)+ from storage.studio_db import upsert_app_settings++ upsert_app_settings(+ {+ ML_WARMUP_FEATURES_SETTING_KEY: [+ feature for feature in ML_WARMUP_FEATURES if feature in selected+ ],+ }+ )+ return selected+++def effective_ml_warmup_features(features: Iterable[str]) -> frozenset[str]:+ """Text, media and quantization share hardware setup; datasets do not need it."""+ selected = _validate_features(features)+ if selected & _HARDWARE_DEPENDENTS:+ return selected | {"hardware"}+ return selected+++def get_startup_ml_warmup_features() -> frozenset[str]:+ """Resolve the launch's feature selection, respecting the broad disable flag."""+ if ml_warmup_disabled_by_env():+ return frozenset()+ return effective_ml_warmup_features(get_ml_warmup_features())diff --git a/studio/backend/utils/stall_watchdog.py b/studio/backend/utils/stall_watchdog.pyindex 7ae38caa87f..b49320c039d 100644--- a/studio/backend/utils/stall_watchdog.py+++ b/studio/backend/utils/stall_watchdog.py@@ -30,16 +30,19 @@ DEAD_MAN_TIMEOUT_S = 8.0DUMP_COOLDOWN_S = 600.0-def stand_down_for_the_warm() -> bool:- """True from process start until the warm is over: a switch armed before the warm's- GIL-holding ``import torch`` cannot be disarmed and would dump a known stall."""+def stand_down_for_the_warm(*, warm_expected: bool = True) -> bool:+ """Suppress an expected or active warm; a cold launch has no warm to wait for.++ A switch armed before a selected warm's GIL-holding ``import torch`` cannot be+ disarmed and would dump a known stall. Capture warm_expected for the lifespan.+ """from utils.torch_warmup import DISABLE_ENV_VAR as _WARM_DISABLEDfrom utils.torch_warmup import warm_statusstatus = warm_status()if status["started"]:return bool(status["alive"] and not status["finished"])- return os.environ.get(_WARM_DISABLED) != "1"+ return warm_expected and os.environ.get(_WARM_DISABLED) != "1"async def _noop() -> None:diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.pyindex e52e4b7930c..18d7e9f2af7 100644--- a/studio/backend/utils/torch_warmup.py+++ b/studio/backend/utils/torch_warmup.py@@ -16,7 +16,7 @@ import timefrom contextlib import contextmanagerfrom functools import partial, wrapsfrom importlib._bootstrap import _ModuleLockManager-from typing import Optional+from typing import Collection, Optionalfrom loggers import get_logger@@ -197,7 +197,7 @@ def _warm_transformers() -> None:def _warm_datasets() -> None:- # `import main` pulled it in; keep the first dataset op as cheap. Ungated: no torch needed.+ # Independent of hardware detection; datasets may import shared libraries such as torch.importlib.import_module("datasets")@@ -437,6 +437,21 @@ _STAGES = ()+def _selected_stage_names(features: Collection[str]) -> set[str]:+ """Dependencies are shared, but an unselected feature never gets its own warm stage."""+ selected = set(features)+ stages = set()+ if selected.intersection({"hardware", "text", "media", "quantization"}):+ stages.add("hardware")+ if selected.intersection({"text", "media", "quantization"}):+ stages.add("inference_backend") # Dynamo must finish before any compile-stack consumer.+ if "text" in selected:+ stages.add("transformers")+ if "datasets" in selected:+ stages.add("datasets")+ return stages++START_GATE_MAX_WAIT_S = 2.0@@ -452,27 +467,36 @@ def _wait_for_start_gate(gate: Optional[threading.Event]) -> None:)-def _warm(epoch: Optional[int] = None, gate: Optional[threading.Event] = None) -> None:+def _warm(+ epoch: Optional[int] = None,+ gate: Optional[threading.Event] = None,+ features: Optional[frozenset[str]] = None,+) -> None:_wait_for_start_gate(gate)started = time.perf_counter()if epoch is None:epoch = _detection_epoch()+ # None preserves explicit legacy callers; startup always supplies its immutable selection.+ stages = None if features is None else _selected_stage_names(features)+ warm_quantization = features is None or "quantization" in features# The scope binds the epoch so a mid-stage shutdown discards this pass, not republishes DEVICE.with _owning_epoch(epoch):for name, fn in _STAGES:+ if stages is not None and name not in stages:+ continueif epoch is not None and _detection_epoch() != epoch:# Before the first stage too: a shutdown between the epoch read and start().logger.info("torch warm stopped before %s: its lifespan ended", name)return# Only the real stage takes the epoch; a patched _STAGES entry is called bare._run_stage(name, partial(fn, epoch) if fn is _warm_hardware else fn)- if name == "inference_backend":- # dynamo is imported by now, so the probe's imports cannot race its first import (#10350).- _kick_early_quant_probe()if epoch is not None and _detection_epoch() != epoch:# Later stages reach get_device(), republishing DEVICE after teardown.logger.info("torch warm stopped after %s: its lifespan ended", name)return+ if name == "inference_backend" and warm_quantization:+ # Dynamo is ready and this lifespan still owns the work.+ _kick_early_quant_probe()_status["finished"] = True_status["seconds"] = round(time.perf_counter() - started, 3)logger.info("torch warm finished in %.1fms", (time.perf_counter() - started) * 1000)@@ -504,30 +528,37 @@ def _warm_after(previous: threading.Thread,epoch: Optional[int],gate: Optional[threading.Event] = None,+ features: Optional[frozenset[str]] = None,) -> None:"""Wait out a retired warm, then warm for ``epoch``. One importer at a time."""previous.join()- _warm(epoch, gate)+ _warm(epoch, gate, features)-def start_background_warm(gate: Optional[threading.Event] = None) -> bool:- """A finished thread from an earlier lifespan does not count; shutdown cleared the state it warmed.+def start_background_warm(+ gate: Optional[threading.Event] = None, *, features: Optional[Collection[str]] = None+) -> bool:+ """Warm selected features; omitting features preserves an explicit caller's full warm.+ A finished thread from an earlier lifespan does not count; shutdown cleared the state it warmed.``gate``: reports started now, runs stages once set or after START_GATE_MAX_WAIT_S (utils/first_response_gate.py)."""global _threadif os.environ.get(DISABLE_ENV_VAR) == "1":return False+ selection = None if features is None else frozenset(features)+ if selection is not None and not _selected_stage_names(selection):+ return Falseglobal _thread_epoch# Epoch read before start(): reading it in the child would adopt the post-shutdown one.epoch = _detection_epoch()with _start_lock:- target, args = _warm, (epoch, gate)+ target, args = _warm, (epoch, gate, selection)if _thread is not None:if _thread_epoch is not None and epoch == _thread_epoch:return Falseif _thread.is_alive():# Stale but mid-stage: hand off to a successor that joins it first, keeping one importer.- target, args = _warm_after, (_thread, epoch, gate)+ target, args = _warm_after, (_thread, epoch, gate, selection)else:_clear_finished_warm_locked()_thread = threading.Thread(@@ -673,7 +704,21 @@ def _prewarm_quant_probe() -> None:logger.debug("quant smoke probe prewarm skipped: %r", exc)-def prewarm_diffusers_if_image_models_exist() -> bool:+def prewarm_quant_probe_if_image_models_exist() -> None:+ """Fallback for a selected quantization check, including when early probing is disabled."""+ if os.environ.get(DISABLE_ENV_VAR) == "1":+ return+ try:+ if not _a_local_model_would_load_through_diffusers():+ return+ except Exception as exc:+ logger.debug("quant smoke probe gate unavailable: %r", exc)+ return+ # Unlike the early hint, validate any persisted table against the current stack.+ _prewarm_quant_probe()+++def prewarm_diffusers_if_image_models_exist(*, warm_quantization: bool = True) -> bool:"""Runs after the warm joins so it cannot delay a stage; skipped once a load claims the window; opt out with UNSLOTH_STUDIO_DISABLE_DIFFUSERS_PREWARM=1."""global _diffusers_prewarmedif _diffusers_prewarmed:@@ -767,8 +812,9 @@ def prewarm_diffusers_if_image_models_exist() -> bool:"diffusers prewarmed in %.0fms; the first image load skips that import",(time.perf_counter() - started) * 1000,)- # Outside the window: a child-process probe, not an import.- _prewarm_quant_probe()+ # Outside the window: a child-process probe, not an import. Startup opts into it separately.+ if warm_quantization:+ _prewarm_quant_probe()return Truediff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsxindex f634042ed0a..48840277966 100644--- a/studio/frontend/src/app/provider.tsx+++ b/studio/frontend/src/app/provider.tsx@@ -23,6 +23,7 @@ import {forgetMeasuredVerdict,usePlatformStore,} from "@/config/env";+import { routeNeedsHardware } from "@/config/hardware-verdict";import { getTauriAuthFailure, tauriAutoAuth } from "@/features/auth";import { resyncInferenceStatusAfterServerModelChange } from "@/features/chat/hooks/use-chat-model-runtime";import { DeepLinkHandler } from "@/features/deep-links";@@ -889,6 +890,9 @@ function TauriWrapper({ children }: { children: ReactNode }) {// Set once a backend that already answered goes away: the next one measures its hardware again.const servedRef = useRef(false);const verdictStaleRef = useRef(false);+ // Read at reconnect time only: a navigation must not trigger another health read.+ const pathnameRef = useRef(pathname);+ pathnameRef.current = pathname;useEffect(() => {if (status === "running") servedRef.current = true;else if (servedRef.current) verdictStaleRef.current = true;@@ -900,7 +904,11 @@ function TauriWrapper({ children }: { children: ReactNode }) {verdictStaleRef.current = false;forgetMeasuredVerdict();}- void fetchDeviceType({ force: true }).catch(() => undefined);+ void fetchDeviceType({+ force: true,+ // The open page's beforeLoad will not rerun, so it asks for detection here.+ detectHardware: routeNeedsHardware(pathnameRef.current),+ }).catch(() => undefined);}, [status, desktopAuthReady]);useEffect(() => {diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 9a9ab23c6b7..eefc7c889d1 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -14,7 +14,7 @@ import { Navbar } from "@/components/navbar";import { SidebarEdgeTrigger } from "@/components/sidebar-edge-trigger";import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";import { fetchDeviceType, usePlatformStore } from "@/config/env";-import { videoNavHint } from "@/config/hardware-verdict";+import { routeNeedsHardware, videoNavHint } from "@/config/hardware-verdict";import { ApiMonitorOverlay } from "@/features/api-monitor/api-monitor-overlay";import { DownloadApprovalDialog } from "@/features/browser";import {@@ -378,14 +378,19 @@ function isChatOnlyAllowed(pathname: string, trainAvailable: boolean): boolean {}export const Route = createRootRoute({- beforeLoad: async ({ location }) => {- await fetchDeviceType();- const { isChatOnly, isTrainUnavailable, capabilitiesUnknown } = usePlatformStore.getState();+ beforeLoad: async ({ location, preload }) => {+ await fetchDeviceType({+ // Hover preloads must leave an idle session cold.+ detectHardware: !preload && routeNeedsHardware(location.pathname),+ });+ const { isChatOnly, isTrainUnavailable, capabilitiesUnknown, detectionDeferred } =+ usePlatformStore.getState();const unmeasured = capabilitiesUnknown();if (isChatOnly() &&!isChatOnlyAllowed(location.pathname, !isTrainUnavailable()) &&- !(unmeasured && waitsOutUnknownVerdict(location.pathname))+ // A deferred chat_only is provisional; hardware routes requested detection above.+ !(unmeasured && (detectionDeferred || waitsOutUnknownVerdict(location.pathname)))) {throw redirect({ to: "/chat" });}diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 1748372e5db..e18e3bab9d2 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -1434,9 +1434,10 @@ export function AppSidebar() {// MLX self-heal or late detection can change the verdict after first health; re-poll.useEffect(() => {- // Also while deferred: under the kill switch health settles nothing.+ // Deferred detection starts only on demand, so there is no background verdict to poll.+ if (detectionDeferred) return;const selfHealSettled =- !chatOnly || (chatOnlyReason !== "mlx_unavailable" && !detectionDeferred);+ !chatOnly || chatOnlyReason !== "mlx_unavailable";// And on any platform while the verdict itself is out. fetchDeviceType spends its bounded wait at// most once per page load, so a host that detects slower keeps the provisional reply and nothing// else re-reads it: the rows above would spin and /studio would hold its loading panel for the rest@@ -3406,7 +3407,7 @@ export function AppSidebar() {? { label: "Install Training", onClick: () => setFullInstallOpen(true) }: undefined,spinner: trainingInProgress,- pending: capabilitiesUnknown,+ pending: capabilitiesUnknown && !detectionDeferred,pendingTooltip: t("shell.navigation.trainChecking"),onClick: () => {if (trainBlocked) {@@ -3430,7 +3431,7 @@ export function AppSidebar() {active: pathname === "/video" || pathname.startsWith("/video/"),disabled: videoDisabled,tooltip: videoDisabledHint,- pending: capabilitiesUnknown,+ pending: capabilitiesUnknown && !detectionDeferred,pendingTooltip: t("shell.navigation.videoChecking"),onClick: () => {navigateFromRow({ to: "/video" });diff --git a/studio/frontend/src/config/env.ts b/studio/frontend/src/config/env.tsindex 8f23a1c6b5e..d7487506c0a 100644--- a/studio/frontend/src/config/env.ts+++ b/studio/frontend/src/config/env.ts@@ -53,7 +53,7 @@ interface PlatformState {lanUrls: string[];fetched: boolean;verdictStale: boolean;- // torch-warm kill switch defers detection to first use; the sidebar polls.+ // Detection stays cold until a hardware-dependent page or operation requests it.detectionDeferred: boolean;isChatOnly: () => boolean;// Train and /studio are off: chat-only, except a host that trains on the CPU backend.@@ -98,10 +98,10 @@ export const usePlatformStore = create<PlatformState>()((_, get) => ({const state = get();return state.chatOnly && trainsOnCpu(state.chatOnlyReason, state.cpuTraining);},- // deferred detection is settled because no verdict will arrive this session.+ // Deferred is unknown, not an unsupported host; navigation can request detection.capabilitiesUnknown: () => {const state = get();- return (!state.fetched || state.verdictStale) && !state.detectionDeferred;+ return !state.fetched || state.verdictStale || state.detectionDeferred;},}));@@ -138,6 +138,27 @@ function localPlatformFallback(force?: boolean): DeviceType {// Bumped on a backend replacement so a read sent to the old backend is never joined.let backendGeneration = 0;+// Once detection was requested or observed, an older idle reply cannot defer this backend again.+let requestedHardwareGeneration: number | null = null;+let systemVerdictRead: { generation: number; promise: Promise<DeviceType> } | null = null;++/** Refresh the picker verdict; a cached caller may need to request detection again. */+export function refreshDeviceTypeAfterSystemInfo(+ { detectHardware = false }: { detectHardware?: boolean } = {},+): void {+ if (!usePlatformStore.getState().capabilitiesUnknown()) return;+ if (systemVerdictRead?.generation === backendGeneration) return;+ const entry = {+ generation: backendGeneration,+ promise: fetchDeviceType({ force: true, detectHardware }),+ };+ systemVerdictRead = entry;+ const release = () => {+ if (systemVerdictRead === entry) systemVerdictRead = null;+ };+ // System data remains usable while this independent health read finishes or fails.+ void entry.promise.then(release, release);+}// main.tsx and __root.tsx's beforeLoad both read at startup: an unforced call joins an unforced// read in flight for the same token, URL and backend generation. Forced refreshes never share.@@ -159,13 +180,16 @@ function readAuthToken(): string | null {// `force` re-reads /api/health even if cached, to pick up a late-arriving tunnel URL.export async function fetchDeviceType(options?: {force?: boolean;+ detectHardware?: boolean;}): Promise<DeviceType> {const { fetched } = usePlatformStore.getState();- if (fetched && !options?.force) return usePlatformStore.getState().deviceType;+ if (fetched && !options?.force && !options?.detectHardware)+ return usePlatformStore.getState().deviceType;// Desktop before server-port: port 0 never connects, so take the refused-fetch fallback.if (isTauri && getApiPort() === null) {return localPlatformFallback(options?.force);}+ if (options?.detectHardware) return readHealth({ ...options, force: true });if (options?.force) return readHealth(options);let token: string | null;@@ -200,9 +224,10 @@ export async function fetchDeviceType(options?: {}async function readHealth(- options: { force?: boolean } | undefined,+ options: { force?: boolean; detectHardware?: boolean } | undefined,knownToken?: string | null,): Promise<DeviceType> {+ const generation = backendGeneration;try {const token = knownToken === undefined ? readAuthToken() : knownToken;// Re-read while the backend is still detecting: chat_only is its pre-detection default and@@ -212,7 +237,12 @@ async function readHealth(const spendWait = Boolean(token) && !hardwareWaitSpent;const deadline = spendWait ? Date.now() + HARDWARE_DETECT_WAIT_MS : 0;let tokenRejected = false;- let res = await fetch(apiUrl("/api/health"), { headers });+ let detectionDeferred = false;+ // Only an authenticated, explicit page visit may request the cold hardware probe.+ const healthUrl = apiUrl(+ options?.detectHardware && token ? "/api/health?detect_hardware=true" : "/api/health",+ );+ let res = await fetch(healthUrl, { headers });while (res.ok && Date.now() < deadline) {const peek = (await res.clone().json()) as {hardware_detecting?: boolean;@@ -220,20 +250,23 @@ async function readHealth(version?: string;};// Deferred is not "in progress": nothing will settle, so do not wait.- if (!isProvisionalVerdict(peek) || isDetectionDeferred(peek)) break;+ detectionDeferred = isDetectionDeferred(peek);+ if (!isProvisionalVerdict(peek) || detectionDeferred) break;// A rejected token gets the unauthed body: no `version`, so the wait could only time out.if (peek.version === undefined) {tokenRejected = true;break;}await new Promise((resolve) => setTimeout(resolve, HARDWARE_DETECT_POLL_MS));- res = await fetch(apiUrl("/api/health"), { headers });+ res = await fetch(healthUrl, { headers });}- // Not spent on a rejected token, so a later sign-in in this page load still gets the wait.- if (spendWait && !tokenRejected) hardwareWaitSpent = true;+ if (generation !== backendGeneration) return usePlatformStore.getState().deviceType;+ // A rejected token or a deferred probe has not used the first real detection's wait.+ if (spendWait && !tokenRejected && !detectionDeferred) hardwareWaitSpent = true;if (res.ok) {const data = (await res.json()) as {device_type?: string;+ version?: string;apple_silicon?: boolean;file_manager?: FileManager;chat_only?: boolean;@@ -250,6 +283,21 @@ async function readHealth(hub_proxy?: string | null;datasets_server_proxy?: string | null;};+ if (generation !== backendGeneration) return usePlatformStore.getState().deviceType;+ if (+ data.version !== undefined &&+ !isDetectionDeferred(data) &&+ (options?.detectHardware || !isProvisionalVerdict(data))+ ) {+ requestedHardwareGeneration = generation;+ }+ if (+ !options?.detectHardware &&+ isDetectionDeferred(data) &&+ requestedHardwareGeneration === backendGeneration+ ) {+ return usePlatformStore.getState().deviceType;+ }// Before the authoritative-platform guard: hub_proxy is unauthed and idempotent, and a mirror// whose first authoritative reply already landed would otherwise never route Hub calls.const hubProxy = typeof data.hub_proxy === "string" ? data.hub_proxy : null;@@ -282,7 +330,7 @@ async function readHealth(: keepPlatform? previous.fileManager: undefined;- // Provisional keeps the stored verdict (resolveVerdict); deferred settles it without a replaced backend's reason.+ // Provisional keeps the stored verdict; a replaced backend must not keep the old reason.const { chatOnly, chatOnlyReason, chatOnlyDetail, chatOnlyHint } = resolveVerdict(data,previous.verdictStale && isDetectionDeferred(data)@@ -310,13 +358,15 @@ async function readHealth(cloudflareUrl: data.cloudflare_url ?? null,serverUrl: data.server_url ?? null,secure: data.secure ?? false,- fetched: data.device_type !== undefined || keepPlatform,+ // A deferred reply names the platform but stays unfetched, so later reads can settle the verdict.+ fetched: (data.device_type !== undefined && !isDetectionDeferred(data)) || keepPlatform,verdictStale: previous.verdictStale && isProvisionalVerdict(data) && !isDetectionDeferred(data),detectionDeferred: isDetectionDeferred(data),});return deviceType;}} catch {+ if (generation !== backendGeneration) return usePlatformStore.getState().deviceType;return localPlatformFallback(options?.force);}diff --git a/studio/frontend/src/config/hardware-verdict.ts b/studio/frontend/src/config/hardware-verdict.tsindex c9868ee0774..81a0cfd7847 100644--- a/studio/frontend/src/config/hardware-verdict.ts+++ b/studio/frontend/src/config/hardware-verdict.ts@@ -24,7 +24,7 @@ export function isProvisionalVerdict(data: HealthVerdict): boolean {return data.hardware_detecting === true;}-/** Under UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 nothing settles, so waiting would stall every load. */+/** A deferred probe has not started; an explicit hardware-dependent operation can request it. */export function isDetectionDeferred(data: HealthVerdict): boolean {return data.hardware_detection_deferred === true;}@@ -72,7 +72,7 @@ export function resolveVerdict(previous: ResolvedVerdict,): ResolvedVerdict {if (isDetectionDeferred(data)) {- // Nothing will settle, so take the backend's conservative chat_only instead of the browser guess.+ // Keep a conservative value, but detectionDeferred marks it unmeasured for feature gates.return {chatOnly: data.chat_only ?? true,chatOnlyReason: data.chat_only_reason ?? previous.chatOnlyReason,@@ -95,3 +95,10 @@ export function resolveVerdict(chatOnlyHint: data.chat_only_hint ?? null,};}++/** These pages gate entry on hardware, so an actual visit must start a deferred probe. */+export function routeNeedsHardware(pathname: string): boolean {+ return ["/studio", "/export", "/video"].some(+ (base) => pathname === base || pathname.startsWith(base + "/"),+ );+}diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex a072bfdd5ec..0450fb4776b 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -2936,8 +2936,8 @@ function isGgufLocalRow(row: LocalModelInfo): boolean {/** Chat-only installs run GGUF anywhere and MLX on a Mac; the picker hides every other local format there. */function runsOnThisPlatform(row: LocalModelInfo): boolean {const platform = usePlatformStore.getState();- // chatOnly is a BROWSER guess until the backend reports it; fail open, since validation refuses an ineligible pick.- if (!platform.fetched || !platform.isChatOnly()) return true;+ // chatOnly is a guess until the backend measures it (deferred detection included); fail open, since validation refuses an ineligible pick.+ if (platform.capabilitiesUnknown() || !platform.isChatOnly()) return true;if (isGgufLocalRow(row)) {return true;}@@ -2952,7 +2952,7 @@ function runsOnThisPlatform(row: LocalModelInfo): boolean {/** The picker hides cached non-GGUF rows outright on a chat-only install; same wait-for-the-server rule as above. */function cachedModelsRunOnThisPlatform(): boolean {const platform = usePlatformStore.getState();- return !platform.fetched || !platform.isChatOnly();+ return platform.capabilitiesUnknown() || !platform.isChatOnly();}/** One loadable thing on this device; `listVariants` is lazy, so only the repos the cascade reaches are scanned. */diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsxindex bcfab6e7ebf..c3473b257a6 100644--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx@@ -707,6 +707,7 @@ function ModelSelectorContent({) : (<><HubModelPicker+ open={open}models={models}additionalOnDeviceModels={additionalOnDeviceModels}loadedModelIdOverride={loadedModelIdOverride}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 e2c4708b131..ed714b9c528 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@@ -112,6 +112,7 @@ import {useModelMemory,} from "@/hooks/use-model-memory";import type { GpuInfo } from "@/hooks/use-gpu-info";+import { fetchSystemInfo } from "@/hooks/use-system";import { useVramBudgetFraction } from "@/hooks/use-vram-budget-fraction";import { copyToClipboard } from "@/lib/copy-to-clipboard";import { diffusionRouteSearch } from "@/lib/diffusion-route-search";@@ -3723,6 +3724,7 @@ export type ModelPickerRowFilter = (row: {}) => boolean;export function HubModelPicker({+ open,models,additionalOnDeviceModels = [],loadedModelIdOverride,@@ -3752,6 +3754,7 @@ export function HubModelPicker({rowFilter,moreModels,}: {+ open: boolean;models: ModelOption[];/** Task-runtime downloads whose cache layout the shared Hub inventory cannot represent. */additionalOnDeviceModels?: ModelOption[];@@ -3817,6 +3820,10 @@ export function HubModelPicker({const tasks = task ? (typeof task === "string" ? [task] : task) : [];return tasks.some((entry) => DIFFUSION_TASKS.has(entry));}, [task]);+ useEffect(() => {+ // Capabilities import optional media libraries, so ask only when this picker is open.+ if (open && diffusionLoad) void fetchSystemInfo({ probeMedia: true });+ }, [open, diffusionLoad]);// Run settings is the chat load form, which the Images and Video pages never read.const onConfigure = diffusionLoad ? undefined : onConfigureProp;const audioTaskPicker = taskFilterHasAudio(task);diff --git a/studio/frontend/src/features/settings/api/ml-warmup.ts b/studio/frontend/src/features/settings/api/ml-warmup.tsnew file mode 100644index 00000000000..7d2e069e937--- /dev/null+++ b/studio/frontend/src/features/settings/api/ml-warmup.ts@@ -0,0 +1,81 @@+// 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 { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++export const ML_WARMUP_FEATURES = [+ "hardware",+ "text",+ "datasets",+ "media",+ "quantization",+] as const;++export type MlWarmupFeature = (typeof ML_WARMUP_FEATURES)[number];++export type MlWarmupSettings = {+ features: MlWarmupFeature[];+ effectiveFeatures: MlWarmupFeature[];+ disabledByEnv: boolean;+};++type ApiMlWarmupSettings = {+ features: MlWarmupFeature[];+ // biome-ignore lint/style/useNamingConvention: API schema+ effective_features: MlWarmupFeature[];+ // biome-ignore lint/style/useNamingConvention: API schema+ disabled_by_env: boolean;+};++function fromApi(settings: ApiMlWarmupSettings): MlWarmupSettings {+ return {+ features: settings.features,+ effectiveFeatures: settings.effective_features,+ disabledByEnv: settings.disabled_by_env,+ };+}++export async function loadMlWarmupSettings(): Promise<MlWarmupSettings> {+ const res = await authFetch("/api/settings/ml-warmup");+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to load startup warmup settings"),+ );+ }+ return fromApi(await res.json());+}++export async function updateMlWarmupSettings(+ features: readonly MlWarmupFeature[],+): Promise<MlWarmupSettings> {+ const res = await authFetch("/api/settings/ml-warmup", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ features }),+ });+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to save startup warmup settings"),+ );+ }+ return fromApi(await res.json());+}++/** Keep hardware's explicit preference intact when a dependent selection is removed. */+export function updateWarmupSelection(+ selected: readonly MlWarmupFeature[],+ feature: MlWarmupFeature,+ enabled: boolean,+): MlWarmupFeature[] {+ const next = new Set(selected);+ if (enabled) next.add(feature);+ else next.delete(feature);+ return ML_WARMUP_FEATURES.filter((item) => next.has(item));+}++export function hardwareWarmupRequired(features: readonly MlWarmupFeature[]): boolean {+ return features.some(+ (feature) => feature === "text" || feature === "media" || feature === "quantization",+ );+}diff --git a/studio/frontend/src/features/settings/components/ml-warmup-section.tsx b/studio/frontend/src/features/settings/components/ml-warmup-section.tsxnew file mode 100644index 00000000000..7032c20ed5d--- /dev/null+++ b/studio/frontend/src/features/settings/components/ml-warmup-section.tsx@@ -0,0 +1,133 @@+// 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 { Switch } from "@/components/ui/switch";+import { useT } from "@/i18n";+import { useEffect, useState } from "react";+import {+ type MlWarmupFeature,+ type MlWarmupSettings,+ hardwareWarmupRequired,+ loadMlWarmupSettings,+ updateMlWarmupSettings,+ updateWarmupSelection,+} from "../api/ml-warmup";+import { SettingsRow } from "./settings-row";+import { SettingsSection } from "./settings-section";++const FEATURE_ROWS = [+ ["hardware", "hardwareLabel", "hardwareDescription"],+ ["text", "textLabel", "textDescription"],+ ["datasets", "datasetsLabel", "datasetsDescription"],+ ["media", "mediaLabel", "mediaDescription"],+ ["quantization", "quantizationLabel", "quantizationDescription"],+] as const;++/** Installation-wide choices; mounted only for the owner and applied on restart. */+export function MlWarmupSection() {+ const t = useT();+ const [settings, setSettings] = useState<MlWarmupSettings | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ let cancelled = false;+ void loadMlWarmupSettings()+ .then((next) => {+ if (cancelled) return;+ setSettings(next);+ setError(null);+ })+ .catch((err) => {+ if (cancelled) return;+ setError(+ err instanceof Error+ ? err.message+ : t("settings.general.mlWarmup.loadError"),+ );+ });+ return () => {+ cancelled = true;+ };+ }, [t]);++ const save = async (feature: MlWarmupFeature, enabled: boolean) => {+ if (!settings || saving) return;+ setSaving(true);+ setError(null);+ try {+ const selected = updateWarmupSelection(settings.features, feature, enabled);+ setSettings(await updateMlWarmupSettings(selected));+ } catch (err) {+ setError(+ err instanceof Error+ ? err.message+ : t("settings.general.mlWarmup.saveError"),+ );+ } finally {+ setSaving(false);+ }+ };++ const hardwareRequired = hardwareWarmupRequired(settings?.features ?? []);+ const note =+ error ??+ (settings?.disabledByEnv+ ? t("settings.general.mlWarmup.disabledByEnv")+ : null);++ return (+ <SettingsSection+ title={t("settings.general.mlWarmup.sectionTitle")}+ description={+ t("settings.general.mlWarmup.description") ++ " " ++ t("settings.general.mlWarmup.restartRequired")+ }+ >+ {FEATURE_ROWS.map(([feature, label, description]) => {+ const required = feature === "hardware" && hardwareRequired;+ const row = (+ <SettingsRow+ label={t(`settings.general.mlWarmup.${label}`)}+ description={+ t(`settings.general.mlWarmup.${description}`) ++ (required+ ? " " + t("settings.general.mlWarmup.requiredBySelections")+ : "")+ }+ >+ <Switch+ aria-label={t(`settings.general.mlWarmup.${label}`)}+ checked={settings?.effectiveFeatures.includes(feature) ?? false}+ disabled={!settings || saving || settings.disabledByEnv || required}+ onCheckedChange={(enabled) => void save(feature, enabled)}+ />+ </SettingsRow>+ );+ return feature === "quantization" ? (+ <div key={feature} className="mt-1 border-t border-border/60 pt-3">+ <p className="text-xs font-medium text-muted-foreground">+ {t("settings.general.mlWarmup.advanced")}+ </p>+ {row}+ </div>+ ) : (+ <div key={feature}>{row}</div>+ );+ })}+ {note ? (+ <p+ role={error ? "alert" : undefined}+ className={+ error+ ? "mt-1 text-xs text-destructive"+ : "mt-1 text-xs text-muted-foreground"+ }+ >+ {note}+ </p>+ ) : null}+ </SettingsSection>+ );+}diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex f3311430c54..79964718a74 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -30,6 +30,12 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.general.previewSharing.revokeLabel","settings.general.rag.sectionTitle","settings.general.rag.embeddingModel",+ "settings.general.mlWarmup.sectionTitle",+ "settings.general.mlWarmup.hardwareLabel",+ "settings.general.mlWarmup.textLabel",+ "settings.general.mlWarmup.datasetsLabel",+ "settings.general.mlWarmup.mediaLabel",+ "settings.general.mlWarmup.quantizationLabel","settings.general.helperLlm.sectionTitle","settings.general.helperLlm.preloadOnStartup","settings.general.hub.sectionTitle",@@ -430,6 +436,12 @@ const FULL_INSTALL_ENTRY: TranslationKey = "settings.general.fullInstall.label";// owner-only rows on tabs visible to every account.const OWNER_ONLY_ENTRIES: ReadonlySet<TranslationKey> = new Set([+ "settings.general.mlWarmup.sectionTitle",+ "settings.general.mlWarmup.hardwareLabel",+ "settings.general.mlWarmup.textLabel",+ "settings.general.mlWarmup.datasetsLabel",+ "settings.general.mlWarmup.mediaLabel",+ "settings.general.mlWarmup.quantizationLabel","settings.sandbox.toolsSection","settings.sandbox.python","settings.sandbox.terminal",diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsxindex 664003ce163..55ed52c7c5a 100644--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx@@ -218,7 +218,9 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {const [openingRecipe, setOpeningRecipe] = useState(false);const [loadingTraining, setLoadingTraining] = useState(false);// Hosts that cannot train redirect /studio, so a Train-tab load would strand the user.- const trainUnavailable = usePlatformStore((s) => s.isTrainUnavailable());+ const trainUnavailable = usePlatformStore(+ (s) => s.isTrainUnavailable() && !s.capabilitiesUnknown(),+ );const ragUnavailable = useRagAvailabilityStore((s) => s.isUnavailable());const ragAvailabilityUnknown = useRagAvailabilityStore((s) =>s.availabilityUnknown(),diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex 7448b8468e7..3d6623c5e93 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -97,6 +97,7 @@ import {} from "@/features/hub";import { DownloadTransportRow } from "../components/download-transport-row";import { HubSettingsSection } from "../components/hub-settings-section";+import { MlWarmupSection } from "../components/ml-warmup-section";import { NotificationFrequencySelect } from "../components/notification-frequency-select";import { SettingsRow } from "../components/settings-row";import { SettingsSection } from "../components/settings-section";@@ -812,6 +813,8 @@ export function GeneralTab() {</SettingsSection>+ <MlWarmupSection />+<SettingsSection title={t("settings.general.helperLlm.sectionTitle")}><SettingsRowlabel={t("settings.general.helperLlm.preloadOnStartup")}diff --git a/studio/frontend/src/hooks/use-system.ts b/studio/frontend/src/hooks/use-system.tsindex 91a739992b2..95ddd5b6d2c 100644--- a/studio/frontend/src/hooks/use-system.ts+++ b/studio/frontend/src/hooks/use-system.ts@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { authFetch } from "@/features/auth";+import { refreshDeviceTypeAfterSystemInfo } from "@/config/env";import { useEffect, useMemo, useState } from "react";import { disposableTimeoutSignal } from "../features/hub/lib/abort-signals";import {@@ -114,6 +115,7 @@ export interface SystemInfoResponse {let cachedSystem: SystemInfoResponse | null = null;let systemFetchPromise: Promise<SystemInfoResponse | null> | null = null;+let systemFetchProbesMedia = false;const systemSubscribers = new Set<(data: SystemInfoResponse) => void>();let vulkanRetrySubscribers = 0;let vulkanRetryId: number | null = null;@@ -209,26 +211,35 @@ function scheduleVulkanRetry(): void {export async function fetchSystemInfo({force = false,refreshMemory = false,-}: { force?: boolean; refreshMemory?: boolean } = {}): Promise<SystemInfoResponse | null> {+ probeMedia = false,+}: { force?: boolean; refreshMemory?: boolean; probeMedia?: boolean } = {}): Promise<SystemInfoResponse | null> {if (systemFetchPromise) {- if (!refreshMemory) return systemFetchPromise;- // An in-flight snapshot may predate the resident model.+ if (!refreshMemory && (!probeMedia || systemFetchProbesMedia)) return systemFetchPromise;+ // A resident-memory refresh or media probe needs more than an ordinary snapshot.await systemFetchPromise;- return fetchSystemInfo({ force, refreshMemory });+ return fetchSystemInfo({ force, refreshMemory, probeMedia });+ }+ if (!force && !refreshMemory && !probeMedia && cachedSystem) {+ refreshDeviceTypeAfterSystemInfo({ detectHardware: true });+ return cachedSystem;}- if (!force && !refreshMemory && cachedSystem) return cachedSystem;+ systemFetchProbesMedia = probeMedia;systemFetchPromise = (async () => {const timeout = disposableTimeoutSignal(SYSTEM_FETCH_TIMEOUT_MS);try {+ const query = new URLSearchParams();+ if (refreshMemory) query.set("refresh_memory", "true");+ if (probeMedia) query.set("probe_media", "true");const res = await authFetch(- refreshMemory ? "/api/system?refresh_memory=true" : "/api/system",+ query.size ? "/api/system?" + query.toString() : "/api/system",{ signal: timeout.signal },);if (!res.ok) throw new Error(`HTTP ${res.status}`);const data = await res.json();cachedSystem = { ...(data as SystemInfoResponse), status: "ready" };+ refreshDeviceTypeAfterSystemInfo();systemSubscribers.forEach((subscriber) => subscriber(cachedSystem!));return cachedSystem;} catch {@@ -236,6 +247,7 @@ export async function fetchSystemInfo({} finally {timeout.dispose();systemFetchPromise = null;+ systemFetchProbesMedia = false;scheduleVulkanRetry();}})();diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 3044b8f0974..ab03a088e06 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1871,6 +1871,26 @@ export const ar = {autoTitleNewChats: "عنونة المحادثات الجديدة تلقائيًا",autoTitleNewChatsDescription:"إنشاء عنوان قصير من الرسالة الأولى.",+ mlWarmup: {+ sectionTitle: "أداء بدء التشغيل",+ description: "جهّز الميزات المحددة لتسريع استخدامها لأول مرة. جميع الخيارات معطّلة افتراضيًا. قد تؤدي الخيارات إلى تحميل تبعيات مشتركة واستخدام المزيد من RAM أثناء الخمول.",+ restartRequired: "تُطبّق التغييرات بعد إعادة تشغيل Unsloth.",+ hardwareLabel: "اكتشاف العتاد",+ hardwareDescription: "اكتشف وحدات GPU وجهّز PyTorch.",+ textLabel: "النماذج النصية",+ textDescription: "جهّز دعم النماذج النصية في Transformers.",+ datasetsLabel: "إعداد مجموعات البيانات",+ datasetsDescription: "جهّز Datasets وتبعياتها للمعاينة والمعالجة.",+ mediaLabel: "نماذج الصور والفيديو",+ mediaDescription: "جهّز Diffusers وتبعيات النماذج المشتركة.",+ advanced: "خيارات متقدمة",+ quantizationLabel: "فحوصات أولية لتكميم الصور",+ quantizationDescription: "تحقّق من الدعم قبل تحميل نموذج صور مكمّم لأول مرة. قد يزيد ذلك استخدام RAM لفترة وجيزة.",+ requiredBySelections: "مطلوب للخيارات التي حددتها.",+ disabledByEnv: "مُعطّل بواسطة UNSLOTH_STUDIO_DISABLE_TORCH_WARM في بيئة الخادم.",+ loadError: "فشل تحميل إعدادات التهيئة المسبقة عند بدء التشغيل.",+ saveError: "فشل حفظ إعدادات التهيئة المسبقة عند بدء التشغيل.",+ },helperLlm: {sectionTitle: "نموذج LLM المساعد",preloadOnStartup: "تحميل نموذج LLM المساعد مسبقًا عند بدء التشغيل",diff --git a/studio/frontend/src/i18n/locales/cs.ts b/studio/frontend/src/i18n/locales/cs.tsindex 266bdc83df1..bdfbe032509 100644--- a/studio/frontend/src/i18n/locales/cs.ts+++ b/studio/frontend/src/i18n/locales/cs.ts@@ -2050,6 +2050,26 @@ export const cs = {chatDefaults: "Výchozí nastavení chatu",autoTitleNewChats: "Automaticky pojmenovávat nové chaty",autoTitleNewChatsDescription: "Vygenerovat název z první zprávy.",+ mlWarmup: {+ sectionTitle: "Výkon při spuštění",+ description: "Připravte vybrané funkce pro rychlejší první použití. Všechny možnosti jsou ve výchozím nastavení vypnuté. Mohou načítat sdílené závislosti a zvyšovat využití RAM při nečinnosti.",+ restartRequired: "Změny se projeví po restartování Unsloth.",+ hardwareLabel: "Detekce hardwaru",+ hardwareDescription: "Detekovat GPU a připravit PyTorch.",+ textLabel: "Textové modely",+ textDescription: "Připravit podporu textových modelů Transformers.",+ datasetsLabel: "Příprava datových sad",+ datasetsDescription: "Připravit Datasets a jeho závislosti pro náhledy a zpracování.",+ mediaLabel: "Obrazové a video modely",+ mediaDescription: "Připravit Diffusers a sdílené závislosti modelů.",+ advanced: "Pokročilé",+ quantizationLabel: "Předběžné kontroly kvantizace obrazových modelů",+ quantizationDescription: "Zkontrolovat podporu před prvním načtením kvantizovaného obrazového modelu. Může krátkodobě zvýšit využití RAM.",+ requiredBySelections: "Vyžadováno vybranými možnostmi.",+ disabledByEnv: "Vypnuto proměnnou UNSLOTH_STUDIO_DISABLE_TORCH_WARM v prostředí backendu.",+ loadError: "Nastavení předběžné přípravy při spuštění se nepodařilo načíst.",+ saveError: "Nastavení předběžné přípravy při spuštění se nepodařilo uložit.",+ },helperLlm: {sectionTitle: "Pomocný LLM",preloadOnStartup: "Při spuštění předem stáhnout pomocný LLM",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex a087f0bdae4..f5220c0068b 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1884,6 +1884,26 @@ export const de = {autoTitleNewChats: "Neue Chats automatisch benennen",autoTitleNewChatsDescription:"Erzeugt einen kurzen Titel aus der ersten Nachricht.",+ mlWarmup: {+ sectionTitle: "Leistung beim Start",+ description: "Bereite ausgewählte Funktionen für eine schnellere erste Nutzung vor. Standardmäßig sind alle deaktiviert. Die Optionen können gemeinsam genutzte Abhängigkeiten laden und den RAM-Verbrauch im Leerlauf erhöhen.",+ restartRequired: "Änderungen werden nach einem Neustart von Unsloth wirksam.",+ hardwareLabel: "Hardwareerkennung",+ hardwareDescription: "GPU erkennen und PyTorch vorbereiten.",+ textLabel: "Textmodelle",+ textDescription: "Die Unterstützung für Textmodelle in Transformers vorbereiten.",+ datasetsLabel: "Datensatzvorbereitung",+ datasetsDescription: "Datasets und seine Abhängigkeiten für Vorschauen und die Verarbeitung vorbereiten.",+ mediaLabel: "Bild- und Videomodelle",+ mediaDescription: "Diffusers und gemeinsam genutzte Modellabhängigkeiten vorbereiten.",+ advanced: "Erweitert",+ quantizationLabel: "Vorabprüfungen für die Bildquantisierung",+ quantizationDescription: "Die Unterstützung vor dem ersten Laden eines quantisierten Bildmodells prüfen. Kann den RAM-Verbrauch kurzzeitig erhöhen.",+ requiredBySelections: "Durch deine Auswahl erforderlich.",+ disabledByEnv: "Deaktiviert durch UNSLOTH_STUDIO_DISABLE_TORCH_WARM in der Backend-Umgebung.",+ loadError: "Einstellungen zur Vorbereitung beim Start konnten nicht geladen werden.",+ saveError: "Einstellungen zur Vorbereitung beim Start konnten nicht gespeichert werden.",+ },helperLlm: {sectionTitle: "Helfer-LLM",preloadOnStartup: "Helfer-LLM beim Start vorab zwischenspeichern",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 7001d630df8..19559ee9fa3 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1878,6 +1878,29 @@ export const en = {autoTitleNewChats: "Auto-title new chats",autoTitleNewChatsDescription:"Generate a title from the first message.",+ mlWarmup: {+ sectionTitle: "Startup performance",+ description:+ "Prepare selected features for faster first use. All off by default. Options may load shared dependencies and use more RAM while idle.",+ restartRequired: "Changes apply after restarting Unsloth.",+ hardwareLabel: "Hardware detection",+ hardwareDescription: "Detect GPUs and prepare PyTorch.",+ textLabel: "Text models",+ textDescription: "Prepare Transformers text-model support.",+ datasetsLabel: "Dataset preparation",+ datasetsDescription: "Prepare Datasets and its dependencies for previews and processing.",+ mediaLabel: "Image and video models",+ mediaDescription: "Prepare Diffusers and shared model dependencies.",+ advanced: "Advanced",+ quantizationLabel: "Image quantization prechecks",+ quantizationDescription:+ "Check support before the first quantized image model load. Can briefly increase RAM use.",+ requiredBySelections: "Required by your selections.",+ disabledByEnv:+ "Disabled by UNSLOTH_STUDIO_DISABLE_TORCH_WARM in the backend environment.",+ loadError: "Failed to load startup warmup settings.",+ saveError: "Failed to save startup warmup settings.",+ },helperLlm: {sectionTitle: "Helper LLM",preloadOnStartup: "Pre-cache Helper LLM on startup",diff --git a/studio/frontend/src/i18n/locales/es-419.ts b/studio/frontend/src/i18n/locales/es-419.tsindex 44ab304fab2..06bb3e273f0 100644--- a/studio/frontend/src/i18n/locales/es-419.ts+++ b/studio/frontend/src/i18n/locales/es-419.ts@@ -2062,6 +2062,26 @@ export const es419 = {autoTitleNewChats: "Poner título automático a los chats nuevos",autoTitleNewChatsDescription:"Genera un título a partir del primer mensaje.",+ mlWarmup: {+ sectionTitle: "Rendimiento al iniciar",+ description: "Prepara las funciones seleccionadas para acelerar su primer uso. Todas están desactivadas de forma predeterminada. Estas opciones pueden cargar dependencias compartidas y aumentar el uso de RAM en reposo.",+ restartRequired: "Los cambios se aplican después de reiniciar Unsloth.",+ hardwareLabel: "Detección de hardware",+ hardwareDescription: "Detectar las GPU y preparar PyTorch.",+ textLabel: "Modelos de texto",+ textDescription: "Preparar el soporte de Transformers para modelos de texto.",+ datasetsLabel: "Preparación de conjuntos de datos",+ datasetsDescription: "Preparar Datasets y sus dependencias para las vistas previas y el procesamiento.",+ mediaLabel: "Modelos de imagen y video",+ mediaDescription: "Preparar Diffusers y las dependencias compartidas de los modelos.",+ advanced: "Avanzado",+ quantizationLabel: "Verificaciones previas de cuantización de imagen",+ quantizationDescription: "Verificar la compatibilidad antes de cargar por primera vez un modelo de imagen cuantizado. Puede aumentar brevemente el uso de RAM.",+ requiredBySelections: "Necesario para las opciones seleccionadas.",+ disabledByEnv: "Desactivado por UNSLOTH_STUDIO_DISABLE_TORCH_WARM en el entorno del backend.",+ loadError: "No se pudo cargar la configuración de preparación al iniciar.",+ saveError: "No se pudo guardar la configuración de preparación al iniciar.",+ },helperLlm: {sectionTitle: "LLM auxiliar",preloadOnStartup: "Precargar el LLM auxiliar en caché al iniciar",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex cdca2fd482d..22f5941894d 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1881,6 +1881,26 @@ export const es = {autoTitleNewChats: "Titular automáticamente los chats nuevos",autoTitleNewChatsDescription:"Genera un título breve a partir del primer mensaje.",+ mlWarmup: {+ sectionTitle: "Rendimiento al iniciar",+ description: "Prepara las funciones seleccionadas para acelerar su primer uso. Todas están desactivadas por defecto. Estas opciones pueden cargar dependencias compartidas y aumentar el uso de RAM en reposo.",+ restartRequired: "Los cambios se aplican después de reiniciar Unsloth.",+ hardwareLabel: "Detección de hardware",+ hardwareDescription: "Detectar las GPU y preparar PyTorch.",+ textLabel: "Modelos de texto",+ textDescription: "Preparar el soporte de Transformers para modelos de texto.",+ datasetsLabel: "Preparación de conjuntos de datos",+ datasetsDescription: "Preparar Datasets y sus dependencias para las vistas previas y el procesamiento.",+ mediaLabel: "Modelos de imagen y vídeo",+ mediaDescription: "Preparar Diffusers y las dependencias compartidas de los modelos.",+ advanced: "Avanzado",+ quantizationLabel: "Comprobaciones previas de cuantización de imagen",+ quantizationDescription: "Comprobar la compatibilidad antes de cargar por primera vez un modelo de imagen cuantizado. Puede aumentar brevemente el uso de RAM.",+ requiredBySelections: "Necesario para las opciones seleccionadas.",+ disabledByEnv: "Desactivado por UNSLOTH_STUDIO_DISABLE_TORCH_WARM en el entorno del backend.",+ loadError: "No se pudo cargar la configuración de preparación al iniciar.",+ saveError: "No se pudo guardar la configuración de preparación al iniciar.",+ },helperLlm: {sectionTitle: "LLM auxiliar",preloadOnStartup: "Precargar el LLM auxiliar al iniciar",diff --git a/studio/frontend/src/i18n/locales/fa.ts b/studio/frontend/src/i18n/locales/fa.tsindex 8e562892193..6944c056093 100644--- a/studio/frontend/src/i18n/locales/fa.ts+++ b/studio/frontend/src/i18n/locales/fa.ts@@ -2033,6 +2033,26 @@ export const fa = {chatDefaults: "پیشفرضهای گفتگو",autoTitleNewChats: "عنوانگذاری خودکار گفتگوهای جدید",autoTitleNewChatsDescription: "از اولین پیام یک عنوان تولید میشود.",+ mlWarmup: {+ sectionTitle: "کارایی هنگام راهاندازی",+ description: "قابلیتهای انتخابشده را برای استفادهٔ اولیهٔ سریعتر آماده کنید. همهٔ گزینهها بهطور پیشفرض خاموش هستند. گزینهها ممکن است وابستگیهای مشترک را بارگذاری کنند و در حالت بیکار RAM بیشتری مصرف کنند.",+ restartRequired: "تغییرات پس از راهاندازی مجدد Unsloth اعمال میشوند.",+ hardwareLabel: "شناسایی سختافزار",+ hardwareDescription: "GPUها را شناسایی و PyTorch را آماده کنید.",+ textLabel: "مدلهای متنی",+ textDescription: "پشتیبانی از مدلهای متنی در Transformers را آماده کنید.",+ datasetsLabel: "آمادهسازی مجموعهدادهها",+ datasetsDescription: "Datasets و وابستگیهای آن را برای پیشنمایش و پردازش آماده کنید.",+ mediaLabel: "مدلهای تصویر و ویدیو",+ mediaDescription: "Diffusers و وابستگیهای مشترک مدلها را آماده کنید.",+ advanced: "پیشرفته",+ quantizationLabel: "بررسیهای اولیهٔ کوانتیزهسازی تصویر",+ quantizationDescription: "پیش از نخستین بارگذاری مدل تصویر کوانتیزهشده، پشتیبانی را بررسی کنید. ممکن است مصرف RAM را برای مدت کوتاهی افزایش دهد.",+ requiredBySelections: "برای گزینههای انتخابشدهٔ شما ضروری است.",+ disabledByEnv: "با UNSLOTH_STUDIO_DISABLE_TORCH_WARM در محیط بکاند غیرفعال شده است.",+ loadError: "بارگذاری تنظیمات آمادهسازی اولیه هنگام راهاندازی ناموفق بود.",+ saveError: "ذخیرهٔ تنظیمات آمادهسازی اولیه هنگام راهاندازی ناموفق بود.",+ },helperLlm: {sectionTitle: "LLM کمکی",preloadOnStartup: "پیشدانلود LLM کمکی هنگام راهاندازی",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 6939d25d6f7..faa773515fb 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1883,6 +1883,26 @@ export const fr = {autoTitleNewChats: "Titrer automatiquement les nouvelles discussions",autoTitleNewChatsDescription:"Générer un titre court à partir du premier message.",+ mlWarmup: {+ sectionTitle: "Performances au démarrage",+ description: "Préparez les fonctionnalités sélectionnées pour accélérer leur première utilisation. Toutes sont désactivées par défaut. Ces options peuvent charger des dépendances partagées et augmenter l'utilisation de RAM au repos.",+ restartRequired: "Les modifications s'appliquent après le redémarrage d'Unsloth.",+ hardwareLabel: "Détection du matériel",+ hardwareDescription: "Détecter les GPU et préparer PyTorch.",+ textLabel: "Modèles de texte",+ textDescription: "Préparer la prise en charge des modèles de texte par Transformers.",+ datasetsLabel: "Préparation des jeux de données",+ datasetsDescription: "Préparer Datasets et ses dépendances pour les aperçus et le traitement.",+ mediaLabel: "Modèles d'image et de vidéo",+ mediaDescription: "Préparer Diffusers et les dépendances partagées des modèles.",+ advanced: "Avancé",+ quantizationLabel: "Vérifications préalables à la quantification d'image",+ quantizationDescription: "Vérifier la compatibilité avant le premier chargement d'un modèle d'image quantifié. Peut brièvement augmenter l'utilisation de RAM.",+ requiredBySelections: "Requis par vos sélections.",+ disabledByEnv: "Désactivé par UNSLOTH_STUDIO_DISABLE_TORCH_WARM dans l'environnement du backend.",+ loadError: "Échec du chargement des paramètres de préparation au démarrage.",+ saveError: "Échec de l'enregistrement des paramètres de préparation au démarrage.",+ },helperLlm: {sectionTitle: "LLM assistant",preloadOnStartup: "Précharger le LLM assistant au démarrage",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 874d28f3d59..e0a5bb37153 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -1930,6 +1930,26 @@ export const he = {chatDefaults: "ברירות מחדל של הצ'אט",autoTitleNewChats: "מתן כותרת אוטומטית לצ'אטים חדשים",autoTitleNewChatsDescription: "צור כותרת מההודעה הראשונה.",+ mlWarmup: {+ sectionTitle: "ביצועים בעת ההפעלה",+ description: "הכן את התכונות שנבחרו לשימוש ראשון מהיר יותר. כל האפשרויות כבויות כברירת מחדל. האפשרויות עשויות לטעון תלויות משותפות ולהשתמש ביותר RAM במצב סרק.",+ restartRequired: "השינויים יחולו לאחר הפעלה מחדש של Unsloth.",+ hardwareLabel: "זיהוי חומרה",+ hardwareDescription: "זהה מעבדי GPU והכן את PyTorch.",+ textLabel: "מודלי טקסט",+ textDescription: "הכן את התמיכה במודלי טקסט של Transformers.",+ datasetsLabel: "הכנת מערכי נתונים",+ datasetsDescription: "הכן את Datasets ואת התלויות שלה לתצוגות מקדימות ולעיבוד.",+ mediaLabel: "מודלי תמונה ווידאו",+ mediaDescription: "הכן את Diffusers ואת התלויות המשותפות של המודלים.",+ advanced: "מתקדם",+ quantizationLabel: "בדיקות מקדימות לקוונטיזציה של תמונות",+ quantizationDescription: "בדוק את התמיכה לפני הטעינה הראשונה של מודל תמונה שעבר קוונטיזציה. הדבר עשוי להגדיל לזמן קצר את השימוש ב-RAM.",+ requiredBySelections: "נדרש עבור האפשרויות שבחרת.",+ disabledByEnv: "מושבת על ידי UNSLOTH_STUDIO_DISABLE_TORCH_WARM בסביבת השרת.",+ loadError: "טעינת הגדרות ההכנה המוקדמת בעת ההפעלה נכשלה.",+ saveError: "שמירת הגדרות ההכנה המוקדמת בעת ההפעלה נכשלה.",+ },helperLlm: {sectionTitle: "מודל עזר (Helper LLM)",preloadOnStartup: "שמור מודל עזר במטמון בעת ההפעלה",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex e56d34c9118..4b9feb1bc01 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1876,6 +1876,26 @@ export const hi = {autoTitleNewChats: "नई चैट को स्वतः शीर्षक दें",autoTitleNewChatsDescription:"पहले संदेश से एक छोटा शीर्षक बनाएं।",+ mlWarmup: {+ sectionTitle: "स्टार्टअप प्रदर्शन",+ description: "पहले उपयोग को तेज़ करने के लिए चुनी गई सुविधाओं को पहले से तैयार करें। सभी विकल्प डिफ़ॉल्ट रूप से बंद हैं। इन्हें चालू करने पर साझा डिपेंडेंसी लोड हो सकती हैं और निष्क्रिय अवस्था में RAM का उपयोग बढ़ सकता है।",+ restartRequired: "Unsloth को पुनः शुरू करने के बाद बदलाव लागू होंगे।",+ hardwareLabel: "हार्डवेयर की पहचान",+ hardwareDescription: "GPU की पहचान करें और PyTorch तैयार करें।",+ textLabel: "टेक्स्ट मॉडल",+ textDescription: "Transformers का टेक्स्ट मॉडल समर्थन तैयार करें।",+ datasetsLabel: "डेटासेट की तैयारी",+ datasetsDescription: "प्रीव्यू और प्रोसेसिंग के लिए Datasets और उसकी डिपेंडेंसी तैयार करें।",+ mediaLabel: "इमेज और वीडियो मॉडल",+ mediaDescription: "Diffusers और मॉडलों की साझा डिपेंडेंसी तैयार करें।",+ advanced: "उन्नत",+ quantizationLabel: "इमेज क्वांटाइज़ेशन की पूर्व-जाँच",+ quantizationDescription: "क्वांटाइज़्ड इमेज मॉडल को पहली बार लोड करने से पहले समर्थन की जाँच करें। इससे RAM का उपयोग थोड़ी देर के लिए बढ़ सकता है।",+ requiredBySelections: "आपके चुने हुए विकल्पों के लिए आवश्यक है।",+ disabledByEnv: "बैकएंड एनवायरनमेंट में UNSLOTH_STUDIO_DISABLE_TORCH_WARM द्वारा अक्षम।",+ loadError: "स्टार्टअप की पूर्व-तैयारी की सेटिंग्स लोड करने में विफल।",+ saveError: "स्टार्टअप की पूर्व-तैयारी की सेटिंग्स सहेजने में विफल।",+ },helperLlm: {sectionTitle: "Helper LLM",preloadOnStartup: "स्टार्टअप पर Helper LLM को प्री-कैश करें",diff --git a/studio/frontend/src/i18n/locales/id.ts b/studio/frontend/src/i18n/locales/id.tsindex cdded327a55..d356caeb8b1 100644--- a/studio/frontend/src/i18n/locales/id.ts+++ b/studio/frontend/src/i18n/locales/id.ts@@ -2041,6 +2041,26 @@ export const id = {chatDefaults: "Default chat",autoTitleNewChats: "Beri judul chat baru secara otomatis",autoTitleNewChatsDescription: "Buat judul dari pesan pertama.",+ mlWarmup: {+ sectionTitle: "Performa startup",+ description: "Siapkan fitur yang dipilih agar lebih cepat saat pertama kali digunakan. Semua opsi nonaktif secara default. Mengaktifkannya dapat memuat dependensi bersama dan menambah penggunaan RAM saat tidak ada aktivitas.",+ restartRequired: "Perubahan berlaku setelah Unsloth dimulai ulang.",+ hardwareLabel: "Deteksi perangkat keras",+ hardwareDescription: "Deteksi GPU dan siapkan PyTorch.",+ textLabel: "Model teks",+ textDescription: "Siapkan dukungan model teks Transformers.",+ datasetsLabel: "Persiapan dataset",+ datasetsDescription: "Siapkan Datasets dan dependensinya untuk pratinjau dan pemrosesan.",+ mediaLabel: "Model gambar dan video",+ mediaDescription: "Siapkan Diffusers dan dependensi yang digunakan bersama oleh model.",+ advanced: "Lanjutan",+ quantizationLabel: "Pemeriksaan awal kuantisasi gambar",+ quantizationDescription: "Periksa dukungan sebelum pertama kali memuat model gambar terkuantisasi. Dapat meningkatkan penggunaan RAM untuk sementara.",+ requiredBySelections: "Diperlukan oleh pilihan Anda.",+ disabledByEnv: "Dinonaktifkan oleh UNSLOTH_STUDIO_DISABLE_TORCH_WARM di lingkungan backend.",+ loadError: "Gagal memuat pengaturan persiapan saat startup.",+ saveError: "Gagal menyimpan pengaturan persiapan saat startup.",+ },helperLlm: {sectionTitle: "LLM Pembantu",preloadOnStartup: "Cache LLM Pembantu saat startup",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 848755b63e5..97ee2b4182b 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1782,6 +1782,26 @@ export const it = {autoTitleNewChats: "Titola automaticamente le nuove chat",autoTitleNewChatsDescription:"Genera un titolo breve a partire dal primo messaggio.",+ mlWarmup: {+ sectionTitle: "Prestazioni all'avvio",+ description: "Prepara le funzionalità selezionate per velocizzarne il primo utilizzo. Sono tutte disattivate per impostazione predefinita. Queste opzioni possono caricare dipendenze condivise e aumentare l'uso di RAM quando l'applicazione è inattiva.",+ restartRequired: "Le modifiche si applicano dopo il riavvio di Unsloth.",+ hardwareLabel: "Rilevamento hardware",+ hardwareDescription: "Rilevare le GPU e preparare PyTorch.",+ textLabel: "Modelli di testo",+ textDescription: "Preparare il supporto di Transformers per i modelli di testo.",+ datasetsLabel: "Preparazione dei dataset",+ datasetsDescription: "Preparare Datasets e le sue dipendenze per le anteprime e l'elaborazione.",+ mediaLabel: "Modelli di immagini e video",+ mediaDescription: "Preparare Diffusers e le dipendenze condivise dei modelli.",+ advanced: "Avanzate",+ quantizationLabel: "Controlli preliminari della quantizzazione delle immagini",+ quantizationDescription: "Verificare la compatibilità prima del primo caricamento di un modello di immagini quantizzato. Può aumentare brevemente l'uso di RAM.",+ requiredBySelections: "Richiesto dalle opzioni selezionate.",+ disabledByEnv: "Disattivato da UNSLOTH_STUDIO_DISABLE_TORCH_WARM nell'ambiente del backend.",+ loadError: "Caricamento delle impostazioni di preparazione all'avvio non riuscito.",+ saveError: "Salvataggio delle impostazioni di preparazione all'avvio non riuscito.",+ },helperLlm: {sectionTitle: "LLM di supporto",preloadOnStartup: "Scarica in anticipo l'LLM di supporto all'avvio",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex a121602e96a..b3ffe1b8466 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1867,6 +1867,26 @@ export const ja = {chatDefaults: "チャットのデフォルト設定",autoTitleNewChats: "新規チャットのタイトル自動生成",autoTitleNewChatsDescription: "最初のメッセージから短いタイトルを自動生成します。",+ mlWarmup: {+ sectionTitle: "起動時のパフォーマンス",+ description: "選択した機能を事前に準備し、初回使用を高速化します。デフォルトではすべてオフです。共有の依存ライブラリが読み込まれ、アイドル時の RAM 使用量が増える場合があります。",+ restartRequired: "変更は Unsloth の再起動後に適用されます。",+ hardwareLabel: "ハードウェア検出",+ hardwareDescription: "GPU を検出し、PyTorch を準備します。",+ textLabel: "テキストモデル",+ textDescription: "Transformers のテキストモデルサポートを準備します。",+ datasetsLabel: "データセットの準備",+ datasetsDescription: "プレビューや処理に使用する Datasets とその依存ライブラリを準備します。",+ mediaLabel: "画像・動画モデル",+ mediaDescription: "Diffusers とモデルで共有する依存ライブラリを準備します。",+ advanced: "詳細設定",+ quantizationLabel: "画像量子化の事前チェック",+ quantizationDescription: "量子化された画像モデルを初めて読み込む前に、対応状況を確認します。RAM 使用量が一時的に増える場合があります。",+ requiredBySelections: "選択した項目に必要です。",+ disabledByEnv: "バックエンド環境の UNSLOTH_STUDIO_DISABLE_TORCH_WARM によって無効化されています。",+ loadError: "起動時の事前準備の設定を読み込めませんでした。",+ saveError: "起動時の事前準備の設定を保存できませんでした。",+ },helperLlm: {sectionTitle: "ヘルパー LLM",preloadOnStartup: "起動時に ヘルパー LLM をプリキャッシュする",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 2ff866143ce..c20caecb2e5 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1869,6 +1869,26 @@ export const ko = {autoTitleNewChats: "새 채팅 제목 자동 생성",autoTitleNewChatsDescription:"첫 메시지를 기반으로 짧은 제목을 생성합니다.",+ mlWarmup: {+ sectionTitle: "시작 성능",+ description: "선택한 기능을 미리 준비하여 처음 사용할 때 더 빠르게 실행되도록 합니다. 기본값은 모두 꺼짐입니다. 공유 의존성이 로드되어 유휴 상태의 RAM 사용량이 늘어날 수 있습니다.",+ restartRequired: "변경 사항은 Unsloth를 다시 시작한 후 적용됩니다.",+ hardwareLabel: "하드웨어 감지",+ hardwareDescription: "GPU를 감지하고 PyTorch를 준비합니다.",+ textLabel: "텍스트 모델",+ textDescription: "Transformers의 텍스트 모델 지원을 준비합니다.",+ datasetsLabel: "데이터셋 준비",+ datasetsDescription: "미리보기와 처리에 사용할 Datasets 및 관련 의존성을 준비합니다.",+ mediaLabel: "이미지 및 동영상 모델",+ mediaDescription: "Diffusers와 모델 간 공유 의존성을 준비합니다.",+ advanced: "고급",+ quantizationLabel: "이미지 양자화 사전 검사",+ quantizationDescription: "양자화된 이미지 모델을 처음 로드하기 전에 지원 여부를 확인합니다. RAM 사용량이 잠시 늘어날 수 있습니다.",+ requiredBySelections: "선택한 항목에 필요합니다.",+ disabledByEnv: "백엔드 환경의 UNSLOTH_STUDIO_DISABLE_TORCH_WARM에 의해 비활성화되었습니다.",+ loadError: "시작 시 사전 준비 설정을 불러오지 못했습니다.",+ saveError: "시작 시 사전 준비 설정을 저장하지 못했습니다.",+ },helperLlm: {sectionTitle: "보조 LLM",preloadOnStartup: "시작 시 보조 LLM 미리 캐시",diff --git a/studio/frontend/src/i18n/locales/nl.ts b/studio/frontend/src/i18n/locales/nl.tsindex d7e0f131381..346bddfeae4 100644--- a/studio/frontend/src/i18n/locales/nl.ts+++ b/studio/frontend/src/i18n/locales/nl.ts@@ -2068,6 +2068,26 @@ export const nl = {autoTitleNewChats: "Nieuwe chats automatisch een titel geven",autoTitleNewChatsDescription:"Een titel genereren op basis van het eerste bericht.",+ mlWarmup: {+ sectionTitle: "Prestaties bij het opstarten",+ description: "Bereid geselecteerde functies voor om ze bij het eerste gebruik sneller beschikbaar te maken. Alles staat standaard uit. Deze opties kunnen gedeelde afhankelijkheden laden en meer RAM gebruiken wanneer de app inactief is.",+ restartRequired: "Wijzigingen worden toegepast nadat Unsloth opnieuw is gestart.",+ hardwareLabel: "Hardwaredetectie",+ hardwareDescription: "GPU's detecteren en PyTorch voorbereiden.",+ textLabel: "Tekstmodellen",+ textDescription: "Ondersteuning voor tekstmodellen in Transformers voorbereiden.",+ datasetsLabel: "Datasetvoorbereiding",+ datasetsDescription: "Datasets en de bijbehorende afhankelijkheden voorbereiden voor voorvertoningen en verwerking.",+ mediaLabel: "Afbeeldings- en videomodellen",+ mediaDescription: "Diffusers en gedeelde modelafhankelijkheden voorbereiden.",+ advanced: "Geavanceerd",+ quantizationLabel: "Voorafgaande controles voor afbeeldingskwantisatie",+ quantizationDescription: "De ondersteuning controleren voordat een gekwantiseerd afbeeldingsmodel voor het eerst wordt geladen. Kan het RAM-gebruik kort verhogen.",+ requiredBySelections: "Vereist voor je geselecteerde opties.",+ disabledByEnv: "Uitgeschakeld door UNSLOTH_STUDIO_DISABLE_TORCH_WARM in de backendomgeving.",+ loadError: "Kan de instellingen voor voorbereiding bij het opstarten niet laden.",+ saveError: "Kan de instellingen voor voorbereiding bij het opstarten niet opslaan.",+ },helperLlm: {sectionTitle: "Helper-LLM",preloadOnStartup: "Helper-LLM vooraf cachen bij opstarten",diff --git a/studio/frontend/src/i18n/locales/pl.ts b/studio/frontend/src/i18n/locales/pl.tsindex cce88b5901f..a8452433581 100644--- a/studio/frontend/src/i18n/locales/pl.ts+++ b/studio/frontend/src/i18n/locales/pl.ts@@ -2062,6 +2062,26 @@ export const pl = {autoTitleNewChats: "Automatyczne tytuły nowych czatów",autoTitleNewChatsDescription:"Generuj tytuł na podstawie pierwszej wiadomości.",+ mlWarmup: {+ sectionTitle: "Wydajność przy uruchamianiu",+ description: "Przygotuj wybrane funkcje, aby przyspieszyć ich pierwsze użycie. Wszystkie opcje są domyślnie wyłączone. Mogą one wczytywać współdzielone zależności i zwiększać zużycie RAM w stanie bezczynności.",+ restartRequired: "Zmiany zostaną zastosowane po ponownym uruchomieniu Unsloth.",+ hardwareLabel: "Wykrywanie sprzętu",+ hardwareDescription: "Wykryj GPU i przygotuj PyTorch.",+ textLabel: "Modele tekstowe",+ textDescription: "Przygotuj obsługę modeli tekstowych Transformers.",+ datasetsLabel: "Przygotowanie zbiorów danych",+ datasetsDescription: "Przygotuj Datasets i jego zależności do podglądu i przetwarzania.",+ mediaLabel: "Modele obrazu i wideo",+ mediaDescription: "Przygotuj Diffusers i współdzielone zależności modeli.",+ advanced: "Zaawansowane",+ quantizationLabel: "Wstępne kontrole kwantyzacji obrazów",+ quantizationDescription: "Sprawdź obsługę przed pierwszym wczytaniem skwantyzowanego modelu obrazu. Może to na krótko zwiększyć zużycie RAM.",+ requiredBySelections: "Wymagane przez wybrane opcje.",+ disabledByEnv: "Wyłączone przez UNSLOTH_STUDIO_DISABLE_TORCH_WARM w środowisku backendu.",+ loadError: "Nie udało się wczytać ustawień wstępnego przygotowania przy uruchamianiu.",+ saveError: "Nie udało się zapisać ustawień wstępnego przygotowania przy uruchamianiu.",+ },helperLlm: {sectionTitle: "Pomocniczy LLM",preloadOnStartup: "Wstępnie pobieraj pomocniczy LLM przy uruchamianiu",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 903e21b9b4d..39afa12bd48 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1877,6 +1877,26 @@ export const ptBR = {autoTitleNewChats: "Gerar título automático para novos chats",autoTitleNewChatsDescription:"Gera um título curto a partir da primeira mensagem.",+ mlWarmup: {+ sectionTitle: "Desempenho na inicialização",+ description: "Prepare os recursos selecionados para acelerar o primeiro uso. Todos vêm desativados por padrão. Essas opções podem carregar dependências compartilhadas e aumentar o uso de RAM enquanto o aplicativo estiver ocioso.",+ restartRequired: "As alterações são aplicadas após reiniciar o Unsloth.",+ hardwareLabel: "Detecção de hardware",+ hardwareDescription: "Detectar unidades GPU e preparar o PyTorch.",+ textLabel: "Modelos de texto",+ textDescription: "Preparar o suporte do Transformers para modelos de texto.",+ datasetsLabel: "Preparação de conjuntos de dados",+ datasetsDescription: "Preparar o Datasets e suas dependências para prévias e processamento.",+ mediaLabel: "Modelos de imagem e vídeo",+ mediaDescription: "Preparar o Diffusers e as dependências compartilhadas dos modelos.",+ advanced: "Avançado",+ quantizationLabel: "Verificações prévias de quantização de imagem",+ quantizationDescription: "Verificar a compatibilidade antes de carregar um modelo de imagem quantizado pela primeira vez. Pode aumentar brevemente o uso de RAM.",+ requiredBySelections: "Necessário para as opções selecionadas.",+ disabledByEnv: "Desativado por UNSLOTH_STUDIO_DISABLE_TORCH_WARM no ambiente do backend.",+ loadError: "Falha ao carregar as configurações de preparação na inicialização.",+ saveError: "Falha ao salvar as configurações de preparação na inicialização.",+ },helperLlm: {sectionTitle: "LLM auxiliar",preloadOnStartup: "Armazenar o LLM auxiliar em cache na inicialização",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 24316834c17..4965b86eba2 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1876,6 +1876,26 @@ export const ru = {autoTitleNewChats: "Автоматически называть новые чаты",autoTitleNewChatsDescription:"Создавать короткое название по первому сообщению.",+ mlWarmup: {+ sectionTitle: "Производительность при запуске",+ description: "Подготовьте выбранные функции, чтобы ускорить их первое использование. По умолчанию все параметры выключены. Они могут загружать общие зависимости и увеличивать расход RAM в режиме ожидания.",+ restartRequired: "Изменения вступят в силу после перезапуска Unsloth.",+ hardwareLabel: "Определение оборудования",+ hardwareDescription: "Определить GPU и подготовить PyTorch.",+ textLabel: "Текстовые модели",+ textDescription: "Подготовить поддержку текстовых моделей Transformers.",+ datasetsLabel: "Подготовка датасетов",+ datasetsDescription: "Подготовить Datasets и её зависимости для предварительного просмотра и обработки.",+ mediaLabel: "Модели изображений и видео",+ mediaDescription: "Подготовить Diffusers и общие зависимости моделей.",+ advanced: "Дополнительно",+ quantizationLabel: "Предварительные проверки квантизации изображений",+ quantizationDescription: "Проверить поддержку перед первой загрузкой квантованной модели изображений. Может ненадолго увеличить расход RAM.",+ requiredBySelections: "Необходимо для выбранных параметров.",+ disabledByEnv: "Отключено переменной UNSLOTH_STUDIO_DISABLE_TORCH_WARM в окружении бэкенда.",+ loadError: "Не удалось загрузить настройки предварительной подготовки при запуске.",+ saveError: "Не удалось сохранить настройки предварительной подготовки при запуске.",+ },helperLlm: {sectionTitle: "Вспомогательная LLM",preloadOnStartup: "Предзагружать вспомогательную LLM при запуске",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 24b0813c491..777ddb094d2 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -1979,6 +1979,26 @@ export const sv = {autoTitleNewChats: "Skapa automatiskt rubriker för nya chattar",autoTitleNewChatsDescription:"Generera en rubrik från det första meddelandet.",+ mlWarmup: {+ sectionTitle: "Prestanda vid start",+ description: "Förbered valda funktioner för snabbare första användning. Alla är av som standard. Alternativen kan läsa in delade beroenden och använda mer RAM när appen är inaktiv.",+ restartRequired: "Ändringarna tillämpas efter att Unsloth har startats om.",+ hardwareLabel: "Identifiering av maskinvara",+ hardwareDescription: "Identifiera GPU och förbered PyTorch.",+ textLabel: "Textmodeller",+ textDescription: "Förbered stödet för textmodeller i Transformers.",+ datasetsLabel: "Förberedelse av dataset",+ datasetsDescription: "Förbered Datasets och dess beroenden för förhandsvisningar och bearbetning.",+ mediaLabel: "Bild- och videomodeller",+ mediaDescription: "Förbered Diffusers och delade modellberoenden.",+ advanced: "Avancerat",+ quantizationLabel: "Förkontroller för bildkvantisering",+ quantizationDescription: "Kontrollera stödet innan en kvantiserad bildmodell läses in för första gången. Kan tillfälligt öka RAM-användningen.",+ requiredBySelections: "Krävs för dina val.",+ disabledByEnv: "Inaktiverat av UNSLOTH_STUDIO_DISABLE_TORCH_WARM i backendens miljö.",+ loadError: "Det gick inte att läsa in inställningarna för förberedelse vid start.",+ saveError: "Det gick inte att spara inställningarna för förberedelse vid start.",+ },helperLlm: {sectionTitle: "Hjälp-LLM",preloadOnStartup: "Förcacha hjälp-LLM vid start",diff --git a/studio/frontend/src/i18n/locales/th.ts b/studio/frontend/src/i18n/locales/th.tsindex a9d9630ed1d..4add0ec55f4 100644--- a/studio/frontend/src/i18n/locales/th.ts+++ b/studio/frontend/src/i18n/locales/th.ts@@ -1948,6 +1948,26 @@ export const th = {chatDefaults: "ค่าเริ่มต้นของแชท",autoTitleNewChats: "ตั้งชื่อแชทใหม่โดยอัตโนมัติ",autoTitleNewChatsDescription: "สร้างชื่อจากข้อความแรก",+ mlWarmup: {+ sectionTitle: "ประสิทธิภาพเมื่อเริ่มต้น",+ description: "เตรียมฟีเจอร์ที่เลือกไว้ล่วงหน้าเพื่อให้ใช้งานครั้งแรกได้เร็วขึ้น ทุกตัวเลือกปิดเป็นค่าเริ่มต้น การเปิดใช้อาจโหลดไลบรารีที่ใช้ร่วมกันและเพิ่มการใช้ RAM ขณะไม่ได้ใช้งาน",+ restartRequired: "การเปลี่ยนแปลงจะมีผลหลังจากเริ่ม Unsloth ใหม่",+ hardwareLabel: "การตรวจหาฮาร์ดแวร์",+ hardwareDescription: "ตรวจหา GPU และเตรียม PyTorch",+ textLabel: "โมเดลข้อความ",+ textDescription: "เตรียมการรองรับโมเดลข้อความของ Transformers",+ datasetsLabel: "การเตรียมชุดข้อมูล",+ datasetsDescription: "เตรียม Datasets และไลบรารีที่จำเป็นสำหรับการแสดงตัวอย่างและการประมวลผล",+ mediaLabel: "โมเดลรูปภาพและวิดีโอ",+ mediaDescription: "เตรียม Diffusers และไลบรารีที่โมเดลใช้ร่วมกัน",+ advanced: "ขั้นสูง",+ quantizationLabel: "การตรวจสอบเบื้องต้นสำหรับการควอนไทซ์รูปภาพ",+ quantizationDescription: "ตรวจสอบการรองรับก่อนโหลดโมเดลรูปภาพที่ผ่านการควอนไทซ์เป็นครั้งแรก อาจเพิ่มการใช้ RAM ชั่วครู่",+ requiredBySelections: "จำเป็นสำหรับตัวเลือกที่คุณเลือก",+ disabledByEnv: "ปิดใช้โดย UNSLOTH_STUDIO_DISABLE_TORCH_WARM ในสภาพแวดล้อมของแบ็กเอนด์",+ loadError: "โหลดการตั้งค่าการเตรียมความพร้อมเมื่อเริ่มต้นไม่สำเร็จ",+ saveError: "บันทึกการตั้งค่าการเตรียมความพร้อมเมื่อเริ่มต้นไม่สำเร็จ",+ },helperLlm: {sectionTitle: "LLM ผู้ช่วย",preloadOnStartup: "แคช LLM ผู้ช่วยล่วงหน้าเมื่อเริ่มต้น",diff --git a/studio/frontend/src/i18n/locales/tr.ts b/studio/frontend/src/i18n/locales/tr.tsindex 882eda294ab..e926ba5f314 100644--- a/studio/frontend/src/i18n/locales/tr.ts+++ b/studio/frontend/src/i18n/locales/tr.ts@@ -2036,6 +2036,26 @@ export const tr = {chatDefaults: "Sohbet varsayılanları",autoTitleNewChats: "Yeni sohbetlere otomatik başlık ver",autoTitleNewChatsDescription: "İlk mesajdan bir başlık oluşturun.",+ mlWarmup: {+ sectionTitle: "Başlangıç performansı",+ description: "Seçilen özellikleri ilk kullanımın daha hızlı olması için hazırlayın. Tüm seçenekler varsayılan olarak kapalıdır. Seçenekler ortak bağımlılıkları yükleyebilir ve boşta daha fazla RAM kullanabilir.",+ restartRequired: "Değişiklikler Unsloth yeniden başlatıldıktan sonra uygulanır.",+ hardwareLabel: "Donanım algılama",+ hardwareDescription: "GPU'ları algılayın ve PyTorch'u hazırlayın.",+ textLabel: "Metin modelleri",+ textDescription: "Transformers metin modeli desteğini hazırlayın.",+ datasetsLabel: "Veri kümesi hazırlığı",+ datasetsDescription: "Önizleme ve işleme için Datasets'i ve bağımlılıklarını hazırlayın.",+ mediaLabel: "Görüntü ve video modelleri",+ mediaDescription: "Diffusers'ı ve ortak model bağımlılıklarını hazırlayın.",+ advanced: "Gelişmiş",+ quantizationLabel: "Görüntü kuantizasyonu ön kontrolleri",+ quantizationDescription: "Kuantize edilmiş bir görüntü modeli ilk kez yüklenmeden önce desteği kontrol edin. RAM kullanımını kısa süreliğine artırabilir.",+ requiredBySelections: "Seçimleriniz için gereklidir.",+ disabledByEnv: "Arka uç ortamındaki UNSLOTH_STUDIO_DISABLE_TORCH_WARM tarafından devre dışı bırakıldı.",+ loadError: "Başlangıçta ön hazırlık ayarları yüklenemedi.",+ saveError: "Başlangıçta ön hazırlık ayarları kaydedilemedi.",+ },helperLlm: {sectionTitle: "Yardımcı LLM",preloadOnStartup: "Yardımcı LLM'yi başlangıçta önbelleğe al",diff --git a/studio/frontend/src/i18n/locales/uk.ts b/studio/frontend/src/i18n/locales/uk.tsindex 44dde615faa..ae70cd5c800 100644--- a/studio/frontend/src/i18n/locales/uk.ts+++ b/studio/frontend/src/i18n/locales/uk.ts@@ -2056,6 +2056,26 @@ export const uk = {chatDefaults: "Типові параметри чату",autoTitleNewChats: "Автоматичні назви нових чатів",autoTitleNewChatsDescription: "Генерувати назву з першого повідомлення.",+ mlWarmup: {+ sectionTitle: "Продуктивність під час запуску",+ description: "Підготуйте вибрані функції для швидшого першого використання. За замовчуванням усі параметри вимкнено. Вони можуть завантажувати спільні залежності та збільшувати використання RAM у стані простою.",+ restartRequired: "Зміни набудуть чинності після перезапуску Unsloth.",+ hardwareLabel: "Виявлення обладнання",+ hardwareDescription: "Виявити GPU та підготувати PyTorch.",+ textLabel: "Текстові моделі",+ textDescription: "Підготувати підтримку текстових моделей Transformers.",+ datasetsLabel: "Підготовка наборів даних",+ datasetsDescription: "Підготувати Datasets та її залежності для попереднього перегляду й обробки.",+ mediaLabel: "Моделі зображень і відео",+ mediaDescription: "Підготувати Diffusers і спільні залежності моделей.",+ advanced: "Додатково",+ quantizationLabel: "Попередні перевірки квантування зображень",+ quantizationDescription: "Перевірити підтримку перед першим завантаженням квантованої моделі зображень. Може ненадовго збільшити використання RAM.",+ requiredBySelections: "Необхідно для вибраних параметрів.",+ disabledByEnv: "Вимкнено змінною UNSLOTH_STUDIO_DISABLE_TORCH_WARM у середовищі бекенда.",+ loadError: "Не вдалося завантажити налаштування попередньої підготовки під час запуску.",+ saveError: "Не вдалося зберегти налаштування попередньої підготовки під час запуску.",+ },helperLlm: {sectionTitle: "Допоміжна LLM",preloadOnStartup: "Попередньо кешувати допоміжну LLM під час запуску",diff --git a/studio/frontend/src/i18n/locales/vi.ts b/studio/frontend/src/i18n/locales/vi.tsindex bd7ab632800..07cbfdcf90b 100644--- a/studio/frontend/src/i18n/locales/vi.ts+++ b/studio/frontend/src/i18n/locales/vi.ts@@ -2047,6 +2047,26 @@ export const vi = {chatDefaults: "Mặc định cho trò chuyện",autoTitleNewChats: "Tự động đặt tiêu đề cho cuộc trò chuyện mới",autoTitleNewChatsDescription: "Tạo tiêu đề từ tin nhắn đầu tiên.",+ mlWarmup: {+ sectionTitle: "Hiệu suất khởi động",+ description: "Chuẩn bị trước các tính năng đã chọn để sử dụng lần đầu nhanh hơn. Mặc định tất cả đều tắt. Khi bật, các tùy chọn có thể tải các thư viện phụ thuộc dùng chung và tăng mức sử dụng RAM khi không hoạt động.",+ restartRequired: "Thay đổi có hiệu lực sau khi khởi động lại Unsloth.",+ hardwareLabel: "Phát hiện phần cứng",+ hardwareDescription: "Phát hiện GPU và chuẩn bị PyTorch.",+ textLabel: "Mô hình văn bản",+ textDescription: "Chuẩn bị khả năng hỗ trợ mô hình văn bản của Transformers.",+ datasetsLabel: "Chuẩn bị tập dữ liệu",+ datasetsDescription: "Chuẩn bị Datasets và các thư viện phụ thuộc để xem trước và xử lý dữ liệu.",+ mediaLabel: "Mô hình hình ảnh và video",+ mediaDescription: "Chuẩn bị Diffusers và các thư viện phụ thuộc dùng chung của mô hình.",+ advanced: "Nâng cao",+ quantizationLabel: "Kiểm tra trước lượng tử hóa hình ảnh",+ quantizationDescription: "Kiểm tra khả năng hỗ trợ trước lần đầu tải mô hình hình ảnh đã lượng tử hóa. Có thể tạm thời làm tăng mức sử dụng RAM.",+ requiredBySelections: "Bắt buộc đối với các tùy chọn bạn đã chọn.",+ disabledByEnv: "Bị tắt bởi UNSLOTH_STUDIO_DISABLE_TORCH_WARM trong môi trường backend.",+ loadError: "Không thể tải cài đặt chuẩn bị sẵn khi khởi động.",+ saveError: "Không thể lưu cài đặt chuẩn bị sẵn khi khởi động.",+ },helperLlm: {sectionTitle: "LLM trợ giúp",preloadOnStartup: "Lưu sẵn LLM trợ giúp vào bộ nhớ đệm khi khởi động",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex cae81f05929..5df6e1ba482 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -1855,6 +1855,26 @@ export const zhCN = {chatDefaults: "聊天默认设置",autoTitleNewChats: "自动为新聊天命名",autoTitleNewChatsDescription: "根据第一条消息生成简短标题。",+ mlWarmup: {+ sectionTitle: "启动性能",+ description: "提前准备所选功能,加快首次使用。所有选项默认关闭。启用后可能加载共享依赖项,并增加空闲时的 RAM 占用。",+ restartRequired: "更改将在重启 Unsloth 后生效。",+ hardwareLabel: "硬件检测",+ hardwareDescription: "检测 GPU 并准备 PyTorch。",+ textLabel: "文本模型",+ textDescription: "准备 Transformers 文本模型支持。",+ datasetsLabel: "数据集准备",+ datasetsDescription: "准备 Datasets 及其依赖项,以供预览和处理使用。",+ mediaLabel: "图像和视频模型",+ mediaDescription: "准备 Diffusers 及模型共享的依赖项。",+ advanced: "高级",+ quantizationLabel: "图像量化预检查",+ quantizationDescription: "在首次加载量化图像模型前检查支持情况。可能短暂增加 RAM 占用。",+ requiredBySelections: "所选选项需要此功能。",+ disabledByEnv: "已由后端环境中的 UNSLOTH_STUDIO_DISABLE_TORCH_WARM 禁用。",+ loadError: "加载启动准备设置失败。",+ saveError: "保存启动准备设置失败。",+ },helperLlm: {sectionTitle: "辅助 LLM",preloadOnStartup: "启动时预缓存辅助 LLM",diff --git a/studio/frontend/src/i18n/locales/zh-TW.ts b/studio/frontend/src/i18n/locales/zh-TW.tsindex 6f42130d6f5..00b51a3900e 100644--- a/studio/frontend/src/i18n/locales/zh-TW.ts+++ b/studio/frontend/src/i18n/locales/zh-TW.ts@@ -1937,6 +1937,26 @@ export const zhTW = {chatDefaults: "聊天預設值",autoTitleNewChats: "自動為新聊天命名",autoTitleNewChatsDescription: "根據第一則訊息產生標題。",+ mlWarmup: {+ sectionTitle: "啟動效能",+ description: "預先準備所選功能,加快首次使用速度。所有選項預設為關閉。啟用後可能載入共用相依套件,並增加閒置時的 RAM 用量。",+ restartRequired: "變更將在重新啟動 Unsloth 後生效。",+ hardwareLabel: "硬體偵測",+ hardwareDescription: "偵測 GPU 並準備 PyTorch。",+ textLabel: "文字模型",+ textDescription: "準備 Transformers 的文字模型支援。",+ datasetsLabel: "資料集準備",+ datasetsDescription: "準備 Datasets 及其相依套件,以供預覽和處理使用。",+ mediaLabel: "圖片與影片模型",+ mediaDescription: "準備 Diffusers 及模型共用的相依套件。",+ advanced: "進階",+ quantizationLabel: "圖片量化預先檢查",+ quantizationDescription: "在首次載入量化圖片模型前檢查支援情況。可能短暫增加 RAM 用量。",+ requiredBySelections: "您所選的選項需要此功能。",+ disabledByEnv: "已由後端環境中的 UNSLOTH_STUDIO_DISABLE_TORCH_WARM 停用。",+ loadError: "無法載入啟動準備設定。",+ saveError: "無法儲存啟動準備設定。",+ },helperLlm: {sectionTitle: "輔助 LLM",preloadOnStartup: "啟動時預先快取輔助 LLM",diff --git a/studio/frontend/tests/chat-only-route-guard.test.ts b/studio/frontend/tests/chat-only-route-guard.test.tsindex 434ea0ab62a..c5f34a0606b 100644--- a/studio/frontend/tests/chat-only-route-guard.test.ts+++ b/studio/frontend/tests/chat-only-route-guard.test.ts@@ -42,8 +42,15 @@ const redirectsToChatWith = new Function("chatOnly","unmeasured","trainUnavailable",+ "detectionDeferred",`${declarations}\nreturn Boolean(${condition});`,-) as (pathname: string, chatOnly: boolean, unmeasured: boolean, trainUnavailable: boolean) => boolean;+) as (+ pathname: string,+ chatOnly: boolean,+ unmeasured: boolean,+ trainUnavailable: boolean,+ detectionDeferred?: boolean,+) => boolean;// A chat-only host that cannot train either, which is every chat-only reason but a CPU training host.const redirectsToChat = (pathname: string, chatOnly: boolean, unmeasured: boolean) =>redirectsToChatWith(pathname, chatOnly, unmeasured, chatOnly);@@ -90,6 +97,12 @@ test("an unmeasured verdict still lets both pages wait it out", () => {}});+test("a deferred verdict is provisional, so no page is redirected on it", () => {+ for (const path of ["/settings", "/api", "/studio"]) {+ assert.equal(redirectsToChatWith(path, true, true, true, true), false, path);+ }+});+test("the pages that self-gate are unaffected, and everything else still redirects", () => {for (const path of ["/chat", "/export", "/images", "/api-monitor", "/data-recipes"]) {assert.equal(measuredChatOnly(path), false, `${path} no longer survives the guard`);diff --git a/studio/frontend/tests/deferred-hardware-first-use.test.ts b/studio/frontend/tests/deferred-hardware-first-use.test.tsnew file mode 100644index 00000000000..83be7bea1cb--- /dev/null+++ b/studio/frontend/tests/deferred-hardware-first-use.test.ts@@ -0,0 +1,225 @@+// 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 { register } from "node:module";+import test from "node:test";+import { installLocalStorageFake, readSrc, registerBundlerResolver } from "./helpers/kit.ts";++register("./helpers/vite-env-loader.mjs", import.meta.url);+registerBundlerResolver();+const { store } = installLocalStorageFake();+Object.defineProperty(globalThis, "navigator", {+ configurable: true,+ value: { platform: "MacIntel", userAgent: "Macintosh" },+});++const DEFERRED = {+ chat_only: true,+ hardware_detecting: true,+ hardware_detection_deferred: true,+ version: "2026.1.1",+};+const DETECTING = { chat_only: true, hardware_detecting: true, version: "2026.1.1" };+const GPU = { device_type: "linux", chat_only: false, chat_only_reason: null, version: "2026.1.1" };+let replies: Array<Record<string, unknown>> = [];+let urls: string[] = [];+globalThis.fetch = (async (url: string) => {+ urls.push(url);+ const body = replies.shift() ?? DEFERRED;+ const response = { ok: true, json: async () => ({ ...body }), clone: () => response };+ return response;+}) as unknown as typeof fetch;++const { fetchDeviceType, forgetMeasuredVerdict, usePlatformStore } = await import("../src/config/env.ts");+const { routeNeedsHardware } = await import("../src/config/hardware-verdict.ts");++function reset() {+ store.set("unsloth_auth_token", "token");+ forgetMeasuredVerdict();+ usePlatformStore.setState({+ fetched: false,+ verdictStale: false,+ detectionDeferred: false,+ chatOnly: true,+ chatOnlyReason: null,+ });+ urls = [];+ replies = [];+}++test("idle health keeps capabilities unknown and preserves the first real detection wait", async () => {+ reset();+ await fetchDeviceType();+ let state = usePlatformStore.getState();+ assert.deepEqual(urls, ["/api/health"]);+ assert.equal(state.detectionDeferred, true);+ assert.equal(state.capabilitiesUnknown(), true);+ assert.equal(state.isTrainUnavailable() && !state.capabilitiesUnknown(), false);++ replies = [DETECTING, GPU];+ await fetchDeviceType({ detectHardware: true });+ state = usePlatformStore.getState();+ assert.deepEqual(urls, [+ "/api/health",+ "/api/health?detect_hardware=true",+ "/api/health?detect_hardware=true",+ ]);+ assert.equal(state.detectionDeferred, false);+ assert.equal(state.capabilitiesUnknown(), false);+ assert.equal(state.isTrainUnavailable(), false);+});++test("explicit detection bypasses a cached platform and honours an unsupported result", async () => {+ reset();+ usePlatformStore.setState({ fetched: true, detectionDeferred: true, chatOnly: false });+ replies = [{ ...GPU, chat_only: true, chat_only_reason: "no_torch" }];+ await fetchDeviceType({ detectHardware: true });+ const state = usePlatformStore.getState();+ assert.deepEqual(urls, ["/api/health?detect_hardware=true"]);+ assert.equal(state.capabilitiesUnknown(), false);+ assert.equal(state.isTrainUnavailable(), true);+ assert.equal(state.chatOnlyReason, "no_torch");+});++test("an unauthenticated navigation never requests a hardware probe", async () => {+ reset();+ store.delete("unsloth_auth_token");+ await fetchDeviceType({ detectHardware: true });+ assert.deepEqual(urls, ["/api/health"]);+});++test("only hardware-gated destinations request detection, including direct child links", () => {+ for (const path of ["/studio", "/studio/run", "/video", "/video/model", "/export"]) {+ assert.equal(routeNeedsHardware(path), true, path);+ }+ for (const path of ["/", "/chat", "/login", "/hub", "/projects", "/studio-other"]) {+ assert.equal(routeNeedsHardware(path), false, path);+ }+ assert.match(+ readSrc("app/routes/__root.tsx"),+ /detectHardware: !preload && routeNeedsHardware\(location\.pathname\)/,+ "hover preloads must not trigger an otherwise idle ML import",+ );+});++test("an older idle response cannot defer detection after a first-use request was accepted", async () => {+ reset();+ await fetchDeviceType();+ const originalFetch = globalThis.fetch;+ const originalNow = Date.now;+ let releaseIdle: (() => void) | undefined;+ let clock = originalNow();+ // Finish the first-use bounded wait immediately with an actively detecting reply.+ Date.now = () => (clock += 6000);+ globalThis.fetch = (async (url: string) => {+ const demand = url.includes("detect_hardware=true");+ if (!demand) await new Promise<void>((resolve) => { releaseIdle = resolve; });+ const body = demand ? DETECTING : DEFERRED;+ const response = { ok: true, json: async () => ({ ...body }), clone: () => response };+ return response;+ }) as unknown as typeof fetch;+ try {+ const idle = fetchDeviceType({ force: true });+ await fetchDeviceType({ detectHardware: true });+ assert.equal(usePlatformStore.getState().detectionDeferred, false);+ releaseIdle?.();+ await idle;+ assert.equal(usePlatformStore.getState().detectionDeferred, false);+ assert.equal(usePlatformStore.getState().capabilitiesUnknown(), true);+ } finally {+ globalThis.fetch = originalFetch;+ Date.now = originalNow;+ }+});++test("the real route guard keeps hover preloads cold and starts detection on navigation", async () => {+ reset();+ const rootSource = readSrc("app/routes/__root.tsx");+ const match = /beforeLoad: async \(\{ location, preload \}\) => \{([\s\S]*?)\n \},\n component: RootLayout/.exec(rootSource);+ assert.ok(match, "root route guard moved");+ const beforeLoad = new Function(+ "fetchDeviceType", "routeNeedsHardware", "usePlatformStore",+ "isChatOnlyAllowed", "waitsOutUnknownVerdict", "redirect",+ "return async ({ location, preload }) => {" + match[1] + "};",+ )(+ fetchDeviceType, routeNeedsHardware, usePlatformStore,+ () => true, () => true, () => { throw new Error("unexpected redirect"); },+ ) as (options: { location: { pathname: string }; preload: boolean }) => Promise<void>;++ await beforeLoad({ location: { pathname: "/studio" }, preload: true });+ assert.deepEqual(urls, ["/api/health"]);+ replies = [GPU];+ await beforeLoad({ location: { pathname: "/studio" }, preload: false });+ assert.deepEqual(urls, ["/api/health", "/api/health?detect_hardware=true"]);+ assert.equal(usePlatformStore.getState().capabilitiesUnknown(), false);+});++test("auto-load keeps cached non-GGUF models while detection is deferred", () => {+ reset();+ const adapterSource = readSrc("features/chat/api/chat-adapter.ts");+ const lift = (name: string) => {+ const match = new RegExp(`function ${name}\\([^)]*\\): boolean \\{([\\s\\S]*?)\\n\\}`).exec(adapterSource);+ assert.ok(match, `${name} moved`);+ return new Function("usePlatformStore", "isGgufLocalRow", "isMlxId", "row", match[1])+ .bind(null, usePlatformStore, (row: { path: string }) => row.path.endsWith(".gguf"), () => false);+ };+ const cachedModelsRun = lift("cachedModelsRunOnThisPlatform");+ const runsHere = lift("runsOnThisPlatform");+ const safetensors = { id: "org/model", path: "/models/org/model" };++ usePlatformStore.setState({ fetched: true, detectionDeferred: true, chatOnly: true, deviceType: "linux" });+ assert.equal(cachedModelsRun(), true);+ assert.equal(runsHere(safetensors), true);++ usePlatformStore.setState({ detectionDeferred: false });+ assert.equal(cachedModelsRun(), false);+ assert.equal(runsHere(safetensors), false);+ assert.equal(runsHere({ id: "org/model-GGUF", path: "/models/m.gguf" }), true);+});++test("a deferred reply names the server platform and is re-read until measured", async () => {+ reset();+ replies = [{ ...DEFERRED, device_type: "linux" }, GPU];+ await fetchDeviceType();+ let state = usePlatformStore.getState();+ assert.equal(state.deviceType, "linux");+ assert.equal(state.capabilitiesUnknown(), true);+ await fetchDeviceType();+ state = usePlatformStore.getState();+ assert.deepEqual(urls, ["/api/health", "/api/health"]);+ assert.equal(state.capabilitiesUnknown(), false);+});++test("a deferred verdict neither redirects nor blocks Train entry points on a guess", async () => {+ reset();+ const rootSource = readSrc("app/routes/__root.tsx");+ const match = /beforeLoad: async \(\{ location, preload \}\) => \{([\s\S]*?)\n \},\n component: RootLayout/.exec(rootSource);+ assert.ok(match, "root route guard moved");+ const beforeLoad = new Function(+ "fetchDeviceType", "routeNeedsHardware", "usePlatformStore",+ "isChatOnlyAllowed", "waitsOutUnknownVerdict", "redirect",+ "return async ({ location, preload }) => {" + match[1] + "};",+ )(+ fetchDeviceType, routeNeedsHardware, usePlatformStore,+ () => false, () => false, () => { throw new Error("redirected"); },+ ) as (options: { location: { pathname: string }; preload: boolean }) => Promise<void>;++ await beforeLoad({ location: { pathname: "/settings" }, preload: false });+ replies = [{ ...GPU, chat_only: true, chat_only_reason: "no_gpu" }];+ await fetchDeviceType({ force: true });+ await assert.rejects(beforeLoad({ location: { pathname: "/settings" }, preload: false }), /redirected/);++ assert.match(+ readSrc("features/settings/tabs/data-tab.tsx"),+ /s\.isTrainUnavailable\(\) && !s\.capabilitiesUnknown\(\)/,+ );+});++test("a desktop backend reconnect asks for detection on an open hardware page", () => {+ const reconnect = /if \(verdictStaleRef\.current\) \{[\s\S]*?\}, \[status, desktopAuthReady\]\);/.exec(+ readSrc("app/provider.tsx"),+ );+ assert.ok(reconnect, "the reconnect refresh moved");+ assert.match(reconnect[0], /force: true,[\s\S]*detectHardware: routeNeedsHardware\(pathnameRef\.current\)/);+});diff --git a/studio/frontend/tests/general-settings-token-sync.test.ts b/studio/frontend/tests/general-settings-token-sync.test.tsindex 86637c5a331..cd4bb1f4c58 100644--- a/studio/frontend/tests/general-settings-token-sync.test.ts+++ b/studio/frontend/tests/general-settings-token-sync.test.ts@@ -213,6 +213,7 @@ function generalTab(initialToken: string) {"../components/developer-mode-section": componentStub,"../components/engine-versions-section": componentStub,"../components/hub-settings-section": componentStub,+ "../components/ml-warmup-section": componentStub,"../components/notification-frequency-select": componentStub,"../components/settings-row": componentStub,"../components/settings-section": componentStub,diff --git a/studio/frontend/tests/hardware-verdict-recovery.test.ts b/studio/frontend/tests/hardware-verdict-recovery.test.tsindex 4f7fa47f974..b2e977f41e1 100644--- a/studio/frontend/tests/hardware-verdict-recovery.test.ts+++ b/studio/frontend/tests/hardware-verdict-recovery.test.ts@@ -102,7 +102,7 @@ test("the recovery poll runs while the verdict is unknown, on every platform", aassert.ok(start > 0 && end > start, "could not read the recovery poll effect");const effect = src.slice(start, end);- const guard = /if \(([^;]*)\) return;/.exec(effect);+ const guard = /if \((selfHealSettled[^;]*)\) return;/.exec(effect);assert.ok(guard, "the poll never bails out, so it runs for the life of the app");assert.match(guard[1],@@ -112,7 +112,7 @@ test("the recovery poll runs while the verdict is unknown, on every platform", a);assert.match(effect,- /chatOnlyReason !== "mlx_unavailable" && !detectionDeferred/,+ /chatOnlyReason !== "mlx_unavailable"/,"a repaired MLX install no longer re-enables Train without a reload",);const deps = /\}, \[([^\]]*)\]\);$/.exec(effect);diff --git a/studio/frontend/tests/helpers/store-stubs/env.ts b/studio/frontend/tests/helpers/store-stubs/env.tsindex 5b040561836..f5e1ebf05a5 100644--- a/studio/frontend/tests/helpers/store-stubs/env.ts+++ b/studio/frontend/tests/helpers/store-stubs/env.ts@@ -11,3 +11,5 @@ export const usePlatformStore = {};export async function fetchDeviceType(_options?: { force?: boolean }): Promise<void> {}++export function refreshDeviceTypeAfterSystemInfo(): void {}diff --git a/studio/frontend/tests/media-capability-first-use.test.ts b/studio/frontend/tests/media-capability-first-use.test.tsnew file mode 100644index 00000000000..b4cfdb7d9c8--- /dev/null+++ b/studio/frontend/tests/media-capability-first-use.test.ts@@ -0,0 +1,99 @@+// 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 type * as SystemHooks from "../src/hooks/use-system.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";+import { readSrc } from "./helpers/kit.ts";++function harness() {+ const requests: { url: string; resolve: (response: Response) => void }[] = [];+ const system = loadWithStubs<typeof SystemHooks>(+ new URL("../src/hooks/use-system.ts", import.meta.url),+ {+ react: {},+ "@/config/env": { refreshDeviceTypeAfterSystemInfo: () => {} },+ "@/features/auth": {+ authFetch: (url: string) => new Promise<Response>((resolve) => requests.push({ url, resolve })),+ },+ },+ { relativePassthrough: true },+ );+ return { system, requests };+}++test("a media probe follows an ordinary in-flight system read and publishes its capabilities", async () => {+ const { system, requests } = harness();+ const ordinary = system.fetchSystemInfo();+ const media = system.fetchSystemInfo({ probeMedia: true });+ assert.equal(requests.length, 1);+ assert.equal(requests[0].url, "/api/system");+ requests[0].resolve(Response.json({ dense_quant_supported: false }));+ await ordinary;+ await Promise.resolve();+ assert.equal(requests[1].url, "/api/system?probe_media=true");+ requests[1].resolve(Response.json({ dense_quant_supported: true, quantised_streaming: true }));+ assert.equal((await media)?.dense_quant_supported, true);+ assert.equal((await system.fetchSystemInfo())?.quantised_streaming, true);+ assert.equal(requests.length, 2);+});++test("media discovery bypasses the cold cache and concurrent media requests share its probe", async () => {+ const { system, requests } = harness();+ const initial = system.fetchSystemInfo();+ requests[0].resolve(Response.json({ dense_quant_supported: false }));+ await initial;+ const first = system.fetchSystemInfo({ probeMedia: true });+ const second = system.fetchSystemInfo({ probeMedia: true });+ assert.equal(requests.length, 2);+ assert.equal(requests[1].url, "/api/system?probe_media=true");+ requests[1].resolve(Response.json({ dense_quant_supported: true }));+ const [a, b] = await Promise.all([first, second]);+ assert.equal(a, b);+ assert.equal(a?.dense_quant_supported, true);+});++test("a failed media probe can retry without poisoning ordinary system reads", async () => {+ const { system, requests } = harness();+ const first = system.fetchSystemInfo({ probeMedia: true });+ requests[0].resolve(new Response(null, { status: 503 }));+ assert.equal(await first, null);+ const next = system.fetchSystemInfo();+ assert.equal(requests[1].url, "/api/system");+ requests[1].resolve(Response.json({ dense_quant_supported: false }));+ assert.equal((await next)?.dense_quant_supported, false);+});++test("the picker requests media capabilities only while open for image or video tasks", () => {+ const source = readSrc("features/model-picker/components/model-selector/pickers.tsx");+ const taskNames = (name: string): string[] => {+ const match = new RegExp("export const " + name + " = \\[([\\s\\S]*?)\\] as const;").exec(source);+ assert.ok(match, name);+ return [...match[1].matchAll(/"([^"]+)"/g)].map((entry) => entry[1]);+ };+ const diffusionTasks = new Set([...taskNames("IMAGE_GEN_TASKS"), ...taskNames("VIDEO_GEN_TASKS")]);+ const decision = /const diffusionLoad = useMemo\(\(\) => \{([\s\S]*?)\}, \[task\]\);/.exec(source);+ assert.ok(decision, "picker task decision moved");+ const isMedia = new Function("task", "DIFFUSION_TASKS", decision[1]);+ const effect = /useEffect\(\(\) => \{([^{}]*?if \(open && diffusionLoad\) void fetchSystemInfo\(\{ probeMedia: true \}\);)\s*\}, \[open, diffusionLoad\]\);/.exec(source);+ assert.ok(effect, "picker capability effect moved");+ const runEffect = new Function("open", "diffusionLoad", "fetchSystemInfo", effect[1]);+ const calls: unknown[] = [];+ const fetch = (options: unknown) => { calls.push(options); };++ for (const task of ["text-to-image", "text-to-video"]) {+ runEffect(false, isMedia(task, diffusionTasks), fetch);+ }+ for (const task of [undefined, "text-generation", "text-to-speech", "text-to-audio"]) {+ runEffect(true, isMedia(task, diffusionTasks), fetch);+ }+ assert.equal(calls.length, 0);+ runEffect(true, isMedia("text-to-image", diffusionTasks), fetch);+ runEffect(true, isMedia(["text-to-video", "image-to-video"], diffusionTasks), fetch);+ assert.deepEqual(calls, [{ probeMedia: true }, { probeMedia: true }]);+ assert.match(+ readSrc("features/model-picker/components/model-selector.tsx"),+ /<HubModelPicker\s+open=\{open\}/,+ );+});diff --git a/studio/frontend/tests/memory-probe-known.test.ts b/studio/frontend/tests/memory-probe-known.test.tsindex c1f07ac3f54..dff795bf886 100644--- a/studio/frontend/tests/memory-probe-known.test.ts+++ b/studio/frontend/tests/memory-probe-known.test.ts@@ -88,6 +88,7 @@ test("resident refresh bypasses cached and in-flight pre-load memory", async ()new URL("../src/hooks/use-system.ts", import.meta.url),{react: {},+ "@/config/env": { refreshDeviceTypeAfterSystemInfo: () => {} },"@/features/auth": {authFetch: (url: string) =>new Promise<Response>((resolve) => {diff --git a/studio/frontend/tests/ml-warmup-settings.test.ts b/studio/frontend/tests/ml-warmup-settings.test.tsnew file mode 100644index 00000000000..08913892f3e--- /dev/null+++ b/studio/frontend/tests/ml-warmup-settings.test.ts@@ -0,0 +1,98 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";++type Feature = "hardware" | "text" | "datasets" | "media" | "quantization";+type Settings = {+ features: Feature[];+ effectiveFeatures: Feature[];+ disabledByEnv: boolean;+};++function settingsApi(fetch: (url: string, init?: RequestInit) => Promise<Response>) {+ return loadWithStubs<{+ loadMlWarmupSettings(): Promise<Settings>;+ updateMlWarmupSettings(features: readonly Feature[]): Promise<Settings>;+ updateWarmupSelection(selected: readonly Feature[], feature: Feature, enabled: boolean): Feature[];+ hardwareWarmupRequired(features: readonly Feature[]): boolean;+ }>(+ new URL("../src/features/settings/api/ml-warmup.ts", import.meta.url),+ {+ "@/features/auth": { authFetch: fetch },+ "@/lib/format-fastapi-error": {+ readFastApiError: async (response: Response) => (await response.json()).detail,+ },+ },+ );+}++test("reads fresh requested and effective preferences independently", async () => {+ let features: Feature[] = [];+ const api = settingsApi(async (url) => {+ assert.equal(url, "/api/settings/ml-warmup");+ return Response.json({+ features,+ effective_features: features.length ? ["hardware", "text"] : [],+ disabled_by_env: true,+ });+ });+ assert.deepEqual(await api.loadMlWarmupSettings(), {+ features: [],+ effectiveFeatures: [],+ disabledByEnv: true,+ });+ features = ["text"];+ assert.deepEqual(await api.loadMlWarmupSettings(), {+ features: ["text"],+ effectiveFeatures: ["hardware", "text"],+ disabledByEnv: true,+ });+});++test("saves only the user's selections and returns expanded server features", async () => {+ const api = settingsApi(async (url, init) => {+ assert.equal(url, "/api/settings/ml-warmup");+ assert.equal(init?.method, "PUT");+ assert.deepEqual(JSON.parse(init?.body as string), { features: ["text"] });+ return Response.json({+ features: ["text"],+ effective_features: ["hardware", "text"],+ disabled_by_env: false,+ });+ });+ assert.deepEqual(await api.updateMlWarmupSettings(["text"]), {+ features: ["text"],+ effectiveFeatures: ["hardware", "text"],+ disabledByEnv: false,+ });+});++test("removing text restores hardware's explicit saved preference", () => {+ const api = settingsApi(async () => Response.json({}));+ assert.deepEqual(api.updateWarmupSelection(["text"], "text", false), []);+ assert.deepEqual(api.updateWarmupSelection(["hardware", "text"], "text", false), ["hardware"]);+ assert.deepEqual(api.updateWarmupSelection(["media"], "text", true), ["text", "media"]);+ assert.deepEqual(api.updateWarmupSelection(["text"], "text", true), ["text"]);+});++test("only text, media and quantization lock the hardware switch", () => {+ const api = settingsApi(async () => Response.json({}));+ for (const feature of ["text", "media", "quantization"] as const) {+ assert.equal(api.hardwareWarmupRequired([feature]), true);+ }+ assert.equal(api.hardwareWarmupRequired([]), false);+ assert.equal(api.hardwareWarmupRequired(["datasets"]), false);+ assert.equal(api.hardwareWarmupRequired(["hardware", "datasets"]), false);+});++test("failed reads and writes report the server error", async () => {+ const api = settingsApi(async () =>+ Response.json({ detail: "Only the owner can change this setting." }, { status: 403 }),+ );+ await assert.rejects(api.loadMlWarmupSettings(), /Only the owner/);+ await assert.rejects(api.updateMlWarmupSettings(["text"]), /Only the owner/);+});diff --git a/studio/frontend/tests/provisional-hardware-verdict.test.ts b/studio/frontend/tests/provisional-hardware-verdict.test.tsindex 700dc5eacac..2cdc9749efa 100644--- a/studio/frontend/tests/provisional-hardware-verdict.test.ts+++ b/studio/frontend/tests/provisional-hardware-verdict.test.ts@@ -200,13 +200,13 @@ test("a provisional forced refresh keeps the server-reported platform", async ());assert.match(ENV,- /fetched: data\.device_type !== undefined \|\| keepPlatform/,+ /fetched: \(data\.device_type !== undefined && !isDetectionDeferred\(data\)\) \|\| keepPlatform/,"fetched drops to false, so the authoritative platform is not treated as held",);});-// Under the kill switch only a first-use operation detects, so the sidebar must poll.-test("a deferred verdict is recorded so the sidebar can poll out of it", async () => {+// A deferred probe has not started; the sidebar must wait for a real hardware request.+test("a deferred verdict is recorded without starting a background recovery poll", async () => {const { readFile } = await import("node:fs/promises");assert.match(ENV,@@ -215,8 +215,8 @@ test("a deferred verdict is recorded so the sidebar can poll out of it", async ();assert.match(APP_SIDEBAR,- /chatOnlyReason !== "mlx_unavailable" && !detectionDeferred/,- "the recovery poll still ignores a deferred verdict, so it never recovers",+ /if \(detectionDeferred\) return;/,+ "the sidebar polls a probe that has deliberately not started",);});@@ -244,7 +244,7 @@ test("a rejected token does not consume the once-per-load window", async () => {const { readFile } = await import("node:fs/promises");assert.match(ENV,- /if \(spendWait && !tokenRejected\) hardwareWaitSpent = true;/,+ /if \(spendWait && !tokenRejected && !detectionDeferred\) hardwareWaitSpent = true;/,"the latch is claimed even when the break came from a rejected token, so the " +"first accepted token in this page load skips its window",);@@ -266,21 +266,21 @@ test("the store exposes an unknown state, not just chat-only", async () => {assert.match(ENV,// verdictStale: the stored verdict came from a backend a repair or restart has replaced.- /return \(!state\.fetched \|\| state\.verdictStale\) && !state\.detectionDeferred;/,+ /return !state\.fetched \|\| state\.verdictStale \|\| state\.detectionDeferred;/,"the selector is not derived from `fetched`, the flag that already means " +"'a server-reported verdict is stored'",);});-// Under the torch-warm kill switch `fetched` never flips, so unknown would spin forever.-test("a deferred verdict counts as settled, not as still checking", async () => {+// Deferred remains unmeasured; only an active probe should put navigation into a pending state.+test("a deferred verdict stays unknown without leaving navigation pending", async () => {const { readFile } = await import("node:fs/promises");const selector = /capabilitiesUnknown: \(\) => \{([\s\S]*?)\n \},/.exec(ENV);assert.ok(selector, "capabilitiesUnknown is no longer a block the deferred case can live in");assert.match(selector[1],/detectionDeferred/,- "a deferred reply leaves the tabs spinning with nothing left to wait for",+ "the selector lost the distinction between an unmeasured and unsupported host",);});@@ -299,7 +299,7 @@ test("the sidebar gates Train and Video on a measured verdict", async () => {);}assert.equal(- APP_SIDEBAR.match(/pending: capabilitiesUnknown,/g)?.length,+ APP_SIDEBAR.match(/pending: capabilitiesUnknown && !detectionDeferred,/g)?.length,2,"Train and Video do not both mark themselves pending while the verdict is out",);@@ -316,7 +316,7 @@ test("the route guard waits out an unknown verdict on Train and Video", async ()}assert.match(src,- /!\(unmeasured && waitsOutUnknownVerdict\(location\.pathname\)\)/,+ /!\(unmeasured && \(detectionDeferred \|\| waitsOutUnknownVerdict\(location\.pathname\)\)\)/,"the redirect does not consult the unknown state",);// Child routes count too, or /studio/anything bounces while /studio does not.diff --git a/studio/frontend/tests/settings-search.test.ts b/studio/frontend/tests/settings-search.test.tsindex 00fe7b15322..4574a6351cc 100644--- a/studio/frontend/tests/settings-search.test.ts+++ b/studio/frontend/tests/settings-search.test.ts@@ -210,3 +210,26 @@ test("GPU rendering is searchable on desktop only", () => {);assert.equal(desktop.appearance.length, browser.appearance.length + 1);});+++test("ML startup warmup is searchable in General for the owner on web and desktop", () => {+ const entries = [+ "settings.general.mlWarmup.sectionTitle",+ "settings.general.mlWarmup.hardwareLabel",+ "settings.general.mlWarmup.textLabel",+ "settings.general.mlWarmup.datasetsLabel",+ "settings.general.mlWarmup.mediaLabel",+ "settings.general.mlWarmup.quantizationLabel",+ ] as const;+ for (const desktop of [false, true]) {+ const index = createSettingsSearchIndex({+ desktop,+ closeToTray: false,+ menuBarIcon: false,+ });+ for (const entry of entries) {+ assert.ok(renderedSearchEntries(index, "general", "huggingface", true).includes(entry));+ assert.ok(!renderedSearchEntries(index, "general", "huggingface", false).includes(entry));+ }+ }+});diff --git a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts b/studio/frontend/tests/sidebar-nav-backend-parity.test.tsindex 7f862b02991..98b9aaf9fc6 100644--- a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts+++ b/studio/frontend/tests/sidebar-nav-backend-parity.test.ts@@ -73,7 +73,7 @@ test("Train and Video are still the capability-gated rows", async () => {assert.ok(body, `no ${id} row`);assert.match(body,- /pending: capabilitiesUnknown,/,+ /pending: capabilitiesUnknown && !detectionDeferred,/,`the ${id} row renders its disabled state before the verdict is measured`,);assert.match(diff --git a/studio/frontend/tests/system-hardware-first-use.test.ts b/studio/frontend/tests/system-hardware-first-use.test.tsnew file mode 100644index 00000000000..d1a64ac0ea6--- /dev/null+++ b/studio/frontend/tests/system-hardware-first-use.test.ts@@ -0,0 +1,222 @@+// 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 { register } from "node:module";+import test from "node:test";+import type * as SystemHooks from "../src/hooks/use-system.ts";+import { installLocalStorageFake, registerBundlerResolver } from "./helpers/kit.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++register("./helpers/vite-env-loader.mjs", import.meta.url);+registerBundlerResolver();+const { store } = installLocalStorageFake();+Object.defineProperty(globalThis, "navigator", {+ configurable: true,+ value: { platform: "Win32", userAgent: "Windows" },+});+const platform = await import("../src/config/env.ts");+const { usePlatformStore, forgetMeasuredVerdict, fetchDeviceType } = platform;+const DEFERRED = { chat_only: true, hardware_detecting: true, hardware_detection_deferred: true, version: "test" };+const CPU = { device_type: "linux", chat_only: true, chat_only_reason: "no_gpu", version: "test" };+const MLX = { device_type: "mac", apple_silicon: true, chat_only: false, chat_only_reason: null, version: "test" };++function systemApi(fetch: (url: string) => Promise<Response>) {+ return loadWithStubs<typeof SystemHooks>(+ new URL("../src/hooks/use-system.ts", import.meta.url),+ {+ react: {},+ "@/features/auth": { authFetch: fetch },+ "@/config/env": platform,+ },+ { relativePassthrough: true },+ );+}++function reset(chatOnly = true) {+ store.set("unsloth_auth_token", "test-token");+ forgetMeasuredVerdict();+ usePlatformStore.setState({+ deviceType: "windows", fetched: true, verdictStale: false,+ detectionDeferred: true, chatOnly, chatOnlyReason: null,+ });+}++async function settle() {+ for (let i = 0; i < 5; i++) await new Promise<void>((resolve) => setImmediate(resolve));+}++for (const [name, health, initialChatOnly, backend] of [+ ["CPU", CPU, false, "cpu"],+ ["MLX", MLX, true, "mlx"],+] as const) {+ test(`first successful system read replaces the deferred ${name} picker verdict`, async () => {+ reset(initialChatOnly);+ const urls: string[] = [];+ globalThis.fetch = (async (url: string) => {+ urls.push(url);+ return Response.json(health);+ }) as typeof fetch;+ const system = systemApi(async (url) => {+ urls.push(url);+ return Response.json({ device_backend: backend, gpu: { available: backend === "mlx", devices: [] } });+ });+ await settle();+ assert.deepEqual(urls, [], "a closed/unused picker must not start discovery");+ const info = await system.fetchSystemInfo();+ await settle();+ assert.equal(info?.device_backend, backend);+ assert.deepEqual(urls, ["/api/system", "/api/health"]);+ const state = usePlatformStore.getState();+ assert.equal(state.capabilitiesUnknown(), false);+ assert.equal(state.detectionDeferred, false);+ assert.equal(state.isChatOnly(), health.chat_only);+ assert.equal(state.deviceType, health.device_type);+ await system.fetchSystemInfo();+ assert.equal(urls.length, 2, "a measured cached verdict needs no extra health read");+ });+}++test("failed system reads do not request a platform refresh", async () => {+ reset();+ let healthCalls = 0;+ globalThis.fetch = (async () => { healthCalls++; return Response.json(CPU); }) as typeof fetch;+ const system = systemApi(async () => new Response(null, { status: 503 }));+ assert.equal(await system.fetchSystemInfo(), null);+ await settle();+ assert.equal(healthCalls, 0);+ assert.equal(usePlatformStore.getState().detectionDeferred, true);+});++test("system readers share one pending verdict refresh without delaying GPU results", async () => {+ reset();+ let healthCalls = 0;+ let release: ((response: Response) => void) | undefined;+ globalThis.fetch = (async () => {+ healthCalls++;+ return new Promise<Response>((resolve) => { release = resolve; });+ }) as typeof fetch;+ const system = systemApi(async () => Response.json({ device_backend: "cpu" }));+ assert.equal((await system.fetchSystemInfo())?.device_backend, "cpu");+ assert.equal((await system.fetchSystemInfo({ force: true }))?.device_backend, "cpu");+ assert.equal((await system.fetchSystemInfo())?.device_backend, "cpu");+ assert.equal(healthCalls, 1);+ release?.(Response.json(CPU));+ await settle();+ assert.equal(usePlatformStore.getState().capabilitiesUnknown(), false);+});++test("a failed verdict refresh leaves GPU data usable and retries on the next cached demand", async () => {+ reset();+ let healthCalls = 0;+ let systemCalls = 0;+ globalThis.fetch = (async () => {+ healthCalls++;+ return healthCalls === 1 ? new Response(null, { status: 503 }) : Response.json(CPU);+ }) as typeof fetch;+ const system = systemApi(async () => { systemCalls++; return Response.json({ device_backend: "cpu" }); });+ assert.equal((await system.fetchSystemInfo())?.device_backend, "cpu");+ await settle();+ assert.equal(usePlatformStore.getState().detectionDeferred, true);+ assert.equal((await system.fetchSystemInfo())?.device_backend, "cpu");+ await settle();+ assert.equal(systemCalls, 1);+ assert.equal(healthCalls, 2);+ assert.equal(usePlatformStore.getState().capabilitiesUnknown(), false);+});++test("an earlier deferred health response cannot undo a system-triggered settled verdict", async () => {+ reset();+ let healthCalls = 0;+ let release: ((response: Response) => void) | undefined;+ globalThis.fetch = (async () => {+ healthCalls++;+ if (healthCalls === 1) return new Promise<Response>((resolve) => { release = resolve; });+ return Response.json(MLX);+ }) as typeof fetch;+ const oldIdleRead = fetchDeviceType({ force: true });+ const system = systemApi(async () => Response.json({ device_backend: "mlx" }));+ await system.fetchSystemInfo();+ await settle();+ assert.equal(usePlatformStore.getState().isChatOnly(), false);+ release?.(Response.json(DEFERRED));+ await oldIdleRead;+ assert.equal(usePlatformStore.getState().detectionDeferred, false);+ assert.equal(usePlatformStore.getState().isChatOnly(), false);+});++test("a new backend may defer again after the previous backend was measured", async () => {+ reset();+ globalThis.fetch = (async () => Response.json(MLX)) as typeof fetch;+ const system = systemApi(async () => Response.json({ device_backend: "mlx" }));+ await system.fetchSystemInfo();+ await settle();+ assert.equal(usePlatformStore.getState().capabilitiesUnknown(), false);+ forgetMeasuredVerdict();+ globalThis.fetch = (async () => Response.json(DEFERRED)) as typeof fetch;+ await fetchDeviceType({ force: true });+ assert.equal(usePlatformStore.getState().detectionDeferred, true);+ assert.equal(usePlatformStore.getState().capabilitiesUnknown(), true);+});++test("a pending refresh from a replaced backend cannot block or overwrite its successor", async () => {+ reset();+ let oldRelease: ((response: Response) => void) | undefined;+ let healthCalls = 0;+ globalThis.fetch = (async () => {+ healthCalls++;+ if (healthCalls === 1) return new Promise<Response>((resolve) => { oldRelease = resolve; });+ return Response.json(MLX);+ }) as typeof fetch;+ const system = systemApi(async () => Response.json({ device_backend: "mlx" }));+ await system.fetchSystemInfo();+ forgetMeasuredVerdict();+ await system.fetchSystemInfo({ force: true });+ await settle();+ assert.equal(healthCalls, 2);+ assert.equal(usePlatformStore.getState().isChatOnly(), false);+ oldRelease?.(Response.json(CPU));+ await settle();+ assert.equal(usePlatformStore.getState().isChatOnly(), false);+ assert.equal(usePlatformStore.getState().deviceType, "mac");+});++test("cached picker demand settles a backend restarted with warmup disabled", async () => {+ reset();+ let detected = true;+ const requests: string[] = [];+ globalThis.fetch = (async (url: string) => {+ requests.push(url);+ if (url.includes("detect_hardware=true")) detected = true;+ return Response.json(detected ? MLX : DEFERRED);+ }) as typeof fetch;+ const system = systemApi(async (url) => {+ requests.push(url);+ detected = true;+ return Response.json({ device_backend: "mlx", gpu: { available: true, devices: [] } });+ });+ await system.fetchSystemInfo();+ await settle();+ assert.equal(usePlatformStore.getState().capabilitiesUnknown(), false);++ forgetMeasuredVerdict();+ detected = false;+ await fetchDeviceType({ force: true });+ assert.equal(usePlatformStore.getState().detectionDeferred, true);+ const idleRequests = [...requests];+ await settle();+ assert.deepEqual(requests, idleRequests, "idle restart must not start discovery");++ await Promise.all([system.fetchSystemInfo(), system.fetchSystemInfo()]);+ await settle();+ assert.equal(usePlatformStore.getState().capabilitiesUnknown(), false,+ "reopening a cached picker must measure the new backend: " + requests.join(", "));+ assert.equal(usePlatformStore.getState().detectionDeferred, false);+ assert.equal(usePlatformStore.getState().isChatOnly(), false);+ assert.equal(requests.filter((url) => url.includes("detect_hardware=true")).length, 1,+ "concurrent cached demands share one hardware refresh");+ const settledRequests = [...requests];+ await system.fetchSystemInfo();+ await settle();+ assert.deepEqual(requests, settledRequests, "a settled cache hit needs no new health read");+});diff --git a/studio/frontend/tests/system-poll-visibility.test.ts b/studio/frontend/tests/system-poll-visibility.test.tsindex 8820cfd09d7..cfe2d06d074 100644--- a/studio/frontend/tests/system-poll-visibility.test.ts+++ b/studio/frontend/tests/system-poll-visibility.test.ts@@ -34,6 +34,7 @@ function loadSystem(body: unknown) {cleanup = effect();},},+ "@/config/env": { refreshDeviceTypeAfterSystemInfo: () => {} },"@/features/auth": {authFetch: async (url: string, init?: RequestInit) => {requests.push({ url, init });diff --git a/studio/frontend/tests/verdict-after-backend-restart.test.ts b/studio/frontend/tests/verdict-after-backend-restart.test.tsindex 3010663e004..b8aa91a0f60 100644--- a/studio/frontend/tests/verdict-after-backend-restart.test.ts+++ b/studio/frontend/tests/verdict-after-backend-restart.test.ts@@ -78,7 +78,7 @@ test("a replaced backend's verdict is unmeasured until the new one answers", asy});test("a replaced backend under deferred detection does not inherit the old reason", async () => {- // UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1: a deferred reply counts as settled.+ // A deferred backend has not measured hardware and cannot inherit the predecessor's verdict.reply = CHAT_ONLY;await fetchDeviceType({ force: true });assert.equal(usePlatformStore.getState().chatOnlyReason, "no_torch");@@ -86,7 +86,7 @@ test("a replaced backend under deferred detection does not inherit the old reasoreply = { ...DETECTING, hardware_detection_deferred: true };await fetchDeviceType({ force: true });const s = usePlatformStore.getState();- assert.equal(s.capabilitiesUnknown(), false);+ assert.equal(s.capabilitiesUnknown(), true);assert.equal(s.isChatOnly(), true);assert.equal(s.chatOnlyReason, null);assert.equal(s.deviceType, "windows");@@ -114,6 +114,6 @@ test("only a backend that already answered marks the verdict stale", async () =>);assert.match(src,- /if \(verdictStaleRef\.current\) \{\s*verdictStaleRef\.current = false;\s*forgetMeasuredVerdict\(\);\s*\}\s*void fetchDeviceType\(\{ force: true \}\)/,+ /if \(verdictStaleRef\.current\) \{\s*verdictStaleRef\.current = false;\s*forgetMeasuredVerdict\(\);\s*\}\s*void fetchDeviceType\(\{\s*force: true,/,);});diff --git a/tests/studio/mac_capability_verdict_smoke.py b/tests/studio/mac_capability_verdict_smoke.pyindex 04cc1dc5bd1..de284138f75 100644--- a/tests/studio/mac_capability_verdict_smoke.py+++ b/tests/studio/mac_capability_verdict_smoke.py@@ -8,6 +8,8 @@ clock and a stand-in worker. Nothing there boots a server, and nothing there runhost where `import mlx.core` succeeds or fails for real. This does: it boots the real`unsloth studio` on Apple Silicon, polls /api/health from the first reply the socketgives, and judges the whole sequence rather than the last answer.+Once login succeeds, each scenario explicitly requests hardware detection, as a+capability-dependent feature does; ordinary health alone stays cold by default.Three scenarios, one per boot (the self-heal is once per process, so they cannot shareone):@@ -587,6 +589,26 @@ def assert_settled_and_stable(poller: HealthPoller, chat_only: bool, reason, labok(f"the {label} verdict held for {STABLE_HOLD_S:.0f}s across {len(tail)} replies")+def request_hardware_detection(poller: HealthPoller, getter: TokenGetter) -> bool:+ """Keep observing idle health, then make the authenticated demand a picker makes."""+ sample = poller.wait_for(+ lambda s: s.authed, 120, "an authenticated health reply before hardware demand"+ )+ if sample is None or not poller.token:+ fail(f"cannot request hardware detection ({getter.error or 'login had not landed yet'})")+ return False+ if not sample.published and sample.body.get("hardware_detection_deferred"):+ ok("ordinary health stayed provisional before the hardware request")+ step("requesting hardware detection for the capability-dependent feature")+ status, body = _get(f"{poller.base}/api/health?detect_hardware=true", poller.token)+ if status != 200 or not isinstance(body, dict) or "version" not in body:+ fail(f"authenticated hardware detection returned {status} without an accepted health reply")+ return False+ # The response can still be provisional while detection or MLX repair runs.+ # Leave the ordinary poller and every stability/repair assertion in control.+ return True++def first_authed_published(poller: HealthPoller, getter: TokenGetter, budget: float) -> Sample | None:@@ -661,6 +683,8 @@ def scenario_real_mlx(port: int, log: Path) -> None:returnwith booted(port, log, dict(os.environ)) as (poller, getter):+ if not request_hardware_detection(poller, getter):+ returnsettled = poller.wait_for(lambda s: s.published, SETTLE_BUDGET_S, "the verdict to settle")if settled is None:wait_for_health(port, log)@@ -709,6 +733,8 @@ def scenario_no_mlx_settles(port: int, log: Path, work: Path) -> None:env["UNSLOTH_DISABLE_MLX_AUTOREPAIR"] = "1"with booted(port, log, env) as (poller, getter):+ if not request_hardware_detection(poller, getter):+ returnif not wait_for_health(port, log):fail("the server never became healthy")return@@ -755,6 +781,8 @@ def scenario_no_mlx_repair(port: int, log: Path, work: Path) -> None:env.pop("UNSLOTH_DISABLE_MLX_AUTOREPAIR", None)with booted(port, log, env) as (poller, getter):+ if not request_hardware_detection(poller, getter):+ returnif not wait_for_health(port, log):fail("the server never became healthy")returndiff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.pyindex b7469c7dd1f..46e77347928 100644--- a/tests/studio/test_chat_autoload_failure_gate.py+++ b/tests/studio/test_chat_autoload_failure_gate.py@@ -127,6 +127,8 @@ export type Scenario = {tokenDecision: string | null;/** false = the backend platform probe has not landed yet. */platformFetched: boolean;+ /** true = the backend answered but deferred hardware detection. */+ detectionDeferred: boolean;variants: Record<string, any>;lastLoaded: any;validate: (payload: any) => any;@@ -598,6 +600,8 @@ const usePlatformStore = {// Server-reported unless a scenario says the probe has not landed.fetched: SCENARIO.platformFetched !== false,isChatOnly: () => SCENARIO.chatOnly === true,+ capabilitiesUnknown: () =>+ SCENARIO.platformFetched === false || SCENARIO.detectionDeferred === true,}),};function isMlxId(value: string) {@@ -1694,6 +1698,15 @@ def test_a_provisional_platform_does_not_hide_cached_non_gguf_rows():assert _loaded_paths(out) == ["org/st"]+def test_a_deferred_hardware_verdict_does_not_hide_cached_non_gguf_rows():+ """Deferred detection reports a provisional chat_only, not a measurement."""+ out = _run(+ "scenario({ chatOnly: true, platformFetched: true, detectionDeferred: true,"+ " modelRepos: [{ repo_id: 'org/st', load_id: 'org/st', size_bytes: 1 }] })"+ )+ assert _loaded_paths(out) == ["org/st"]++def test_a_cached_adapter_repo_is_never_auto_loaded():"""A cached LoRA has no weights of its own: /load fetches the base from theHub when it is not cached, which is why the local twin is dropped too.diff --git a/tests/studio/test_mac_verdict_hardware_demand.py b/tests/studio/test_mac_verdict_hardware_demand.pynew file mode 100644index 00000000000..c14b8da7f08--- /dev/null+++ b/tests/studio/test_mac_verdict_hardware_demand.py@@ -0,0 +1,107 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Exercise the smoke driver against a cold HTTP contract, without claiming MLX coverage."""++import importlib.util+import json+import sys+import threading+from contextlib import contextmanager+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from types import SimpleNamespace+from urllib.parse import parse_qs, urlsplit++import pytest++[email protected]("scenario", ["real-mlx", "no-mlx-settles"])+def test_mac_smoke_requests_detection_before_waiting_for_a_verdict(monkeypatch, tmp_path, scenario):+ spec = importlib.util.spec_from_file_location(+ "_mac_verdict_demand_smoke", Path(__file__).with_name("mac_capability_verdict_smoke.py")+ )+ smoke = importlib.util.module_from_spec(spec)+ monkeypatch.setitem(sys.modules, spec.name, smoke)+ spec.loader.exec_module(smoke)+ monkeypatch.setitem(+ sys.modules, "utils.mlx_repair", SimpleNamespace(mlx_stack_available = lambda: True)+ )+ monkeypatch.setattr(smoke, "POLL_INTERVAL_S", 0.01)+ monkeypatch.setattr(smoke, "SETTLE_BUDGET_S", 0.5)+ monkeypatch.setattr(smoke, "STABLE_HOLD_S", 0.05)+ monkeypatch.setattr(smoke, "wait_for_health", lambda *args: True)+ monkeypatch.setattr(smoke, "tail_log", lambda *args: None)++ requested = threading.Event()+ requests = []+ chat_only = scenario == "no-mlx-settles"++ class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ path = urlsplit(self.path)+ auth = self.headers.get("Authorization") == "Bearer smoke-test"+ demand = parse_qs(path.query).get("detect_hardware") == ["true"]+ requests.append((path.path, demand, auth))+ status = 200+ if path.path == "/api/system":+ body = {"device_backend": "mlx"}+ elif path.path == "/api/health":+ if demand and auth:+ requested.set()+ elif demand:+ status = 401+ body = {"status": "healthy", "chat_only": chat_only if requested.is_set() else True}+ if auth:+ body.update(version = "test", device_type = "mac" if requested.is_set() else None)+ body["chat_only_reason"] = (+ "mlx_unavailable" if requested.is_set() and chat_only else None+ )+ if not requested.is_set():+ body.update(hardware_detecting = True, hardware_detection_deferred = True)+ else:+ status, body = 404, {}+ encoded = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(encoded)))+ self.end_headers()+ self.wfile.write(encoded)++ def log_message(self, *args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server_thread = threading.Thread(target = server.serve_forever, daemon = True)+ server_thread.start()+ port = server.server_port+ poller = smoke.HealthPoller(f"http://127.0.0.1:{port}")+ poller.token = "smoke-test"++ @contextmanager+ def booted(*args):+ poller.start()+ try:+ yield poller, SimpleNamespace(error = None)+ finally:+ poller.stop()++ monkeypatch.setattr(smoke, "booted", booted)+ original_path = list(sys.path)+ try:+ if scenario == "real-mlx":+ smoke.scenario_real_mlx(port, tmp_path / "unused.log")+ else:+ smoke.scenario_no_mlx_settles(port, tmp_path / "unused.log", tmp_path)+ assert not smoke._failed, smoke._failed+ assert requested.is_set(), "ordinary health must be followed by an explicit feature demand"+ assert requests[0] == ("/api/health", False, True)+ assert [r for r in requests if r[1]] == [("/api/health", True, True)]+ assert any(not sample.published for sample in poller.snapshot())+ assert any(sample.published and sample.authed for sample in poller.snapshot())+ finally:+ poller.stop()+ server.shutdown()+ server.server_close()+ server_thread.join(timeout = 2)+ sys.path[:] = original_pathdiff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 112c2c3594b..e55b06c5a20 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -3597,7 +3597,7 @@ def test_format_gates_wait_for_the_server_reported_platform():Linux Unsloth would hide every local safetensors model."""src = _read("features/chat/api/chat-adapter.ts")gate = src.split("function runsOnThisPlatform", 1)[1].split("\n}", 1)[0]- assert "if (!platform.fetched || !platform.isChatOnly()) return true;" in gate+ assert "if (platform.capabilitiesUnknown() || !platform.isChatOnly()) return true;" in gatedef test_the_default_is_preflighted_before_the_managed_download():@@ -3617,7 +3617,7 @@ def test_cached_non_gguf_rows_get_the_chat_only_platform_gate():"""The picker hides them outright there (visibleCachedModelRows)."""src = _read("features/chat/api/chat-adapter.ts")gate = src.split("function cachedModelsRunOnThisPlatform", 1)[1].split("\n}", 1)[0]- assert "return !platform.fetched || !platform.isChatOnly();" in gate+ assert "return platform.capabilitiesUnknown() || !platform.isChatOnly();" in gateassert "cachedModelsRunOnThisPlatform()\n ? allModelRepos.filter(" in srcassert "allGgufRepos.filter(isChattableCachedRepo)," in src