Skip to content

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

studio: stop prompting to stop chats for a model already loaded (#8943)

Maheswar Kumar43a91d87691d
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 60a28b7ab53..73023ff8c65 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1064,6 +1064,81 @@ class InferenceStatusResponse(_InferenceRuntimeFields):
"None when the requested strategy engaged or was not requested."
),
)
+ spec_fallback_binary_changed: Optional[bool] = Field(
+ None,
+ description = (
+ "For a 'binary_no_mtp' / 'binary_outdated' stand-down only: whether a "
+ "different llama-server is installed than the live one launched from, "
+ "which is the necessary condition in "
+ "LlamaCppBackend.spec_binary_fallback_can_retry. False -> an identical "
+ "/load cannot repair the drafter and dedupes, so a client need not "
+ "reload for it. None for every other reason, and on a backend too old "
+ "to report it."
+ ),
+ )
+ spec_probe_retry_pending: Optional[bool] = Field(
+ None,
+ description = (
+ "The capability probe has started answering since a launch it degraded, so "
+ "an identical /load is rejected once to re-derive the runtime "
+ "(_runtime_matches_intent's _capability_probe_inconclusive arm). No "
+ "speculative mode gates it. None on a backend too old to report it."
+ ),
+ )
+ spec_dflash_retry_pending: Optional[bool] = Field(
+ None,
+ description = (
+ "A DFlash sidecar fetch failed retryably, which under Auto records no "
+ "spec_fallback_reason at all, so an identical /load is rejected to fetch "
+ "again. Applies to the 'auto' and 'dflash' modes. None on a backend too old "
+ "to report it."
+ ),
+ )
+ spec_dspark_sidecar_absent: Optional[bool] = Field(
+ None,
+ description = (
+ "The DSpark drafter is absent rather than transiently unfetchable, which is "
+ "the permanent state of every repo but one. _runtime_matches_intent excludes "
+ "it from the drafter_not_found retry arm, so an identical /load dedupes and a "
+ "client need not reload for it. None on a backend too old to report it."
+ ),
+ )
+ tensor_parallel_dropped_by_arch_gate: Optional[bool] = Field(
+ None,
+ description = (
+ "The GPU architecture gate normalized a tensor-parallel request to layer "
+ "mode, so tensor_parallel reads false while the request that produced it was "
+ "true. _runtime_matches_intent accepts the same true request against this "
+ "runtime. None on a backend too old to report it."
+ ),
+ )
+ gpu_placement_paravirtual: Optional[bool] = Field(
+ None,
+ description = (
+ "Metal is a virtualised Apple GPU, so paravirtual_normalized_request rewrites "
+ "every GGUF request to manual / zero layers / no split / no MoE before the "
+ "duplicate-load comparators run. Placement cannot tell two requests apart "
+ "here. None on a backend too old to report it."
+ ),
+ )
+ audio_probe_pending: bool = Field(
+ False,
+ description = (
+ "The post-launch audio probe did not finish and has to be retried. The route "
+ "refuses its own already-loaded answer while this is true so load_model can "
+ "re-probe, and nothing else does, so a client must not skip /load for it."
+ ),
+ )
+ diffusion_split_supported: Optional[bool] = Field(
+ None,
+ description = (
+ "A diffusion launch right now would honour --ngl. _runtime_matches_intent "
+ "rejects an otherwise identical request once this is true and gpu_layers "
+ "differs from diffusion_requested_ngl, so a split an older shim dropped can "
+ "be applied. None off a diffusion runner, and on a backend too old to report "
+ "it."
+ ),
+ )
llama_cpp_prebuilt_stale: bool = Field(
False,
description = (
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a13b5d292a0..4989a2995aa 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -6992,6 +6992,139 @@ class _LoadPlacement(NamedTuple):
diffusion_kind: Optional[bool]
+def _spec_fallback_binary_changed(llama_backend) -> Optional[bool]:
+ """``spec_binary_fallback_can_retry``, for the status poll.
+
+ Only the two binary stand-downs can be repaired by an identical reload, so a client
+ that reloads for any ``binary_*`` reason prompts to stop running chats for a load
+ that would dedupe. Answered only for those reasons: this is polled from first paint,
+ and neither the binary lookup nor the capability probe has business running on every
+ poll of a healthy runtime.
+
+ The whole predicate, not just its revision half. ``binary_no_mtp`` also asks whether
+ the replacement advertises what the drafter kind needs, and a replacement that still
+ lacks it never repairs: the live process keeps its launch revision, so a half answer
+ would prompt on every later re-pick and never stop. The probe caches on the binary's
+ revision, and this route already relies on that elsewhere.
+ """
+ if getattr(llama_backend, "spec_fallback_reason", None) not in (
+ "binary_no_mtp",
+ "binary_outdated",
+ ):
+ return None
+ try:
+ return bool(llama_backend.spec_binary_fallback_can_retry())
+ except Exception:
+ return None
+
+
+def _spec_probe_retry_pending(llama_backend) -> Optional[bool]:
+ """Whether the capability probe has started answering since a degraded launch.
+
+ Mirrors the ``_capability_probe_inconclusive`` arm of ``_runtime_matches_intent``,
+ which rejects an identical load once the probe turns conclusive so the degraded
+ runtime is re-derived. No speculative mode gates it, and it records the conclusive
+ probe and clears, so it is one reload rather than a loop. Probing is cheap here:
+ ``probe_server_capabilities`` caches on the binary's revision and this route already
+ calls it.
+ """
+ if not getattr(llama_backend, "_capability_probe_inconclusive", False):
+ return False
+ if getattr(llama_backend, "_is_diffusion", False):
+ return False
+ try:
+ return not llama_backend.probe_server_capabilities().get("mtp_probe_inconclusive")
+ except Exception:
+ return None
+
+
+def _diffusion_split_supported(llama_backend) -> Optional[bool]:
+ """Whether a diffusion launch right now would honour --ngl.
+
+ Only meaningful for a resident diffusion runner. ``_runtime_matches_intent`` rejects
+ an otherwise identical request once this turns true and the live gpu_layers differs
+ from the requested NGL, so the split an older shim dropped can finally be applied.
+ A client comparing only the retained request would skip that load.
+ """
+ if not getattr(llama_backend, "_is_diffusion", False):
+ return None
+ try:
+ return bool(llama_backend.diffusion_split_supported())
+ except Exception:
+ return None
+
+
+def _audio_probe_pending(llama_backend) -> bool:
+ """Whether the post-launch audio probe still has to be retried.
+
+ ``_reuse_loaded_gguf`` refuses the route's own already-loaded answer while this is
+ true, so ``load_model`` reaches its fast path and re-probes there. A client that
+ skips /load skips the retry with it, and nothing else re-probes, so the model's
+ audio capabilities would stay undetected for as long as the server runs.
+ """
+ return not getattr(llama_backend, "_audio_probed", True)
+
+
+def _gpu_placement_paravirtual() -> Optional[bool]:
+ """Whether every GGUF request on this host is rewritten to the CPU pin.
+
+ ``paravirtual_normalized_request`` maps any placement to manual / zero layers / no
+ split / no MoE on a virtualised Metal device, and ``adopt_load_intent_if_matched``
+ applies it before comparing, so placement cannot distinguish two requests here at
+ all. A client comparing the raw values sees its Auto pick against a manual status and
+ reloads on every re-pick. The detector is lru_cached, so this costs one probe per
+ process and nothing after.
+ """
+ try:
+ from core.inference.llama_cpp import _metal_device_is_paravirtual
+ return bool(_metal_device_is_paravirtual())
+ except Exception:
+ return None
+
+
+def _arch_gate_dropped_tensor_parallel(llama_backend) -> Optional[bool]:
+ """Whether the GPU architecture gate normalized a tensor-parallel request away.
+
+ ``_runtime_matches_intent`` accepts the same true request against the resulting
+ layer-mode runtime, since that runtime IS the request as the gate rewrote it. Status
+ reports the mode that launched, so a client comparing it raw prompts to stop running
+ chats on every re-pick of a model whose split was gated off.
+ """
+ try:
+ return bool(llama_backend._arch_gate_dropped_tensor_parallel)
+ except Exception:
+ return None
+
+
+def _spec_dspark_sidecar_absent(llama_backend) -> Optional[bool]:
+ """Whether the DSpark drafter is missing permanently rather than transiently.
+
+ The ``drafter_not_found`` arm of ``_runtime_matches_intent`` reloads so the next
+ Apply retries the fetch, but excludes an absent DSpark sidecar: that is the permanent
+ state of every repo but one, and retrying it would relaunch an identical server
+ forever. A client reading only the reason cannot tell the two apart and prompts to
+ stop running chats for a load that dedupes.
+ """
+ try:
+ return bool(llama_backend._dspark_sidecar_absent)
+ except Exception:
+ return None
+
+
+def _spec_dflash_retry_pending(llama_backend) -> Optional[bool]:
+ """Whether a DFlash sidecar fetch failed in a way the next identical load retries.
+
+ Under Auto a failed fetch records no ``spec_fallback_reason``, so a client reading
+ only that adopts a runtime the backend would have rebuilt. Set only for retryable
+ failures: a repo publishing no sidecar is ``_dflash_sidecar_absent``'s business.
+ Applies to the Auto and DFlash modes, as the arm does.
+ """
+ try:
+ return bool(llama_backend._dflash_retry_needed)
+ except Exception:
+ return None
+
+
class _NoParallelRequest:
"""A stand-in for a load that named no slot count, for reading the default."""
@@ -10506,6 +10639,16 @@ async def get_status(current_subject: str = Depends(get_current_subject)):
requested_context_length = llama_backend.requested_n_ctx,
llama_cpp_supports_mtp = _supports_mtp,
spec_fallback_reason = llama_backend.spec_fallback_reason,
+ spec_fallback_binary_changed = _spec_fallback_binary_changed(llama_backend),
+ spec_probe_retry_pending = _spec_probe_retry_pending(llama_backend),
+ spec_dflash_retry_pending = _spec_dflash_retry_pending(llama_backend),
+ spec_dspark_sidecar_absent = _spec_dspark_sidecar_absent(llama_backend),
+ gpu_placement_paravirtual = _gpu_placement_paravirtual(),
+ audio_probe_pending = _audio_probe_pending(llama_backend),
+ diffusion_split_supported = _diffusion_split_supported(llama_backend),
+ tensor_parallel_dropped_by_arch_gate = _arch_gate_dropped_tensor_parallel(
+ llama_backend
+ ),
spec_drafter_kind = llama_backend.spec_drafter_kind,
llama_cpp_prebuilt_stale = _stale,
llama_cpp_installed_tag = _installed_tag,
diff --git a/studio/backend/tests/test_spec_retry_status_signals.py b/studio/backend/tests/test_spec_retry_status_signals.py
new file mode 100644
index 00000000000..cc5283e28ba
--- /dev/null
+++ b/studio/backend/tests/test_spec_retry_status_signals.py
@@ -0,0 +1,287 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The status fields a client reads before declining the resident-model shortcut.
+
+``spec_binary_fallback_can_retry`` needs a different llama-server installed before an
+identical /load can repair a binary stand-down. The chat UI cannot see that, so it
+reloaded (and prompted to stop running chats) for every re-pick of a model whose drafter
+stood down, for a load the backend would have deduplicated.
+
+``_spec_fallback_binary_changed`` publishes it. It is answered ONLY for the two binary
+reasons: /api/inference/status is polled from first paint, and neither the binary lookup
+nor the capability probe has business running on every poll of a healthy runtime.
+
+Two more arms of ``_runtime_matches_intent`` reject an identical load while leaving
+``spec_fallback_reason`` null entirely, so a client reading only the reason adopts a
+degraded runtime and nothing ever retries it: a retryable DFlash sidecar fetch, and a
+capability probe that has started answering since a launch it degraded.
+``_spec_dflash_retry_pending`` and ``_spec_probe_retry_pending`` publish those.
+
+The ``drafter_not_found`` arm excludes the kinds whose absence is not transient, so
+``_spec_dspark_sidecar_absent`` publishes that too: retrying a DSpark drafter no repo but
+one publishes would relaunch an identical server forever.
+
+``_arch_gate_dropped_tensor_parallel`` is here for the same reason: the gate rewrites a
+tensor-parallel request to layer mode, so status reports the launched mode rather than
+the requested one, and the backend accepts the same request back against it.
+
+The helper is extracted from the route module's source rather than imported, so the test
+costs nothing and does not drag FastAPI in behind it.
+"""
+
+from __future__ import annotations
+
+import ast
+import sys
+import types as _types
+from pathlib import Path
+from typing import Optional
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+# conftest's autouse fixture imports core.inference.llama_cpp, which wants these.
+_loggers_stub = _types.ModuleType("loggers")
+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
+sys.modules.setdefault("loggers", _loggers_stub)
+
+_structlog_stub = _types.ModuleType("structlog")
+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")
+sys.modules.setdefault("structlog", _structlog_stub)
+
+_ROUTE = Path(__file__).resolve().parent.parent / "routes" / "inference.py"
+_NAME = "_spec_fallback_binary_changed"
+
+
+def _load_helper(name = _NAME):
+ tree = ast.parse(_ROUTE.read_text(encoding = "utf-8"))
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name == name:
+ namespace: dict = {"Optional": Optional}
+ exec(compile(ast.Module([node], []), str(_ROUTE), "exec"), namespace)
+ return namespace[name]
+ raise AssertionError(f"{name} is gone; the status no longer reports it")
+
+
+class _Backend:
+ def __init__(
+ self,
+ reason,
+ changed = False,
+ raises = False,
+ ):
+ self.spec_fallback_reason = reason
+ self._changed = changed
+ self._raises = raises
+ self.calls = 0
+
+ def spec_binary_fallback_can_retry(self):
+ self.calls += 1
+ if self._raises:
+ raise RuntimeError("binary lookup failed")
+ return self._changed
+
+
+def test_answers_only_for_the_two_binary_reasons():
+ helper = _load_helper()
+ for reason in (
+ None,
+ "drafter_not_found",
+ "drafter_no_vram",
+ "runtime_error",
+ "mla_mtp_disabled",
+ ):
+ backend = _Backend(reason)
+ assert helper(backend) is None
+ # The point of the gate: no binary lookup on a poll that cannot need one.
+ assert backend.calls == 0
+
+
+def test_reports_the_whole_retry_predicate():
+ # The predicate, not just its revision half: binary_no_mtp also asks whether the
+ # replacement advertises what the drafter kind needs, and a replacement that still
+ # lacks it never repairs, so a half answer would prompt on every later re-pick.
+ helper = _load_helper()
+ for reason in ("binary_no_mtp", "binary_outdated"):
+ assert helper(_Backend(reason, changed = False)) is False
+ assert helper(_Backend(reason, changed = True)) is True
+
+
+def test_an_unreadable_binary_is_unknown_not_false():
+ # False would tell the client the drafter cannot be repaired and suppress the reload
+ # an update was meant to enable; None leaves it with the coarser answer.
+ helper = _load_helper()
+ assert helper(_Backend("binary_no_mtp", raises = True)) is None
+
+
+class _SpecBackend:
+ """The three attributes the other two helpers read."""
+
+ def __init__(
+ self,
+ *,
+ dflash = False,
+ inconclusive = False,
+ probe = None,
+ raises = False,
+ ):
+ self._dflash_retry_needed = dflash
+ self._capability_probe_inconclusive = inconclusive
+ self._is_diffusion = False
+ self._probe = probe
+ self._raises = raises
+ self.probes = 0
+
+ def probe_server_capabilities(self):
+ self.probes += 1
+ if self._raises:
+ raise RuntimeError("probe failed")
+ return {"mtp_probe_inconclusive": self._probe}
+
+
+def test_the_probe_arm_only_probes_once_a_launch_was_degraded():
+ helper = _load_helper("_spec_probe_retry_pending")
+ settled = _SpecBackend(inconclusive = False)
+ assert helper(settled) is False
+ # The status is polled from first paint; a healthy runtime must not pay for this.
+ assert settled.probes == 0
+ # Still inconclusive: nothing has changed, so an identical load would dedupe.
+ assert helper(_SpecBackend(inconclusive = True, probe = True)) is False
+ # Answering now: the degraded runtime is re-derived once.
+ assert helper(_SpecBackend(inconclusive = True, probe = False)) is True
+
+
+def test_the_probe_arm_skips_diffusion_and_survives_a_failed_probe():
+ helper = _load_helper("_spec_probe_retry_pending")
+ diffusion = _SpecBackend(inconclusive = True, probe = False)
+ diffusion._is_diffusion = True
+ assert helper(diffusion) is False
+ assert helper(_SpecBackend(inconclusive = True, raises = True)) is None
+
+
+def test_the_dflash_arm_reports_the_retry_flag():
+ helper = _load_helper("_spec_dflash_retry_pending")
+ assert helper(_SpecBackend(dflash = True)) is True
+ assert helper(_SpecBackend(dflash = False)) is False
+
+
+def test_a_backend_without_the_dflash_flag_is_unknown():
+ helper = _load_helper("_spec_dflash_retry_pending")
+
+ class _Bare:
+ # Attribute access raises rather than returning a default, so the helper's
+ # try/except is what keeps the status route answering at all.
+ def __getattr__(self, name):
+ raise AttributeError(name)
+
+ assert helper(_Bare()) is None
+
+
+def test_the_dspark_arm_reports_permanent_absence():
+ helper = _load_helper("_spec_dspark_sidecar_absent")
+
+ class _Dspark:
+ def __init__(self, absent):
+ self._dspark_sidecar_absent = absent
+
+ assert helper(_Dspark(True)) is True
+ assert helper(_Dspark(False)) is False
+
+ class _Bare:
+ def __getattr__(self, name):
+ raise AttributeError(name)
+
+ assert helper(_Bare()) is None
+
+
+def test_the_arch_gate_drop_is_reported():
+ helper = _load_helper("_arch_gate_dropped_tensor_parallel")
+
+ class _Gated:
+ def __init__(self, dropped):
+ self._arch_gate_dropped_tensor_parallel = dropped
+
+ assert helper(_Gated(True)) is True
+ assert helper(_Gated(False)) is False
+
+ class _Bare:
+ def __getattr__(self, name):
+ raise AttributeError(name)
+
+ assert helper(_Bare()) is None
+
+
+def test_the_paravirtual_pin_follows_the_detector(monkeypatch):
+ # The helper reads the detector rather than deciding anything itself, so drive the
+ # detector. It is lru_cached, which is what keeps this free on the status poll.
+ helper = _load_helper("_gpu_placement_paravirtual")
+ from core.inference import llama_cpp
+
+ monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: True)
+ assert helper() is True
+ monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
+ assert helper() is False
+
+
+def test_a_detector_that_raises_is_unknown_not_false(monkeypatch):
+ # False would tell the client placement is comparable on a host where it is not,
+ # which is the direction that adopts a runtime the user did not ask for.
+ helper = _load_helper("_gpu_placement_paravirtual")
+ from core.inference import llama_cpp
+
+ def _boom():
+ raise RuntimeError("probe failed")
+
+ monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", _boom)
+ assert helper() is None
+
+
+def test_a_pending_audio_probe_is_reported():
+ # _reuse_loaded_gguf reads _audio_probed with a True default, and this mirrors it: a
+ # backend that never tracked the probe is not one with an outstanding probe.
+ helper = _load_helper("_audio_probe_pending")
+
+ class _Probed:
+ def __init__(self, probed):
+ self._audio_probed = probed
+
+ assert helper(_Probed(False)) is True
+ assert helper(_Probed(True)) is False
+
+ class _Bare:
+ pass
+
+ assert helper(_Bare()) is False
+
+
+def test_the_diffusion_split_support_is_reported_for_diffusion_only():
+ # Off a diffusion runner there is no split to apply, and answering False there would
+ # tell a client the recheck does not apply when the question never arose.
+ helper = _load_helper("_diffusion_split_supported")
+
+ class _Runner:
+ def __init__(
+ self,
+ diffusion,
+ supported = True,
+ raises = False,
+ ):
+ self._is_diffusion = diffusion
+ self._supported = supported
+ self._raises = raises
+ self.calls = 0
+
+ def diffusion_split_supported(self):
+ self.calls += 1
+ if self._raises:
+ raise RuntimeError("no shim")
+ return self._supported
+
+ chat = _Runner(False)
+ assert helper(chat) is None
+ assert chat.calls == 0
+ assert helper(_Runner(True, supported = True)) is True
+ assert helper(_Runner(True, supported = False)) is False
+ assert helper(_Runner(True, raises = True)) is None
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 024828f95f8..4b5476a724f 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -6,6 +6,14 @@ import { createElement, useCallback, useEffect, useRef, useState } from "react";
import { toast } from "@/lib/toast";
import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
import { confirmRemoteCodeIfNeeded } from "@/features/security";
+import { defaultInferenceParams } from "../presets/preset-policy";
+import {
+ type ReloadHint,
+ serverWideReloadRequired,
+} from "../lib/server-wide-reload";
+import { isSettingsRouteAbsent } from "@/features/settings/api/settings-route-absent";
+import { loadModelMemorySettings } from "@/features/settings/api/model-memory";
+import { loadVramBudgetSettings } from "@/features/settings/api/vram-budget";
import {
confirmTransformersUpgradeIfNeeded,
useTransformersUpgradeDialogStore,
@@ -43,6 +51,7 @@ import {
isLocalModelPath,
loadedGpuMemoryFields,
persistGpuMemoryModeOnLoad,
+ readPersistedGpuMemoryMode,
readPersistedSpeculativeType,
reconcilePersistedGpuIds,
resolveToolsEnabledOnLoad,
@@ -58,6 +67,11 @@ import {
normalizeSpeculativeType,
resolveInferenceCheckpointId,
} from "../lib/apply-inference-status-to-store";
+import {
+ residentRuntimeMatchesConfig,
+ residentSpeculativeNeedsRepair,
+} from "../lib/resident-config-match";
+import { residentModelMatchesPick } from "../lib/resident-model-match";
import {
mergeBackendRecommendedInference,
resolveFitMaxSeqLength,
@@ -67,14 +81,23 @@ import {
import { recordLastLocalModelLoad } from "../utils/last-local-model-load";
import { refreshContextUsage } from "../utils/refresh-context-usage";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
-import { type CpuFallbackReason, isMultimodalResponse } from "../types/api";
+import {
+ type CpuFallbackReason,
+ type InferenceStatusResponse,
+ isMultimodalResponse,
+} from "../types/api";
import { isExternalModelId } from "../external-providers";
import {
+ DEFAULT_PER_MODEL_CONFIG,
applyPerModelConfigToRuntime,
+ currentRuntimePerModelConfig,
normalizeMaxSeqLength,
type PerModelConfig,
} from "@/features/model-picker";
-import { invalidateLlamaFlagCatalog } from "@/features/model-picker/api/llama-flags";
+import {
+ invalidateLlamaFlagCatalog,
+ loadManagedLlamaFlags,
+} from "@/features/model-picker/api/llama-flags";
import type {
ChatLoraSummary,
ChatModelSummary,
@@ -112,6 +135,43 @@ export type SelectedModelInput = {
// Approved fingerprints by checkpoint, so a rollback after a failed switch can resend
// the pinned approval the worker requires instead of being blocked.
+/** An absent route is not a failed read: only the second one withholds an answer. */
+async function readReloadHint(
+ read: () => Promise<{ reloadRequired: boolean } | null>,
+): Promise<ReloadHint> {
+ try {
+ return (await read()) ?? "unsupported";
+ } catch (error) {
+ return isSettingsRouteAbsent(error) ? "unsupported" : "unknown";
+ }
+}
+
+/** The two settings reads `serverWideReloadRequired` judges, fetched together. */
+async function readServerWideReloadHints(): Promise<boolean> {
+ const [modelMemory, vramBudget] = await Promise.all([
+ // Forced, like the budget below: a read that started before a save answers about
+ // the policy it replaced, and a false from that would suppress the very reload the
+ // save was made for.
+ readReloadHint(() => loadModelMemorySettings({ force: true })),
+ // rethrow, or a failed read is indistinguishable from an absent route: this reader
+ // answers null for both, which every other caller is right to treat alike.
+ readReloadHint(() =>
+ loadVramBudgetSettings({ force: true, rethrow: true }),
+ ),
+ ]);
+ return serverWideReloadRequired({ modelMemory, vramBudget });
+}
+
+/** Placement is a set: the backend narrows and reorders it at fit time. */
+function sameGpuSelection(
+ left: readonly number[] | null | undefined,
+ right: readonly number[] | null | undefined,
+): boolean {
+ const a = [...(left ?? [])].sort((x, y) => x - y);
+ const b = [...(right ?? [])].sort((x, y) => x - y);
+ return a.length === b.length && a.every((id, index) => id === b[index]);
+}
+
const approvedRemoteCodeFingerprints = new Map<string, string>();
function rememberApprovedRemoteCode(
checkpoint: string,
@@ -654,49 +714,204 @@ export function useChatModelRuntime() {
};
if (bailIfLoadInFlight()) return;
- // Picking an external provider leaves the local model resident and stops the status poll
- // mirroring it, so params.checkpoint cannot tell whether this pick is that same model.
- // Ask the backend before prompting: /load answers already_loaded ahead of its cancel
- // hook, so the dialog would promise to stop chats this pick never interrupts. A staged
- // config always carries forceReload, so Apply still reloads and prompts.
+ // Ask the backend, not params.checkpoint: an external pick leaves the local model
+ // resident, and a pinned cached row loads under a name its picker row never shows.
+ // A staged config always carries forceReload, so Apply still reloads and prompts.
const selectedCheckpoint =
useChatRuntimeStore.getState().params.checkpoint;
- if (!forceReload && isExternalModelId(selectedCheckpoint)) {
+ const pendingConfig =
+ typeof selection !== "string" ? selection.config : undefined;
+ // nativePathToken is excluded: a leased file is named by a label two files can share,
+ // and only a completed load writes the lease, so adopting would keep a stale token.
+ if (!forceReload && !nativePathToken) {
const residentStatus = await getInferenceStatus().catch(() => null);
+ // Warm before reconciling the remembered GPU pick below: load-on-selection can run
+ // before any GPU hook mounted, and a cold cache passes the pick through unvalidated
+ // while performLoad, which warms it first, would have dropped it.
+ if (residentStatus && pendingConfig?.selectedGpuIds !== undefined) {
+ await ensureGpuDeviceCache().catch(() => {});
+ }
+ // What /load would carry for a pick with no saved config, which is not always the
+ // live runtime: performLoad treats a different checkpoint or variant as a model
+ // switch and clears the per-model fields first (resetsPerModelSettings), so on that
+ // door the request is the defaults, and comparing the outgoing model's settings
+ // would both prompt for a load that dedupes and adopt one that does not.
+ // gpuMemoryMode is standing and kvCacheDtype and tensorParallel are not reset, so
+ // those three still come from the store.
+ const live = useChatRuntimeStore.getState();
+ const resetsPerModelSettings = Boolean(
+ live.params.checkpoint &&
+ (live.params.checkpoint !== modelId ||
+ (live.activeGgufVariant ?? null) !== (ggufVariant ?? null)) &&
+ !keepSpeculative,
+ );
+ const comparedConfig =
+ pendingConfig ??
+ (resetsPerModelSettings
+ ? {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ kvCacheDtype: live.kvCacheDtype ?? null,
+ tensorParallel: live.tensorParallel ?? false,
+ gpuMemoryMode: live.gpuMemoryMode,
+ }
+ : currentRuntimePerModelConfig());
+ // The slot count an unset --parallel resolves to. Session-cached, and 0 is the
+ // catalogue's own "unknown", which the comparison reads as a reload.
+ const managedFlags = residentStatus
+ ? await loadManagedLlamaFlags().catch(() => null)
+ : null;
+ // Hoisted so it can run twice: everything above was awaited, and in that window
+ // another tab can swap the resident model, which this one is never told about
+ // (the lifecycle events are dispatched on its own window).
+ const adoptable = (status: InferenceStatusResponse) =>
+ residentModelMatchesPick(status, {
+ id: modelId,
+ loadPath,
+ ggufVariant,
+ }) &&
+ // _reuse_loaded_gguf refuses its own already-loaded answer while the audio probe
+ // is outstanding, so load_model reaches its fast path and re-probes there.
+ // Nothing else does, so skipping /load would leave the model's audio
+ // capabilities undetected for as long as the server runs.
+ status.audio_probe_pending !== true &&
+ // A repairable speculative fallback is the one case where an identical request is
+ // not a no-op: _runtime_matches_intent deliberately answers False for it so the
+ // next load retries the drafter. Short-circuiting would suppress that and strand
+ // the user with speculation off, so let /load through and let the backend decide.
+ !residentSpeculativeNeedsRepair(
+ status,
+ normalizeSpeculativeType(pendingConfig?.speculativeType) ??
+ readPersistedSpeculativeType(),
+ // The route derives gguf_path from the identifier alone, and the
+ // drafter_not_found retry is guarded on its absence.
+ (loadPath ?? modelId).toLowerCase().endsWith(".gguf"),
+ ) &&
+ // The id names the weights, not how the server was invoked. A remembered context
+ // length, drafter, placement or extra arg the resident load does not run is a real
+ // reload, and skipping it would drop the setting with nothing on screen to say so.
+ // Not `pendingConfig`: with no saved record the caller has already run
+ // applyModelLoadConfigToRuntime(null), which resets the store to
+ // DEFAULT_PER_MODEL_CONFIG, and performLoad reads the store for every field the
+ // config does not carry. The live store is therefore what /load would send, on
+ // both doors: reset to defaults after a hub or handoff pick, and still the
+ // resident values where nothing reset it.
+ residentRuntimeMatchesConfig(status, comparedConfig, {
+ // What the applier fills an unset field with, so the comparison is against
+ // what /load would send rather than against silence.
+ speculativeType: readPersistedSpeculativeType(),
+ gpuMemoryMode: readPersistedGpuMemoryMode(),
+ gpuLayers: GPU_LAYERS_AUTO,
+ nCpuMoe: 0,
+ // The n_ctx /load would send. Built from the live store, as performLoad
+ // builds it, so an unset length resolves the same way on both sides.
+ resolveContextLength: (customContextLength) => {
+ const live = useChatRuntimeStore.getState();
+ return resolveLoadMaxSeqLength({
+ modelId,
+ ggufVariant,
+ // Identity matched above, so the resident model is this pick.
+ isGguf: status.is_gguf,
+ customContextLength,
+ ggufContextLength: live.ggufContextLength,
+ currentCheckpoint: live.params.checkpoint,
+ activeGgufVariant: live.activeGgufVariant,
+ maxSeqLength: live.params.maxSeqLength,
+ presetSource: live.activePresetSource,
+ });
+ },
+ parallelSlots: managedFlags?.defaultParallelSlots || null,
+ // Never a config field, so the store is the only place it can come from,
+ // and the reset clears it before the load reads it.
+ splitRatio: resetsPerModelSettings
+ ? null
+ : useChatRuntimeStore.getState().splitRatio,
+ // What /load sends: a pick saved in another index namespace, or naming GPUs
+ // that are gone, is reconciled to Automatic before it leaves.
+ reconcileGpuIds: (ids, savedIndexKind) =>
+ reconcilePersistedGpuIds(
+ ids,
+ savedIndexKind,
+ status.is_diffusion ?? false,
+ ),
+ normalizeSpeculative: normalizeSpeculativeType,
+ });
if (
residentStatus &&
- resolveInferenceCheckpointId(residentStatus) === modelId &&
- (residentStatus.gguf_variant ?? null) === (ggufVariant ?? null)
+ adoptable(residentStatus) &&
+ // Both are server-wide, so a save leaves the pick and its config identical while
+ // adopt_load_intent_if_matched forces a reload anyway. Without them a policy or
+ // budget change made between two picks of one model would never reach the child.
+ !(await readServerWideReloadHints())
) {
- // Same window as the confirm below: a rival load may have started during that GET,
- // and it owns the resident model now.
- if (bailIfLoadInFlight()) return;
- // Roll back the config pre-applied for the load that is not happening BEFORE hydrating,
- // so the resident model's status wins over the staged snapshot.
- if (typeof selection !== "string" && selection.previousConfig) {
- applyPerModelConfigToRuntime(selection.previousConfig);
- }
- const previousGgufVariant =
- useChatRuntimeStore.getState().activeGgufVariant;
- // The poll skips its own clearing while an external pick is active, so a pin taken
- // for an earlier resident can survive; Apply would then reload that old model.
- if (useChatRuntimeStore.getState().activeLoadId !== modelId) {
- useChatRuntimeStore.setState({ activeLoadId: null });
+ // Read again, and judge again. A status fetched before those awaits describes the
+ // model that was resident then, and adopting it would leave the picker naming
+ // this model while prompts went to the one now loaded. A read that fails, or a
+ // verdict that no longer holds, falls through to /load, where a real
+ // disagreement belongs.
+ const confirmedStatus = await getInferenceStatus().catch(() => null);
+ if (confirmedStatus && adoptable(confirmedStatus)) {
+ // Same window as the confirm below: a rival load may have started during that GET,
+ // and it owns the resident model now.
+ if (bailIfLoadInFlight()) return;
+ // Roll back the config pre-applied for the load that is not happening, before
+ // hydrating, so the resident status wins over the staged snapshot. The helper form
+ // carries the loaded diffusion flag a resident image model needs.
+ restorePreviousConfig();
+ // ...except for maxSeqLength, which the rollback has the last word on: it is a
+ // client-side generation cap, no status field echoes it, and applyActiveModelStatus
+ // below therefore cannot correct it. Leaving it rolled back would hand this model
+ // the OUTGOING one's cap, which is visible in truncation but nowhere on screen.
+ // An absent cap is not silence either: applyPerModelConfigToRuntime resolves it to
+ // defaultInferenceParams.maxSeqLength, so leaving it unset kept the outgoing cap.
+ const pickedMaxSeqLength =
+ normalizeMaxSeqLength(pendingConfig?.maxSeqLength) ??
+ defaultInferenceParams.maxSeqLength;
+ const restored = useChatRuntimeStore.getState();
+ if (restored.params.maxSeqLength !== pickedMaxSeqLength) {
+ restored.setParams({
+ ...restored.params,
+ maxSeqLength: pickedMaxSeqLength,
+ });
+ }
+ const previousGgufVariant =
+ useChatRuntimeStore.getState().activeGgufVariant;
+ // Adopt this pick's own pin, by the rule a completed load writes it: the poll skips
+ // its clearing while an external pick is active, so a pin taken for an earlier
+ // resident would survive and Apply would reload that old model.
+ useChatRuntimeStore.setState({
+ activeLoadId: loadPath === modelId ? null : loadPath,
+ });
+ useChatRuntimeStore
+ .getState()
+ .setCheckpoint(modelId, confirmedStatus.gguf_variant);
+ applyActiveModelStatusToStore(confirmedStatus, {
+ previousCheckpoint: selectedCheckpoint,
+ previousGgufVariant,
+ });
+ syncModelCapabilities(modelId, confirmedStatus);
+ // The pick's own GPU selection, which the hydration above would otherwise
+ // widen back. adopt_load_intent_if_matched records the incoming pool when it
+ // adopts on the fitted subset (_record_matching_gpu_request), and skipping
+ // /load skips that, so the status still names the GPUs the user removed.
+ if (pendingConfig?.selectedGpuIds !== undefined) {
+ const picked = reconcilePersistedGpuIds(
+ pendingConfig.selectedGpuIds,
+ pendingConfig.selectedGpuIndexKind,
+ confirmedStatus.is_diffusion ?? false,
+ );
+ const hydrated = useChatRuntimeStore.getState();
+ if (!sameGpuSelection(hydrated.selectedGpuIds, picked)) {
+ useChatRuntimeStore.setState({
+ selectedGpuIds: picked,
+ loadedGpuIds: picked,
+ });
+ }
+ }
+ // setCheckpoint above blanked the bar, this path returns before the post-load recount,
+ // and a mounted thread does not rerun its history loader, so the bar would stay empty.
+ void refreshContextUsage({ afterModelLoad: true });
+ return;
}
- useChatRuntimeStore
- .getState()
- .setCheckpoint(modelId, residentStatus.gguf_variant);
- applyActiveModelStatusToStore(residentStatus, {
- previousCheckpoint: selectedCheckpoint,
- previousGgufVariant,
- // Id and variant matched above: same model, only the tab moved.
- readoptingSameModel: true,
- });
- syncModelCapabilities(modelId, residentStatus);
- // setCheckpoint above blanked the bar, this path returns before the post-load recount,
- // and a mounted thread does not rerun its history loader, so the bar would stay empty.
- void refreshContextUsage({ afterModelLoad: true });
- return;
}
}
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index 575f470126b..014d02f2932 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -130,9 +130,6 @@ export type ApplyInferenceStatusOptions = {
* status -- without it a variant-only switch underneath the tab reads as
* steady state and the hydration reseed keeps the old quant's baselines. */
previousGgufVariant?: string | null;
- /** The caller verified the status is the model this tab just picked, so the
- * slot control it holds belongs to that model and must survive. */
- readoptingSameModel?: boolean;
};
/** Mirror refresh() hydration so adopted CLI models get reasoning/tools flags. */
@@ -208,11 +205,11 @@ export function applyActiveModelStatusToStore(
// While a load is in flight, performLoad owns the load params. Seeding them
// from a stale poll here would clobber the values the load dialog just set.
const seedLoadParams = !prevState.modelLoading;
- // A model/variant change underneath this tab, as opposed to re-adopting the
- // model the tab just picked, where hydratingExistingModel fires on the stale
- // checkpoint. The echo cannot stand in: a new model can report the old count.
- const slotsModelChanged =
- hydratingExistingModel && !options.readoptingSameModel;
+ // A model/variant change underneath this tab. The controls in the store belong
+ // to the model that just left, so they are reseeded here the way every other
+ // load param at this site already is: the echo cannot stand in, since a new
+ // model can report the old count.
+ const slotsModelChanged = hydratingExistingModel;
// This model's remembered override, read only on a fresh store or a model
// change, so a steady poll cannot re-pin a control the user just blanked.
// Through the resident resolver, not the raw id: an API-driven load reports the
diff --git a/studio/frontend/src/features/chat/lib/llama-extra-args-normalize.ts b/studio/frontend/src/features/chat/lib/llama-extra-args-normalize.ts
new file mode 100644
index 00000000000..5bebbcbaae9
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/llama-extra-args-normalize.ts
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The pass-through arguments `/load` resolves before its already-loaded comparator runs.
+ *
+ * Two of them change what the request means rather than adding to it, so a comparison
+ * against the resident runtime has to resolve them the same way or it judges a request the
+ * server never received. Mirrors `parse_split_mode_override` / `resolve_tensor_parallel`
+ * and `parse_gpu_layers_override` in `core/inference/llama_server_args.py`, and the manual
+ * offload strip the route applies in `routes/inference.py` before comparing.
+ *
+ * A malformed list answers null rather than throwing, unlike the backend's parser: this
+ * runs while deciding whether to skip a load, and the load itself is where a bad argument
+ * belongs.
+ */
+
+const SPLIT_MODE_FLAGS = new Set(["-sm", "--split-mode"]);
+const GPU_LAYER_FLAGS = new Set(["-ngl", "--gpu-layers", "--n-gpu-layers"]);
+/** `_LAYER_OFFLOAD_FLAGS | _MOE_OFFLOAD_FLAGS`, which manual mode owns and strips. */
+const OFFLOAD_SHADOWING_FLAGS = new Set([
+ ...GPU_LAYER_FLAGS,
+ "-fit",
+ "--fit",
+ "-ncmoe",
+ "--n-cpu-moe",
+ "-cmoe",
+ "--cpu-moe",
+]);
+
+/**
+ * `_flag_name`: the flag a token names, or null when it is a value.
+ *
+ * Shorts always start with a letter, so `-1` and `-0.5` are values, which is what lets
+ * `--n-gpu-layers -1` parse at all. Long options fold underscores the way llama.cpp does.
+ * The backend's attached `-np8` folding is left out: nothing here reads `-np`.
+ */
+function flagName(token: string): string | null {
+ const trimmed = token.trim();
+ if (!trimmed.startsWith("-") || trimmed === "-" || trimmed === "--") {
+ return null;
+ }
+ const second = trimmed[1];
+ if (second !== undefined && (/[0-9]/.test(second) || second === ".")) {
+ return null;
+ }
+ const name = trimmed.split("=", 1)[0];
+ return name.startsWith("--") ? name.replaceAll("_", "-") : name;
+}
+
+/** `_last_flag_value`: the last-wins value among *flags*, in either form. */
+function lastFlagValue(
+ args: readonly string[] | null | undefined,
+ flags: ReadonlySet<string>,
+): string | null {
+ let value: string | null = null;
+ for (let i = 0; i < (args?.length ?? 0); i += 1) {
+ const token = String(args?.[i]);
+ const flag = flagName(token);
+ if (flag === null || !flags.has(flag)) {
+ continue;
+ }
+ if (token.includes("=")) {
+ value = token.slice(token.indexOf("=") + 1);
+ continue;
+ }
+ const next = args?.[i + 1];
+ // A flag with no value is malformed; the load rejects it, and until then it says
+ // nothing about what was requested.
+ if (next === undefined || flagName(String(next)) !== null) {
+ return null;
+ }
+ value = String(next);
+ i += 1;
+ }
+ return value;
+}
+
+/**
+ * `resolve_tensor_parallel`: an explicit `--split-mode` in extras last-wins over the
+ * toggle, and tensor parallelism is on only when that mode is `tensor`.
+ */
+export function resolveTensorParallel(
+ extraArgs: readonly string[] | null | undefined,
+ tensorParallel: boolean,
+): boolean {
+ const override = lastFlagValue(extraArgs, SPLIT_MODE_FLAGS);
+ return override === null
+ ? tensorParallel
+ : override.trim().toLowerCase() === "tensor";
+}
+
+/**
+ * `parse_gpu_layers_override`, in the three states its caller has to tell apart.
+ *
+ * The backend raises on a malformed value, so the load fails and says so. A comparison
+ * that folded that into "no override" would strip the offending token, find the rest
+ * agreeable and adopt, and the user's saved setting would go missing in silence instead.
+ */
+export type GpuLayersOverride =
+ | { kind: "absent" }
+ | { kind: "value"; layers: number }
+ | { kind: "invalid" };
+
+export function parseGpuLayersOverride(
+ extraArgs: readonly string[] | null | undefined,
+): GpuLayersOverride {
+ const raw = lastFlagValue(extraArgs, GPU_LAYER_FLAGS);
+ if (raw === null) {
+ return { kind: "absent" };
+ }
+ const value = Number.parseInt(raw, 10);
+ return Number.isInteger(value) && value >= -1 && String(value) === raw.trim()
+ ? { kind: "value", layers: value }
+ : { kind: "invalid" };
+}
+
+/**
+ * The offload flags manual mode owns, dropped as the route drops them before comparing.
+ * Only under manual: in auto an inherited `-ngl` is respected and reaches the child.
+ */
+export function stripManagedOffloadFlags(
+ extraArgs: readonly string[] | null | undefined,
+): string[] | null | undefined {
+ if (extraArgs == null) {
+ return extraArgs;
+ }
+ const kept: string[] = [];
+ for (let i = 0; i < extraArgs.length; i += 1) {
+ const token = String(extraArgs[i]);
+ const flag = flagName(token);
+ if (flag === null || !OFFLOAD_SHADOWING_FLAGS.has(flag)) {
+ kept.push(token);
+ continue;
+ }
+ // Its value goes with it, unless the flag carried one itself.
+ if (!token.includes("=")) {
+ const next = extraArgs[i + 1];
+ if (next !== undefined && flagName(String(next)) === null) {
+ i += 1;
+ }
+ }
+ }
+ return kept;
+}
diff --git a/studio/frontend/src/features/chat/lib/resident-config-match.ts b/studio/frontend/src/features/chat/lib/resident-config-match.ts
new file mode 100644
index 00000000000..8124b70da2d
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/resident-config-match.ts
@@ -0,0 +1,591 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { PerModelConfig } from "@/features/model-picker";
+
+import {
+ parseGpuLayersOverride,
+ resolveTensorParallel,
+ stripManagedOffloadFlags,
+} from "./llama-extra-args-normalize";
+import type { GpuIndexKind } from "@/hooks/gpu-selection";
+
+import type { InferenceStatusResponse } from "../types/api";
+
+/** The resident load's own invocation, as `/api/inference/status` echoes it. */
+type ResidentRuntime = Pick<
+ InferenceStatusResponse,
+ | "requested_context_length"
+ | "cache_type_kv"
+ | "mlx_kv_bits_requested"
+ | "speculative_type"
+ | "spec_draft_n_max"
+ | "requested_parallel_slots"
+ | "requested_n_batch"
+ | "requested_n_ubatch"
+ | "tensor_parallel"
+ | "chat_template_override"
+ | "requested_llama_extra_args"
+ | "gpu_memory_mode"
+ | "gpu_layers"
+ | "n_cpu_moe"
+ | "requested_gpu_ids"
+ | "gpu_ids"
+ | "is_gguf"
+ | "is_diffusion"
+ | "diffusion_requested_ngl"
+ | "diffusion_split_supported"
+ | "tensor_parallel_dropped_by_arch_gate"
+ | "gpu_placement_paravirtual"
+ | "tensor_split"
+ | "cpu_fallback_reason"
+>;
+
+function sameList(
+ left: readonly (string | number)[] | null | undefined,
+ right: readonly (string | number)[] | null | undefined,
+): boolean {
+ const a = left ?? [];
+ const b = right ?? [];
+ return a.length === b.length && a.every((item, index) => item === b[index]);
+}
+
+/** Placement is a set, not an order: the backend narrows and reorders it at fit time. */
+function sameGpuSet(
+ left: readonly number[] | null | undefined,
+ right: readonly number[] | null | undefined,
+): boolean {
+ const sort = (ids: readonly number[]) => [...ids].sort((a, b) => a - b);
+ return sameList(sort(left ?? []), sort(right ?? []));
+}
+
+/**
+ * What a config field resolves to when left unset.
+ *
+ * These four are not per-model, so omitting them is not silence: the applier fills them
+ * from a standing preference or a constant (`applyPerModelConfigToRuntime`), and the load
+ * sends that. The caller supplies them rather than this module reading the store, so the
+ * comparison stays a pure function of its inputs. Required, not optional: a resolver a
+ * caller can forget is one that silently keeps a runtime the user did not ask for.
+ */
+export type StandingConfigDefaults = {
+ /** `readPersistedSpeculativeType()`, already normalized. */
+ speculativeType: string | null;
+ /** `readPersistedGpuMemoryMode()`. */
+ gpuMemoryMode: "auto" | "manual";
+ /** `GPU_LAYERS_AUTO`. */
+ gpuLayers: number;
+ /** The applier's own constant, 0. */
+ nCpuMoe: number;
+ /**
+ * `reconcilePersistedGpuIds`, with the device cache already warm and the resident model's
+ * diffusion flag bound. `performLoad` sends the reconciled pick, not the saved one: a
+ * selection saved in another index namespace, or naming GPUs that are gone, becomes
+ * Automatic before `/load`. Comparing the raw ids would let a saved physical `[1]` adopt a
+ * server pinned to Vulkan device 1.
+ */
+ reconcileGpuIds: (
+ ids: number[] | null,
+ savedIndexKind: GpuIndexKind | null | undefined,
+ ) => number[] | null;
+ /**
+ * `resolveLoadMaxSeqLength` bound to the inputs `performLoad` gives it, so the comparison
+ * is against the n_ctx the load would send. An unset length is not simply 0: for a GGUF
+ * re-pick it resolves to the resident context, and only otherwise to 0, which is Auto.
+ */
+ resolveContextLength: (customContextLength: number | null) => number;
+ /**
+ * The slot count the server resolves an unset `--parallel` to, or null when it could not
+ * be read. `_resolve_parallel_slots` fills an omitted request from the server-wide
+ * default and stores THAT as `requested_parallel_slots`, so an unset ask is never null on
+ * the status side and comparing the two directly reloaded every default pick.
+ */
+ parallelSlots: number | null;
+ /**
+ * `splitRatio` as the store holds it now, which is what the load sends. Never a config
+ * field: `applyPerModelConfigToRuntime` clears it, so applying any remembered config
+ * asks for the default distribution rather than the resident custom one.
+ */
+ splitRatio: number[] | null;
+ /**
+ * `normalizeSpeculativeType`, passed rather than imported. It lives on the chat runtime
+ * store, which reaches React, and this module is deliberately a leaf so the node suite
+ * can drive it; copying its mapping here (comma-chained legacy echoes and all) would be
+ * a second copy free to drift from the one the load actually uses.
+ */
+ normalizeSpeculative: (value: string | null | undefined) => string | null;
+};
+
+/**
+ * One setting the resident load can disagree about. `pinned` is whether the config has an
+ * opinion at all, `agrees` whether the running server satisfies it. The pair survives for
+ * `llamaExtraArgs`, the only field the applier leaves unresolved.
+ */
+type SettingCheck = {
+ /** Placement, which the backend rewrites wholesale on a preserved CPU fallback. */
+ placement?: true;
+ /**
+ * One of the two fields `_mlx_runtime_settings_match` compares. The non-GGUF branch of
+ * /load checks identity and those, then answers already_loaded, so nothing else here
+ * may decide against a safetensors or MLX resident.
+ */
+ mlxComparable?: true;
+ /**
+ * Placement the diffusion branch of `_runtime_matches_intent` replaces wholesale with
+ * one `_diffusion_manual_ngl` comparison, rather than comparing field by field.
+ */
+ ggufPlacement?: true;
+ /** The diffusion branch's own comparison, which has no meaning off it. */
+ diffusionOnly?: true;
+ /**
+ * A chat-only invocation setting. `_runtime_matches_intent` guards these on
+ * `not self._is_diffusion`, and the status nulls the ones it publishes at all, so
+ * comparing them against a diffusion runtime rejects a load that would deduplicate.
+ */
+ chatOnly?: true;
+ pinned: (config: PerModelConfig) => boolean;
+ agrees: (
+ config: PerModelConfig,
+ status: ResidentRuntime,
+ standing: StandingConfigDefaults,
+ ) => boolean;
+};
+
+/**
+ * Fallback reasons the backend retries on an IDENTICAL next load, taken from the arms of
+ * `LlamaCppBackend._runtime_matches_intent` that return False to force the repair: a drafter
+ * fetch that can be attempted again, and the stand-down the UI asks the user to fix by
+ * updating llama.cpp. The rest are not here on purpose. "drafter_no_vram" and
+ * "mla_mtp_disabled" are Auto-mode policy, and "runtime_error" only reopens when the draft
+ * count changes, which the settings comparison already sees; treating them as repairable
+ * would prompt to stop running chats on every re-pick and repair nothing.
+ */
+const RETRYABLE_SPEC_FALLBACKS = new Set([
+ "drafter_not_found",
+ "binary_no_mtp",
+ "binary_outdated",
+]);
+
+/** The two of those the user is told to fix by updating llama.cpp. */
+const BINARY_SPEC_FALLBACKS = new Set(["binary_no_mtp", "binary_outdated"]);
+
+/** The modes the backend's retry arms are guarded on; anything else asked for no drafter. */
+const SPECULATIVE_MODES = new Set([
+ "auto",
+ "mtp",
+ "mtp+ngram",
+ "dspark",
+ "dflash",
+]);
+
+/**
+ * Whether the resident load's speculative decoding is degraded in a way the next identical
+ * `/load` would repair.
+ *
+ * This is the one place where sending a request the runtime already satisfies is not a
+ * no-op, so it is the one reason to decline the shortcut on settings that match. The
+ * decision stays coarser than the backend's: the status echoes the fallback reason but not
+ * `_dflash_retry_needed` or an inconclusive capability probe, so a load that would dedupe
+ * on the far side can still be sent. That costs one round trip through `already_loaded`,
+ * which returns before any teardown.
+ */
+export function residentSpeculativeNeedsRepair(
+ status: Pick<
+ InferenceStatusResponse,
+ | "spec_fallback_reason"
+ | "spec_fallback_binary_changed"
+ | "spec_probe_retry_pending"
+ | "spec_dflash_retry_pending"
+ | "spec_dspark_sidecar_absent"
+ | "spec_drafter_kind"
+ >,
+ resolvedSpeculativeType: string | null,
+ /**
+ * Whether the load carries a `gguf_path`, which the route sets from the identifier
+ * alone: `source.gguf_path if model_identifier.lower().endswith(".gguf") else None`.
+ */
+ sendsGgufPath = false,
+): boolean {
+ const mode = resolvedSpeculativeType ?? "auto";
+ // Two arms that record no fallback reason, so the reason check below cannot see them.
+ // The probe arm is not gated on a mode; the DFlash one is, as the backend gates it.
+ if (status.spec_probe_retry_pending === true) {
+ return true;
+ }
+ if (
+ status.spec_dflash_retry_pending === true &&
+ (mode === "auto" || mode === "dflash")
+ ) {
+ return true;
+ }
+ if (
+ !RETRYABLE_SPEC_FALLBACKS.has(status.spec_fallback_reason ?? "") ||
+ !SPECULATIVE_MODES.has(mode)
+ ) {
+ return false;
+ }
+ // The drafter_not_found arm reloads so the next Apply retries the fetch, but excludes
+ // the two kinds whose absence is not transient: DFlash asks through its retry flag
+ // above, and an absent DSpark sidecar is the permanent state of every repo but one, so
+ // retrying either would relaunch an identical server forever.
+ if (status.spec_fallback_reason === "drafter_not_found") {
+ // The arm is guarded on `intent.gguf_path is None`, so a standalone file never
+ // reaches it and an identical load dedupes rather than retrying the fetch.
+ if (sendsGgufPath) {
+ return false;
+ }
+ if (status.spec_drafter_kind === "dflash") {
+ return false;
+ }
+ if (
+ status.spec_drafter_kind === "dspark" &&
+ status.spec_dspark_sidecar_absent === true
+ ) {
+ return false;
+ }
+ }
+ // A binary stand-down repairs only once a different llama-server is installed, which is
+ // the necessary condition in spec_binary_fallback_can_retry. Without that the reload
+ // dedupes and the prompt was for nothing. Only an explicit false settles it: a backend
+ // too old to report it keeps the coarser answer rather than suppress a real repair, and
+ // the field says nothing about a stand-down that was never about the binary.
+ return !(
+ BINARY_SPEC_FALLBACKS.has(status.spec_fallback_reason ?? "") &&
+ status.spec_fallback_binary_changed === false
+ );
+}
+
+/** The mode the load sends, which is what the backend gates its placement arms on. */
+const requestedGpuMemoryMode = (
+ config: PerModelConfig,
+ standing: StandingConfigDefaults,
+): "auto" | "manual" => config.gpuMemoryMode ?? standing.gpuMemoryMode;
+
+const cleanTemplate = (value: string | null | undefined): string | null =>
+ value?.trim() ? value : null;
+
+/**
+ * Mirrors the fields `_runtime_matches_intent` reloads for, plus the MLX pair
+ * `_mlx_runtime_settings_match` compares.
+ *
+ * Nearly every check is unconditionally pinned. A config reaches here only after
+ * `applyModelLoadConfigToRuntime` wrote it over the runtime store (`chat-page.tsx:3242`,
+ * `hub-page.tsx:1329`), and that applier resolves each of these with `?? null`, so the
+ * snapshot `performLoad` takes reads null rather than inheriting the resident value: an
+ * unset field asks for the default, not for whatever is running. Only `llamaExtraArgs` is
+ * genuinely optional, being the one field with no `?? null` fallback.
+ */
+const SETTING_CHECKS: SettingCheck[] = [
+ {
+ // Resolved, not compared raw: an unset length is Auto, which the load sends as 0 for a
+ // cross-model GGUF pick and as the resident context when re-picking the same one.
+ // Reading null as "no opinion" against a status echoing either number was a reload.
+ pinned: () => true,
+ // A GGUF invocation field: a safetensors or MLX status never sets it, and the general
+ // non-GGUF rule below is what keeps this from reading that absence as 0.
+ agrees: (c, s, standing) =>
+ standing.resolveContextLength(c.customContextLength ?? null) ===
+ (s.requested_context_length ?? 0),
+ },
+ {
+ pinned: () => true,
+ agrees: (c, s) => (c.kvCacheDtype ?? null) === (s.cache_type_kv ?? null),
+ },
+ {
+ mlxComparable: true,
+ pinned: () => true,
+ agrees: (c, s) =>
+ (c.mlxKvBits ?? null) === (s.mlx_kv_bits_requested ?? null),
+ },
+ {
+ // Always pinned: an unset mode resolves to the standing preference, and the load sends
+ // it. Reading it as silence let a pick asking for "off" adopt a resident MTP runtime.
+ pinned: () => true,
+ agrees: (c, s, standing) =>
+ (standing.normalizeSpeculative(c.speculativeType) ??
+ standing.speculativeType) ===
+ (standing.normalizeSpeculative(s.speculative_type) ??
+ standing.speculativeType),
+ },
+ {
+ // Only when the pick names one, as _runtime_matches_intent is guarded on
+ // `intent.spec_draft_n_max is not None`: an unset limit asks for no change, so
+ // comparing null against the count the resident load was launched with was a reload.
+ pinned: (c) => c.specDraftNMax != null,
+ agrees: (c, s) => c.specDraftNMax === (s.spec_draft_n_max ?? null),
+ },
+ {
+ chatOnly: true,
+ // Unknown default: null against the status's resolved count is a reload, the safe
+ // direction. defaultParallelSlots is the EFFECTIVE count, so a build that clamps to one
+ // slot reloads rather than adopts, which is the same bias.
+ pinned: () => true,
+ agrees: (c, s, standing) =>
+ (c.nParallel ?? standing.parallelSlots) ===
+ (s.requested_parallel_slots ?? standing.parallelSlots),
+ },
+ {
+ chatOnly: true,
+ pinned: () => true,
+ agrees: (c, s) => (c.nBatch ?? null) === (s.requested_n_batch ?? null),
+ },
+ {
+ chatOnly: true,
+ pinned: () => true,
+ agrees: (c, s) => (c.nUbatch ?? null) === (s.requested_n_ubatch ?? null),
+ },
+ {
+ // Not nullable, so it always has an opinion; a status omitting it ran without.
+ pinned: () => true,
+ agrees: (c, s) =>
+ // The toggle after a pass-through --split-mode has last-won over it, which is what
+ // resolve_tensor_parallel hands the comparator.
+ resolveTensorParallel(c.llamaExtraArgs, c.tensorParallel) ===
+ (s.tensor_parallel ?? false) ||
+ // Rewritten away with the rest of the placement on a virtualised Metal device.
+ s.gpu_placement_paravirtual === true ||
+ // A split the architecture gate normalized away: that layer-mode runtime IS this
+ // request as the gate rewrote it, and the backend accepts it back unchanged. The
+ // resolved mode again, since a pass-through --split-mode is what was gated.
+ (resolveTensorParallel(c.llamaExtraArgs, c.tensorParallel) &&
+ s.tensor_parallel !== true &&
+ s.tensor_parallel_dropped_by_arch_gate === true),
+ },
+ {
+ // Blank-trimmed on both ends: the applier and the load both send "" as null.
+ mlxComparable: true,
+ pinned: () => true,
+ agrees: (c, s) =>
+ cleanTemplate(c.chatTemplateOverride) ===
+ cleanTemplate(s.chat_template_override),
+ },
+ {
+ // undefined: never read the stored value. null: the user cleared the box, which agrees
+ // only with a load invoked with no pass-through args.
+ chatOnly: true,
+ pinned: (c) => c.llamaExtraArgs !== undefined,
+ agrees: (c, s, standing) =>
+ sameList(
+ requestedGpuMemoryMode(c, standing) === "manual"
+ ? stripManagedOffloadFlags(c.llamaExtraArgs)
+ : c.llamaExtraArgs,
+ s.requested_llama_extra_args,
+ ),
+ },
+ {
+ // Standing preference, like the speculative mode above.
+ placement: true,
+ ggufPlacement: true,
+ pinned: () => true,
+ agrees: (c, s, standing) =>
+ (c.gpuMemoryMode ?? standing.gpuMemoryMode) ===
+ (s.gpu_memory_mode ?? standing.gpuMemoryMode),
+ },
+ {
+ // Resolves to GPU_LAYERS_AUTO rather than to a preference, but the load still sends it.
+ // Only under Manual, as _runtime_matches_intent compares it: under Auto the fitter
+ // chooses the offload, so the layer count the load carries decides nothing.
+ placement: true,
+ ggufPlacement: true,
+ pinned: () => true,
+ agrees: (c, s, standing) =>
+ requestedGpuMemoryMode(c, standing) !== "manual" ||
+ requestedGpuLayers(c, standing) === (s.gpu_layers ?? standing.gpuLayers),
+ },
+ {
+ // Manual with a non-negative pin, the same guard the backend uses. A config keeps a
+ // hidden nCpuMoe after the layer slider goes back to Auto, and llama.cpp records 0,
+ // so comparing it there rejected an otherwise identical runtime.
+ placement: true,
+ ggufPlacement: true,
+ pinned: () => true,
+ agrees: (c, s, standing) =>
+ requestedGpuMemoryMode(c, standing) !== "manual" ||
+ requestedGpuLayers(c, standing) < 0 ||
+ (c.nCpuMoe ?? standing.nCpuMoe) === (s.n_cpu_moe ?? standing.nCpuMoe),
+ },
+ {
+ // Absent resolves to a null selection in the applier, and a null selection is sent as
+ // Automatic, so this is pinned like the rest: an unset pick does not adopt a server
+ // that was placed on a chosen GPU. Reconciled first, since that is what /load sends.
+ placement: true,
+ pinned: () => true,
+ agrees: (c, s, standing) => {
+ const reconciled = standing.reconcileGpuIds(
+ c.selectedGpuIds ?? null,
+ c.selectedGpuIndexKind,
+ );
+ // The diffusion runner drives one device, so matches_gpu_ids reduces the request to
+ // its lowest id and the status reports only that. Comparing the configured set
+ // rejected a runtime the backend would have called identical.
+ const pick =
+ s.is_diffusion === true && reconciled?.length
+ ? [Math.min(...reconciled)]
+ : reconciled;
+ if (sameGpuSet(pick, s.requested_gpu_ids)) {
+ return true;
+ }
+ // Either pool, as matches_gpu_ids accepts either: fitting may narrow the request to
+ // the smallest subset that holds the model, and asking for that subset does not
+ // reload. Comparing only the raw request prompted for a load that dedupes. Guarded on
+ // a non-empty echo, since an absent one is no placement rather than Automatic, and
+ // reading it as Automatic would make an unpinned pick match every pinned server.
+ return Boolean(s.gpu_ids?.length) && sameGpuSet(pick, s.gpu_ids);
+ },
+ },
+ {
+ // The split is placement the config cannot carry: the applier clears splitRatio, so a
+ // remembered config asks for the default distribution while a resident manual load may
+ // be running a custom one. Omitting it kept that custom split with nothing saying so.
+ placement: true,
+ ggufPlacement: true,
+ pinned: () => true,
+ agrees: (_c, s, standing) => sameList(standing.splitRatio, s.tensor_split),
+ },
+ {
+ // A managed override the backend would reject outright. It raises there, so the load
+ // fails and says so; folding it into "no override" here would strip the token, find
+ // the rest agreeable and adopt, losing the saved setting in silence.
+ pinned: (c) => c.llamaExtraArgs !== undefined,
+ agrees: (c, _s, standing) =>
+ requestedGpuMemoryMode(c, standing) !== "manual" ||
+ parseGpuLayersOverride(c.llamaExtraArgs).kind !== "invalid",
+ },
+ {
+ // What the diffusion branch compares in place of the placement fields above:
+ // _diffusion_manual_ngl, the layer count only under Manual with a non-negative pin and
+ // the runner's own default otherwise. An older shim that dropped a manual NGL leaves
+ // the status reporting Auto while keeping the request here, so comparing the mode raw
+ // rejected a load that deduplicates.
+ diffusionOnly: true,
+ pinned: () => true,
+ agrees: (c, s, standing) => {
+ const ngl = diffusionManualNgl(c, standing);
+ if (ngl !== (s.diffusion_requested_ngl ?? null)) {
+ return false;
+ }
+ // The request is retained even when an older shim dropped the split, so once the
+ // installed shim gains --ngl support the same request has to go through and finally
+ // apply it. The backend rejects it for exactly that window.
+ return !(
+ ngl !== null &&
+ s.gpu_layers !== ngl &&
+ s.diffusion_split_supported === true
+ );
+ },
+ },
+];
+
+/**
+ * The layer count `/load` ends up with. Under manual a pass-through `-ngl` is copied into
+ * the first-class field before the comparator runs, so the raw toggle is not what was
+ * requested.
+ */
+function requestedGpuLayers(
+ config: PerModelConfig,
+ standing: StandingConfigDefaults,
+): number {
+ const override =
+ requestedGpuMemoryMode(config, standing) === "manual"
+ ? parseGpuLayersOverride(config.llamaExtraArgs)
+ : { kind: "absent" as const };
+ return override.kind === "value"
+ ? override.layers
+ : (config.gpuLayers ?? standing.gpuLayers);
+}
+
+/** `_diffusion_manual_ngl`: only an explicit manual count reaches the child. */
+function diffusionManualNgl(
+ config: PerModelConfig,
+ standing: StandingConfigDefaults,
+): number | null {
+ const layers = requestedGpuLayers(config, standing);
+ return requestedGpuMemoryMode(config, standing) === "manual" && layers >= 0
+ ? layers
+ : null;
+}
+
+/**
+ * Whether the backend would rewrite this request into the resident CPU fallback.
+ *
+ * `adopt_load_intent_if_matched` runs `_preserve_cpu_fallback_intent` first, so after a
+ * Vulkan startup crash an Auto request becomes the resident manual/zero-layer intent and
+ * dedupes. Comparing placement literally rejected it and raised the prompt this PR removes.
+ *
+ * Mirrors `_cpu_fallback_request_eligible`, minus its environment terms: the resident
+ * server already fell back under this same env, and a request carrying its own placement
+ * args is excluded here rather than guessed at.
+ */
+function cpuFallbackPlacementPreserved(
+ config: PerModelConfig,
+ status: ResidentRuntime,
+ standing: StandingConfigDefaults,
+): boolean {
+ if (status.cpu_fallback_reason !== "vulkan_startup_crash") {
+ return false;
+ }
+ const mode = config.gpuMemoryMode ?? standing.gpuMemoryMode;
+ const layers = config.gpuLayers ?? standing.gpuLayers;
+ return (
+ (mode === "auto" || (mode === "manual" && layers === 0)) &&
+ !standing.reconcileGpuIds(
+ config.selectedGpuIds ?? null,
+ config.selectedGpuIndexKind,
+ )?.length &&
+ !config.tensorParallel &&
+ !standing.splitRatio?.length &&
+ (config.nCpuMoe ?? standing.nCpuMoe) === 0 &&
+ !config.llamaExtraArgs?.length
+ );
+}
+
+/**
+ * Whether the resident load already runs the settings this pick would ask for.
+ *
+ * Identity is not the whole of a load: `LlamaCppBackend` reuses a running server only when
+ * the request also agrees on context, KV dtype, slots, batch sizes, placement, speculative
+ * mode, chat template and pass-through args. An unset field is still an opinion, since the
+ * applier resolves it before the load reads it: unset asks for the default, not for whatever
+ * is running. What keeps the common case working is the other door: a model the user never
+ * configured arrives with no config at all, and a model they did configure carries what
+ * `currentRuntimePerModelConfig` wrote from the load that made it resident.
+ *
+ * The bias is one-sided on purpose. "Differs" costs one reload, which is what happened
+ * before any of this existed; a wrong "matches" leaves the user on settings they did not
+ * ask for, with the panel rolled back to the resident model so nothing says so.
+ *
+ * `maxSeqLength` is not compared: a client-side generation cap no status echoes, and it
+ * never reaches llama-server's invocation.
+ */
+export function residentRuntimeMatchesConfig(
+ status: ResidentRuntime,
+ config: PerModelConfig | null | undefined,
+ standing: StandingConfigDefaults,
+): boolean {
+ // No config at all is not the same as a config that pins nothing: with none, the load
+ // path reads the live runtime, which was hydrated from the resident model, so there is
+ // nothing that could differ.
+ if (!config) {
+ return true;
+ }
+ const placementPreserved =
+ // A virtualised Metal device pins every GGUF request to the CPU before either
+ // comparator runs, so placement cannot tell two requests apart there at all.
+ status.gpu_placement_paravirtual === true ||
+ cpuFallbackPlacementPreserved(config, status, standing);
+ // The diffusion runner takes no --parallel, no batch sizes and no pass-through args, so
+ // the backend does not compare them and the status nulls what it publishes at all.
+ const diffusion = status.is_diffusion === true;
+ return SETTING_CHECKS.every(
+ (check) =>
+ // The non-GGUF branch of /load checks identity and the MLX pair, then answers
+ // already_loaded, so no llama.cpp invocation field may decide against one.
+ (status.is_gguf === false && !check.mlxComparable) ||
+ (diffusion && check.chatOnly) ||
+ (diffusion && check.ggufPlacement) ||
+ (!diffusion && check.diffusionOnly) ||
+ (check.placement && placementPreserved) ||
+ !check.pinned(config) ||
+ check.agrees(config, status, standing),
+ );
+}
diff --git a/studio/frontend/src/features/chat/lib/resident-model-match.ts b/studio/frontend/src/features/chat/lib/resident-model-match.ts
new file mode 100644
index 00000000000..fade1864800
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/resident-model-match.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// eslint-disable-next-line no-restricted-imports -- Avoid the hub barrel's React and download-manager exports.
+import {
+ ggufVariantsMatch,
+ isHfCacheSnapshotPath,
+ isStandaloneGgufPath,
+ modelIdsMatch,
+ residentModelIdMatches,
+} from "@/features/hub/lib/model-identity";
+
+/** The two names one pick answers to: its picker row's catalog id, and the `model_path`
+ * its load sends. They differ whenever a cached row pins a snapshot dir. */
+export type ModelPickNames = {
+ id: string;
+ loadPath?: string | null;
+ ggufVariant?: string | null;
+};
+
+/** The resident model as `/api/inference/status` reports it. */
+export type ResidentModelStatus = {
+ active_model?: string | null;
+ model_identifier?: string | null;
+ gguf_variant?: string | null;
+};
+
+/**
+ * Whether the resident model is the one this pick names.
+ *
+ * Each side holds two strings for one model and they need not be equal: a pinned cached row
+ * loads by snapshot path while its row keeps the repo id, and the status publishes the public
+ * id beside the raw one. Recognising that here skips a reload `/load` would have answered
+ * `already_loaded`, and the confirmation that goes with it.
+ */
+export function residentModelMatchesPick(
+ status: ResidentModelStatus,
+ pick: ModelPickNames,
+): boolean {
+ if (!status.active_model) {
+ return false;
+ }
+ // A standalone file has no quant to choose between, and its row carries no label
+ // (settingsGgufVariantForRow) while the backend derives one from the filename.
+ const picksItsOwnVariant = !(
+ !pick.ggufVariant && isStandaloneGgufPath(pick.loadPath ?? pick.id)
+ );
+ // a quant switch within one repo is a real reload
+ if (
+ picksItsOwnVariant &&
+ !ggufVariantsMatch(status.gguf_variant, pick.ggufVariant)
+ ) {
+ return false;
+ }
+ // Only the raw identifier says WHICH weights are resident, as matches_load_source does:
+ // every snapshot of a repo publishes the same public id.
+ if (status.model_identifier) {
+ return modelIdsMatch(status.model_identifier, pick.loadPath ?? pick.id);
+ }
+ // No raw identifier. The name this pick loads by still names one revision, so try it
+ // literally first: an older backend put the raw path in active_model.
+ const loadName = pick.loadPath ?? pick.id;
+ if (modelIdsMatch(status.active_model, loadName)) {
+ return true;
+ }
+ // What is left collapses onto a public id, which cannot tell one snapshot of a repo from
+ // another, so a pick pinned to one reloads rather than risk keeping the old weights.
+ if (isHfCacheSnapshotPath(loadName)) {
+ return false;
+ }
+ // a native lease withholds the raw path and reports its display label alone
+ return residentModelIdMatches(status.active_model, pick.id, pick.loadPath);
+}
diff --git a/studio/frontend/src/features/chat/lib/server-wide-reload.ts b/studio/frontend/src/features/chat/lib/server-wide-reload.ts
new file mode 100644
index 00000000000..c69836c0b05
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/server-wide-reload.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** One settings read, in the three states the shortcut has to tell apart. */
+export type ReloadHint =
+ | { reloadRequired: boolean }
+ /** The backend does not serve this route, so it has no such state to disagree about. */
+ | "unsupported"
+ /** The read could not be made. It says nothing, which is not the same as "no". */
+ | "unknown";
+
+function declines(hint: ReloadHint): boolean {
+ return hint === "unknown" || (hint !== "unsupported" && hint.reloadRequired);
+}
+
+/**
+ * Whether a server-wide setting changed since the resident child launched.
+ *
+ * `adopt_load_intent_if_matched` refuses to reuse a running server when the Model Memory
+ * policy no longer describes it, or when the VRAM budget moved. Neither is part of the load
+ * intent, so identity and per-model config both still match and the resident shortcut would
+ * skip a `/load` the backend was going to honour.
+ *
+ * An unknown answer declines. The two failures are not symmetric: one extra reload costs
+ * the prompt this PR removes, while adopting on a read that failed after the user changed
+ * a policy leaves the child on the old one with nothing on screen to say so. An absent
+ * route is not an unknown answer, and keeps the shortcut working on a backend too old to
+ * report either.
+ */
+export function serverWideReloadRequired(signals: {
+ modelMemory: ReloadHint;
+ vramBudget: ReloadHint;
+}): boolean {
+ return declines(signals.modelMemory) || declines(signals.vramBudget);
+}
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index f0444a50790..24bafe455b6 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -383,6 +383,22 @@ export interface InferenceStatusResponse {
*/
spec_drafter_kind?: string | null;
spec_fallback_reason?: string | null;
+ /** Only for a binary stand-down: whether a different llama-server is installed now. */
+ spec_fallback_binary_changed?: boolean | null;
+ /** The capability probe has started answering since a launch it degraded. */
+ spec_probe_retry_pending?: boolean | null;
+ /** A DFlash sidecar fetch failed retryably, which records no fallback reason. */
+ spec_dflash_retry_pending?: boolean | null;
+ /** The DSpark drafter is absent for good, not transiently unfetchable. */
+ spec_dspark_sidecar_absent?: boolean | null;
+ /** The architecture gate normalized a tensor-parallel request to layer mode. */
+ tensor_parallel_dropped_by_arch_gate?: boolean | null;
+ /** A virtualised Metal device: every GGUF request is rewritten to the CPU pin. */
+ gpu_placement_paravirtual?: boolean | null;
+ /** The post-launch audio probe did not finish; only a load retries it. */
+ audio_probe_pending?: boolean | null;
+ /** A diffusion launch right now would honour --ngl. */
+ diffusion_split_supported?: boolean | null;
}
export interface ApiMonitorEntry {
diff --git a/studio/frontend/src/features/hub/lib/model-identity.ts b/studio/frontend/src/features/hub/lib/model-identity.ts
index 01bdb8d578f..a84f623ae56 100644
--- a/studio/frontend/src/features/hub/lib/model-identity.ts
+++ b/studio/frontend/src/features/hub/lib/model-identity.ts
@@ -107,6 +107,16 @@ function hfCacheRepoId(path: string): string | null {
return null;
}
+/**
+* Whether *identifier* is an HF cache snapshot dir, so its public id names the repo rather
+* than the revision inside it. Mirrors ``hf_cache_repo_id`` in core/inference/model_ids.py.
+*/
+export function isHfCacheSnapshotPath(
+ identifier: string | null | undefined,
+): boolean {
+ return identifier != null && hfCacheRepoId(identifier) !== null;
+}
+
/**
* The clean id the backend reports for a model loaded by path. Mirrors ``public_model_id`` in
* core/inference/model_ids.py, which is what ``/api/inference/status`` puts in ``active_model``:
diff --git a/studio/frontend/src/features/model-picker/index.ts b/studio/frontend/src/features/model-picker/index.ts
index 4f1f771573b..4a2f90c14b8 100644
--- a/studio/frontend/src/features/model-picker/index.ts
+++ b/studio/frontend/src/features/model-picker/index.ts
@@ -44,6 +44,7 @@ export {
} from "./model-config/apply-per-model-config";
export {
DEFAULT_MAX_SEQ_LENGTH,
+ DEFAULT_PER_MODEL_CONFIG,
normalizeMaxSeqLength,
type PerModelConfig,
adoptLegacyConfigKey,
diff --git a/studio/frontend/src/features/settings/api/model-memory.ts b/studio/frontend/src/features/settings/api/model-memory.ts
index 8784cba88a8..c24fde9a092 100644
--- a/studio/frontend/src/features/settings/api/model-memory.ts
+++ b/studio/frontend/src/features/settings/api/model-memory.ts
@@ -3,6 +3,8 @@
import { authFetch } from "@/features/auth";
import { readFastApiError } from "@/lib/format-fastapi-error";
+
+import { SettingsRouteAbsentError } from "./settings-route-absent";
import { invalidateOpenAIAutoSwitchSettings } from "./openai-auto-switch";
const MODEL_MEMORY_EVENT = "unsloth-model-memory-change";
@@ -38,6 +40,9 @@ type ApiModelMemorySettings = {
};
let inFlightModelMemory: Promise<ModelMemorySettings> | null = null;
+// Bumped by every forced read, so a displaced one can tell it is no longer the current
+// answer. It still resolves for its own caller; it just stops speaking for everyone else.
+let modelMemoryGeneration = 0;
export function subscribeModelMemorySettings(
listener: (settings: ModelMemorySettings) => void,
@@ -73,6 +78,11 @@ function publishModelMemory(settings: ModelMemorySettings) {
async function fetchModelMemorySettings(): Promise<ModelMemorySettings> {
const res = await authFetch("/api/settings/model-memory");
+ if (res.status === 404) {
+ // Told apart from a failed read: a caller deciding whether it may skip a load has to
+ // treat "this backend has no such setting" and "could not ask" oppositely.
+ throw new SettingsRouteAbsentError("/api/settings/model-memory");
+ }
if (!res.ok) {
throw new Error(
await readFastApiError(res, "Failed to load model memory settings"),
@@ -85,12 +95,35 @@ async function fetchModelMemorySettings(): Promise<ModelMemorySettings> {
* Always refetches: `reloadRequired` and `memlockLimitBytes` describe the
* currently loaded process, so a cached copy goes stale as soon as a model is
* loaded or swapped. Concurrent calls still share one request.
+ *
+ * `force` drops that sharing, as the VRAM budget's reader does: a read that started
+ * before a save or a model transition answers about the state being replaced, and a
+ * caller deciding whether to reload for a policy change must not be handed it.
*/
-export async function loadModelMemorySettings() {
+export async function loadModelMemorySettings(
+ options: { force?: boolean } = {},
+) {
+ if (options.force) {
+ inFlightModelMemory = null;
+ modelMemoryGeneration += 1;
+ }
+ const generation = modelMemoryGeneration;
inFlightModelMemory ??= fetchModelMemorySettings()
- .then(publishModelMemory)
+ .then((settings) =>
+ // A displaced read describes the state its replacement was issued because of, so
+ // publishing it would repaint every subscriber with the answer that was already
+ // known to be stale, and in whichever order the two land.
+ generation === modelMemoryGeneration
+ ? publishModelMemory(settings)
+ : settings,
+ )
.finally(() => {
- inFlightModelMemory = null;
+ // Only the current request owns the slot. Clearing it from a displaced one drops
+ // the newer promise's sharing handle while it is still in flight, so the next
+ // caller opens a third request rather than joining the second.
+ if (generation === modelMemoryGeneration) {
+ inFlightModelMemory = null;
+ }
});
return inFlightModelMemory;
}
diff --git a/studio/frontend/src/features/settings/api/settings-route-absent.ts b/studio/frontend/src/features/settings/api/settings-route-absent.ts
new file mode 100644
index 00000000000..6487181af01
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/settings-route-absent.ts
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * A settings route this build of the UI knows about and the running backend does not.
+ *
+ * Distinct from a failed read on purpose. A caller deciding whether it may skip work
+ * treats the two oppositely: an absent route means the backend has no such state to
+ * disagree about, while a read that could not be made says nothing at all, and assuming
+ * it said "no" is how a saved setting goes missing.
+ */
+export class SettingsRouteAbsentError extends Error {
+ constructor(route: string) {
+ super(`Settings route not served by this backend: ${route}`);
+ this.name = "SettingsRouteAbsentError";
+ }
+}
+
+export function isSettingsRouteAbsent(error: unknown): boolean {
+ return error instanceof SettingsRouteAbsentError;
+}
diff --git a/studio/frontend/src/features/settings/api/vram-budget.ts b/studio/frontend/src/features/settings/api/vram-budget.ts
index 5877b5ec369..84a2f22285b 100644
--- a/studio/frontend/src/features/settings/api/vram-budget.ts
+++ b/studio/frontend/src/features/settings/api/vram-budget.ts
@@ -4,6 +4,8 @@
import { authFetch } from "@/features/auth";
import { readFastApiError } from "@/lib/format-fastapi-error";
+import { SettingsRouteAbsentError } from "./settings-route-absent";
+
const VRAM_BUDGET_EVENT = "unsloth-vram-budget-change";
const VRAM_BUDGET_LOCK_EVENT = "unsloth-vram-budget-lock";
@@ -146,6 +148,9 @@ function publishVramBudget(settings: VramBudgetSettings) {
async function fetchVramBudgetSettings(): Promise<VramBudgetSettings> {
const res = await authFetch("/api/settings/vram-budget");
+ if (res.status === 404) {
+ throw new SettingsRouteAbsentError("/api/settings/vram-budget");
+ }
if (!res.ok) {
throw new Error(await readFastApiError(res, "Failed to load VRAM budget"));
}
@@ -158,7 +163,7 @@ async function fetchVramBudgetSettings(): Promise<VramBudgetSettings> {
* endpoint is absent, so a newer UI on an older backend hides the control.
*/
export async function loadVramBudgetSettings(
- options: { force?: boolean } = {},
+ options: { force?: boolean; rethrow?: boolean } = {},
): Promise<VramBudgetSettings | null> {
// Read behind any open write: a row remounting right after a flushed drag can
// otherwise GET the old fraction before the PUT commits and answer after it,
@@ -205,9 +210,14 @@ export async function loadVramBudgetSettings(
}
try {
return await inFlightVramBudget;
- } catch {
+ } catch (error) {
// Null is already the "no usable answer" contract here: an older backend with
- // no such route reads the same way, and every caller keeps what it has.
+ // no such route reads the same way, and every caller keeps what it has. `rethrow`
+ // is for the one caller that must tell those apart, since it decides whether a
+ // save may be skipped rather than what to paint.
+ if (options.rethrow) {
+ throw error;
+ }
return null;
}
}
diff --git a/studio/frontend/tests/chat-model-residency.test.ts b/studio/frontend/tests/chat-model-residency.test.ts
index e7f3891a3bb..f505091b515 100644
--- a/studio/frontend/tests/chat-model-residency.test.ts
+++ b/studio/frontend/tests/chat-model-residency.test.ts
@@ -191,9 +191,11 @@ test("an eviction drops the pick, not just the loaded marks", () => {
),
"utf8",
);
+ // Anchored on the branch, not on the file: other catches sit above it now.
+ const branchStart = hook.indexOf("} else if (!statusRes.active_model");
const branch = hook.slice(
- hook.indexOf("} else if (!statusRes.active_model"),
- hook.indexOf("} catch (error) {"),
+ branchStart,
+ hook.indexOf("} catch (error) {", branchStart),
);
assert.match(branch, /clearCheckpoint\(\)/);
// Guarded twice: a model that was never confirmed resident has nothing to
diff --git a/studio/frontend/tests/llama-extra-args-normalize.test.ts b/studio/frontend/tests/llama-extra-args-normalize.test.ts
new file mode 100644
index 00000000000..4cd0a644c03
--- /dev/null
+++ b/studio/frontend/tests/llama-extra-args-normalize.test.ts
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The three pass-through resolutions `/load` performs before its already-loaded
+ * comparator runs, mirrored so the resident-model shortcut judges the request the server
+ * would actually receive rather than the one the panel typed.
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const {
+ parseGpuLayersOverride,
+ resolveTensorParallel,
+ stripManagedOffloadFlags,
+} = await import("../src/features/chat/lib/llama-extra-args-normalize.ts");
+
+test("an explicit split mode last-wins over the toggle", () => {
+ assert.equal(resolveTensorParallel(null, true), true);
+ assert.equal(resolveTensorParallel([], false), false);
+ assert.equal(resolveTensorParallel(["--split-mode", "tensor"], false), true);
+ assert.equal(resolveTensorParallel(["--split-mode", "layer"], true), false);
+ assert.equal(resolveTensorParallel(["-sm", "row"], true), false);
+ // Both spellings, and the last one wins.
+ assert.equal(
+ resolveTensorParallel(["-sm=tensor", "--split-mode", "none"], true),
+ false,
+ );
+ assert.equal(
+ resolveTensorParallel(["--split-mode", "none", "-sm=TENSOR"], false),
+ true,
+ );
+ // A flag with no value says nothing about what was requested.
+ assert.equal(resolveTensorParallel(["--split-mode"], true), true);
+ assert.equal(
+ resolveTensorParallel(["--split-mode", "--flash-attn"], true),
+ true,
+ );
+});
+
+test("a pass-through layer count is read the way the route reads it", () => {
+ const absent = { kind: "absent" };
+ const invalid = { kind: "invalid" };
+ const value = (layers: number) => ({ kind: "value", layers });
+
+ assert.deepEqual(parseGpuLayersOverride(null), absent);
+ assert.deepEqual(parseGpuLayersOverride(["--flash-attn", "on"]), absent);
+ assert.deepEqual(parseGpuLayersOverride(["-ngl", "20"]), value(20));
+ assert.deepEqual(parseGpuLayersOverride(["--gpu-layers=0"]), value(0));
+ assert.deepEqual(parseGpuLayersOverride(["--n-gpu-layers", "-1"]), value(-1));
+ assert.deepEqual(
+ parseGpuLayersOverride(["-ngl", "8", "-ngl", "99"]),
+ value(99),
+ );
+ // Below -1 and non-integers are what the backend rejects outright, and it RAISES
+ // rather than defaulting, so these stay distinct from an absent override.
+ assert.deepEqual(parseGpuLayersOverride(["-ngl", "-2"]), invalid);
+ assert.deepEqual(parseGpuLayersOverride(["-ngl", "many"]), invalid);
+ assert.deepEqual(parseGpuLayersOverride(["-ngl", "20.5"]), invalid);
+ // -1 is a value, not a flag: shorts always start with a letter. Without that rule the
+ // commonest pass-through of all, an explicit Auto, reads as malformed.
+ assert.deepEqual(
+ parseGpuLayersOverride(["-ngl", "-1", "--flash-attn", "on"]),
+ value(-1),
+ );
+ // llama.cpp takes the underscore spelling of a long option, and so does this.
+ assert.deepEqual(parseGpuLayersOverride(["--n_gpu_layers", "12"]), value(12));
+});
+
+test("the offload family is dropped with its values, and nothing else is", () => {
+ assert.deepEqual(stripManagedOffloadFlags(null), null);
+ assert.deepEqual(stripManagedOffloadFlags(undefined), undefined);
+ assert.deepEqual(stripManagedOffloadFlags([]), []);
+ assert.deepEqual(
+ stripManagedOffloadFlags(["-ngl", "20", "--flash-attn", "on"]),
+ ["--flash-attn", "on"],
+ );
+ assert.deepEqual(stripManagedOffloadFlags(["--gpu-layers=20"]), []);
+ assert.deepEqual(
+ stripManagedOffloadFlags(["--fit", "on", "-ncmoe", "4", "--cpu-moe"]),
+ [],
+ );
+ // A split mode is not offload, and manual does not own it.
+ assert.deepEqual(stripManagedOffloadFlags(["-sm", "tensor"]), [
+ "-sm",
+ "tensor",
+ ]);
+ // A trailing offload flag with no value takes nothing with it.
+ assert.deepEqual(stripManagedOffloadFlags(["--flash-attn", "on", "-ngl"]), [
+ "--flash-attn",
+ "on",
+ ]);
+});
diff --git a/studio/frontend/tests/model-memory-cache.test.ts b/studio/frontend/tests/model-memory-cache.test.ts
index 1e55de9c6d7..09c6912a143 100644
--- a/studio/frontend/tests/model-memory-cache.test.ts
+++ b/studio/frontend/tests/model-memory-cache.test.ts
@@ -84,6 +84,121 @@ test("concurrent reads share one request", async () => {
assert.deepEqual(b, c);
});
+test("a 404 is an absent route, not a failed read", async () => {
+ // The resident-model shortcut treats the two oppositely: an older backend has no such
+ // setting to disagree about, while a read that could not be made says nothing, and
+ // assuming it said no is how a saved policy goes missing.
+ calls = [];
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () =>
+ new Response("{}", { status: 404 })) as typeof fetch;
+ await assert.rejects(
+ loadModelMemorySettings({ force: true }),
+ (error: Error) => {
+ assert.equal(error.name, "SettingsRouteAbsentError");
+ return true;
+ },
+ );
+ globalThis.fetch = (async () =>
+ new Response("boom", { status: 503 })) as typeof fetch;
+ await assert.rejects(
+ loadModelMemorySettings({ force: true }),
+ (error: Error) => {
+ assert.notEqual(error.name, "SettingsRouteAbsentError");
+ return true;
+ },
+ );
+ globalThis.fetch = original;
+});
+
+test("a forced read does not join one already in flight", async () => {
+ // Sharing is right for two panels painting the same answer and wrong for the
+ // resident-model shortcut: a read that started before a policy save describes the
+ // policy it replaced, and a reloadRequired false from that would suppress the very
+ // load the save was made for.
+ calls = [];
+ const joined = loadModelMemorySettings();
+ // The fake snapshots the body when the request goes out, so the second GET carries the
+ // saved policy and the first still carries the one it replaced.
+ nextBody = { ...API, reload_required: true };
+ const forced = loadModelMemorySettings({ force: true });
+ assert.equal(calls.length, 2, "the forced read must issue its own GET");
+ const [stale, fresh] = await Promise.all([joined, forced]);
+ assert.equal(
+ stale.reloadRequired,
+ false,
+ "the shared read keeps its own answer",
+ );
+ assert.equal(
+ fresh.reloadRequired,
+ true,
+ "the forced read sees the saved policy",
+ );
+ nextBody = { ...API };
+});
+
+test("a displaced read neither publishes nor frees the slot", async () => {
+ // Forcing replaces an in-flight read, and that older request is still running. It
+ // describes the state its replacement was issued because of, so it must not repaint
+ // subscribers, and it must not clear a sharing handle it no longer owns.
+ const original = globalThis.fetch;
+ const pending: ((body: Record<string, unknown>) => void)[] = [];
+ let issued = 0;
+ globalThis.fetch = (async () => {
+ issued += 1;
+ return new Promise<Response>((resolve) => {
+ pending.push((body) =>
+ resolve(
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+ });
+ }) as typeof fetch;
+
+ const published: boolean[] = [];
+ const stop = subscribeModelMemorySettings((settings) => {
+ published.push(settings.reloadRequired);
+ });
+ try {
+ const displaced = loadModelMemorySettings();
+ const forced = loadModelMemorySettings({ force: true });
+ assert.equal(issued, 2);
+
+ // The displaced request lands first, while its replacement is still in flight.
+ pending[0]({ ...API, reload_required: false });
+ assert.equal(
+ await displaced,
+ await displaced,
+ "its own caller still gets an answer",
+ );
+ await Promise.resolve();
+ assert.deepEqual(
+ published,
+ [],
+ "a superseded read must not repaint subscribers",
+ );
+
+ // The slot still belongs to the forced read, so a new caller joins it.
+ const joiner = loadModelMemorySettings();
+ assert.equal(issued, 2, "the displaced read freed a slot it did not own");
+
+ pending[1]({ ...API, reload_required: true });
+ assert.equal((await forced).reloadRequired, true);
+ assert.equal((await joiner).reloadRequired, true);
+ assert.deepEqual(
+ published,
+ [true],
+ "only the current read speaks for everyone",
+ );
+ } finally {
+ stop();
+ globalThis.fetch = original;
+ }
+});
+
test("a later read is NOT served from a cache", async () => {
calls = [];
await loadModelMemorySettings();
diff --git a/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts
new file mode 100644
index 00000000000..df46797528d
--- /dev/null
+++ b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts
@@ -0,0 +1,443 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * `residentRuntimeMatchesConfig` across the accelerators Studio runs on, crossed with every
+ * setting a remembered config can pin.
+ *
+ * The two failures are not symmetric. A wrong FALSE costs one reload, which is what
+ * happened before #8893. A wrong TRUE leaves the user on a server invoked differently from
+ * what they asked for, with the panel rolled back so nothing says so. Hence both directions
+ * for every field rather than sampling.
+ *
+ * The accelerator axis is real even though no paths are compared, because the fields read
+ * are the GPU ones: CUDA and ROCm report a placement pool and an offload mode, a CPU-only
+ * host reports `manual` with zero layers, MLX reports none of them and a KV width instead.
+ * "The status does not carry this field" must never read as agreement.
+ *
+ * The structural test at the bottom is the one that lasts: it fails when a field is added
+ * to `PerModelConfig` without being classified here.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import type { PerModelConfig } from "../src/features/model-picker/model-config/per-model-config.ts";
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { residentRuntimeMatchesConfig: matchesWithStanding } = await import(
+ "../src/features/chat/lib/resident-config-match.ts"
+);
+
+/**
+ * What the applier resolves an unset field to. Four fields are not per-model, so leaving
+ * them out of a config is not silence; the caller passes what `/load` would actually send.
+ * These are the shipped defaults: speculation off, memory mode "auto", `GPU_LAYERS_AUTO`
+ * and no CPU MoE offload.
+ */
+const STANDING = {
+ speculativeType: null,
+ gpuMemoryMode: "auto" as const,
+ gpuLayers: -1,
+ nCpuMoe: 0,
+ // Identity: the sweep is about the fields, not about a stale pick. The reconciler's own
+ // effect is covered in resident-config-match.test.ts.
+ reconcileGpuIds: (ids: number[] | null) => ids,
+ // Auto resolves to 0 here; the resident-repick branch is exercised on its own below.
+ resolveContextLength: (customContextLength: number | null) =>
+ customContextLength ?? 0,
+ parallelSlots: 1,
+ splitRatio: null,
+ normalizeSpeculative: (value: string | null | undefined) =>
+ value == null || value === "" || value === "none" ? null : value,
+};
+
+const residentRuntimeMatchesConfig = (
+ status: Parameters<typeof matchesWithStanding>[0],
+ config: Parameters<typeof matchesWithStanding>[1],
+) => matchesWithStanding(status, config, STANDING);
+
+/** A config that pins nothing: what a model the user never configured carries. */
+const BLANK = {
+ customContextLength: null,
+ maxSeqLength: null,
+ kvCacheDtype: null,
+ mlxKvBits: null,
+ speculativeType: null,
+ specDraftNMax: null,
+ nParallel: null,
+ nBatch: null,
+ nUbatch: null,
+ tensorParallel: false,
+ chatTemplateOverride: null,
+};
+
+/** What `/api/inference/status` reports per host, measured against a running Studio rather
+ * than copied from the type: a default CUDA load answers auto / -1 / 0 / null / false. */
+const ACCELERATORS: Record<string, Record<string, unknown>> = {
+ "nvidia-cuda": {
+ gpu_memory_mode: "auto",
+ gpu_layers: -1,
+ n_cpu_moe: 0,
+ // A default load requests no particular GPU, so the echo is null. The set comparison
+ // on a real placement pool has its own test below; here a non-null pool would make
+ // BLANK disagree, since an unset pick resolves to Automatic rather than to "any".
+ requested_gpu_ids: null,
+ tensor_parallel: false,
+ },
+ "amd-rocm": {
+ gpu_memory_mode: "auto",
+ gpu_layers: -1,
+ n_cpu_moe: 0,
+ // Left unrequested for the same reason as above; the ROCm-shaped pool of several
+ // physical indices, compared as a SET, has its own test below.
+ requested_gpu_ids: null,
+ tensor_parallel: false,
+ },
+ // A host with no GPU still reports the invocation it was ASKED for, not what llama.cpp
+ // settled on: a default load sends Auto, so the echo is "auto" / -1 exactly as on a CUDA
+ // box, with no placement pool. A manual zero-layer load is a different thing and is
+ // covered on its own below, since an unset config resolves to Auto and so differs from it.
+ "cpu-only": {
+ gpu_memory_mode: "auto",
+ gpu_layers: -1,
+ n_cpu_moe: 0,
+ requested_gpu_ids: null,
+ tensor_parallel: false,
+ },
+ // An MLX server records a KV width and none of the llama.cpp placement fields at all. A
+ // default load leaves the width unrequested; a pinned width is swept below like any other
+ // field, and is not part of the base for the same reason placement is not.
+ "apple-mlx": {
+ mlx_kv_bits_requested: null,
+ },
+};
+
+/** One field a remembered config can pin, and a value that is NOT what the status runs. */
+type FieldCase = {
+ key: string;
+ statusKey: string;
+ same: unknown;
+ different: unknown;
+ /**
+ * What must hold on both sides for the field to be live at all. The backend compares
+ * the offload knobs only under Manual, and the MoE count only with a layer pin beside
+ * it, so sweeping them under Auto would assert a comparison that does not happen.
+ */
+ live?: { config: Record<string, unknown>; status: Record<string, unknown> };
+};
+
+const MANUAL_MODE = {
+ config: { gpuMemoryMode: "manual" },
+ status: { gpu_memory_mode: "manual" },
+};
+
+const FIELDS: FieldCase[] = [
+ {
+ key: "customContextLength",
+ statusKey: "requested_context_length",
+ same: 32768,
+ different: 8192,
+ },
+ {
+ key: "kvCacheDtype",
+ statusKey: "cache_type_kv",
+ same: "q8_0",
+ different: "f16",
+ },
+ {
+ key: "mlxKvBits",
+ statusKey: "mlx_kv_bits_requested",
+ same: 8,
+ different: 4,
+ },
+ {
+ key: "speculativeType",
+ statusKey: "speculative_type",
+ same: "ngram",
+ different: "auto",
+ },
+ {
+ key: "specDraftNMax",
+ statusKey: "spec_draft_n_max",
+ same: 16,
+ different: 8,
+ },
+ {
+ key: "nParallel",
+ statusKey: "requested_parallel_slots",
+ same: 4,
+ different: 2,
+ },
+ {
+ key: "nBatch",
+ statusKey: "requested_n_batch",
+ same: 2048,
+ different: 1024,
+ },
+ {
+ key: "nUbatch",
+ statusKey: "requested_n_ubatch",
+ same: 512,
+ different: 256,
+ },
+ {
+ key: "chatTemplateOverride",
+ statusKey: "chat_template_override",
+ same: "{{ bos }}",
+ different: "{{ eos }}",
+ },
+ {
+ key: "llamaExtraArgs",
+ statusKey: "requested_llama_extra_args",
+ same: ["--threads", "8"],
+ different: ["--threads", "4"],
+ },
+ {
+ key: "gpuMemoryMode",
+ statusKey: "gpu_memory_mode",
+ same: "manual",
+ different: "auto",
+ },
+ {
+ key: "gpuLayers",
+ statusKey: "gpu_layers",
+ same: 20,
+ different: 10,
+ live: MANUAL_MODE,
+ },
+ {
+ key: "nCpuMoe",
+ statusKey: "n_cpu_moe",
+ same: 8,
+ different: 4,
+ live: {
+ config: { ...MANUAL_MODE.config, gpuLayers: 20 },
+ status: { ...MANUAL_MODE.status, gpu_layers: 20 },
+ },
+ },
+ {
+ key: "selectedGpuIds",
+ statusKey: "requested_gpu_ids",
+ same: [1, 0],
+ different: [0, 2],
+ },
+ {
+ key: "tensorParallel",
+ statusKey: "tensor_parallel",
+ same: true,
+ different: false,
+ },
+];
+
+for (const [accelerator, base] of Object.entries(ACCELERATORS)) {
+ test(`[${accelerator}] a config pinning nothing adopts the resident load`, () => {
+ assert.equal(residentRuntimeMatchesConfig(base, BLANK), true);
+ assert.equal(residentRuntimeMatchesConfig(base, null), true);
+ });
+
+ for (const field of FIELDS) {
+ test(`[${accelerator}] ${field.key} the resident load already runs is adopted`, () => {
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ { ...base, ...field.live?.status, [field.statusKey]: field.same },
+ { ...BLANK, ...field.live?.config, [field.key]: field.same },
+ ),
+ true,
+ );
+ });
+
+ test(`[${accelerator}] ${field.key} the resident load does not run is a reload`, () => {
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ { ...base, ...field.live?.status, [field.statusKey]: field.different },
+ { ...BLANK, ...field.live?.config, [field.key]: field.same },
+ ),
+ false,
+ );
+ });
+
+ test(`[${accelerator}] ${field.key} pinned against a status that omits it is a reload`, () => {
+ // Never agreement: a field the server cannot report is one this cannot verify.
+ const status = { ...base, ...field.live?.status } as Record<
+ string,
+ unknown
+ >;
+ delete status[field.statusKey];
+ assert.equal(
+ residentRuntimeMatchesConfig(status, {
+ ...BLANK,
+ ...field.live?.config,
+ [field.key]: field.same,
+ }),
+ // tensorParallel has no unset state: false is a real request for a layer split,
+ // and a status omitting the flag ran without one, so they agree.
+ field.key === "tensorParallel" ? field.same === false : false,
+ );
+ });
+ }
+}
+
+test("placement compares as a set on a multi-GPU host, not as an order", () => {
+ // The backend narrows and reorders the pool at fit time, so only membership counts.
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ { ...ACCELERATORS["amd-rocm"], requested_gpu_ids: [0, 1] },
+ { ...BLANK, selectedGpuIds: [1, 0] },
+ ),
+ true,
+ );
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ { ...ACCELERATORS["amd-rocm"], requested_gpu_ids: [0, 1] },
+ { ...BLANK, selectedGpuIds: [0, 1, 2] },
+ ),
+ false,
+ );
+});
+
+test("automatic placement is a request of its own, not a wildcard", () => {
+ // The applier turns an absent or null selection into a null selection, and the load sends
+ // that as Automatic. Automatic is not "whatever is running": a server the user placed on
+ // four specific GPUs was invoked differently and has to be reloaded.
+ for (const ids of [null, undefined]) {
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ { ...ACCELERATORS["nvidia-cuda"], requested_gpu_ids: [0, 1, 2, 3] },
+ { ...BLANK, selectedGpuIds: ids },
+ ),
+ false,
+ );
+ assert.equal(
+ residentRuntimeMatchesConfig(ACCELERATORS["nvidia-cuda"], {
+ ...BLANK,
+ selectedGpuIds: ids,
+ }),
+ true,
+ );
+ }
+});
+
+test("a CPU-only host distinguishes zero offloaded layers from automatic", () => {
+ // gpu_layers 0 under manual is "all on the CPU", -1 is "let llama.cpp size it": two
+ // different loads, and 0 must not read as absent.
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ { ...ACCELERATORS["cpu-only"], gpu_memory_mode: "manual", gpu_layers: 0 },
+ { ...BLANK, gpuMemoryMode: "manual", gpuLayers: 0 },
+ ),
+ true,
+ );
+ // The other direction, which is the one the standing defaults buy: a config that pins
+ // neither field resolves to Auto and so does NOT adopt a manual zero-layer server.
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ { ...ACCELERATORS["cpu-only"], gpu_memory_mode: "manual", gpu_layers: 0 },
+ BLANK,
+ ),
+ false,
+ );
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ { ...ACCELERATORS["nvidia-cuda"] },
+ { ...BLANK, gpuMemoryMode: "manual", gpuLayers: 0 },
+ ),
+ false,
+ );
+});
+
+test("a config stored by an older Studio does not throw and does not over-adopt", () => {
+ // Blobs written before a field existed lack the key. Optional ones express no opinion
+ // and adopt; a missing tensorParallel cannot be confirmed and reloads. Neither throws.
+ // Cast at the boundary on purpose: these come off localStorage, so the point is the
+ // shapes the current type says cannot occur.
+ const legacyBlobs = [
+ // Pre-GPU-controls, pre-extra-args, pre-MLX.
+ {
+ customContextLength: null,
+ maxSeqLength: null,
+ kvCacheDtype: null,
+ speculativeType: null,
+ specDraftNMax: null,
+ nParallel: null,
+ nBatch: null,
+ nUbatch: null,
+ tensorParallel: false,
+ chatTemplateOverride: null,
+ },
+ // A blob so old it carries only what the very first version stored.
+ { customContextLength: null, kvCacheDtype: null },
+ // Corrupt-but-parseable: the key is there with the wrong emptiness.
+ { ...BLANK, selectedGpuIds: [] },
+ ];
+ for (const blob of legacyBlobs) {
+ for (const base of Object.values(ACCELERATORS)) {
+ assert.equal(
+ typeof residentRuntimeMatchesConfig(base, blob as PerModelConfig),
+ "boolean",
+ );
+ }
+ }
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ ACCELERATORS["nvidia-cuda"],
+ legacyBlobs[1] as PerModelConfig,
+ ),
+ // tensorParallel absent vs status false: reloads, the direction that loses nothing.
+ false,
+ );
+});
+
+test("an empty pinned pool is Automatic, not a demand for no GPUs", () => {
+ assert.equal(
+ residentRuntimeMatchesConfig(
+ { ...ACCELERATORS["nvidia-cuda"], requested_gpu_ids: [0, 1] },
+ { ...BLANK, selectedGpuIds: [] },
+ ),
+ // set() treats [] as pinned, so this reloads. Recorded, not endorsed: the panel
+ // writes null for Automatic.
+ false,
+ );
+});
+
+test("every PerModelConfig field is either compared or deliberately excluded", () => {
+ // A new setting not classified here is one an adopted pick would drop silently.
+ const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/model-picker/model-config/per-model-config.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ const body = source.slice(
+ source.indexOf("export interface PerModelConfig {"),
+ source.indexOf("export const DEFAULT_PER_MODEL_CONFIG"),
+ );
+ const declared = new Set(
+ [...body.matchAll(/^\s{2}(\w+)\??:/gm)].map((match) => match[1]),
+ );
+ assert.ok(declared.size > 10, "failed to parse PerModelConfig");
+
+ const compared = new Set(FIELDS.map((field) => field.key));
+ const excluded = new Set([
+ // A client-side generation cap: no status echoes it, so it cannot force a reload.
+ "maxSeqLength",
+ // Qualifies selectedGpuIds rather than adding a dimension of its own: it is read, as
+ // the reconciler's namespace argument, but /status has no field to compare it against.
+ "selectedGpuIndexKind",
+ ]);
+ const unclassified = [...declared].filter(
+ (field) => !compared.has(field) && !excluded.has(field),
+ );
+ assert.deepEqual(unclassified, []);
+ // And the reverse, so a removed field leaves no dead check here.
+ const stale = [...compared, ...excluded].filter(
+ (field) => !declared.has(field),
+ );
+ assert.deepEqual(stale, []);
+});
diff --git a/studio/frontend/tests/resident-config-match.test.ts b/studio/frontend/tests/resident-config-match.test.ts
new file mode 100644
index 00000000000..b6f7cf01a11
--- /dev/null
+++ b/studio/frontend/tests/resident-config-match.test.ts
@@ -0,0 +1,1770 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * #8893's fix skips the reload when the picked model is already resident. Identity is not
+ * the whole of a load, though: the picker and Hub's Run button both pass a REMEMBERED
+ * config without forceReload (chat-page.tsx stageOrLoad, hub-page.tsx handleRun), and the
+ * backend reloads for any of those settings changing. Adopting on identity alone dropped
+ * them silently, because the same path rolls the panel back to the resident model and so
+ * looks consistent either way.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { residentRuntimeMatchesConfig, residentSpeculativeNeedsRepair } =
+ await import("../src/features/chat/lib/resident-config-match.ts");
+
+/** Every field unset: what a model the user never configured would carry. */
+const DEFAULT_ISH = {
+ customContextLength: null,
+ maxSeqLength: null,
+ kvCacheDtype: null,
+ mlxKvBits: null,
+ speculativeType: null,
+ specDraftNMax: null,
+ nParallel: null,
+ nBatch: null,
+ nUbatch: null,
+ tensorParallel: false,
+ chatTemplateOverride: null,
+} as const;
+
+const BLANK = {
+ customContextLength: null,
+ maxSeqLength: null,
+ kvCacheDtype: null,
+ mlxKvBits: null,
+ speculativeType: null,
+ specDraftNMax: null,
+ nParallel: null,
+ nBatch: null,
+ nUbatch: null,
+ tensorParallel: false,
+ chatTemplateOverride: null,
+};
+
+/** A resident llama-server running nothing but defaults. */
+const DEFAULTS = {};
+
+/**
+ * What the applier fills an unset field with. Four fields are not per-model, so leaving
+ * them out of a config is not silence: applyPerModelConfigToRuntime resolves them from a
+ * standing preference or a constant, and the load sends the result.
+ */
+const STANDING = {
+ speculativeType: "auto",
+ gpuMemoryMode: "auto" as const,
+ gpuLayers: -1,
+ nCpuMoe: 0,
+ // Identity by default: reconciliation is exercised on its own below.
+ reconcileGpuIds: (ids: number[] | null) => ids,
+ // Auto resolves to 0 here; the resident-repick branch is exercised on its own below.
+ resolveContextLength: (customContextLength: number | null) =>
+ customContextLength ?? 0,
+ parallelSlots: 1,
+ splitRatio: null,
+ // Enough of normalizeSpeculativeType for these cases; the real mapping is the store's
+ // and is tested there. What matters here is that the comparator USES it on both sides.
+ normalizeSpeculative: (v: string | null | undefined) =>
+ v == null || !String(v).trim()
+ ? null
+ : String(v).trim().toLowerCase() === "default"
+ ? "auto"
+ : String(v).trim().toLowerCase(),
+};
+
+/** Shorthand: the comparator always needs the standing defaults. */
+const matches = (
+ status: Parameters<typeof residentRuntimeMatchesConfig>[0],
+ config: Parameters<typeof residentRuntimeMatchesConfig>[1],
+ standing: Parameters<typeof residentRuntimeMatchesConfig>[2] = STANDING,
+) => residentRuntimeMatchesConfig(status, config, standing);
+
+test("no config at all adopts the resident model", () => {
+ assert.equal(matches(DEFAULTS, null), true);
+ assert.equal(matches(DEFAULTS, undefined), true);
+});
+
+test("a config that pins nothing adopts the resident model", () => {
+ assert.equal(matches(DEFAULTS, BLANK), true);
+});
+
+/** The regression this file exists for: the setting must reach the server. */
+test("a remembered context length the resident load does not run is a reload", () => {
+ assert.equal(
+ matches(
+ { requested_context_length: 4096 },
+ { ...BLANK, customContextLength: 32768 },
+ ),
+ false,
+ );
+});
+
+test("a remembered context length the resident load already runs adopts it", () => {
+ assert.equal(
+ matches(
+ { requested_context_length: 32768 },
+ { ...BLANK, customContextLength: 32768 },
+ ),
+ true,
+ );
+});
+
+/** Every field the backend's _runtime_matches_intent reloads for, one per row. */
+const FIELDS: {
+ name: string;
+ config: Record<string, unknown>;
+ same: Record<string, unknown>;
+ differs: Record<string, unknown>;
+}[] = [
+ {
+ name: "context length",
+ config: { customContextLength: 8192 },
+ same: { requested_context_length: 8192 },
+ differs: { requested_context_length: 4096 },
+ },
+ {
+ name: "KV cache dtype",
+ config: { kvCacheDtype: "q8_0" },
+ same: { cache_type_kv: "q8_0" },
+ differs: { cache_type_kv: "f16" },
+ },
+ {
+ name: "MLX KV bits",
+ config: { mlxKvBits: 4 },
+ same: { mlx_kv_bits_requested: 4 },
+ differs: { mlx_kv_bits_requested: 8 },
+ },
+ {
+ name: "speculative mode",
+ config: { speculativeType: "mtp" },
+ same: { speculative_type: "mtp" },
+ differs: { speculative_type: "off" },
+ },
+ {
+ name: "draft depth",
+ config: { specDraftNMax: 8 },
+ same: { spec_draft_n_max: 8 },
+ differs: { spec_draft_n_max: 3 },
+ },
+ {
+ name: "parallel slots",
+ config: { nParallel: 4 },
+ same: { requested_parallel_slots: 4 },
+ differs: { requested_parallel_slots: 1 },
+ },
+ {
+ name: "batch size",
+ config: { nBatch: 2048 },
+ same: { requested_n_batch: 2048 },
+ differs: { requested_n_batch: 512 },
+ },
+ {
+ name: "micro-batch size",
+ config: { nUbatch: 512 },
+ same: { requested_n_ubatch: 512 },
+ differs: { requested_n_ubatch: 128 },
+ },
+ {
+ name: "tensor parallel",
+ config: { tensorParallel: true },
+ same: { tensor_parallel: true },
+ differs: { tensor_parallel: false },
+ },
+ {
+ name: "chat template override",
+ config: { chatTemplateOverride: "{{ custom }}" },
+ same: { chat_template_override: "{{ custom }}" },
+ differs: { chat_template_override: null },
+ },
+ {
+ name: "pass-through llama args",
+ config: { llamaExtraArgs: ["--flash-attn", "on"] },
+ same: { requested_llama_extra_args: ["--flash-attn", "on"] },
+ differs: { requested_llama_extra_args: ["--flash-attn", "off"] },
+ },
+ {
+ name: "GPU memory mode",
+ config: { gpuMemoryMode: "manual" },
+ same: { gpu_memory_mode: "manual" },
+ differs: { gpu_memory_mode: "auto" },
+ },
+ {
+ // Manual on both sides: the backend compares the offload knobs only there, and the
+ // MoE count only with a layer pin beside it, so Auto would assert nothing.
+ name: "GPU layers",
+ config: { gpuMemoryMode: "manual", gpuLayers: 20 },
+ same: { gpu_memory_mode: "manual", gpu_layers: 20 },
+ differs: { gpu_memory_mode: "manual", gpu_layers: 99 },
+ },
+ {
+ name: "CPU MoE layers",
+ config: { gpuMemoryMode: "manual", gpuLayers: 20, nCpuMoe: 12 },
+ same: { gpu_memory_mode: "manual", gpu_layers: 20, n_cpu_moe: 12 },
+ differs: { gpu_memory_mode: "manual", gpu_layers: 20, n_cpu_moe: 0 },
+ },
+ {
+ name: "GPU placement",
+ config: { selectedGpuIds: [0, 2] },
+ same: { requested_gpu_ids: [2, 0] },
+ differs: { requested_gpu_ids: [0, 1] },
+ },
+];
+
+for (const field of FIELDS) {
+ test(`a matching ${field.name} adopts the resident model`, () => {
+ assert.equal(matches(field.same, { ...BLANK, ...field.config }), true);
+ });
+ test(`a differing ${field.name} is a real reload`, () => {
+ assert.equal(
+ matches(field.differs, {
+ ...BLANK,
+ ...field.config,
+ }),
+ false,
+ );
+ });
+ test(`a ${field.name} the resident load never reported is a real reload`, () => {
+ // An older backend that does not echo the field cannot prove it agrees, and guessing
+ // that it does is the one answer that loses a setting with nothing on screen to say so.
+ assert.equal(matches({}, { ...BLANK, ...field.config }), false);
+ });
+}
+
+/** Ordering is the backend's to choose: it narrows and reorders placement at fit time. */
+test("GPU placement compares as a set, not as an order", () => {
+ assert.equal(
+ matches(
+ { requested_gpu_ids: [3, 1, 0] },
+ { ...BLANK, selectedGpuIds: [0, 1, 3] },
+ ),
+ true,
+ );
+});
+
+test("automatic placement does not adopt a load pinned to chosen GPUs", () => {
+ // Automatic is what the applier resolves an unset selection to, and it is what the load
+ // would then send, so it disagrees with a server placed on a chosen pool.
+ assert.equal(
+ matches({ requested_gpu_ids: [0, 1] }, { ...BLANK, selectedGpuIds: null }),
+ false,
+ );
+ assert.equal(matches({}, { ...BLANK, selectedGpuIds: null }), true);
+});
+
+/** The three states of llamaExtraArgs are load-bearing; see PerModelConfig. */
+test("llama args never read by this copy express no opinion", () => {
+ assert.equal(
+ matches({ requested_llama_extra_args: ["--verbose"] }, { ...BLANK }),
+ true,
+ );
+});
+
+test("llama args the user cleared only agree with a load that has none", () => {
+ assert.equal(
+ matches(
+ { requested_llama_extra_args: ["--verbose"] },
+ { ...BLANK, llamaExtraArgs: null },
+ ),
+ false,
+ );
+ assert.equal(matches({}, { ...BLANK, llamaExtraArgs: null }), true);
+ assert.equal(
+ matches(
+ { requested_llama_extra_args: [] },
+ { ...BLANK, llamaExtraArgs: null },
+ ),
+ true,
+ );
+});
+
+test("llama args differing only in order are a real reload", () => {
+ // argv order changes what llama-server does; unlike GPU ids these are not a set.
+ assert.equal(
+ matches(
+ { requested_llama_extra_args: ["b", "a"] },
+ { ...BLANK, llamaExtraArgs: ["a", "b"] },
+ ),
+ false,
+ );
+});
+
+/** tensorParallel is the one non-nullable field, so it always has an opinion. */
+test("tensor parallel off agrees with a status that omits the field", () => {
+ assert.equal(matches({}, { ...BLANK, tensorParallel: false }), true);
+});
+
+test("tensor parallel off is a reload when the resident load split tensors", () => {
+ assert.equal(
+ matches({ tensor_parallel: true }, { ...BLANK, tensorParallel: false }),
+ false,
+ );
+});
+
+/** maxSeqLength never reaches llama-server, so it cannot force a reload. */
+test("a generation cap alone still adopts the resident model", () => {
+ assert.equal(matches(DEFAULTS, { ...BLANK, maxSeqLength: 2048 }), true);
+});
+
+/** Zero is a real value in this API (0 = Auto for context, 0 layers = CPU only). */
+test("zero is a pinned value, not an absent one", () => {
+ const manual = { ...BLANK, gpuMemoryMode: "manual" as const };
+ assert.equal(
+ matches(
+ { gpu_memory_mode: "manual", gpu_layers: 40 },
+ { ...manual, gpuLayers: 0 },
+ ),
+ false,
+ );
+ assert.equal(
+ matches(
+ { gpu_memory_mode: "manual", gpu_layers: 0 },
+ { ...manual, gpuLayers: 0 },
+ ),
+ true,
+ );
+ assert.equal(
+ matches(
+ { requested_context_length: 0 },
+ { ...BLANK, customContextLength: 0 },
+ ),
+ // 0 is Auto and PerModelConfig stores "unset" as null, so a stored 0 is a real pin.
+ true,
+ );
+});
+
+/** Several pins at once, which is what a configured model actually carries. */
+test("one differing field among many agreeing ones is still a reload", () => {
+ const config = {
+ ...BLANK,
+ customContextLength: 8192,
+ kvCacheDtype: "q8_0",
+ nParallel: 2,
+ gpuLayers: 99,
+ };
+ const status = {
+ requested_context_length: 8192,
+ cache_type_kv: "q8_0",
+ requested_parallel_slots: 2,
+ gpu_layers: 99,
+ };
+ assert.equal(matches(status, config), true);
+ assert.equal(matches({ ...status, cache_type_kv: "f16" }, config), false);
+});
+
+/**
+ * The comparator only helps if the pick is tested against it BEFORE the reload is decided,
+ * and the two gates beside it are invariants rather than preferences: a staged config
+ * carries forceReload, and a native pick carries a lease this path cannot adopt.
+ */
+test("selectModel weighs the config and the lease before confirming a reload", () => {
+ const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ // Newline-tolerant: the call wraps once its argument list grows.
+ const configCheck = source.search(/residentRuntimeMatchesConfig\(\s*status/);
+ const identityCheck = source.indexOf("residentModelMatchesPick(status");
+ const confirmPrompt = source.indexOf(
+ "await confirmStopRunningChatsIfNeeded(",
+ );
+ assert.ok(identityCheck > 0, "selectModel no longer checks residency");
+ assert.ok(
+ configCheck > 0,
+ "selectModel adopts a resident model without weighing the pick's own config",
+ );
+ assert.ok(confirmPrompt > 0, "selectModel no longer confirms running chats");
+ assert.ok(identityCheck < confirmPrompt);
+ assert.ok(configCheck < confirmPrompt);
+ // A leased native file is named by a label two files can share, and the lease itself is
+ // written only by a completed load, so this path must not adopt one.
+ // Widened as the gate's preamble grows: what matters is that the guard opens the block
+ // the identity check sits in, not how many reads it makes first.
+ const guard = source.lastIndexOf(
+ "if (!forceReload && !nativePathToken) {",
+ identityCheck,
+ );
+ assert.ok(
+ guard > 0,
+ "the resident short-circuit no longer excludes native-lease picks",
+ );
+});
+
+/**
+ * The four fields that are NOT per-model. Leaving one out of a config is not silence:
+ * applyPerModelConfigToRuntime resolves it from a standing preference or a constant and
+ * the load sends that, so reading it as unpinned let a pick adopt a runtime it did not
+ * ask for. Reported on this file by review, reproduced against the applier, fixed here.
+ */
+test("an unset speculative mode is the standing preference, not silence", () => {
+ // Standing preference is "off"; the resident model is running MTP. The load would send
+ // "off", so this is a real reload even though the config names no mode.
+ assert.equal(
+ matches({ ...DEFAULTS, speculative_type: "mtp" }, BLANK, {
+ ...STANDING,
+ speculativeType: "off",
+ }),
+ false,
+ );
+ // Same standing preference, and the resident model already runs it.
+ assert.equal(
+ matches({ ...DEFAULTS, speculative_type: "off" }, BLANK, {
+ ...STANDING,
+ speculativeType: "off",
+ }),
+ true,
+ );
+});
+
+test("a config that names a mode still beats the standing preference", () => {
+ assert.equal(
+ matches(
+ { ...DEFAULTS, speculative_type: "mtp" },
+ { ...BLANK, speculativeType: "mtp" },
+ { ...STANDING, speculativeType: "off" },
+ ),
+ true,
+ );
+});
+
+test("the speculative mode is normalized on both sides", () => {
+ // "default" and "auto" are the same mode; a spelling difference is not a reload.
+ assert.equal(
+ matches({ ...DEFAULTS, speculative_type: "default" }, BLANK),
+ true,
+ );
+});
+
+test("the GPU pick is compared after reconciliation, not as saved", () => {
+ // performLoad sends reconcilePersistedGpuIds(ids, kind): a pick saved in another index
+ // namespace, or naming GPUs that are gone, leaves as Automatic. Comparing the saved ids
+ // let a physical [1] adopt a server pinned to Vulkan device 1.
+ const dropped = { ...STANDING, reconcileGpuIds: () => null };
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_gpu_ids: [1] },
+ { ...BLANK, selectedGpuIds: [1], selectedGpuIndexKind: "physical" },
+ dropped,
+ ),
+ false,
+ );
+ // The reverse, so the reconciler is not merely refusing everything: once the pick is
+ // Automatic it agrees with a server that was placed automatically.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_gpu_ids: null },
+ { ...BLANK, selectedGpuIds: [1], selectedGpuIndexKind: "physical" },
+ dropped,
+ ),
+ true,
+ );
+ // And the kind reaches the reconciler, which is the only thing that can use it.
+ const kinds: (string | null | undefined)[] = [];
+ matches(
+ DEFAULTS,
+ { ...BLANK, selectedGpuIds: [0], selectedGpuIndexKind: "vulkan" },
+ {
+ ...STANDING,
+ reconcileGpuIds: (ids, kind) => {
+ kinds.push(kind);
+ return ids;
+ },
+ },
+ );
+ assert.deepEqual(kinds, ["vulkan"]);
+});
+
+test("an unset context length is resolved the way the load resolves it", () => {
+ // resolveLoadMaxSeqLength answers 0 for a cross-model GGUF pick and the resident context
+ // when re-picking the same one. Comparing null against either was a reload the backend
+ // would have deduplicated.
+ assert.equal(
+ matches({ ...DEFAULTS, requested_context_length: 0 }, BLANK),
+ true,
+ );
+ assert.equal(
+ matches({ ...DEFAULTS, requested_context_length: 32768 }, BLANK, {
+ ...STANDING,
+ // The re-pick branch: ggufContextLength, not 0.
+ resolveContextLength: (pin) => pin ?? 32768,
+ }),
+ true,
+ );
+ // Still a reload when the resolved value really differs.
+ assert.equal(
+ matches({ ...DEFAULTS, requested_context_length: 32768 }, BLANK),
+ false,
+ );
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_context_length: 8192 },
+ { ...BLANK, customContextLength: 4096 },
+ ),
+ false,
+ );
+});
+
+test("an unset slot count is the server default, not null", () => {
+ // _resolve_parallel_slots fills an omitted --parallel from the server-wide default and
+ // stores THAT as requested_parallel_slots, so the status never echoes null. Comparing
+ // null against it reloaded every default pick, which is the common case.
+ assert.equal(
+ matches({ ...DEFAULTS, requested_parallel_slots: 4 }, BLANK, {
+ ...STANDING,
+ parallelSlots: 4,
+ }),
+ true,
+ );
+ // A pick that names a different count is still a reload.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_parallel_slots: 4 },
+ { ...BLANK, nParallel: 8 },
+ {
+ ...STANDING,
+ parallelSlots: 4,
+ },
+ ),
+ false,
+ );
+ // And a resident load pinned above the default is not adopted by an unset pick.
+ assert.equal(
+ matches({ ...DEFAULTS, requested_parallel_slots: 8 }, BLANK, {
+ ...STANDING,
+ parallelSlots: 4,
+ }),
+ false,
+ );
+ // Unknown default: reload, the safe direction.
+ assert.equal(
+ matches({ ...DEFAULTS, requested_parallel_slots: 4 }, BLANK, {
+ ...STANDING,
+ parallelSlots: null,
+ }),
+ false,
+ );
+});
+
+test("a pick naming the fitted subset of a wider pool is not a reload", () => {
+ // matches_gpu_ids accepts the request or the effective pool: fitting narrows [0, 1] to
+ // [0] when that is the smallest subset holding the model, and asking for [0] dedupes.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_gpu_ids: [0, 1], gpu_ids: [0] },
+ { ...BLANK, selectedGpuIds: [0] },
+ ),
+ true,
+ );
+ // The raw request still answers for itself.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_gpu_ids: [0, 1], gpu_ids: [0] },
+ { ...BLANK, selectedGpuIds: [0, 1] },
+ ),
+ true,
+ );
+ // A pool neither of them names is still a reload.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_gpu_ids: [0, 1], gpu_ids: [0] },
+ { ...BLANK, selectedGpuIds: [1] },
+ ),
+ false,
+ );
+ // An absent echo is no placement, not Automatic: reading it as Automatic would let an
+ // unpinned pick adopt every pinned server.
+ assert.equal(
+ matches({ ...DEFAULTS, requested_gpu_ids: [0, 1] }, BLANK),
+ false,
+ );
+});
+
+test("a retry arm that records no fallback reason still declines the shortcut", () => {
+ // _dflash_retry_needed and the capability-probe arm both reject an identical load while
+ // leaving spec_fallback_reason null, so reading only the reason adopted a runtime the
+ // backend would have rebuilt, and nothing else would ever retry it.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ { spec_fallback_reason: null, spec_dflash_retry_pending: true },
+ "auto",
+ ),
+ true,
+ );
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ { spec_fallback_reason: null, spec_dflash_retry_pending: true },
+ "dflash",
+ ),
+ true,
+ );
+ // The backend gates that arm on those two modes; a pick asking for MTP is not it.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ { spec_fallback_reason: null, spec_dflash_retry_pending: true },
+ "mtp",
+ ),
+ false,
+ );
+ // The probe arm has no mode gate at all.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ { spec_fallback_reason: null, spec_probe_retry_pending: true },
+ "off",
+ ),
+ true,
+ );
+ // Neither pending, and no reason: nothing to repair.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: null,
+ spec_probe_retry_pending: false,
+ spec_dflash_retry_pending: false,
+ },
+ "auto",
+ ),
+ false,
+ );
+});
+
+test("a binary stand-down that cannot repair does not decline the shortcut", () => {
+ // spec_binary_fallback_can_retry needs a different llama-server installed before an
+ // identical /load repairs anything; without one it dedupes and the prompt was for nothing.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "binary_no_mtp",
+ spec_fallback_binary_changed: false,
+ },
+ "auto",
+ ),
+ false,
+ );
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "binary_outdated",
+ spec_fallback_binary_changed: false,
+ },
+ "mtp",
+ ),
+ false,
+ );
+ // Updated since launch: the repair the update was for must still go through.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "binary_no_mtp",
+ spec_fallback_binary_changed: true,
+ },
+ "auto",
+ ),
+ true,
+ );
+ // A backend too old to report it keeps the coarser answer rather than suppress a repair.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ { spec_fallback_reason: "binary_no_mtp" },
+ "auto",
+ ),
+ true,
+ );
+ // The flag says nothing about a reason that was never about the binary.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "drafter_not_found",
+ spec_fallback_binary_changed: false,
+ },
+ "auto",
+ ),
+ true,
+ );
+});
+
+test("a non-GGUF resident is not judged on a GGUF invocation field", () => {
+ // requested_context_length is set only by the llama.cpp path. A safetensors or MLX
+ // status never carries it, and the resolver answers the generation length for a
+ // non-GGUF pick, so reading the absence as 0 rejected every one of these re-picks.
+ assert.equal(
+ matches({ ...DEFAULTS, is_gguf: false }, BLANK, {
+ ...STANDING,
+ resolveContextLength: () => 8192,
+ }),
+ true,
+ );
+ // The GGUF side is unchanged: there the absence really is Auto.
+ assert.equal(
+ matches({ ...DEFAULTS, is_gguf: true }, BLANK, {
+ ...STANDING,
+ resolveContextLength: () => 8192,
+ }),
+ false,
+ );
+ // And a non-GGUF resident answers for the two fields the backend actually compares,
+ // which is all _mlx_runtime_settings_match looks at. cache_type_kv is deliberately not
+ // among them: it is a llama.cpp flag, and the non-GGUF branch never reads it.
+ assert.equal(
+ matches({ ...DEFAULTS, is_gguf: false, cache_type_kv: "q8_0" }, BLANK),
+ true,
+ );
+ assert.equal(
+ matches({ ...DEFAULTS, is_gguf: false, mlx_kv_bits_requested: 4 }, BLANK),
+ false,
+ );
+ assert.equal(
+ matches(
+ { ...DEFAULTS, is_gguf: false, chat_template_override: "{{ bos }}" },
+ BLANK,
+ ),
+ false,
+ );
+});
+
+test("a hidden MoE count under Auto layers is not a reload", () => {
+ // The panel keeps nCpuMoe after the layer slider goes back to Auto, and llama.cpp
+ // records n_cpu_moe 0, so comparing it there rejected an identical runtime.
+ // _runtime_matches_intent compares it only under Manual with a non-negative pin.
+ assert.equal(
+ matches({ ...DEFAULTS, n_cpu_moe: 0 }, { ...BLANK, nCpuMoe: 8 }),
+ true,
+ );
+ const manual = { ...BLANK, gpuMemoryMode: "manual" as const };
+ const running = { ...DEFAULTS, gpu_memory_mode: "manual" as const };
+ // Manual with the layers themselves on Auto: still not compared, same as the backend.
+ assert.equal(
+ matches(
+ { ...running, gpu_layers: -1, n_cpu_moe: 0 },
+ { ...manual, gpuLayers: -1, nCpuMoe: 8 },
+ ),
+ true,
+ );
+ // Manual with a real pin: compared, and a difference is a reload.
+ assert.equal(
+ matches(
+ { ...running, gpu_layers: 4, n_cpu_moe: 0 },
+ { ...manual, gpuLayers: 4, nCpuMoe: 8 },
+ ),
+ false,
+ );
+});
+
+test("a standalone .gguf never reaches the drafter retry arm", () => {
+ // The arm is guarded on `intent.gguf_path is None`, and the route sets that field from
+ // the identifier alone, so a directly loaded file dedupes rather than retrying the
+ // fetch. Recorded as a note when the rest of this arm was mirrored, closed now.
+ const status = {
+ spec_fallback_reason: "drafter_not_found",
+ spec_drafter_kind: "mtp",
+ };
+ assert.equal(residentSpeculativeNeedsRepair(status, "auto", true), false);
+ // A repo id sends no path, so the retry still applies there.
+ assert.equal(residentSpeculativeNeedsRepair(status, "auto", false), true);
+ // It only excuses this arm: a binary stand-down repairs whatever the pick names.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "binary_no_mtp",
+ spec_fallback_binary_changed: true,
+ },
+ "auto",
+ true,
+ ),
+ true,
+ );
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ { spec_fallback_reason: null, spec_probe_retry_pending: true },
+ "auto",
+ true,
+ ),
+ true,
+ );
+});
+
+test("a permanently absent drafter does not decline the shortcut", () => {
+ // The drafter_not_found arm reloads so the next Apply retries the fetch, and excludes
+ // the two kinds whose absence is not transient. Retrying either relaunches forever.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "drafter_not_found",
+ spec_drafter_kind: "dspark",
+ spec_dspark_sidecar_absent: true,
+ },
+ "auto",
+ ),
+ false,
+ );
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "drafter_not_found",
+ spec_drafter_kind: "dflash",
+ },
+ "auto",
+ ),
+ false,
+ );
+ // A DSpark fetch that merely failed is still worth retrying.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "drafter_not_found",
+ spec_drafter_kind: "dspark",
+ spec_dspark_sidecar_absent: false,
+ },
+ "auto",
+ ),
+ true,
+ );
+ // As is an MTP drafter, which the arm never excluded.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ { spec_fallback_reason: "drafter_not_found", spec_drafter_kind: "mtp" },
+ "auto",
+ ),
+ true,
+ );
+ // A backend too old to report the sidecar keeps the coarser answer.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "drafter_not_found",
+ spec_drafter_kind: "dspark",
+ },
+ "auto",
+ ),
+ true,
+ );
+ // DFlash still declines through its own retry flag, which is the arm that owns it.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ {
+ spec_fallback_reason: "drafter_not_found",
+ spec_drafter_kind: "dflash",
+ spec_dflash_retry_pending: true,
+ },
+ "auto",
+ ),
+ true,
+ );
+});
+
+test("a tensor split the architecture gate normalized away still matches", () => {
+ // The gate rewrites a tensor-parallel request to layer mode, so status reports false
+ // for a launch the request produced, and the backend accepts the same true request
+ // back. Comparing raw prompted on every re-pick of a model whose split was gated off.
+ const gated = {
+ ...DEFAULTS,
+ tensor_parallel: false,
+ tensor_parallel_dropped_by_arch_gate: true,
+ };
+ assert.equal(matches(gated, { ...BLANK, tensorParallel: true }), true);
+ // Without the drop it is an ordinary disagreement.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, tensor_parallel: false },
+ { ...BLANK, tensorParallel: true },
+ ),
+ false,
+ );
+ // A backend too old to report the drop keeps the coarser answer.
+ assert.equal(
+ matches(
+ {
+ ...DEFAULTS,
+ tensor_parallel: false,
+ tensor_parallel_dropped_by_arch_gate: null,
+ },
+ { ...BLANK, tensorParallel: true },
+ ),
+ false,
+ );
+ // It only ever excuses a true request: a pick asking for no split against a runtime
+ // that has one is still a reload.
+ assert.equal(
+ matches(
+ {
+ ...DEFAULTS,
+ tensor_parallel: true,
+ tensor_parallel_dropped_by_arch_gate: true,
+ },
+ BLANK,
+ ),
+ false,
+ );
+});
+
+test("the arch-gate excuse reads the resolved split, not the toggle", () => {
+ // resolve_tensor_parallel lets --split-mode tensor in the pass-through args ask for a
+ // split the toggle does not, and that is the request the gate dropped. Reading the raw
+ // toggle here made the excuse miss exactly the configs it exists for.
+ assert.equal(
+ matches(
+ {
+ ...DEFAULTS,
+ tensor_parallel: false,
+ tensor_parallel_dropped_by_arch_gate: true,
+ requested_llama_extra_args: ["--split-mode", "tensor"],
+ },
+ {
+ ...BLANK,
+ tensorParallel: false,
+ llamaExtraArgs: ["--split-mode", "tensor"],
+ },
+ ),
+ true,
+ );
+ // Pass-through args turning the split OFF leave nothing for the gate to have dropped,
+ // so that arm answers on the resolved mode alone, as it did before.
+ assert.equal(
+ matches(
+ {
+ ...DEFAULTS,
+ tensor_parallel: true,
+ requested_llama_extra_args: ["-sm", "layer"],
+ },
+ { ...BLANK, tensorParallel: true, llamaExtraArgs: ["-sm", "layer"] },
+ ),
+ false,
+ );
+});
+
+test("a malformed manual layer override declines rather than normalizing away", () => {
+ // parse_gpu_layers_override RAISES on these, so the load fails and says so. Folding
+ // them into "no override" here stripped the token, found the rest agreeable, adopted,
+ // and the saved setting went missing without a word. Reachable from an Apply that
+ // persisted the config before its load failed.
+ const running = {
+ ...DEFAULTS,
+ gpu_memory_mode: "manual" as const,
+ gpu_layers: 20,
+ requested_llama_extra_args: [],
+ };
+ const manual = { ...BLANK, gpuMemoryMode: "manual" as const, gpuLayers: 20 };
+ for (const bad of [["-ngl", "-2"], ["--gpu-layers=many"], ["-ngl", "20.5"]]) {
+ assert.equal(matches(running, { ...manual, llamaExtraArgs: bad }), false);
+ }
+ // A well-formed override is still read, not refused.
+ assert.equal(
+ matches(
+ { ...running, gpu_layers: 99 },
+ {
+ ...manual,
+ llamaExtraArgs: ["-ngl", "99"],
+ },
+ ),
+ true,
+ );
+ // Automatic never reaches the parser: the args go through untouched and the backend
+ // decides, so a bad token there is not this comparison's to judge.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_llama_extra_args: ["-ngl", "-2"] },
+ {
+ ...BLANK,
+ gpuMemoryMode: "auto" as const,
+ llamaExtraArgs: ["-ngl", "-2"],
+ },
+ ),
+ true,
+ );
+});
+
+test("a virtualised Metal host cannot disagree about placement", () => {
+ // paravirtual_normalized_request rewrites every GGUF request to manual / zero layers /
+ // no split / no MoE, and adopt_load_intent_if_matched applies it before comparing, so
+ // an Auto pick against the resident manual status is the SAME request. Comparing raw
+ // reloaded on every re-pick, which on such a host is every re-pick there is.
+ const pv = {
+ ...DEFAULTS,
+ gpu_placement_paravirtual: true,
+ gpu_memory_mode: "manual" as const,
+ gpu_layers: 0,
+ tensor_parallel: false,
+ };
+ assert.equal(matches(pv, BLANK), true);
+ assert.equal(
+ matches(pv, { ...BLANK, gpuLayers: 40, nCpuMoe: 8, tensorParallel: true }),
+ true,
+ );
+ assert.equal(
+ matches(
+ { ...pv, requested_gpu_ids: null },
+ { ...BLANK, selectedGpuIds: [1] },
+ ),
+ true,
+ );
+ // Placement only: everything else still decides.
+ assert.equal(matches({ ...pv, cache_type_kv: "q8_0" }, BLANK), false);
+ // And a physical Mac is judged normally.
+ assert.equal(
+ matches({ ...DEFAULTS, gpu_memory_mode: "manual", gpu_layers: 0 }, BLANK),
+ false,
+ );
+});
+
+test("a diffusion resident is not judged on the chat-only invocation fields", () => {
+ // The diffusion runner receives no --parallel, no batch sizes and no pass-through args.
+ // _runtime_matches_intent guards all four on `not self._is_diffusion`, and
+ // _llama_runtime_fields nulls the ones the status publishes at all, so a config that
+ // pins any of them rejected a load the backend would have deduplicated.
+ const diffusion = {
+ ...DEFAULTS,
+ is_diffusion: true,
+ requested_parallel_slots: null,
+ requested_n_batch: null,
+ requested_n_ubatch: null,
+ requested_llama_extra_args: null,
+ };
+ assert.equal(
+ matches(diffusion, {
+ ...BLANK,
+ nParallel: 2,
+ nBatch: 2048,
+ nUbatch: 512,
+ llamaExtraArgs: ["--flash-attn", "on"],
+ }),
+ true,
+ );
+ // A chat resident with the same status is judged on all four.
+ assert.equal(
+ matches({ ...diffusion, is_diffusion: false }, { ...BLANK, nParallel: 2 }),
+ false,
+ );
+ // And a real difference outside those four still reloads on diffusion.
+ assert.equal(matches({ ...diffusion, cache_type_kv: "q8_0" }, BLANK), false);
+});
+
+test("a dropped diffusion split is rechecked once the shim can apply it", () => {
+ // diffusion_requested_ngl retains the request even when an older shim ignored it, so
+ // once the installed shim gains --ngl support the same request must go through and
+ // finally apply the split. _runtime_matches_intent rejects it for exactly that window.
+ const manual = { ...BLANK, gpuMemoryMode: "manual" as const, gpuLayers: 12 };
+ const dropped = {
+ ...DEFAULTS,
+ is_diffusion: true,
+ diffusion_requested_ngl: 12,
+ gpu_layers: 0,
+ };
+ assert.equal(
+ matches({ ...dropped, diffusion_split_supported: true }, manual),
+ false,
+ );
+ // Still no support: the request is as satisfied as it can be, so this adopts.
+ assert.equal(
+ matches({ ...dropped, diffusion_split_supported: false }, manual),
+ true,
+ );
+ // A backend too old to report it keeps the coarser answer, which is to adopt.
+ assert.equal(matches(dropped, manual), true);
+ // Nothing to apply when the launch already runs the requested count.
+ assert.equal(
+ matches(
+ { ...dropped, gpu_layers: 12, diffusion_split_supported: true },
+ manual,
+ ),
+ true,
+ );
+ // And no NGL was requested at all, so there is no split to recheck.
+ assert.equal(
+ matches(
+ {
+ ...DEFAULTS,
+ is_diffusion: true,
+ diffusion_requested_ngl: null,
+ gpu_layers: 8,
+ diffusion_split_supported: true,
+ },
+ BLANK,
+ ),
+ true,
+ );
+});
+
+test("a diffusion pick is reduced to its lowest GPU, as the backend reduces it", () => {
+ // matches_gpu_ids takes [sorted(gpu_ids)[0]] for a diffusion runner, which drives one
+ // device, and the status reports only that id. Comparing the configured set rejected a
+ // runtime the backend would have called identical.
+ const diffusion = { ...DEFAULTS, is_diffusion: true, requested_gpu_ids: [1] };
+ assert.equal(matches(diffusion, { ...BLANK, selectedGpuIds: [3, 1] }), true);
+ assert.equal(matches(diffusion, { ...BLANK, selectedGpuIds: [1] }), true);
+ // A pool whose lowest is a different device is still a reload.
+ assert.equal(matches(diffusion, { ...BLANK, selectedGpuIds: [2, 3] }), false);
+ // Automatic is unchanged: nothing to reduce, and it does not adopt a pinned runtime.
+ assert.equal(matches(diffusion, BLANK), false);
+ // Chat is judged on the whole set, as before.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_gpu_ids: [1] },
+ { ...BLANK, selectedGpuIds: [3, 1] },
+ ),
+ false,
+ );
+});
+
+test("no llama.cpp invocation field decides against a non-GGUF resident", () => {
+ // The non-GGUF branch of /load checks identity and _mlx_runtime_settings_match, then
+ // answers already_loaded. Every other field here is a llama.cpp flag it never reads, so
+ // a persisted Manual mode, tensor split, slot count or batch size raised the prompt for
+ // a load that could not have changed anything.
+ const resident = { ...DEFAULTS, is_gguf: false };
+ assert.equal(
+ matches(resident, {
+ ...BLANK,
+ gpuMemoryMode: "manual",
+ gpuLayers: 20,
+ nCpuMoe: 8,
+ tensorParallel: true,
+ nParallel: 4,
+ nBatch: 2048,
+ nUbatch: 512,
+ selectedGpuIds: [1],
+ llamaExtraArgs: ["--flash-attn", "on"],
+ kvCacheDtype: "q8_0",
+ }),
+ true,
+ );
+ // The same config against a GGUF resident is judged in full.
+ assert.equal(
+ matches({ ...resident, is_gguf: true }, { ...BLANK, nParallel: 4 }),
+ false,
+ );
+});
+
+test("a diffusion resident is judged on its NGL, not on the placement fields", () => {
+ // The diffusion branch of _runtime_matches_intent replaces the placement comparison with
+ // one _diffusion_manual_ngl check, and an older shim that dropped a manual NGL leaves
+ // the status reporting Auto while the request here still says Manual.
+ const diffusion = {
+ ...DEFAULTS,
+ is_diffusion: true,
+ gpu_memory_mode: "auto" as const,
+ diffusion_requested_ngl: null,
+ };
+ // Manual with Auto layers resolves to no explicit NGL, so it agrees with the runner's
+ // default even though the modes read differently.
+ assert.equal(
+ matches(diffusion, { ...BLANK, gpuMemoryMode: "manual", gpuLayers: -1 }),
+ true,
+ );
+ // A real manual pin against a runtime that launched with none is still a reload.
+ assert.equal(
+ matches(diffusion, { ...BLANK, gpuMemoryMode: "manual", gpuLayers: 12 }),
+ false,
+ );
+ // And it adopts when the pin is the one the runner was given.
+ assert.equal(
+ matches(
+ { ...diffusion, diffusion_requested_ngl: 12 },
+ { ...BLANK, gpuMemoryMode: "manual", gpuLayers: 12 },
+ ),
+ true,
+ );
+ // The NGL comparison has no meaning off diffusion, where the modes decide as before.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, gpu_memory_mode: "auto" },
+ { ...BLANK, gpuMemoryMode: "manual", gpuLayers: -1 },
+ ),
+ false,
+ );
+});
+
+test("a model switch is judged on the defaults it resets to, not the outgoing settings", () => {
+ // The two directions the outgoing snapshot got wrong. performLoad clears the per-model
+ // fields on a switch, so the request is the defaults: a resident running them should
+ // adopt even when the outgoing model was configured, and a resident matching the
+ // outgoing settings must NOT adopt, since the load would not have asked for them.
+ const outgoing = { ...BLANK, nParallel: 4 };
+ const reset = {
+ ...DEFAULT_ISH,
+ kvCacheDtype: null,
+ tensorParallel: false,
+ };
+ assert.equal(
+ matches({ ...DEFAULTS, requested_parallel_slots: 1 }, reset, {
+ ...STANDING,
+ parallelSlots: 1,
+ }),
+ true,
+ );
+ assert.equal(
+ matches({ ...DEFAULTS, requested_parallel_slots: 4 }, reset, {
+ ...STANDING,
+ parallelSlots: 1,
+ }),
+ false,
+ );
+ // The same resident against the outgoing snapshot answers the other way round, which is
+ // what made the choice of config the whole question.
+ assert.equal(
+ matches({ ...DEFAULTS, requested_parallel_slots: 4 }, outgoing, {
+ ...STANDING,
+ parallelSlots: 1,
+ }),
+ true,
+ );
+});
+
+test("a pass-through split mode decides the tensor-parallel comparison", () => {
+ // resolve_tensor_parallel lets an explicit --split-mode last-win over the toggle before
+ // the comparator sees it, so comparing the raw toggle judged a request the server never
+ // received.
+ assert.equal(
+ matches(
+ {
+ ...DEFAULTS,
+ tensor_parallel: true,
+ requested_llama_extra_args: ["--split-mode", "tensor"],
+ },
+ {
+ ...BLANK,
+ tensorParallel: false,
+ llamaExtraArgs: ["--split-mode", "tensor"],
+ },
+ ),
+ true,
+ );
+ assert.equal(
+ matches(
+ {
+ ...DEFAULTS,
+ tensor_parallel: false,
+ requested_llama_extra_args: ["-sm", "layer"],
+ },
+ { ...BLANK, tensorParallel: true, llamaExtraArgs: ["-sm", "layer"] },
+ ),
+ true,
+ );
+ // Without an override the toggle still answers for itself.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, tensor_parallel: true },
+ { ...BLANK, tensorParallel: false },
+ ),
+ false,
+ );
+});
+
+test("a manual pass-through layer count is compared as the field it becomes", () => {
+ // The route copies the last -ngl into request.gpu_layers and strips the flag before the
+ // already-loaded comparator runs, so the resident status reports 20 and a stripped list
+ // while the config still carries the raw form.
+ const manual = { ...BLANK, gpuMemoryMode: "manual" as const };
+ const running = {
+ ...DEFAULTS,
+ gpu_memory_mode: "manual" as const,
+ gpu_layers: 20,
+ requested_llama_extra_args: ["--flash-attn", "on"],
+ };
+ assert.equal(
+ matches(running, {
+ ...manual,
+ llamaExtraArgs: ["-ngl", "20", "--flash-attn", "on"],
+ }),
+ true,
+ );
+ // A different count is still a reload.
+ assert.equal(
+ matches(running, {
+ ...manual,
+ llamaExtraArgs: ["-ngl", "8", "--flash-attn", "on"],
+ }),
+ false,
+ );
+ // Auto does not own the offload flags, so an inherited -ngl reaches the child and the
+ // list is compared as written.
+ assert.equal(
+ matches(
+ { ...DEFAULTS, requested_llama_extra_args: ["--flash-attn", "on"] },
+ { ...BLANK, llamaExtraArgs: ["-ngl", "20", "--flash-attn", "on"] },
+ ),
+ false,
+ );
+});
+
+test("a custom tensor split the config cannot carry is still a reload", () => {
+ // applyPerModelConfigToRuntime clears splitRatio, so a remembered config asks for the
+ // default distribution while the resident manual load runs a custom one.
+ assert.equal(
+ matches({ ...DEFAULTS, tensor_split: [0.7, 0.3] }, BLANK),
+ false,
+ );
+ assert.equal(
+ matches({ ...DEFAULTS, tensor_split: [0.7, 0.3] }, BLANK, {
+ ...STANDING,
+ splitRatio: [0.7, 0.3],
+ }),
+ true,
+ );
+ assert.equal(matches({ ...DEFAULTS, tensor_split: null }, BLANK), true);
+});
+
+test("a preserved Vulkan CPU fallback is not a placement disagreement", () => {
+ // _preserve_cpu_fallback_intent rewrites an eligible Auto request into the resident
+ // manual/zero-layer intent before the comparison, so /load would report already-loaded.
+ const fallback = {
+ ...DEFAULTS,
+ gpu_memory_mode: "manual" as const,
+ gpu_layers: 0,
+ cpu_fallback_reason: "vulkan_startup_crash" as const,
+ };
+ assert.equal(matches(fallback, BLANK), true);
+ // Only placement is exempt: a real setting difference still reloads.
+ assert.equal(matches({ ...fallback, cache_type_kv: "q8_0" }, BLANK), false);
+ // And only for a request the backend would actually rewrite. _cpu_fallback_request_eligible
+ // refuses one that pins its own placement.
+ assert.equal(matches(fallback, { ...BLANK, selectedGpuIds: [0] }), false);
+ assert.equal(matches(fallback, { ...BLANK, tensorParallel: true }), false);
+ assert.equal(matches(fallback, { ...BLANK, nCpuMoe: 4 }), false);
+ assert.equal(
+ matches(fallback, { ...BLANK, llamaExtraArgs: ["--device", "Vulkan0"] }),
+ false,
+ );
+ // A fallback from another cause is not this one.
+ assert.equal(
+ matches({ ...fallback, cpu_fallback_reason: null }, BLANK),
+ false,
+ );
+});
+
+test("an unset GPU memory mode is the standing preference, not silence", () => {
+ assert.equal(
+ matches({ ...DEFAULTS, gpu_memory_mode: "manual" }, BLANK),
+ false,
+ );
+ assert.equal(
+ matches({ ...DEFAULTS, gpu_memory_mode: "manual" }, BLANK, {
+ ...STANDING,
+ gpuMemoryMode: "manual",
+ }),
+ true,
+ );
+});
+
+test("unset GPU layers and CPU MoE layers resolve to Auto and 0", () => {
+ // GPU_LAYERS_AUTO is -1; a resident manual pin is a real reload. Under Manual, since
+ // that is the only mode the backend compares either knob in.
+ const manual = { ...BLANK, gpuMemoryMode: "manual" as const };
+ const running = { ...DEFAULTS, gpu_memory_mode: "manual" as const };
+ assert.equal(matches({ ...running, gpu_layers: 20 }, manual), false);
+ assert.equal(matches({ ...running, gpu_layers: -1 }, manual), true);
+ assert.equal(
+ matches(
+ { ...running, gpu_layers: 4, n_cpu_moe: 12 },
+ { ...manual, gpuLayers: 4 },
+ ),
+ false,
+ );
+ assert.equal(
+ matches(
+ { ...running, gpu_layers: 4, n_cpu_moe: 0 },
+ { ...manual, gpuLayers: 4 },
+ ),
+ true,
+ );
+ // And under Auto neither is compared: the fitter chooses the offload.
+ assert.equal(
+ matches({ ...DEFAULTS, gpu_layers: 20, n_cpu_moe: 12 }, BLANK),
+ true,
+ );
+});
+
+test("no config at all still adopts, whatever the resident runtime is", () => {
+ // Nothing to send means nothing can differ: the load path reads the live runtime, which
+ // was hydrated from the resident model.
+ assert.equal(
+ matches(
+ {
+ speculative_type: "mtp",
+ gpu_layers: 20,
+ gpu_memory_mode: "manual",
+ n_cpu_moe: 12,
+ },
+ null,
+ ),
+ true,
+ );
+});
+
+/**
+ * The nullable per-model settings are pinned for the same reason the standing four are, and
+ * the reason is the applier rather than the field's type. `applyModelLoadConfigToRuntime`
+ * writes the config over the runtime store before `selectModel` runs (`chat-page.tsx:3242`,
+ * `hub-page.tsx:1329`) and resolves each of these with `?? null`, so the snapshot
+ * `performLoad` takes reads null rather than inheriting the resident model's value. A pick
+ * that leaves the box empty is asking for the default, not for silence.
+ */
+test("unset nullable settings ask for the default, not for the resident value", () => {
+ const pinnedResident = {
+ ...DEFAULTS,
+ requested_context_length: 8192,
+ cache_type_kv: "q8_0",
+ mlx_kv_bits_requested: 4,
+ requested_parallel_slots: 4,
+ requested_n_batch: 2048,
+ requested_n_ubatch: 512,
+ chat_template_override: "{{ bos }}",
+ };
+ assert.equal(matches(pinnedResident, BLANK), false);
+ // Field by field, so a regression names itself rather than reporting one false.
+ for (const [key, value] of Object.entries({
+ requested_context_length: 8192,
+ cache_type_kv: "q8_0",
+ mlx_kv_bits_requested: 4,
+ requested_parallel_slots: 4,
+ requested_n_batch: 2048,
+ requested_n_ubatch: 512,
+ chat_template_override: "{{ bos }}",
+ })) {
+ assert.equal(
+ matches({ ...DEFAULTS, [key]: value }, BLANK),
+ false,
+ `${key} pinned on the resident load must not be adopted by a blank config`,
+ );
+ }
+ // spec_draft_n_max is the exception, and it is the backend's: _runtime_matches_intent
+ // rejects a draft-count difference only when `intent.spec_draft_n_max is not None`, so
+ // an unset limit asks for no change and /load answers already_loaded. Reloading for it
+ // could not deliver the default anyway, since that same answer leaves the count alone.
+ assert.equal(matches({ ...DEFAULTS, spec_draft_n_max: 16 }, BLANK), true);
+ assert.equal(
+ matches(
+ { ...DEFAULTS, spec_draft_n_max: 16 },
+ { ...BLANK, specDraftNMax: 8 },
+ ),
+ false,
+ );
+ // And the default-against-default case still adopts, which is the whole point of #8893.
+ assert.equal(matches(DEFAULTS, BLANK), true);
+});
+
+test("a blank chat template agrees with a load that has none", () => {
+ // Both ends trim: the applier's cleanTemplate and the load both send "" as null, so an
+ // all-whitespace override is not a difference.
+ assert.equal(
+ matches({ ...DEFAULTS, chat_template_override: "" }, BLANK),
+ true,
+ );
+ assert.equal(
+ matches(
+ { ...DEFAULTS, chat_template_override: null },
+ {
+ ...BLANK,
+ chatTemplateOverride: " ",
+ },
+ ),
+ true,
+ );
+});
+
+/**
+ * The speculative repair window. `_runtime_matches_intent` answers False for a retryable
+ * drafter failure so the next identical load fixes it, which is the only case where
+ * skipping the load is not free. Reading a permanent downgrade as repairable is the
+ * opposite failure: it would prompt to stop running chats on every re-pick, which is #8893
+ * again, and repair nothing.
+ */
+test("a retryable drafter failure declines the shortcut", () => {
+ for (const reason of [
+ "drafter_not_found",
+ "binary_no_mtp",
+ "binary_outdated",
+ ]) {
+ for (const mode of ["auto", "mtp", "mtp+ngram", "dspark", "dflash"]) {
+ assert.equal(
+ residentSpeculativeNeedsRepair({ spec_fallback_reason: reason }, mode),
+ true,
+ `${reason} under ${mode} must reload`,
+ );
+ }
+ }
+});
+
+test("an Auto-mode policy downgrade is not a repair the load can make", () => {
+ for (const reason of [
+ "drafter_no_vram",
+ "mla_mtp_disabled",
+ "runtime_error",
+ ]) {
+ assert.equal(
+ residentSpeculativeNeedsRepair({ spec_fallback_reason: reason }, "auto"),
+ false,
+ `${reason} must not reload`,
+ );
+ }
+});
+
+test("a healthy runtime and a pick wanting no drafter both stay on the shortcut", () => {
+ assert.equal(residentSpeculativeNeedsRepair({}, "auto"), false);
+ assert.equal(
+ residentSpeculativeNeedsRepair({ spec_fallback_reason: null }, "mtp"),
+ false,
+ );
+ // Speculation off: the retry arms are all guarded on a speculative mode, so a pick that
+ // asks for none has nothing to repair.
+ for (const mode of ["off", "none", "ngram"]) {
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ { spec_fallback_reason: "drafter_not_found" },
+ mode,
+ ),
+ false,
+ `${mode} must not reload`,
+ );
+ }
+ // A null resolved mode is Auto, which is a speculative mode.
+ assert.equal(
+ residentSpeculativeNeedsRepair(
+ { spec_fallback_reason: "drafter_not_found" },
+ null,
+ ),
+ true,
+ );
+});
+
+/**
+ * maxSeqLength is the one setting the comparator deliberately ignores, because no status
+ * field echoes it, and that is exactly why the shortcut has to carry it: the rollback that
+ * makes the panel agree with the resident server is the last word on a client-only cap, and
+ * it speaks for the OUTGOING model. Structural because the write happens inside selectModel
+ * against the live store rather than in this leaf.
+ */
+test("the resident shortcut keeps the picked model's own sequence cap", () => {
+ const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ const configCheck = source.search(/residentRuntimeMatchesConfig\(\s*status/);
+ const rollback = source.indexOf("restorePreviousConfig();", configCheck);
+ const reapply = source.indexOf("pickedMaxSeqLength", configCheck);
+ assert.ok(
+ rollback > 0,
+ "the shortcut no longer rolls the staged config back",
+ );
+ assert.ok(
+ reapply > rollback,
+ "the shortcut leaves the outgoing model's maxSeqLength in place",
+ );
+ const confirmPrompt = source.indexOf(
+ "await confirmStopRunningChatsIfNeeded(",
+ );
+ assert.ok(reapply < confirmPrompt, "the re-apply escaped the shortcut");
+ // An absent cap is not "leave it alone": applyPerModelConfigToRuntime resolves it to the
+ // default, so a pick without one must land on the default rather than the outgoing cap.
+ assert.match(
+ source.slice(reapply, reapply + 260),
+ /\?\?\s*defaultInferenceParams\.maxSeqLength/,
+ "an absent cap no longer resolves to the default",
+ );
+});
+
+/**
+ * The one non-settings reason the route refuses its own already-loaded answer.
+ *
+ * _reuse_loaded_gguf requires _audio_probed, and when it is false load_model reaches its
+ * fast path and re-probes there. Nothing else re-probes, so a shortcut that skips /load
+ * leaves the model's audio capabilities undetected for as long as the server runs, which
+ * is a silent loss rather than one extra reload.
+ */
+test("an outstanding audio probe keeps the shortcut from skipping the load", () => {
+ const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ const identity = source.search(/residentModelMatchesPick\(\s*status/);
+ const probe = source.indexOf("status.audio_probe_pending !== true", identity);
+ // The caller tells the repair check whether the load carries a gguf_path, since the
+ // route derives that from the identifier and the drafter retry is guarded on it.
+ assert.match(
+ source,
+ /\(loadPath \?\? modelId\)\.toLowerCase\(\)\.endsWith\("\.gguf"\)/,
+ "the repair check no longer knows whether the pick sends a path",
+ );
+ assert.ok(
+ probe > identity,
+ "the shortcut adopts a model whose audio probe never finished",
+ );
+ // Inside the verdict, so the re-read before adopting judges it again.
+ const decision = source.indexOf("const confirmedStatus", identity);
+ assert.ok(probe < decision, "the probe check escaped the residency verdict");
+ // Only an explicit true declines: a backend too old to report it behaves as before.
+ assert.match(source.slice(probe - 40, probe + 40), /!== true/);
+});
+
+/**
+ * The status that opens the window is not the one adopted.
+ *
+ * Between the first /api/inference/status and the decision there are awaits: the GPU
+ * device cache, the llama-flags catalogue, and the two server-wide settings reads. Another
+ * tab can swap the resident model inside that window, and this one is never told
+ * (subscribeModelLifecycle dispatches on its own window), so adopting the opening status
+ * would leave the picker naming this model while prompts went to the one now loaded.
+ */
+test("the shortcut re-reads and re-judges the status before adopting", () => {
+ const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ // The verdict is a named predicate, so it can be applied to more than one status.
+ assert.match(
+ source,
+ /const adoptable = \(status: InferenceStatusResponse\) =>/,
+ "the residency verdict is no longer callable against a second status",
+ );
+ const decision = source.search(
+ /const confirmedStatus = await getInferenceStatus\(\)/,
+ );
+ assert.ok(
+ decision > 0,
+ "the shortcut adopts the status it opened with, across every await above it",
+ );
+ assert.match(
+ source.slice(decision, decision + 200),
+ /if \(confirmedStatus && adoptable\(confirmedStatus\)\)/,
+ "the re-read is not judged, only fetched",
+ );
+ // And the adopted status is the fresh one, not the one the window opened with.
+ const adopt = source.indexOf("applyActiveModelStatusToStore(", decision);
+ assert.match(
+ source.slice(adopt, adopt + 60),
+ /applyActiveModelStatusToStore\(confirmedStatus/,
+ );
+ // The pick's own GPU selection survives the hydration, which would otherwise widen it
+ // back: the backend records the incoming pool when it adopts on a fitted subset, and
+ // skipping /load skips that, so the status still names the GPUs the user removed.
+ const restore = source.indexOf("selectedGpuIds: picked", decision);
+ const hydrate = source.indexOf("applyActiveModelStatusToStore(", decision);
+ assert.ok(
+ restore > hydrate,
+ "the adopted pick no longer keeps its own GPU selection",
+ );
+ // A failed re-read must not adopt either: falling out of the block reaches /load.
+ assert.ok(
+ source.indexOf("await getInferenceStatus().catch(() => null)", decision) ===
+ decision + "const confirmedStatus = ".length,
+ "the re-read no longer tolerates a failed status",
+ );
+});
+
+/**
+ * The comparison must be against what /load would send, and with no saved config that is
+ * one of two things. performLoad treats a different checkpoint or variant as a model
+ * switch and clears the per-model fields first, so on that door the request is the
+ * defaults; where nothing switches, it reads the live runtime store. Passing the absent
+ * config straight through made the gate a wildcard, adopting whatever another tab or API
+ * client had left running.
+ */
+test("with no saved config the gate compares what the load would send", () => {
+ const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ const configCheck = source.search(/residentRuntimeMatchesConfig\(\s*status/);
+ assert.ok(
+ configCheck > 0 &&
+ /const comparedConfig =\s*\n\s*pendingConfig \?\?/.test(source),
+ "the gate takes an absent config as a wildcard again",
+ );
+ // Both doors, and the reset one must not be the live store.
+ assert.match(
+ source,
+ /resetsPerModelSettings\s*\?\s*\{\s*\n\s*\.\.\.DEFAULT_PER_MODEL_CONFIG/,
+ "a model switch no longer compares against the defaults it would send",
+ );
+ assert.match(
+ source,
+ /: currentRuntimePerModelConfig\(\)\)/,
+ "a re-pick that switches nothing no longer compares against the live runtime",
+ );
+});
+
+test("adopting reseeds the slot and batch controls the rollback left behind", () => {
+ // The rollback restores the OUTGOING model's config, so the slot and batch controls in
+ // the store belong to the model the tab just left. Suppressing the model-change reseed
+ // kept them: the adopted model could run 4 slots while the control showed the outgoing
+ // count, and the next Apply saved that over it. Reachable coming back from an external
+ // provider to a still-resident GGUF, which is the case this shortcut began as.
+ const hydrator = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/chat/lib/apply-inference-status-to-store.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ assert.match(
+ hydrator.replace(/\s+/g, " "),
+ /const slotsModelChanged = hydratingExistingModel;/,
+ );
+ // Every other load-param seed at that call site already keys off the same flag, so the
+ // suppression is gone rather than merely unused.
+ assert.equal(hydrator.includes("readoptingSameModel"), false);
+ const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ assert.equal(source.includes("readoptingSameModel"), false);
+});
+
+/** The repair window is only useful if it is consulted before the reload is decided. */
+test("selectModel asks about a repairable drafter before adopting", () => {
+ const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ const repairCheck = source.indexOf("residentSpeculativeNeedsRepair(");
+ const confirmPrompt = source.indexOf(
+ "await confirmStopRunningChatsIfNeeded(",
+ );
+ assert.ok(
+ repairCheck > 0,
+ "selectModel no longer reloads a degraded drafter",
+ );
+ assert.ok(repairCheck < confirmPrompt);
+});
diff --git a/studio/frontend/tests/resident-model-match-legacy-status.test.ts b/studio/frontend/tests/resident-model-match-legacy-status.test.ts
new file mode 100644
index 00000000000..ebdf952387a
--- /dev/null
+++ b/studio/frontend/tests/resident-model-match-legacy-status.test.ts
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The arm `residentModelMatchesPick` takes when the status reports no `model_identifier`.
+ *
+ * The raw-identifier arm above settles which revision is resident. This one has no raw
+ * identifier to compare, so all that is left is a public id every snapshot of the repo
+ * shares, and adopting on it leaves the user on weights they did not pick.
+ *
+ * Reachable from a backend predating the field, and from a native lease, which withholds
+ * the raw path by design. Found by fuzzing this function against the server's own
+ * already-loaded test, `LlamaCppBackend.matches_load_source`.
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { residentModelMatchesPick } = await import(
+ "../src/features/chat/lib/resident-model-match.ts"
+);
+
+const REPO = "unsloth/Qwen3-0.6B-GGUF";
+const Q = "Q4_K_M";
+const RESIDENT_SHA = "50968a4468ef4233ed78cd7c3de230dd1d61a56b";
+const NEWER_SHA = "d7f544eead698dbd1f15126ef60b45a1e1933222";
+
+/** The cache dir holding one repo, spelled the way each host spells it. */
+const CACHE_ROOTS: Record<string, string> = {
+ linux:
+ "/home/dev/.cache/huggingface/hub/models--unsloth--Qwen3-0.6B-GGUF/snapshots/",
+ // A second disk at /mnt/<letter> is ordinary on Linux and indistinguishable from WSL
+ // to a string comparator, so it is its own host here.
+ linuxMounted: "/mnt/d/hf/hub/models--unsloth--Qwen3-0.6B-GGUF/snapshots/",
+ mac: "/Users/dev/.cache/huggingface/hub/models--unsloth--Qwen3-0.6B-GGUF/snapshots/",
+ wsl: "/mnt/c/Users/dev/hf/hub/models--unsloth--Qwen3-0.6B-GGUF/snapshots/",
+ windows: "D:\\hf\\hub\\models--unsloth--Qwen3-0.6B-GGUF\\snapshots\\",
+ windowsForwardSlashes:
+ "D:/hf/hub/models--unsloth--Qwen3-0.6B-GGUF/snapshots/",
+ unc: "\\\\nas\\hf\\hub\\models--unsloth--Qwen3-0.6B-GGUF\\snapshots\\",
+};
+
+for (const [host, root] of Object.entries(CACHE_ROOTS)) {
+ const resident = `${root}${RESIDENT_SHA}`;
+ const newer = `${root}${NEWER_SHA}`;
+
+ test(`[${host}] a status with no raw identifier does not adopt a different snapshot`, () => {
+ assert.equal(
+ residentModelMatchesPick(
+ // What an install predating model_identifier publishes: the repo id, the same
+ // string for every revision in the cache.
+ { active_model: REPO, gguf_variant: Q },
+ { id: REPO, loadPath: newer, ggufVariant: Q },
+ ),
+ false,
+ );
+ });
+
+ test(`[${host}] the same shape still adopts the snapshot that is actually resident`, () => {
+ // The control: without it the test above passes for a function that never adopts.
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: resident, gguf_variant: Q },
+ { id: REPO, loadPath: resident, ggufVariant: Q },
+ ),
+ true,
+ );
+ });
+
+ test(`[${host}] a null identifier is treated the same as an absent one`, () => {
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: REPO, model_identifier: null, gguf_variant: Q },
+ { id: REPO, loadPath: newer, ggufVariant: Q },
+ ),
+ false,
+ );
+ });
+
+ test(`[${host}] the raw identifier, when present, still settles it`, () => {
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: REPO, model_identifier: resident, gguf_variant: Q },
+ { id: REPO, loadPath: resident, ggufVariant: Q },
+ ),
+ true,
+ );
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: REPO, model_identifier: resident, gguf_variant: Q },
+ { id: REPO, loadPath: newer, ggufVariant: Q },
+ ),
+ false,
+ );
+ });
+}
+
+test("an unpinned pick is its own load id, so the public id still answers", () => {
+ // No loadPath: the repo id is what the server was given, so there is no revision the
+ // comparison could be wrong about.
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: REPO, gguf_variant: Q },
+ { id: REPO, ggufVariant: Q },
+ ),
+ true,
+ );
+});
+
+test("a native lease keeps matching on the label it was granted under", () => {
+ // What the public-id arm exists for: a bare label is not a cache snapshot, so the
+ // refusal above must not reach it.
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: "Qwen3-0.6B-Q4_K_M.gguf", model_identifier: null },
+ { id: "Qwen3-0.6B-Q4_K_M.gguf" },
+ ),
+ true,
+ );
+});
+
+test("a standalone .gguf is not adopted on its stem alone", () => {
+ // Two directories can each hold a Qwen3-0.6B-Q4_K_M.gguf, so the stem is shareable and
+ // residentModelIdMatches takes its public pass only for a namespaced repo id.
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: "Qwen3-0.6B-Q4_K_M", gguf_variant: Q },
+ { id: "/srv/models/Qwen3-0.6B-Q4_K_M.gguf" },
+ ),
+ false,
+ );
+ // With the raw identifier there is nothing to guess about, and it adopts.
+ assert.equal(
+ residentModelMatchesPick(
+ {
+ active_model: "Qwen3-0.6B-Q4_K_M",
+ model_identifier: "/srv/models/Qwen3-0.6B-Q4_K_M.gguf",
+ gguf_variant: Q,
+ },
+ { id: "/srv/models/Qwen3-0.6B-Q4_K_M.gguf" },
+ ),
+ true,
+ );
+});
+
+test("a models-- dir that is not the cache layout is not treated as a snapshot", () => {
+ // hf_cache_repo_id only recognises models--*/snapshots/*, so a blobs dir has no revision
+ // to be wrong about and the public-id arm still applies.
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: "unsloth/Qwen3-0.6B-GGUF", gguf_variant: Q },
+ {
+ id: "/hf/hub/models--unsloth--Qwen3-0.6B-GGUF/blobs/abc",
+ ggufVariant: Q,
+ },
+ ),
+ false,
+ );
+});
diff --git a/studio/frontend/tests/resident-model-match-matrix.test.ts b/studio/frontend/tests/resident-model-match-matrix.test.ts
new file mode 100644
index 00000000000..bf2112035dc
--- /dev/null
+++ b/studio/frontend/tests/resident-model-match-matrix.test.ts
@@ -0,0 +1,410 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * A wrong TRUE here keeps weights the user did not ask for; a wrong FALSE reloads for
+ * nothing. Both answers depend on strings the BACKEND chose, which differ on two axes:
+ *
+ * host a snapshot path is POSIX on Linux and macOS, a drive path or UNC share on
+ * Windows, /mnt/<letter> under WSL; separators and case fold differently
+ * version older backends published no model_identifier, or put the RAW path in
+ * active_model; a native lease withholds it on every version
+ *
+ * The table is those two crossed with the model kinds Studio loads. Every row states the
+ * answer the USER needs, not the one the code happens to give.
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { residentModelMatchesPick } = await import(
+ "../src/features/chat/lib/resident-model-match.ts"
+);
+
+type Row = {
+ host: string;
+ what: string;
+ status: {
+ active_model?: string | null;
+ model_identifier?: string | null;
+ gguf_variant?: string | null;
+ };
+ pick: { id: string; loadPath?: string | null; ggufVariant?: string | null };
+ resident: boolean;
+};
+
+const REPO = "unsloth/Qwen3-0.6B-GGUF";
+const OTHER = "unsloth/gemma-4-12b-GGUF";
+const Q = "Q4_K_M";
+
+// One snapshot of one repo, spelled the way each host spells it.
+const SNAP = {
+ linux:
+ "/home/dev/.cache/huggingface/hub/models--unsloth--Qwen3-0.6B-GGUF/snapshots/a1b2c3",
+ mac: "/Users/dev/.cache/huggingface/hub/models--unsloth--Qwen3-0.6B-GGUF/snapshots/a1b2c3",
+ win: "D:\\models\\hub\\models--unsloth--Qwen3-0.6B-GGUF\\snapshots\\a1b2c3",
+ unc: "\\\\nas\\models\\hub\\models--unsloth--Qwen3-0.6B-GGUF\\snapshots\\a1b2c3",
+ wsl: "/mnt/c/Users/dev/models/hub/models--unsloth--Qwen3-0.6B-GGUF/snapshots/a1b2c3",
+};
+
+const FILE = {
+ linux: "/home/dev/models/Qwen3-0.6B-Q4_K_M.gguf",
+ mac: "/Users/dev/models/Qwen3-0.6B-Q4_K_M.gguf",
+ win: "C:\\Users\\dev\\models\\Qwen3-0.6B-Q4_K_M.gguf",
+ wsl: "/mnt/c/Users/dev/models/Qwen3-0.6B-Q4_K_M.gguf",
+};
+
+const ROWS: Row[] = [];
+
+// ── The pinned cached row, the shape #8893 was reported on ───────────────────
+for (const [host, snap] of Object.entries(SNAP)) {
+ ROWS.push({
+ host,
+ what: "the picker row's repo id names the resident snapshot it loaded from",
+ status: { active_model: REPO, model_identifier: snap, gguf_variant: Q },
+ pick: { id: REPO, loadPath: snap, ggufVariant: Q },
+ resident: true,
+ });
+ ROWS.push({
+ host,
+ what: "a different quant of that same snapshot is a real reload",
+ status: { active_model: REPO, model_identifier: snap, gguf_variant: Q },
+ pick: { id: REPO, loadPath: snap, ggufVariant: "Q8_0" },
+ resident: false,
+ });
+ ROWS.push({
+ host,
+ what: "a newer snapshot of the resident repo is a real reload",
+ status: { active_model: REPO, model_identifier: snap, gguf_variant: Q },
+ pick: {
+ id: REPO,
+ loadPath: snap.replace("a1b2c3", "d4e5f6"),
+ ggufVariant: Q,
+ },
+ resident: false,
+ });
+ ROWS.push({
+ host,
+ what: "another repo entirely is a real reload",
+ status: { active_model: REPO, model_identifier: snap, gguf_variant: Q },
+ pick: {
+ id: OTHER,
+ loadPath: snap.replace("Qwen3-0.6B", "gemma-4-12b"),
+ ggufVariant: Q,
+ },
+ resident: false,
+ });
+ ROWS.push({
+ host,
+ what: "quant labels differing only in case name the same weights",
+ status: { active_model: REPO, model_identifier: snap, gguf_variant: Q },
+ pick: { id: REPO, loadPath: snap, ggufVariant: Q.toLowerCase() },
+ resident: true,
+ });
+ ROWS.push({
+ host,
+ what: "a quant label the user's browser padded still names the same weights",
+ status: {
+ active_model: REPO,
+ model_identifier: snap,
+ gguf_variant: ` ${Q} `,
+ },
+ pick: { id: REPO, loadPath: snap, ggufVariant: Q },
+ resident: true,
+ });
+}
+
+// ── Windows spells one directory several ways, and means one directory ───────
+ROWS.push({
+ host: "win",
+ what: "forward slashes name the same directory as backslashes",
+ status: { active_model: REPO, model_identifier: SNAP.win, gguf_variant: Q },
+ pick: { id: REPO, loadPath: SNAP.win.replace(/\\/g, "/"), ggufVariant: Q },
+ resident: true,
+});
+ROWS.push({
+ host: "win",
+ what: "a drive letter's case does not change the directory",
+ status: { active_model: REPO, model_identifier: SNAP.win, gguf_variant: Q },
+ pick: { id: REPO, loadPath: SNAP.win.toLowerCase(), ggufVariant: Q },
+ resident: true,
+});
+ROWS.push({
+ host: "win",
+ what: "a trailing separator does not change the directory",
+ status: {
+ active_model: REPO,
+ model_identifier: `${SNAP.win}\\`,
+ gguf_variant: Q,
+ },
+ pick: { id: REPO, loadPath: SNAP.win, ggufVariant: Q },
+ resident: true,
+});
+ROWS.push({
+ host: "unc",
+ what: "a UNC share compares case-insensitively like the rest of Windows",
+ status: { active_model: REPO, model_identifier: SNAP.unc, gguf_variant: Q },
+ pick: { id: REPO, loadPath: SNAP.unc.toUpperCase(), ggufVariant: Q },
+ resident: true,
+});
+
+// ── POSIX is case-SENSITIVE, and two files can differ by case alone ──────────
+ROWS.push({
+ host: "linux",
+ what: "two snapshot dirs differing only in case are different directories",
+ status: { active_model: REPO, model_identifier: SNAP.linux, gguf_variant: Q },
+ pick: { id: REPO, loadPath: SNAP.linux.toUpperCase(), ggufVariant: Q },
+ resident: false,
+});
+ROWS.push({
+ host: "mac",
+ what: "the same holds for a mac home directory",
+ status: { active_model: REPO, model_identifier: SNAP.mac, gguf_variant: Q },
+ pick: {
+ id: REPO,
+ loadPath: SNAP.mac.replace("/Users/dev", "/Users/DEV"),
+ ggufVariant: Q,
+ },
+ resident: false,
+});
+
+// ── The unpinned cached row: the repo id IS the load identifier ──────────────
+for (const host of ["linux", "mac", "win", "wsl"]) {
+ ROWS.push({
+ host,
+ what: "a repo that loads by its own id is resident under that id",
+ status: { active_model: REPO, model_identifier: REPO, gguf_variant: Q },
+ pick: { id: REPO, loadPath: REPO, ggufVariant: Q },
+ resident: true,
+ });
+ ROWS.push({
+ host,
+ what: "a row carrying no pin still names the repo it loaded by id",
+ status: { active_model: REPO, model_identifier: REPO, gguf_variant: Q },
+ pick: { id: REPO, ggufVariant: Q },
+ resident: true,
+ });
+}
+
+// ── A standalone .gguf: one file, no quant to choose between ─────────────────
+for (const [host, file] of Object.entries(FILE)) {
+ ROWS.push({
+ host,
+ what: "a standalone file matches the quant label the backend read off its name",
+ status: { active_model: file, model_identifier: file, gguf_variant: Q },
+ pick: { id: file },
+ resident: true,
+ });
+ ROWS.push({
+ host,
+ what: "a different file in the same directory is a real reload",
+ status: { active_model: file, model_identifier: file, gguf_variant: Q },
+ pick: { id: file.replace("Qwen3-0.6B", "gemma-4-12b") },
+ resident: false,
+ });
+ ROWS.push({
+ host,
+ what: "the same file name in another directory is a different file",
+ status: { active_model: file, model_identifier: file, gguf_variant: Q },
+ pick: { id: file.replace("models", "models-old") },
+ resident: false,
+ });
+}
+
+// ── Safetensors and MLX: no quant at all on either side ──────────────────────
+ROWS.push({
+ host: "mac",
+ what: "an MLX repo is resident under its own id with no variant either side",
+ status: {
+ active_model: "mlx-community/Qwen3-0.6B-4bit",
+ model_identifier: "mlx-community/Qwen3-0.6B-4bit",
+ },
+ pick: { id: "mlx-community/Qwen3-0.6B-4bit" },
+ resident: true,
+});
+ROWS.push({
+ host: "linux",
+ what: "a safetensors repo is resident under its own id",
+ status: {
+ active_model: "unsloth/Qwen3-0.6B",
+ model_identifier: "unsloth/Qwen3-0.6B",
+ },
+ pick: { id: "unsloth/Qwen3-0.6B" },
+ resident: true,
+});
+ROWS.push({
+ host: "linux",
+ what: "a LoRA adapter is not its base model",
+ status: {
+ active_model: "unsloth/Qwen3-0.6B",
+ model_identifier: "unsloth/Qwen3-0.6B",
+ },
+ pick: { id: "dev/my-qwen3-lora" },
+ resident: false,
+});
+ROWS.push({
+ host: "linux",
+ what: "two adapters sharing a base are not each other",
+ status: { active_model: "dev/lora-a", model_identifier: "dev/lora-a" },
+ pick: { id: "dev/lora-b" },
+ resident: false,
+});
+
+// ── Nothing is loaded ────────────────────────────────────────────────────────
+for (const active of [null, undefined, ""]) {
+ ROWS.push({
+ host: "any",
+ what: `nothing resident (active_model ${JSON.stringify(active)}) matches nothing`,
+ status: {
+ active_model: active,
+ model_identifier: SNAP.linux,
+ gguf_variant: Q,
+ },
+ pick: { id: REPO, loadPath: SNAP.linux, ggufVariant: Q },
+ resident: false,
+ });
+}
+
+// ── Older Studio backends, i.e. an install that predates these fields ────────
+ROWS.push({
+ host: "old-install",
+ what: "a status with no model_identifier field falls back to the display id",
+ status: { active_model: REPO, gguf_variant: Q },
+ pick: { id: REPO, ggufVariant: Q },
+ resident: true,
+});
+ROWS.push({
+ host: "old-install",
+ what: "a backend that put the raw path in active_model still matches its own pick",
+ status: { active_model: SNAP.linux, gguf_variant: Q },
+ pick: { id: REPO, loadPath: SNAP.linux, ggufVariant: Q },
+ resident: true,
+});
+ROWS.push({
+ host: "old-install",
+ what: "a backend reporting neither a variant nor a pick variant still matches",
+ status: { active_model: REPO },
+ pick: { id: REPO },
+ resident: true,
+});
+ROWS.push({
+ host: "old-install",
+ what: "an unversioned status must not match a different model",
+ status: { active_model: REPO, gguf_variant: Q },
+ pick: { id: OTHER, ggufVariant: Q },
+ resident: false,
+});
+
+// ── A native-lease load withholds the raw path on every version ──────────────
+ROWS.push({
+ host: "native-lease",
+ what: "a leased file matches the label it was granted under",
+ status: {
+ active_model: "Qwen3-0.6B-Q4_K_M.gguf",
+ model_identifier: null,
+ gguf_variant: Q,
+ },
+ pick: { id: "Qwen3-0.6B-Q4_K_M.gguf" },
+ resident: true,
+});
+ROWS.push({
+ host: "native-lease",
+ what: "a leased file does not match another file of the same name on disk",
+ status: {
+ active_model: "Qwen3-0.6B-Q4_K_M.gguf",
+ model_identifier: null,
+ gguf_variant: Q,
+ },
+ pick: { id: FILE.linux },
+ resident: false,
+});
+ROWS.push({
+ host: "native-lease",
+ what: "a leased file does not match a repo that happens to end in .gguf",
+ status: {
+ active_model: "Qwen3-0.6B-Q4_K_M.gguf",
+ model_identifier: null,
+ gguf_variant: Q,
+ },
+ pick: { id: "unsloth/Qwen3-0.6B-Q4_K_M.gguf" },
+ resident: false,
+});
+
+// ── The documented false negative, pinned so it cannot drift into a true ─────
+ROWS.push({
+ host: "any",
+ what:
+ "a bare repo-id pick does NOT adopt a snapshot-resident model, and must not: " +
+ "the backend would not reuse that load either, so the reload is the honest answer",
+ status: { active_model: REPO, model_identifier: SNAP.linux, gguf_variant: Q },
+ pick: { id: REPO, ggufVariant: Q },
+ resident: false,
+});
+
+for (const row of ROWS) {
+ test(`[${row.host}] ${row.what}`, () => {
+ assert.equal(
+ residentModelMatchesPick(row.status, row.pick),
+ row.resident,
+ `${JSON.stringify(row.status)} vs ${JSON.stringify(row.pick)}`,
+ );
+ });
+}
+
+test("the matrix covers every host and backend shape it claims to", () => {
+ const hosts = new Set(ROWS.map((row) => row.host));
+ for (const expected of [
+ "linux",
+ "mac",
+ "win",
+ "unc",
+ "wsl",
+ "old-install",
+ "native-lease",
+ ]) {
+ assert.ok(hosts.has(expected), `no rows for ${expected}`);
+ }
+ assert.ok(ROWS.length >= 60, `only ${ROWS.length} rows`);
+ // Both answers must be exercised, or the table proves only that it never matches.
+ assert.ok(ROWS.some((row) => row.resident));
+ assert.ok(ROWS.some((row) => !row.resident));
+});
+
+/**
+ * A KNOWN limit, pinned here so it is a decision rather than a surprise.
+ *
+ * normalizeModelIdentity folds case under /mnt/<single letter>/ because that is where WSL
+ * mounts a Windows drive, and Windows is case-insensitive. A Linux host with a real
+ * single-letter mount point gets the same treatment, so two files there differing only in
+ * case read as one. Fixing it needs a platform signal the browser does not have, and the
+ * comparator is shared with the Hub, so this stays as-is: the cost is one skipped reload
+ * for a path shape no Studio install creates on its own.
+ */
+test("case folding under /mnt/<letter> is WSL-shaped, and known to over-match on Linux", () => {
+ assert.equal(
+ residentModelMatchesPick(
+ {
+ active_model: "/mnt/d/models/Model.gguf",
+ model_identifier: "/mnt/d/models/Model.gguf",
+ gguf_variant: Q,
+ },
+ { id: "/mnt/d/models/model.gguf" },
+ ),
+ true,
+ );
+ // Any other Linux mount point is compared case-sensitively, as it must be.
+ assert.equal(
+ residentModelMatchesPick(
+ {
+ active_model: "/mnt/disks/models/Model.gguf",
+ model_identifier: "/mnt/disks/models/Model.gguf",
+ gguf_variant: Q,
+ },
+ { id: "/mnt/disks/models/model.gguf" },
+ ),
+ false,
+ );
+});
diff --git a/studio/frontend/tests/resident-model-match.test.ts b/studio/frontend/tests/resident-model-match.test.ts
new file mode 100644
index 00000000000..30d9bd37f16
--- /dev/null
+++ b/studio/frontend/tests/resident-model-match.test.ts
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * #8893: picking the model that is already loaded raised "Stop 1 running chat?" and reloaded
+ * it. The pick and the status name one model with different strings -- a cached row pinned to
+ * a snapshot dir loads by path while its picker row keeps the repo id -- so comparing the row
+ * id against the status checkpoint alone read a resident model as a different one.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { residentModelMatchesPick } = await import(
+ "../src/features/chat/lib/resident-model-match.ts"
+);
+
+const REPO_ID = "unsloth/Qwen3.5-9B-GGUF";
+const SNAPSHOT =
+ "D:\\models\\hub\\models--unsloth--Qwen3.5-9B-GGUF\\snapshots\\a1b2c3";
+
+/** What /api/inference/status publishes for a pinned cached row: the clean public id next to
+ * the raw path the load actually ran as. */
+const pinnedStatus = {
+ active_model: REPO_ID,
+ model_identifier: SNAPSHOT,
+ gguf_variant: "Q4_K_M",
+};
+
+test("the picker row id names the resident model behind a snapshot path", () => {
+ assert.equal(
+ residentModelMatchesPick(pinnedStatus, {
+ id: REPO_ID,
+ loadPath: SNAPSHOT,
+ ggufVariant: "Q4_K_M",
+ }),
+ true,
+ );
+});
+
+test("the load path alone names the resident model", () => {
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: REPO_ID, model_identifier: SNAPSHOT },
+ { id: "Qwen3.5-9B", loadPath: SNAPSHOT },
+ ),
+ true,
+ );
+});
+
+// windows reports the same directory under either separator and either case
+test("a path naming the same file matches whatever its separators", () => {
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: SNAPSHOT, model_identifier: SNAPSHOT },
+ { id: SNAPSHOT.replace(/\\/g, "/").toLowerCase() },
+ ),
+ true,
+ );
+});
+
+test("a different quant of the same repo is a real reload", () => {
+ assert.equal(
+ residentModelMatchesPick(pinnedStatus, {
+ id: REPO_ID,
+ loadPath: SNAPSHOT,
+ ggufVariant: "Q8_0",
+ }),
+ false,
+ );
+});
+
+/** A local file load derives its quant label from the filename, so the status reports one the
+ * picker row never carries. Comparing them left the reported bug in place for On Device files. */
+test("a standalone .gguf matches the label the backend derived for it", () => {
+ assert.equal(
+ residentModelMatchesPick(
+ {
+ active_model: "/Users/dev/models/Qwen3-8B-Q4_K_M.gguf",
+ model_identifier: "/Users/dev/models/Qwen3-8B-Q4_K_M.gguf",
+ gguf_variant: "Q4_K_M",
+ },
+ { id: "/Users/dev/models/Qwen3-8B-Q4_K_M.gguf" },
+ ),
+ true,
+ );
+});
+
+/** The exemption is for the file's own derived label, not for picking a different quant. */
+test("a repo row still has to name the resident quant", () => {
+ assert.equal(
+ residentModelMatchesPick(pinnedStatus, {
+ id: REPO_ID,
+ ggufVariant: undefined,
+ }),
+ false,
+ );
+});
+
+/** A repo that advanced to a newer snapshot reports the same public id for both, and the
+ * inventory repoints load_id at the newest, so matching on the id alone kept stale weights. */
+test("a newer snapshot of the resident repo is a real reload", () => {
+ assert.equal(
+ residentModelMatchesPick(pinnedStatus, {
+ id: REPO_ID,
+ loadPath: `${SNAPSHOT.slice(0, SNAPSHOT.lastIndexOf("\\"))}\\d4e5f6`,
+ ggufVariant: "Q4_K_M",
+ }),
+ false,
+ );
+});
+
+test("another model does not match the resident one", () => {
+ assert.equal(
+ residentModelMatchesPick(pinnedStatus, {
+ id: "unsloth/gemma-4-12b-GGUF",
+ ggufVariant: "Q4_K_M",
+ }),
+ false,
+ );
+});
+
+test("nothing resident matches nothing", () => {
+ assert.equal(
+ residentModelMatchesPick(
+ { active_model: null, model_identifier: SNAPSHOT },
+ { id: REPO_ID, loadPath: SNAPSHOT },
+ ),
+ false,
+ );
+});
+
+/** The rules above only help if the pick is tested before the confirmation is raised: the
+ * dialog is what the report is about, and /load answers already_loaded without stopping
+ * anything. */
+test("selectModel checks residency before prompting to stop running chats", () => {
+ const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+ );
+ const residencyCheck = source.indexOf(
+ "residentModelMatchesPick(status",
+ );
+ const confirmPrompt = source.indexOf(
+ "await confirmStopRunningChatsIfNeeded(",
+ );
+ assert.ok(residencyCheck > 0, "selectModel no longer checks residency");
+ assert.ok(confirmPrompt > 0, "selectModel no longer confirms running chats");
+ assert.ok(residencyCheck < confirmPrompt);
+ // gating the check on an external checkpoint is the shape that left #8893 open
+ assert.doesNotMatch(
+ source.slice(Math.max(0, residencyCheck - 500), residencyCheck),
+ /isExternalModelId\(selectedCheckpoint\)/,
+ "the residency check is gated on an external checkpoint again",
+ );
+});
diff --git a/studio/frontend/tests/server-wide-reload.test.ts b/studio/frontend/tests/server-wide-reload.test.ts
new file mode 100644
index 00000000000..0efef0be1a9
--- /dev/null
+++ b/studio/frontend/tests/server-wide-reload.test.ts
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The two reload conditions the resident shortcut cannot see in a load intent.
+ *
+ * `adopt_load_intent_if_matched` (llama_cpp.py) returns False when
+ * `memory_state_satisfies_settings` fails or `_vram_fraction_launched` differs from the
+ * active fraction, both of them server-wide. A Model Memory or VRAM budget save between two
+ * picks of one model leaves the pick, its config and the status identical, so without these
+ * the setting would be advertised as applying on the next load and then never reach the
+ * child.
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { serverWideReloadRequired } = await import(
+ "../src/features/chat/lib/server-wide-reload.ts"
+);
+
+const NO = { reloadRequired: false } as const;
+const YES = { reloadRequired: true } as const;
+
+test("either signal alone declines the shortcut", () => {
+ assert.equal(
+ serverWideReloadRequired({ modelMemory: YES, vramBudget: NO }),
+ true,
+ );
+ assert.equal(
+ serverWideReloadRequired({ modelMemory: NO, vramBudget: YES }),
+ true,
+ );
+ assert.equal(
+ serverWideReloadRequired({ modelMemory: YES, vramBudget: YES }),
+ true,
+ );
+});
+
+test("a settled server adopts", () => {
+ assert.equal(
+ serverWideReloadRequired({ modelMemory: NO, vramBudget: NO }),
+ false,
+ );
+});
+
+test("a route this backend does not serve is not a reload", () => {
+ // An older install has no such state to disagree about, so the shortcut keeps working.
+ assert.equal(
+ serverWideReloadRequired({
+ modelMemory: "unsupported",
+ vramBudget: "unsupported",
+ }),
+ false,
+ );
+ assert.equal(
+ serverWideReloadRequired({ modelMemory: "unsupported", vramBudget: NO }),
+ false,
+ );
+});
+
+test("an answer that could not be had declines the shortcut", () => {
+ // Not symmetric with the case above. One extra reload costs the prompt this PR
+ // removes; adopting on a read that failed right after a policy save leaves the child
+ // on the old policy with nothing on screen to say so.
+ assert.equal(
+ serverWideReloadRequired({ modelMemory: "unknown", vramBudget: NO }),
+ true,
+ );
+ assert.equal(
+ serverWideReloadRequired({ modelMemory: NO, vramBudget: "unknown" }),
+ true,
+ );
+ assert.equal(
+ serverWideReloadRequired({
+ modelMemory: "unknown",
+ vramBudget: "unsupported",
+ }),
+ true,
+ );
+});
diff --git a/studio/frontend/tests/vram-budget.test.ts b/studio/frontend/tests/vram-budget.test.ts
index b23d0ef7b64..cb1c425de98 100644
--- a/studio/frontend/tests/vram-budget.test.ts
+++ b/studio/frontend/tests/vram-budget.test.ts
@@ -522,7 +522,12 @@ test("a superseded read is refused, not handed back to the caller", () => {
// "no usable answer", which every caller treats as keep what you have.
const flat = client.replace(/\s+/g, " ");
assert.match(flat, /throw new Error\("superseded"\); \}/);
- assert.match(flat, /try \{ return await inFlightVramBudget; \} catch \{/);
+ // The binding is optional: one caller inspects the error to tell an absent route from
+ // a failed read, and the contract for everyone else is still null.
+ assert.match(
+ flat,
+ /try \{ return await inFlightVramBudget; \} catch( \(error\))? \{/,
+ );
const row = vramBudgetRowSource().replace(/\s+/g, " ");
assert.match(row, /if \(cancelled \|\| !loaded\) \{ return; \}/);
});