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: apply saved per-model settings on API loads, add API monitor (#7473)

Michael Han6b0035b8e6cc
diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.py
index 641f3f626cf..52665a699b9 100644
--- a/studio/backend/core/inference/api_monitor.py
+++ b/studio/backend/core/inference/api_monitor.py
@@ -49,7 +49,10 @@ class ApiMonitorEntry:
status: str
started_at: float
updated_at: float
+ # Who this row is attributed to; on a shared row it does not restrict visibility.
subject: Optional[str] = None
+ # True for sk-unsloth callers only: the panel auto-opens on these, not Studio's chat.
+ via_api_key: bool = False
# Monotonic anchors so duration math survives wall-clock steps (NTP).
started_monotonic: float = 0.0
finished_monotonic: Optional[float] = None
@@ -69,7 +72,12 @@ class ApiMonitorEntry:
# 0-100 for a running download row; None when not applicable.
progress: Optional[float] = None
- def snapshot(self, *, include_details: bool = True) -> dict[str, Any]:
+ def snapshot(
+ self,
+ *,
+ include_details: bool = True,
+ attributed: bool = True,
+ ) -> dict[str, Any]:
duration_ms = None
if self.finished_monotonic is not None:
duration_ms = max(
@@ -86,6 +94,9 @@ class ApiMonitorEntry:
"endpoint": self.endpoint,
"method": self.method,
"model": self.model,
+ # A shared row reaches subjects with nothing to do with it, and the overlay
+ # auto-opens on this flag, so report it only to the attributed caller.
+ "via_api_key": self.via_api_key and attributed,
"prompt_preview": _trim(self.prompt, _PREVIEW_CHARS),
"reply_preview": _trim(self.reply, _PREVIEW_CHARS),
"prompt_truncated": len(self.prompt) > _PREVIEW_CHARS,
@@ -120,6 +131,8 @@ class ApiMonitor:
enabled: bool = True,
):
self._entries: deque[ApiMonitorEntry] = deque()
+ # Shared rows one subject cleared: deleting would erase another caller's history.
+ self._hidden_shared: dict[str, set[str]] = {}
self._max_entries = max(0, max_entries)
self._lock = threading.Lock()
self._enabled = enabled
@@ -139,6 +152,7 @@ class ApiMonitor:
prompt: str,
context_length: Optional[int] = None,
subject: Optional[str] = None,
+ via_api_key: bool = False,
) -> str:
if not self._enabled:
return ""
@@ -147,12 +161,14 @@ class ApiMonitor:
id = f"apireq_{uuid.uuid4().hex[:12]}",
endpoint = endpoint,
method = method,
- model = model or "default",
+ # str(): a raw JSON body can carry any type, and a non-string breaks the UI.
+ model = str(model) if model else "default",
prompt = _trim(prompt, _MAX_PROMPT_CHARS),
status = "running",
started_at = now,
updated_at = now,
subject = subject,
+ via_api_key = via_api_key,
started_monotonic = time.monotonic(),
context_length = context_length,
)
@@ -168,12 +184,18 @@ class ApiMonitor:
model: str,
reason: Optional[str] = None,
running: bool = False,
+ via_api_key: bool = False,
+ subject: Optional[str] = None,
) -> str:
"""Record a model load/unload alongside the request traffic that caused it.
``running=True`` opens the row for the caller to close with :meth:`finish` /
:meth:`fail`; an unload is terminal on arrival. Rows are shared (visible to
every subject) and share the request retention budget.
+
+ ``subject`` names the caller whose request drove this, which is what
+ ``via_api_key`` is reported to; it does not narrow who sees the row. Pass it
+ whenever ``via_api_key`` is set, or the attribution reaches nobody.
"""
if not self._enabled:
return ""
@@ -194,6 +216,12 @@ class ApiMonitor:
event = event,
reason = reason,
shared = True,
+ # The overlay opens on API-key traffic only, and a refused switch never
+ # reaches api_monitor.start, so this row is its whole trace: without the
+ # attribution the monitor stayed shut on the failures it exists to surface.
+ via_api_key = via_api_key,
+ # Shared rows reach every subject, so attribution needs an owner.
+ subject = subject,
)
with self._lock:
self._entries.appendleft(entry)
@@ -360,7 +388,10 @@ class ApiMonitor:
) -> list[dict[str, Any]]:
with self._lock:
return [
- entry.snapshot(include_details = include_details)
+ entry.snapshot(
+ include_details = include_details,
+ attributed = self._attributed(entry, subject),
+ )
for entry in self._entries
if self._visible(entry, subject)
]
@@ -377,7 +408,10 @@ class ApiMonitor:
return None
if not self._visible(entry, subject):
return None
- return entry.snapshot(include_details = True)
+ return entry.snapshot(
+ include_details = True,
+ attributed = self._attributed(entry, subject),
+ )
def active_count(self, *, subject: Optional[str] = None) -> int:
# Lifecycle rows show as "running" while loading but are not in-flight API requests.
@@ -390,13 +424,50 @@ class ApiMonitor:
and (subject is None or entry.subject == subject)
)
- def clear(self) -> None:
+ def clear(self, *, subject: Optional[str] = None) -> None:
+ """Drop recorded entries. ``subject`` limits the wipe to one caller's.
+
+ Every other read on this class is subject-scoped, so an unscoped clear
+ would let one user erase another's history (and zero their active count
+ mid-generation). Callers that genuinely mean "everything" pass None.
+ """
with self._lock:
- self._entries.clear()
+ if subject is None:
+ self._entries.clear()
+ self._hidden_shared.clear()
+ return
+ # A running shared row is a load in progress, not history, so it stays.
+ hidden = self._hidden_shared.setdefault(subject, set())
+ for entry in self._entries:
+ if entry.shared and entry.status != "running":
+ hidden.add(entry.id)
+ # Shared rows are hidden, never dropped, even when owned: they are another
+ # caller's history too. An own running row is not history either, and dropping
+ # it loses the request outright: active_count falls to zero and the finish or
+ # fail that follows has no entry left to land on.
+ self._entries = deque(
+ entry
+ for entry in self._entries
+ if entry.shared or entry.subject != subject or entry.status == "running"
+ )
+
+ def _visible(self, entry: ApiMonitorEntry, subject: Optional[str]) -> bool:
+ if subject is None:
+ return True
+ if entry.shared:
+ # Every subject minus the cleared ones. Before ownership, so a clear hides own rows.
+ return entry.id not in self._hidden_shared.get(subject, ())
+ return entry.subject == subject
- @staticmethod
- def _visible(entry: ApiMonitorEntry, subject: Optional[str]) -> bool:
- return subject is None or entry.subject == subject or entry.shared
+ def _attributed(self, entry: ApiMonitorEntry, subject: Optional[str]) -> bool:
+ """Whether *subject* is the caller this row's API traffic belongs to.
+
+ Only they should have the overlay pop open for it. An unscoped read (no
+ subject: internal callers and tests) sees the row's own flag.
+ """
+ if subject is None:
+ return True
+ return entry.subject == subject
def _find_locked(self, entry_id: str) -> Optional[ApiMonitorEntry]:
for entry in self._entries:
@@ -415,6 +486,12 @@ class ApiMonitor:
kept.append(entry)
terminal_seen += 1
self._entries = kept
+ # Keep hidden sets to live rows so they stay bounded by the ring buffer.
+ live = {entry.id for entry in kept}
+ for subject, hidden in list(self._hidden_shared.items()):
+ hidden &= live
+ if not hidden:
+ del self._hidden_shared[subject]
api_monitor = ApiMonitor(enabled = not _api_monitor_disabled())
diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.py
index 5d2a9e9c870..07d00f03741 100644
--- a/studio/backend/core/inference/local_model_resolver.py
+++ b/studio/backend/core/inference/local_model_resolver.py
@@ -47,10 +47,18 @@ _WARM_DUTY = 10.0
def _is_abs_path_id(value: str) -> bool:
"""True when an id is an absolute filesystem path (the ./models and LM Studio
- scanners use the on-disk path as the id) rather than a repo id like org/name."""
- from pathlib import Path
+ scanners use the on-disk path as the id) rather than a repo id like org/name.
+
+ Both spellings count on every host. Path() follows the running OS, so a
+ Windows backend read "/home/me/x.gguf" as relative and a POSIX one read
+ "C:\\models\\x.gguf" the same way, and either then reached /v1/models as a
+ published id. Ids outlive the machine that wrote them: settings sync, a WSL
+ session and a copied config all carry the other platform's spelling, and the
+ model-override identity already folds both. Neither reading can misfire on a
+ repo id, which has no leading separator, drive or UNC prefix."""
+ from pathlib import PurePosixPath, PureWindowsPath
try:
- return Path(value).is_absolute()
+ return PurePosixPath(value).is_absolute() or PureWindowsPath(value).is_absolute()
except Exception:
return False
diff --git a/studio/backend/core/inference/openai_auto_download.py b/studio/backend/core/inference/openai_auto_download.py
index cad5e40d14d..fa1a3b26c95 100644
--- a/studio/backend/core/inference/openai_auto_download.py
+++ b/studio/backend/core/inference/openai_auto_download.py
@@ -448,6 +448,8 @@ async def maybe_auto_download(
*,
hf_token: Optional[str] = None,
require_vision: bool = False,
+ subject: Optional[str] = None,
+ via_api_key: bool = False,
) -> Optional[AutoDownloadRefusal]:
"""Start (or report on) a background fetch of *requested_model*.
@@ -457,6 +459,10 @@ async def maybe_auto_download(
``require_vision`` refuses a target with no mmproj companion rather than spend
gigabytes on weights that cannot answer the request; the local capability guard
only ever sees an already-downloaded model.
+
+ ``subject`` and ``via_api_key`` describe the caller for the monitor row this
+ opens: the same /v1 endpoints serve Studio's own chat on a session JWT, so the
+ download is not API-key traffic unless the request that asked for it was.
"""
global _active
@@ -529,7 +535,14 @@ async def maybe_auto_download(
try:
return await _admit_and_start(
- repo_id, wanted_variant, requested_model, hf_token, provisional, require_vision
+ repo_id,
+ wanted_variant,
+ requested_model,
+ hf_token,
+ provisional,
+ require_vision,
+ subject = subject,
+ via_api_key = via_api_key,
)
except BaseException:
# Not `except Exception`: a cancel mid-probe would otherwise wedge the provisional slot.
@@ -544,6 +557,9 @@ async def _admit_and_start(
hf_token: Optional[str],
active: _Active,
require_vision: bool = False,
+ *,
+ subject: Optional[str] = None,
+ via_api_key: bool = False,
) -> Optional[AutoDownloadRefusal]:
from hub.utils.hf_errors import hf_error_status
@@ -690,7 +706,16 @@ async def _admit_and_start(
),
)
- return await _dispatch(repo_id, variant, expected_bytes, requested_model, hf_token, active)
+ return await _dispatch(
+ repo_id,
+ variant,
+ expected_bytes,
+ requested_model,
+ hf_token,
+ active,
+ subject = subject,
+ via_api_key = via_api_key,
+ )
def preferred_quant(labels) -> Optional[str]:
@@ -737,6 +762,9 @@ async def _dispatch(
requested_model: str,
hf_token: Optional[str],
active: _Active,
+ *,
+ subject: Optional[str] = None,
+ via_api_key: bool = False,
) -> AutoDownloadRefusal:
global _active
@@ -777,7 +805,16 @@ async def _dispatch(
return busy
monitor_id = api_monitor.record_lifecycle(
- event = "download", model = label, reason = "api", running = True
+ # Reason "api" since only /v1 reaches auto-download, but that is not API-key
+ # traffic: Studio's chat calls /v1 on a JWT, and marking its download would pop
+ # the overlay mid-chat. So attribution comes from the request, plus its caller,
+ # since the row is shared.
+ event = "download",
+ model = label,
+ reason = "api",
+ running = True,
+ via_api_key = via_api_key,
+ subject = subject,
)
with _lock:
if _active is active:
diff --git a/studio/backend/picker/schemas.py b/studio/backend/picker/schemas.py
index b4f956188f3..c43d769817d 100644
--- a/studio/backend/picker/schemas.py
+++ b/studio/backend/picker/schemas.py
@@ -11,13 +11,29 @@ from pydantic import BaseModel, Field, field_validator
MAX_CHAT_TEMPLATE_BYTES = 65_536
+def chat_template_byte_length(value: str) -> Optional[int]:
+ """UTF-8 length, or None if the string cannot be encoded at all.
+
+ JSON can carry an unpaired surrogate, as a truncated emoji paste produces.
+ json decodes it fine and .encode("utf-8") then raises. Callers treat None as
+ "reject": such a template can never render.
+ """
+ try:
+ return len(value.encode("utf-8"))
+ except UnicodeEncodeError:
+ return None
+
+
class ValidateChatTemplateRequest(BaseModel):
template: str = Field(default = "")
@field_validator("template")
@classmethod
def _enforce_template_size(cls, value: str) -> str:
- if len(value.encode("utf-8")) > MAX_CHAT_TEMPLATE_BYTES:
+ size = chat_template_byte_length(value)
+ if size is None:
+ raise ValueError("Chat template contains unpaired surrogate characters.")
+ if size > MAX_CHAT_TEMPLATE_BYTES:
raise ValueError(f"Chat template exceeds the {MAX_CHAT_TEMPLATE_BYTES}-byte limit.")
return value
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index ca54be44c72..bcfdf5624d3 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1885,8 +1885,29 @@ from core.inference.anthropic_compat import (
AnthropicStreamEmitter,
AnthropicPassthroughEmitter,
)
-from auth.authentication import get_current_subject
+from auth.authentication import API_KEY_PREFIX, get_current_subject
from state import active_generations
+
+
+def _request_used_api_key(request: Any) -> bool:
+ """True when this request authenticated with an sk-unsloth key.
+
+ Studio's own chat hits these same endpoints with a session JWT, so this is
+ what separates "someone is using Unsloth as an API server" from "someone is
+ using Unsloth".
+ """
+ # Total by construction: this only decides a monitor label and must never fail a
+ # load. Only a real Request hands back a string; the load routes take stand-ins too.
+ try:
+ header = request.headers.get("authorization")
+ except Exception:
+ return False
+ if not isinstance(header, str):
+ return False
+ scheme, _, token = header.partition(" ")
+ return scheme.lower() == "bearer" and token.startswith(API_KEY_PREFIX)
+
+
from state.tool_approvals import resolve_tool_decision
from core.inference.key_exchange import decrypt_api_key
@@ -4069,6 +4090,7 @@ async def _maybe_auto_download_model(
fastapi_request: Optional[Request],
*,
require_vision: bool = False,
+ current_subject: Optional[str] = None,
) -> None:
"""Opt-in: start fetching a named GGUF this server doesn't have.
@@ -4091,6 +4113,9 @@ async def _maybe_auto_download_model(
requested_model,
hf_token = _auto_download_hf_token(fastapi_request),
require_vision = require_vision,
+ subject = current_subject,
+ # These endpoints also serve Studio's chat on a JWT, so only mark real API traffic.
+ via_api_key = _request_used_api_key(fastapi_request),
)
except Exception as exc:
# Never turn a servable request into a 500 over the download attempt.
@@ -4110,6 +4135,7 @@ async def _maybe_auto_download_model(
if isinstance(path, str)
else refusal.message
)
+ _record_refused_request(fastapi_request, requested_model, refusal, current_subject)
raise HTTPException(
status_code = refusal.status,
detail = detail,
@@ -4117,6 +4143,35 @@ async def _maybe_auto_download_model(
)
+def _record_refused_request(
+ fastapi_request: Optional[Request],
+ requested_model: str,
+ refusal: Any,
+ current_subject: Optional[str],
+) -> None:
+ """Log the refused call itself, not just the download it is waiting on.
+
+ The refusal replaces the request, so the handler's own ``api_monitor.start``
+ never runs. Only the caller that dispatched a download gets a row from
+ ``record_lifecycle``; anyone refused while it runs left no trace at all, and a
+ download some other caller started carries their attribution, so an API-key
+ client waiting on it never opened the overlay and read as Studio's own traffic.
+ """
+ state = getattr(fastapi_request, "state", None)
+ if getattr(state, "skip_api_monitor", False):
+ return
+ path = getattr(getattr(fastapi_request, "url", None), "path", None)
+ entry_id = api_monitor.start(
+ endpoint = path if isinstance(path, str) else "/v1",
+ method = str(getattr(fastapi_request, "method", "") or "POST"),
+ model = requested_model,
+ prompt = "",
+ subject = current_subject,
+ via_api_key = _request_used_api_key(fastapi_request),
+ )
+ api_monitor.fail(entry_id, refusal.message)
+
+
def _loaded_satisfies(requested: str) -> bool:
"""Whether what is serving right now actually answers to *requested*.
@@ -4419,6 +4474,7 @@ async def _maybe_auto_switch_model(
get_openai_auto_switch_enabled,
get_auto_unload_idle_seconds,
get_model_override,
+ model_override_load_kwargs,
)
from core.inference.local_model_resolver import resolve_local_gguf
from core.inference.llama_keepwarm import (
@@ -4459,7 +4515,10 @@ async def _maybe_auto_switch_model(
# Not on disk. Opt-in: fetch in the background and ask the caller to retry.
if auto_switch_on and not reload_only:
await _maybe_auto_download_model(
- requested_model, fastapi_request, require_vision = require_vision
+ requested_model,
+ fastapi_request,
+ require_vision = require_vision,
+ current_subject = current_subject,
)
# Idle-unload may have freed the model; reload exactly what it freed
# (path + quant + advertised id) so an alias/unknown name stays servable
@@ -4567,22 +4626,84 @@ async def _maybe_auto_switch_model(
if _already_serving():
_record_serving_alias()
return
- # Apply this model's saved launch flags so the swap honors the config.
- override = get_model_override(override_id)
+ # Apply the saved launch config so an API swap loads as the picker
+ # would. Order: variant-qualified keys before bare ids, and the
+ # load path before the advertised id, since the settings UI keys
+ # local rows by that path while override_id is a derived alias, so
+ # reading the alias first let an older entry shadow a fresh save. A
+ # cached repo has no path entry and resolves on the second try; an
+ # early build keyed a loose .gguf by its filename label, so
+ # "<path>:LABEL" is read too, after the bare path used today.
+ file_variant = None
+ if not variant and target_id.lower().endswith(".gguf"):
+ from hub.utils.gguf import extract_quant_label
+ file_variant = extract_quant_label(os.path.basename(target_id))
+ override = {}
+ for override_key in (
+ f"{target_id}:{variant}" if variant else None,
+ f"{override_id}:{variant}" if variant else None,
+ target_id,
+ f"{target_id}:{file_variant}" if file_variant else None,
+ override_id,
+ ):
+ if not override_key:
+ continue
+ override = get_model_override(override_key)
+ if override:
+ break
load_kwargs = {"model_path": target_id, "gguf_variant": variant}
- if override.get("llama_extra_args") is not None:
- load_kwargs["llama_extra_args"] = override["llama_extra_args"]
- if override.get("max_seq_length") is not None:
- load_kwargs["max_seq_length"] = override["max_seq_length"]
+ load_kwargs.update(
+ model_override_load_kwargs(
+ override,
+ # Set for every GGUF the resolver returns; the reload
+ # stash carries the quant it froze.
+ is_gguf = bool(variant) or target_id.lower().endswith(".gguf"),
+ )
+ )
+ saved_gpu_ids = load_kwargs.get("gpu_ids")
+ if saved_gpu_ids and not await _override_gpu_ids_still_resolve(
+ saved_gpu_ids
+ ):
+ # Stale pin (GPU removed, another host): drop the one dead
+ # field rather than 400 the whole load.
+ load_kwargs.pop("gpu_ids", None)
+ logger.warning(
+ "Dropping saved gpu_ids %s for %s: not available here.",
+ saved_gpu_ids,
+ override_id,
+ )
# Reuse the load impl so its dedup, tensor fallback, and threading
# apply. Call the impl directly: we already hold the lifecycle gate
# the /load route would otherwise take, so the route would deadlock.
- await _load_model_impl(
- LoadRequest(**load_kwargs),
- fastapi_request,
- current_subject,
- current_request_counted = True,
- )
+ try:
+ await _load_model_impl(
+ LoadRequest(**load_kwargs),
+ fastapi_request,
+ current_subject,
+ current_request_counted = True,
+ )
+ except HTTPException as exc:
+ # The pre-flight check cannot mirror every loader gpu_ids rule,
+ # and a stale pin must never block a request, so retry without it.
+ if not (
+ exc.status_code == 400
+ and load_kwargs.get("gpu_ids")
+ and "gpu" in str(exc.detail).lower()
+ ):
+ raise
+ logger.warning(
+ "Retrying %s without saved gpu_ids %s: %s",
+ override_id,
+ load_kwargs.get("gpu_ids"),
+ exc.detail,
+ )
+ load_kwargs.pop("gpu_ids", None)
+ await _load_model_impl(
+ LoadRequest(**load_kwargs),
+ fastapi_request,
+ current_subject,
+ current_request_counted = True,
+ )
# Advertise the repo id (not the concrete load path) as the loaded
# model's public id and override key for /v1/models and idle stash.
get_llama_cpp_backend()._openai_advertised_id = override_id
@@ -4823,6 +4944,42 @@ def _classify_diffusion_gguf(config: ModelConfig) -> Optional[bool]:
return True if name_says_diffusion else None
+async def _override_gpu_ids_still_resolve(gpu_ids: List[int]) -> bool:
+ """Whether a per-model GPU pin is usable on this machine right now.
+
+ normalize_model_override cannot know the device list, so it stores whatever
+ was valid where the config was written. This is the load-time reconciliation
+ for the device-availability rules, which are the ones that go stale.
+
+ Deliberately not exhaustive: model-dependent rules (a Vulkan diffusion GGUF
+ refuses gpu_ids outright) need a ModelConfig this has no reason to build.
+ The caller's retry-without-the-pin covers those, and covers rules added
+ later, so a check missing here costs one extra attempt, not the load.
+ """
+ try:
+ from utils.hardware import DeviceType, get_device
+ from utils.hardware.hardware import resolve_requested_gpu_ids
+
+ is_vulkan = LlamaCppBackend._is_vulkan_backend()
+ if get_device() == DeviceType.XPU and not is_vulkan:
+ # Rejected outright on XPU.
+ return False
+ resolved = resolve_requested_gpu_ids(gpu_ids, is_vulkan = is_vulkan)
+ if is_vulkan and resolved:
+ # Vulkan ordinals are their own index space, so presence needs the ggml probe.
+ binary = LlamaCppBackend._find_llama_server_binary()
+ if binary:
+ probed = {
+ gpu[0]
+ for gpu in await asyncio.to_thread(LlamaCppBackend._get_gpu_memory, binary)
+ }
+ if not {int(gpu_id) for gpu_id in resolved}.issubset(probed):
+ return False
+ return True
+ except Exception:
+ return False
+
+
def _reject_draft_device_with_gpu_ids(
gpu_ids: Optional[List[int]],
extra_args: Optional[list[str]],
@@ -5526,6 +5683,10 @@ async def _load_model_impl(
event = "load",
model = _lifecycle_model_label(request.model_path, request.gguf_variant),
running = True,
+ # Auto-switch loads run before the request row opens, so a failure leaves only this.
+ via_api_key = _request_used_api_key(fastapi_request),
+ # The row is shared, so name its owner or the overlay pops open in unrelated tabs.
+ subject = current_subject,
)
native_grant_backed = False
@@ -7174,6 +7335,9 @@ async def get_api_monitor(current_subject: str = Depends(get_current_subject)):
# the UI can explain the empty list instead of claiming there was no API traffic.
return {
"status": operating_status,
+ # The clock every entry's started_at is on. The monitor dates its first snapshot
+ # against this, since the browser's clock need not agree over a tunnel.
+ "server_time": time.time(),
"active_model": active_model,
"context_length": _monitor_context_length(),
"active_requests": active_requests,
@@ -7182,6 +7346,22 @@ async def get_api_monitor(current_subject: str = Depends(get_current_subject)):
}
+@studio_router.delete("/monitor")
+async def clear_api_monitor(current_subject: str = Depends(get_current_subject)):
+ """Drop this caller's recorded API history so a debugging session starts clean.
+
+ Scoped to the current subject, like every read on the monitor: an unscoped
+ wipe would erase another user's history and zero their active-request count
+ while their generation is still streaming.
+
+ The caller's own in-flight requests are dropped from the log too; they keep
+ streaming to their client, they just stop being reported here (a later append
+ re-adds nothing, since the entry id no longer resolves).
+ """
+ api_monitor.clear(subject = current_subject)
+ return {"cleared": True}
+
+
@studio_router.get("/monitor/{entry_id}")
async def get_api_monitor_entry(entry_id: str, current_subject: str = Depends(get_current_subject)):
"""Return full prompt/reply details for one OpenAI-compatible API request."""
@@ -8676,6 +8856,7 @@ async def _proxy_to_external_provider(
if not getattr(request.state, "skip_api_monitor", False):
monitor_id = api_monitor.start(
endpoint = request.url.path,
+ via_api_key = _request_used_api_key(request),
method = request.method,
model = model,
prompt = _monitor_prompt_from_messages(payload.messages),
@@ -9239,6 +9420,7 @@ async def openai_chat_completions(
if not getattr(request.state, "skip_api_monitor", False):
tts_monitor_id = api_monitor.start(
endpoint = request.url.path,
+ via_api_key = _request_used_api_key(request),
method = request.method,
model = model_label,
prompt = _monitor_prompt_from_messages(payload.messages),
@@ -9309,6 +9491,7 @@ async def openai_chat_completions(
if not getattr(request.state, "skip_api_monitor", False):
monitor_id = api_monitor.start(
endpoint = request.url.path,
+ via_api_key = _request_used_api_key(request),
method = request.method,
model = model_name,
prompt = _monitor_prompt_from_messages(payload.messages),
@@ -9462,6 +9645,7 @@ async def openai_chat_completions(
if monitor_id is None and not getattr(request.state, "skip_api_monitor", False):
monitor_id = api_monitor.start(
endpoint = request.url.path,
+ via_api_key = _request_used_api_key(request),
method = request.method,
model = model_name,
prompt = _monitor_prompt_from_messages(payload.messages),
@@ -12428,6 +12612,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
monitor_model = str(body.get("model") or _llama_public_model_id(llama_backend) or "default")
monitor_id = api_monitor.start(
endpoint = request.url.path,
+ via_api_key = _request_used_api_key(request),
method = request.method,
model = monitor_model,
prompt = prompt_text,
@@ -12690,6 +12875,7 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(get
if not getattr(request.state, "skip_api_monitor", False):
monitor_id = api_monitor.start(
endpoint = request.url.path,
+ via_api_key = _request_used_api_key(request),
method = request.method,
model = str(body.get("model") or _llama_public_model_id(llama_backend) or "default"),
prompt = prompt_text,
@@ -13320,6 +13506,7 @@ async def _responses_non_streaming(
monitor_id = api_monitor.start(
endpoint = getattr(getattr(request, "url", None), "path", "/v1/responses"),
method = getattr(request, "method", "POST"),
+ via_api_key = _request_used_api_key(request),
model = payload.model,
prompt = _monitor_prompt_from_messages(messages),
context_length = _monitor_context_length(),
@@ -14530,6 +14717,7 @@ async def openai_responses(
if not getattr(request.state, "skip_api_monitor", False):
monitor_id = api_monitor.start(
endpoint = request.url.path,
+ via_api_key = _request_used_api_key(request),
method = request.method,
model = payload.model,
prompt = _monitor_prompt_from_messages(messages),
@@ -15015,6 +15203,7 @@ async def anthropic_messages(
monitor_id = api_monitor.start(
endpoint = getattr(request_url, "path", "/v1/messages"),
method = getattr(request, "method", "POST"),
+ via_api_key = _request_used_api_key(request),
model = model_name,
prompt = _monitor_prompt_from_messages(openai_messages),
context_length = monitor_context_length,
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 7770c12a8a4..b4bf8c8aec5 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -1,8 +1,10 @@
# 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 functools
import re
-from typing import Literal, Optional
+import threading
+from typing import Any, Literal, Optional
from urllib.parse import unquote, urlsplit
from fastapi import APIRouter, Depends, HTTPException
@@ -34,15 +36,22 @@ from utils.helper_precache_settings import (
helper_model_disabled_by_env,
set_helper_precache_enabled,
)
+from picker.schemas import MAX_CHAT_TEMPLATE_BYTES, chat_template_byte_length
from utils.coding_agents import CODING_AGENTS, detect_installed_coding_agents
from utils.openai_auto_switch_settings import (
DEFAULT_AUTO_UNLOAD_KEEP_KV,
DEFAULT_OPENAI_AUTO_DOWNLOAD_ENABLED,
DEFAULT_OPENAI_AUTO_SWITCH_ENABLED,
+ MAX_GPU_ID,
+ PARALLEL_SLOTS_MAX,
+ PARALLEL_SLOTS_MIN,
+ cached_repo_alias_keys,
get_auto_unload_idle_seconds,
get_auto_unload_keep_kv,
get_model_overrides,
get_openai_auto_switch_enabled,
+ resolve_model_override_key,
+ resolve_model_override_keys,
get_stored_auto_unload_idle_seconds,
get_stored_openai_auto_download_enabled,
set_model_override,
@@ -130,12 +139,88 @@ class OpenAIAutoSwitchResponse(BaseModel):
auto_download_model: bool = DEFAULT_OPENAI_AUTO_DOWNLOAD_ENABLED
+# A quant suffix, as modelOverrideKey builds it. Matched against the loader's quant pattern,
+# not a length heuristic: a POSIX path may hold a colon and inherit another model's flags.
+_MAX_VARIANT_SUFFIX_LEN = 64
+
+# A local id is a path plus an optional quant suffix, and LoadRequest.model_path is unbounded.
+# A limit under PATH_MAX would 422 the server sync while the local save succeeded.
+MAX_MODEL_OVERRIDE_KEY_LEN = 4096 + 1 + _MAX_VARIANT_SUFFIX_LEN
+
+# A list longer than MAX_GPU_ID cannot name a device the normalizer would store, so bound it
+# here and reject an oversized array at the boundary instead of walking it.
+MAX_GPU_IDS = MAX_GPU_ID + 1
+
+
class ModelOverridePayload(BaseModel):
- model_id: str = Field(..., min_length = 1)
- llama_extra_args: list[str] = Field(default_factory = list)
- # ge=1: 0 is not a valid sequence length, and the setter drops a falsy value,
- # so reject it at the boundary instead of accepting then silently discarding it.
+ """One model's saved launch config, applied when the API loads that model.
+
+ Everything past ``model_id`` is optional and omitted means "app default", so a
+ payload carrying only ``model_id`` clears the entry. The bounds here mirror
+ ``LoadRequest`` so a bad value is rejected at the boundary instead of being
+ silently dropped by the normalizer; the enum-ish fields (KV dtype, speculative
+ mode) are left to it, since their valid sets follow the llama.cpp build.
+ """
+
+ model_id: str = Field(..., min_length = 1, max_length = MAX_MODEL_OVERRIDE_KEY_LEN)
+ # None leaves the stored value alone (the UI has no control for flags); [] clears them.
+ llama_extra_args: Optional[list[str]] = None
+ # ge=1: the setter drops a falsy value, so reject 0 here instead of discarding it silently.
max_seq_length: Optional[int] = Field(default = None, ge = 1, le = 1048576)
+ custom_context_length: Optional[int] = Field(default = None, ge = 1, le = 1048576)
+ kv_cache_dtype: Optional[str] = Field(default = None, max_length = 32)
+ speculative_type: Optional[str] = Field(default = None, max_length = 32)
+ spec_draft_n_max: Optional[int] = Field(default = None, ge = 1, le = 16)
+ # Parallel decode slots (llama-server --parallel), GGUF-only; None follows the server default.
+ n_parallel: Optional[int] = Field(default = None, ge = PARALLEL_SLOTS_MIN, le = PARALLEL_SLOTS_MAX)
+ tensor_parallel: bool = False
+ # Validated in bytes below: pydantic counts characters, so a multi-byte template would pass.
+ chat_template_override: Optional[str] = None
+ gpu_memory_mode: Optional[Literal["auto", "manual"]] = None
+ # -1 is Auto (llama.cpp --fit sizes the offload); the normalizer treats it as unset.
+ gpu_layers: Optional[int] = Field(default = None, ge = -1, le = 1024)
+ n_cpu_moe: Optional[int] = Field(default = None, ge = 0, le = 1024)
+ gpu_ids: Optional[list[int]] = Field(default = None, max_length = MAX_GPU_IDS)
+ # An all-default save carries no fields, like a forget; None keeps the legacy contract.
+ remove: Optional[bool] = None
+ # Fill in, don't replace: the backfill reads the map once then writes each model, so another
+ # tab's save was overwritten by this browser's older copy. Field level, not entry level: a
+ # legacy entry holds only some fields, and skipping it would strand the rest.
+ fill_absent_fields: bool = False
+
+ @field_validator("chat_template_override")
+ @classmethod
+ def _limit_chat_template_bytes(cls, value: Optional[str]) -> Optional[str]:
+ # Mirrors LoadRequest.normalize_blank_chat_template_override.
+ if value is None:
+ return None
+ size = chat_template_byte_length(value)
+ if size is None:
+ raise ValueError("Chat template contains unpaired surrogate characters.")
+ if size > MAX_CHAT_TEMPLATE_BYTES:
+ raise ValueError(f"Chat template exceeds the {MAX_CHAT_TEMPLATE_BYTES}-byte limit.")
+ return value
+
+ @field_validator(
+ "max_seq_length",
+ "custom_context_length",
+ "spec_draft_n_max",
+ "n_parallel",
+ "gpu_layers",
+ "n_cpu_moe",
+ "gpu_ids",
+ mode = "before",
+ )
+ @classmethod
+ def _no_booleans(cls, value: Any) -> Any:
+ # bool subclasses int and pydantic parses non-strictly, so `true` arrives as 1: a
+ # payload could pin GPU 1 or set a one-token context. _bounded_int rejects bools but
+ # never sees one, since coercion happens here first. Only bools, so lax parsing stays.
+ if isinstance(value, bool):
+ raise ValueError("Expected a number, got a boolean.")
+ if isinstance(value, list) and any(isinstance(item, bool) for item in value):
+ raise ValueError("Expected numbers, got a boolean.")
+ return value
class ModelOverridesResponse(BaseModel):
@@ -294,18 +379,247 @@ def get_openai_auto_switch_overrides(
return ModelOverridesResponse(overrides = get_model_overrides())
+def _bare_model_id(model_id: str) -> Optional[str]:
+ """``repo`` for a ``repo:QUANT`` key, or None when there is no quant suffix."""
+ from utils.openai_auto_switch_settings import split_quant_suffix
+
+ # Must look like a quant, not a short path segment; a bpw modifier and stem label both count.
+ split = split_quant_suffix(model_id)
+ return split[0] if split is not None else None
+
+
+def _other_quants_remain(bare_id: str, removed_ids: list[str]) -> bool:
+ """Whether a quant of ``bare_id`` other than the ones being removed still has an entry.
+
+ Such a quant has its own settings and never reads the bare fallback, so this is not
+ "is anyone inheriting" but "is this forget the last one for the model". If it is not,
+ the bare entry stays: an inheriting quant is exactly what it is there for.
+ """
+ from utils.openai_auto_switch_settings import split_quant_suffix
+
+ removed = {key.strip().lower() for key in removed_ids}
+ prefix = bare_id.strip().lower()
+ for key, entry in get_model_overrides().items():
+ if not isinstance(entry, dict) or key.strip().lower() in removed:
+ continue
+ split = split_quant_suffix(key)
+ if split is not None and split[0].strip().lower() == prefix:
+ return True
+ return False
+
+
+def _legacy_standalone_gguf_key(model_id: str) -> Optional[str]:
+ """The stored ``<path>:LABEL`` entry for a bare standalone .gguf path, if any.
+
+ A loose file has no quant to choose between, so it is keyed by the bare path,
+ but the label derived from its filename is never empty and that is how the
+ picker keyed the same file before, so an upgraded install carries entries
+ under it. The auto-switch loader reads that spelling after the bare path
+ misses; resolve_model_override_key does not, since folding a POSIX path only
+ touches an existing suffix. None for an id that already names a quant, for a
+ repo id, and when nothing is stored under the derived key.
+ """
+ import os
+
+ if not model_id.lower().endswith(".gguf"):
+ return None
+ # Already qualified, so the caller named the entry it meant, as the loader does.
+ if _bare_model_id(model_id) is not None:
+ return None
+ from hub.utils.gguf import extract_quant_label
+
+ label = extract_quant_label(os.path.basename(model_id))
+ if not label:
+ return None
+ # Through the resolver: the browser lowercases the variant, and an ambiguous fold misses.
+ return resolve_model_override_key(f"{model_id}:{label}")
+
+
+def _fill_target_id(target_id: str) -> str:
+ """Where a one-time backfill write for ``target_id`` has to land.
+
+ A fill only adds, so unlike a save it cannot retire the other spelling of a cached
+ repo. Creating the snapshot-path key while the server already holds the repo id
+ would leave two entries for one quant, and the loader reads the load path before the
+ advertised id, so an upgraded browser's pre-upgrade copy would shadow the newer
+ server config on every API load. Fill into the entry already there instead: nothing
+ outranks it, and the fields it lacks still arrive.
+
+ Only in that direction. A repo-id key never outranks an existing path entry, and two
+ snapshot paths name two caches, neither of which is knowably the one loaded here.
+ """
+ from core.inference.model_ids import hf_cache_repo_id
+ from utils.openai_auto_switch_settings import split_quant_suffix
+
+ # Already stored, so this write creates no second key to outrank anything.
+ if isinstance(get_model_overrides().get(target_id), dict):
+ return target_id
+ split = split_quant_suffix(target_id)
+ # A bare id backs every quant and is read last, and only a cache path outranks.
+ if split is None or hf_cache_repo_id(split[0]) is None:
+ return target_id
+ for alias_id in cached_repo_alias_keys(target_id):
+ alias_split = split_quant_suffix(alias_id)
+ if alias_split is not None and hf_cache_repo_id(alias_split[0]) is None:
+ return alias_id
+ return target_id
+
+
+# One override write at a time. A save stores its target key and then reads the map back to
+# retire the other spelling of the same cached repo, and a remove clears up to four keys, each
+# its own transaction: atomic on their own, but not as a sequence. This route is a plain `def`,
+# so FastAPI runs it in a threadpool, and two clients saving one quant under both spellings (the
+# repo id the picker sends and the snapshot path an upgraded install still holds) could each
+# write before either cleanup ran and then retire the other's row, leaving no override at all
+# from two saves that both returned 200. Serialize the whole handler instead: overrides are
+# written by a settings edit, never on a hot path, and the server runs one process.
+_override_write_lock = threading.Lock()
+
+
+def _serialized_override_write(func):
+ """Run ``func`` under _override_write_lock, keeping the handler body as it reads.
+
+ functools.wraps carries __wrapped__, which inspect.signature follows, so FastAPI still
+ sees the endpoint's own parameters and dependencies.
+ """
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ with _override_write_lock:
+ return func(*args, **kwargs)
+
+ return wrapper
+
+
@router.put("/openai-auto-switch/overrides", response_model = ModelOverridesResponse)
+@_serialized_override_write
def update_openai_auto_switch_override(
payload: ModelOverridePayload, current_subject: str = Depends(get_current_subject)
) -> ModelOverridesResponse:
from core.inference.llama_server_args import validate_extra_args
+ from utils.openai_auto_switch_settings import get_model_override
+
try:
- extra_args = validate_extra_args(payload.llama_extra_args)
- set_model_override(
- payload.model_id,
- llama_extra_args = extra_args,
- max_seq_length = payload.max_seq_length,
+ if payload.fill_absent_fields and payload.remove is True:
+ # A fill that is also a delete has no meaning; picking one loses or resurrects.
+ raise ValueError("fill_absent_fields cannot be combined with remove.")
+ # Only model_id is the documented "remove"; otherwise omitted flags carry over.
+ requested_extra_args = payload.llama_extra_args
+ # fill_absent_fields is a write mode, not a saved field: leaving it in would make
+ # every payload look non-empty and break the legacy "no fields means remove".
+ saved_fields = payload.model_dump(
+ exclude = {"model_id", "llama_extra_args", "remove", "fill_absent_fields"},
+ exclude_none = True,
)
+ if payload.remove is not None:
+ is_removal = payload.remove
+ else:
+ is_removal = not payload.tensor_parallel and not {
+ key: value for key, value in saved_fields.items() if key != "tensor_parallel"
+ }
+ if requested_extra_args is None and not is_removal:
+ stored = get_model_override(payload.model_id)
+ # A fill keeps the stored flags without echoing them back through validation: one
+ # denylisted since it was saved would 400 the migration, which then retries forever.
+ if not (payload.fill_absent_fields and stored):
+ requested_extra_args = stored.get("llama_extra_args")
+ if requested_extra_args is None:
+ # First per-quant save for flags under the bare repo id; carry them over.
+ bare_id = _bare_model_id(payload.model_id)
+ if bare_id:
+ requested_extra_args = get_model_override(bare_id).get("llama_extra_args")
+ if requested_extra_args is None:
+ # And for a standalone .gguf upgraded from the build that keyed it by its
+ # filename label: the bare path written here is read before that key, so
+ # its flags would go dark with no page able to show or restore them.
+ legacy_id = _legacy_standalone_gguf_key(payload.model_id)
+ if legacy_id:
+ requested_extra_args = get_model_override(legacy_id).get("llama_extra_args")
+ if requested_extra_args is None:
+ # Same for the other spelling of a cached repo, which this save retires
+ # below: its flags have nowhere else to live, and the page cannot show them.
+ for alias_id in cached_repo_alias_keys(payload.model_id):
+ requested_extra_args = get_model_override(alias_id).get("llama_extra_args")
+ if requested_extra_args is not None:
+ break
+ # Not validated on an explicit remove: a 400 would only leave the override in place.
+ extra_args = [] if payload.remove is True else validate_extra_args(requested_extra_args)
+ if payload.remove is True:
+ # An explicit remove wins over any other field. Remove the key a load resolves to,
+ # not the literal one sent (the browser normalizes casing), and every spelling:
+ # clearing one of two leaves the survivor as the sole fold match.
+ target_ids = resolve_model_override_keys(payload.model_id) or [
+ payload.model_id,
+ ]
+ for target_id in target_ids:
+ set_model_override(target_id, llama_extra_args = [], max_seq_length = None)
+ # A standalone .gguf is keyed by its bare path now, but a load also reads the
+ # filename-derived <path>:LABEL an upgraded install holds, which would outlive this.
+ legacy_id = _legacy_standalone_gguf_key(payload.model_id)
+ if legacy_id and legacy_id not in target_ids:
+ set_model_override(
+ legacy_id,
+ llama_extra_args = [],
+ max_seq_length = None,
+ )
+ # The mirror image of the carry-over above: a save under repo:QUANT copies the
+ # flags off a legacy bare `repo` entry and leaves it in place, and the loader falls
+ # back to it when the qualified key misses, so clearing only the qualified key hands
+ # the same flags straight back and the forget does nothing. Nothing in the UI can
+ # reach that bare entry. Only once it is nobody else's fallback, though: it backs
+ # every quant with no entry of its own, so forgetting Q4 must not strip Q8.
+ bare_id = _bare_model_id(payload.model_id)
+ if (
+ bare_id
+ and bare_id not in target_ids
+ and not _other_quants_remain(
+ bare_id,
+ target_ids,
+ )
+ ):
+ set_model_override(
+ bare_id,
+ llama_extra_args = [],
+ max_seq_length = None,
+ )
+ # And the other spelling of a cached repo: the loader reads the load path before
+ # the advertised id, so clearing only the id leaves the path entry still applying.
+ for alias_id in cached_repo_alias_keys(payload.model_id):
+ set_model_override(alias_id, llama_extra_args = [], max_seq_length = None)
+ else:
+ # Save under the key a load resolves to, as the removal branch does: the literal
+ # id would leave two keys for one model, making every other casing ambiguous.
+ target_id = resolve_model_override_key(payload.model_id) or payload.model_id
+ if payload.fill_absent_fields:
+ # A fill retires nothing below, so it must not create the higher-priority
+ # spelling of a row the server already holds.
+ target_id = _fill_target_id(target_id)
+ set_model_override(
+ target_id,
+ llama_extra_args = extra_args,
+ max_seq_length = payload.max_seq_length,
+ custom_context_length = payload.custom_context_length,
+ kv_cache_dtype = payload.kv_cache_dtype,
+ speculative_type = payload.speculative_type,
+ spec_draft_n_max = payload.spec_draft_n_max,
+ n_parallel = payload.n_parallel,
+ tensor_parallel = payload.tensor_parallel,
+ chat_template_override = payload.chat_template_override,
+ gpu_memory_mode = payload.gpu_memory_mode,
+ gpu_layers = payload.gpu_layers,
+ n_cpu_moe = payload.n_cpu_moe,
+ gpu_ids = payload.gpu_ids,
+ fill_absent_fields = payload.fill_absent_fields,
+ )
+ # A repo cached outside the active HF cache is keyed here by its repo id, while the
+ # loader reads the snapshot path first and an older release keyed the row by that
+ # path, so an upgrade can hold both. Retire the spelling this save supersedes (its
+ # flags were carried over above), or the leftover outranks the key just written.
+ # After the write, so a rejected save deletes nothing. Not on a fill: that pass only
+ # adds, and the migration mirroring both spellings must not delete either.
+ if not payload.fill_absent_fields:
+ for alias_id in cached_repo_alias_keys(target_id):
+ set_model_override(alias_id, llama_extra_args = [], max_seq_length = None)
except ValueError as exc:
raise log_and_http_error(
exc,
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index ec4ea2a494e..ffbfa47973b 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -3048,11 +3048,25 @@ def upsert_app_settings(settings: dict[str, Any]) -> dict[str, Any]:
def upsert_app_setting_map_entry(
- key: str, entry_key: str, entry_value: dict[str, Any] | None
+ key: str,
+ entry_key: str,
+ entry_value: dict[str, Any] | None,
+ *,
+ fill_absent_fields: bool = False,
) -> dict[str, Any]:
"""Set (or delete, when entry_value is falsy) one sub-entry of a dict-valued
app setting, atomically under BEGIN IMMEDIATE so concurrent writers to other
- sub-entries cannot drop each other's updates."""
+ sub-entries cannot drop each other's updates.
+
+ ``fill_absent_fields`` writes only what is missing: the entry is created when
+ it is not there, and otherwise gains the fields it does not already hold while
+ every stored value is left exactly as it is. Nothing is ever deleted. The read
+ and the write share this transaction, so a caller that read the map earlier
+ cannot replace a value written since. Used by the one-time localStorage
+ backfill, whose contract is that the server copy is the newer authority: an
+ upgraded install can hold an entry with only the fields an older release knew,
+ while this browser holds the rest, and entry-level skipping would strand them.
+ """
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
@@ -3060,7 +3074,21 @@ def upsert_app_setting_map_entry(
current = _json_loads(row["value_json"], {}) if row else {}
if not isinstance(current, dict):
current = {}
- if entry_value:
+ if fill_absent_fields:
+ if not entry_value:
+ conn.rollback()
+ return current
+ stored = current.get(entry_key)
+ if isinstance(stored, dict):
+ # Stored values win field by field, so this only adds.
+ merged = {**entry_value, **stored}
+ if merged == stored:
+ conn.rollback()
+ return current
+ current[entry_key] = merged
+ else:
+ current[entry_key] = entry_value
+ elif entry_value:
current[entry_key] = entry_value
else:
current.pop(entry_key, None)
diff --git a/studio/backend/tests/test_api_monitor.py b/studio/backend/tests/test_api_monitor.py
index dd4ffbd7946..55f30b9fa7a 100644
--- a/studio/backend/tests/test_api_monitor.py
+++ b/studio/backend/tests/test_api_monitor.py
@@ -281,6 +281,91 @@ def test_api_monitor_append_reply_exact_cap_then_more_marks_truncated():
assert len(reply) == m._MAX_REPLY_CHARS and reply.endswith("...")
+def test_clear_keeps_the_callers_own_request_that_is_still_running():
+ """Clear log drops history, and a request in flight is not history yet. Dropping it
+ loses the request outright: the active count falls to zero and the finish that follows
+ has no entry left to land on, so a completed call never appears at all."""
+ monitor = ApiMonitor(max_entries = 4)
+ done = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "finished",
+ subject = "alice",
+ )
+ monitor.finish(done)
+ live = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "in flight",
+ subject = "alice",
+ )
+
+ monitor.clear(subject = "alice")
+
+ assert [entry["id"] for entry in monitor.snapshot(subject = "alice")] == [live]
+ assert monitor.active_count(subject = "alice") == 1
+ # And the row is still there to be completed.
+ monitor.finish(live)
+ assert monitor.get(live, subject = "alice")["status"] == "completed"
+
+
+def test_api_monitor_clear_is_scoped_to_one_subject():
+ # Every other read is subject-scoped; an unscoped clear would erase another's history.
+ monitor = ApiMonitor(max_entries = 4)
+ alice = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "alice prompt",
+ subject = "alice",
+ )
+ bob = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "bob prompt",
+ subject = "bob",
+ )
+ # Finished first: a running row is a request in flight, not history, and clear keeps
+ # it. This test is about the subject scoping, so it clears history and nothing else.
+ monitor.finish(alice)
+
+ monitor.clear(subject = "alice")
+ assert monitor.snapshot(subject = "alice") == []
+ assert [entry["id"] for entry in monitor.snapshot(subject = "bob")] == [bob]
+ assert monitor.active_count(subject = "bob") == 1
+ assert monitor.get(alice, subject = "alice") is None
+
+ # Passing no subject is the explicit "everything" path.
+ monitor.clear()
+ assert monitor.snapshot(subject = "bob") == []
+
+
+def test_api_monitor_records_whether_the_caller_used_an_api_key():
+ # Studio's chat hits these endpoints on a JWT, and the panel auto-opens off this flag.
+ monitor = ApiMonitor(max_entries = 4)
+ ui = monitor.start(
+ endpoint = "/api/inference/chat",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ subject = "u",
+ )
+ api = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ subject = "u",
+ via_api_key = True,
+ )
+ by_id = {entry["id"]: entry for entry in monitor.snapshot(subject = "u")}
+ assert by_id[ui]["via_api_key"] is False
+ assert by_id[api]["via_api_key"] is True
+
+
def test_api_monitor_disabled_is_noop():
monitor = ApiMonitor(max_entries = 3, enabled = False)
@@ -435,6 +520,127 @@ def test_request_rows_report_kind_request():
assert monitor.snapshot()[0]["kind"] == "request"
+def test_clear_hides_shared_lifecycle_rows_for_that_caller_only():
+ """A lifecycle row is shared, so it is visible to every caller but owned by
+ none. A subject-scoped clear dropped only that subject's own rows, so the
+ shared ones survived and the reload straight after "Clear log" brought them
+ back: the button visibly did nothing to them. Dropping them outright is not
+ an option either, since that erases another caller's history.
+ """
+ monitor = ApiMonitor(max_entries = 10)
+ mine = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "org/A",
+ prompt = "user: hi",
+ subject = "alice",
+ )
+ monitor.finish(mine)
+ shared = monitor.record_lifecycle(event = "unload", model = "org/A")
+
+ assert {e["id"] for e in monitor.snapshot(subject = "alice")} == {mine, shared}
+ assert {e["id"] for e in monitor.snapshot(subject = "bob")} == {shared}
+
+ monitor.clear(subject = "alice")
+
+ assert monitor.snapshot(subject = "alice") == []
+ # Hidden for alice, not deleted, so bob's view is untouched.
+ assert {e["id"] for e in monitor.snapshot(subject = "bob")} == {shared}
+ assert monitor.get(shared, subject = "alice") is None
+ assert monitor.get(shared, subject = "bob") is not None
+
+
+def test_clear_leaves_a_running_shared_row_visible():
+ """A load still in progress is live state, not history, so clearing the log
+ must not hide the row that shows it."""
+ monitor = ApiMonitor(max_entries = 10)
+ running = monitor.record_lifecycle(event = "load", model = "org/A", running = True)
+ monitor.clear(subject = "alice")
+ assert {e["id"] for e in monitor.snapshot(subject = "alice")} == {running}
+
+
+def test_hidden_shared_ids_do_not_outlive_their_entries():
+ """The hidden set names rows that exist, so it stays bounded by the ring
+ buffer instead of growing for the life of the process."""
+ monitor = ApiMonitor(max_entries = 2)
+ monitor.record_lifecycle(event = "unload", model = "org/A")
+ monitor.clear(subject = "alice")
+ assert monitor._hidden_shared.get("alice")
+ for i in range(5):
+ monitor.record_lifecycle(event = "unload", model = f"org/M{i}")
+ assert not monitor._hidden_shared.get("alice")
+
+
+def test_an_api_triggered_lifecycle_row_carries_the_attribution():
+ """The overlay opens on API-key traffic only. An auto-switch or auto-download
+ that is refused never reaches api_monitor.start, so the lifecycle row is the
+ whole trace of that request; without the attribution the monitor stayed shut
+ on exactly the failures it exists to surface."""
+ monitor = ApiMonitor(max_entries = 5)
+
+ api_load = monitor.record_lifecycle(
+ event = "load", model = "org/Repo-GGUF", running = True, via_api_key = True
+ )
+ monitor.record_lifecycle(event = "unload", model = "org/Repo-GGUF", reason = "idle")
+
+ rows = {e["id"]: e for e in monitor.snapshot()}
+ assert rows[api_load]["via_api_key"] is True
+ # A background unload is not API traffic and must not pop the overlay.
+ idle = [e for e in rows.values() if e["event"] == "unload"]
+ assert idle and all(e["via_api_key"] is False for e in idle)
+
+ # The failure path keeps it: failing the row must not drop the attribution.
+ monitor.fail(api_load, error = "auto-switch refused")
+ after = {e["id"]: e for e in monitor.snapshot()}
+ assert after[api_load]["via_api_key"] is True
+ assert after[api_load]["status"] == "error"
+
+
+def test_an_api_lifecycle_row_pops_the_overlay_only_for_its_own_caller():
+ """A lifecycle row is shared so it appears in every monitor list, and it also
+ carries via_api_key, which is what the floating panel auto-opens on. Reported
+ to everyone, the panel springs open in a browser that had nothing to do with
+ the traffic. The row stays visible to all; only the attribution is scoped."""
+ monitor = ApiMonitor(max_entries = 5)
+
+ row = monitor.record_lifecycle(
+ event = "load",
+ model = "org/Repo-GGUF",
+ running = True,
+ via_api_key = True,
+ subject = "alice",
+ )
+
+ mine = {e["id"]: e for e in monitor.snapshot(subject = "alice")}
+ theirs = {e["id"]: e for e in monitor.snapshot(subject = "bob")}
+ # Shared visibility is deliberate and must survive: bob still sees the load.
+ assert row in mine and row in theirs
+ assert mine[row]["via_api_key"] is True
+ assert theirs[row]["via_api_key"] is False
+
+ # The details read is scoped the same way, so the panel cannot re-derive it.
+ assert monitor.get(row, subject = "alice")["via_api_key"] is True
+ assert monitor.get(row, subject = "bob")["via_api_key"] is False
+ # An unscoped read (internal callers) still sees the row's own flag.
+ assert monitor.get(row)["via_api_key"] is True
+
+
+def test_clearing_hides_a_shared_row_this_caller_owns_rather_than_deleting_it():
+ """An API-key load now owns its shared row. A subject-scoped clear drops that
+ subject's rows, so without this the owner's Clear would delete a row every
+ other caller can still see and wipe it out of their history too."""
+ monitor = ApiMonitor(max_entries = 10)
+ row = monitor.record_lifecycle(
+ event = "unload", model = "org/Repo-GGUF", via_api_key = True, subject = "alice"
+ )
+
+ monitor.clear(subject = "alice")
+
+ assert monitor.snapshot(subject = "alice") == []
+ assert {e["id"] for e in monitor.snapshot(subject = "bob")} == {row}
+ assert monitor.get(row, subject = "bob") is not None
+
+
# ── stream framing must not depend on the monitor ───────────────────
diff --git a/studio/backend/tests/test_openai_auto_download.py b/studio/backend/tests/test_openai_auto_download.py
index b1dde175da5..027df84e369 100644
--- a/studio/backend/tests/test_openai_auto_download.py
+++ b/studio/backend/tests/test_openai_auto_download.py
@@ -684,13 +684,22 @@ class _Req:
self.headers = headers or {}
-def _hook(model, request, enabled):
+def _hook(
+ model,
+ request,
+ enabled,
+ current_subject = None,
+):
import utils.openai_auto_switch_settings as s
original = s.get_openai_auto_download_enabled
s.get_openai_auto_download_enabled = lambda: enabled
try:
- return asyncio.run(inference_route._maybe_auto_download_model(model, request))
+ return asyncio.run(
+ inference_route._maybe_auto_download_model(
+ model, request, current_subject = current_subject
+ )
+ )
finally:
s.get_openai_auto_download_enabled = original
@@ -726,13 +735,98 @@ def test_hook_uses_the_anthropic_envelope_on_messages(hub):
def test_hook_swallows_unexpected_failures(hub, monkeypatch):
# A broken download path must not turn a servable request into a 500.
- async def _boom(model, hf_token = None):
+ async def _boom(
+ model,
+ hf_token = None,
+ **kwargs,
+ ):
raise RuntimeError("boom")
monkeypatch.setattr(auto_dl, "maybe_auto_download", _boom)
assert _hook("unsloth/x-GGUF", _Req(), enabled = True) is None
+def _download_rows():
+ from core.inference.api_monitor import api_monitor
+ return [e for e in api_monitor.snapshot() if e["event"] == "download"]
+
+
+def test_a_ui_session_download_is_not_marked_as_api_traffic(hub):
+ """The monitor overlay auto-opens on via_api_key, which exists to separate
+ "someone is serving other clients" from "someone is using Unsloth". Studio's
+ own chat hits these same /v1 endpoints with a session JWT, so hardcoding the
+ flag on the download row popped the panel open mid-chat."""
+ from fastapi import HTTPException
+ from core.inference.api_monitor import api_monitor
+
+ api_monitor.clear()
+ with pytest.raises(HTTPException):
+ # No Authorization header: the UI's session-JWT path.
+ _hook("unsloth/x-GGUF", _Req(), enabled = True, current_subject = "unsloth")
+ rows = _download_rows()
+ assert rows and all(row["via_api_key"] is False for row in rows)
+
+
+def test_an_api_key_download_keeps_the_attribution_and_names_its_caller(hub):
+ """The row is shared, so it needs the subject as well: without one the
+ attribution is reported to every logged-in browser instead of the caller."""
+ from fastapi import HTTPException
+ from auth.authentication import API_KEY_PREFIX
+ from core.inference.api_monitor import api_monitor
+
+ api_monitor.clear()
+ with pytest.raises(HTTPException):
+ _hook(
+ "unsloth/x-GGUF",
+ _Req(headers = {"authorization": f"Bearer {API_KEY_PREFIX}abc123"}),
+ enabled = True,
+ current_subject = "unsloth",
+ )
+ rows = _download_rows()
+ assert rows and all(row["via_api_key"] is True for row in rows)
+ # Still shared: another subject sees the row, just not the attribution.
+ others = [e for e in api_monitor.snapshot(subject = "someone-else") if e["event"] == "download"]
+ assert len(others) == len(rows)
+ assert all(row["via_api_key"] is False for row in others)
+
+
+def test_an_api_key_caller_waiting_on_someone_elses_download_gets_a_row(hub):
+ """A download started by Studio's own chat is attributed to the session, so an
+ API-key client that asks for the same repo while it runs is refused before the
+ handler's own api_monitor.start. Without a row of its own that call is invisible:
+ the only row is the session's via_api_key=False download, so the overlay stays
+ shut and the monitor presents API traffic as Studio's own."""
+ from fastapi import HTTPException
+ from auth.authentication import API_KEY_PREFIX
+ from core.inference.api_monitor import api_monitor
+
+ api_monitor.clear()
+ with pytest.raises(HTTPException):
+ # Studio's chat (session JWT) starts the download and takes the slot.
+ _hook("unsloth/x-GGUF", _Req(), enabled = True, current_subject = "unsloth")
+ seeded = {row["id"] for row in api_monitor.snapshot(subject = "unsloth")}
+
+ with pytest.raises(HTTPException) as excinfo:
+ # The adopted-download branch: same repo, an sk-unsloth key this time.
+ _hook(
+ "unsloth/x-GGUF",
+ _Req(headers = {"authorization": f"Bearer {API_KEY_PREFIX}abc123"}),
+ enabled = True,
+ current_subject = "unsloth",
+ )
+ assert excinfo.value.status_code == 503
+
+ fresh = [e for e in api_monitor.snapshot(subject = "unsloth") if e["id"] not in seeded]
+ # New (so the overlay counts it as unseen traffic) and attributed to this caller.
+ assert [e for e in fresh if e["via_api_key"]], "the refused API-key call left no row"
+ row = next(e for e in fresh if e["via_api_key"])
+ assert row["endpoint"] == "/v1/chat/completions"
+ assert row["status"] == "error"
+ # Shared rows aside, another subject must not inherit the attribution.
+ others = [e for e in api_monitor.snapshot(subject = "someone-else") if e["id"] == row["id"]]
+ assert others == []
+
+
def test_hook_prefers_the_hub_header_token(hub):
from fastapi import HTTPException
from hub.dependencies import HUB_HF_TOKEN_HEADER
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 89a65a1030d..0e544c6dc63 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -566,7 +566,9 @@ def test_idle_loop_deletes_saved_kv_when_unload_fails(monkeypatch, tmp_path):
async def _drive():
task = asyncio.create_task(kw.idle_unload_loop(poll_seconds = 0.01))
- for _ in range(200):
+ # Wall clock, not an iteration count: Windows rounds a 10 ms sleep to its ~15.6 ms tick.
+ deadline = time.monotonic() + 15.0
+ while time.monotonic() < deadline:
await asyncio.sleep(0.01)
if manifests and not saved.exists():
break
@@ -698,9 +700,24 @@ def _mock_override_store(monkeypatch):
store = {}
- def _merge_entry(key, entry_key, entry_value):
+ def _merge_entry(
+ key,
+ entry_key,
+ entry_value,
+ *,
+ fill_absent_fields = False,
+ ):
current = dict(store.get(key) or {})
- if entry_value:
+ if fill_absent_fields:
+ # Fill only: every stored value wins, nothing is deleted.
+ if not entry_value:
+ return current
+ stored = current.get(entry_key)
+ if isinstance(stored, dict):
+ current[entry_key] = {**entry_value, **stored}
+ else:
+ current[entry_key] = entry_value
+ elif entry_value:
current[entry_key] = entry_value
else:
current.pop(entry_key, None)
@@ -713,6 +730,21 @@ def _mock_override_store(monkeypatch):
return store
+def override_store(monkeypatch):
+ """The in-memory override store, for a test that needs nothing else mocked."""
+ _mock_override_store(monkeypatch)
+
+
+def _put(model_id, **fields):
+ """One override PUT through the route, spelled the way the UI sends it."""
+ import routes.settings as settings_route
+ return settings_route.update_openai_auto_switch_override(
+ settings_route.ModelOverridePayload(model_id = model_id, **fields),
+ "tester",
+ )
+
+
def test_model_override_roundtrip(monkeypatch):
_mock_override_store(monkeypatch)
@@ -4154,6 +4186,919 @@ def test_env_idle_below_floor_is_clamped(monkeypatch):
assert settings.get_auto_unload_idle_seconds() == 0
+# Per-model launch config: normalization, LoadRequest mapping, key resolution.
+
+
+def test_normalize_model_override_drops_unusable_fields_and_keeps_the_rest():
+ # A stale field must not cost the user the whole config, so bad values are
+ # dropped one by one rather than rejecting the payload.
+ entry = settings.normalize_model_override(
+ {
+ "max_seq_length": 8192,
+ "kv_cache_dtype": "not_a_dtype",
+ "speculative_type": "mtp",
+ "spec_draft_n_max": 999, # out of range for the MTP draft count
+ "gpu_memory_mode": "auto", # only "manual" is a real override
+ "gpu_layers": -1, # -1 is Auto, which is already the default
+ "n_cpu_moe": 0,
+ "gpu_ids": [1, 1, 0, "2", -5],
+ "tensor_parallel": False,
+ "llama_extra_args": [],
+ }
+ )
+ assert entry == {"max_seq_length": 8192, "speculative_type": "mtp", "gpu_ids": [1, 0, 2]}
+
+
+def test_normalize_model_override_rejects_oversized_chat_template():
+ small = settings.normalize_model_override({"chat_template_override": "{{ bos }}"})
+ assert small["chat_template_override"] == "{{ bos }}"
+ # The limit is bytes, not characters, so a multi-byte template just under the
+ # character limit can still be over.
+ huge = "é" * settings.MAX_CHAT_TEMPLATE_OVERRIDE_BYTES
+ assert "chat_template_override" not in settings.normalize_model_override(
+ {"chat_template_override": huge}
+ )
+
+
+def test_spec_draft_n_max_only_stored_for_mtp_modes():
+ mtp = settings.normalize_model_override({"speculative_type": "mtp", "spec_draft_n_max": 4})
+ assert mtp["spec_draft_n_max"] == 4
+ # A non-MTP mode ignores the draft count, so storing it shows an edit that
+ # never takes effect.
+ ngram = settings.normalize_model_override({"speculative_type": "ngram", "spec_draft_n_max": 4})
+ assert "spec_draft_n_max" not in ngram
+
+
+def test_resolve_fit_max_seq_length_hands_sizing_to_fit_under_manual_auto_layers():
+ # Manual GPU memory with Auto layers hands the context to llama.cpp --fit, so
+ # the load sends the context pin (or 0), not the stored max seq length.
+ override = {"gpu_memory_mode": "manual", "max_seq_length": 8192}
+ assert settings.resolve_fit_max_seq_length(override, is_gguf = True) == 0
+ assert (
+ settings.resolve_fit_max_seq_length(
+ {**override, "custom_context_length": 4096}, is_gguf = True
+ )
+ == 4096
+ )
+ # Pinning the layer count takes --fit back out of the picture.
+ assert settings.resolve_fit_max_seq_length({**override, "gpu_layers": 20}, is_gguf = True) == 8192
+ # Not a GGUF, so none of this applies.
+ assert settings.resolve_fit_max_seq_length(override, is_gguf = False) == 8192
+
+
+def test_model_override_load_kwargs_gates_gpu_placement_on_gguf():
+ override = {
+ "max_seq_length": 4096,
+ "kv_cache_dtype": "q8_0",
+ "tensor_parallel": True,
+ "gpu_memory_mode": "manual",
+ "gpu_layers": 20,
+ "n_cpu_moe": 3,
+ "gpu_ids": [0, 1],
+ }
+ gguf = settings.model_override_load_kwargs(override, is_gguf = True)
+ assert gguf["cache_type_kv"] == "q8_0"
+ assert gguf["tensor_parallel"] is True
+ assert gguf["gpu_layers"] == 20
+ assert gguf["gpu_ids"] == [0, 1]
+
+ # A safetensors model loads through HF auto-placement, so a GGUF GPU pin would
+ # silently change where the weights land.
+ safetensors = settings.model_override_load_kwargs(override, is_gguf = False)
+ assert safetensors["max_seq_length"] == 4096
+ assert "gpu_layers" not in safetensors
+ assert "gpu_ids" not in safetensors
+ assert "n_cpu_moe" not in safetensors
+ assert "gpu_memory_mode" not in safetensors
+
+ # Every key must be a real LoadRequest field, or the load raises TypeError when
+ # the user's request arrives.
+ LoadRequest(model_path = "unsloth/B-GGUF", **gguf)
+
+
+def test_a_carried_ctx_flag_cannot_outrank_a_freshly_saved_context(monkeypatch):
+ # The settings page has no control for pass-through flags, so a save carries over the
+ # ones already stored while writing the field the user just edited, leaving one entry
+ # holding both. Sent together they reach llama-server with the extras appended last,
+ # and its parser takes the final -c, so the stale flag would pin the old context.
+ _mock_override_store(monkeypatch)
+ _put("unsloth/B-GGUF:Q4_K_M", llama_extra_args = ["--ctx-size", "8192", "--top-k", "40"])
+ saved = _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 32768)
+ entry = saved.overrides["unsloth/B-GGUF:Q4_K_M"]
+ assert entry["max_seq_length"] == 32768
+ assert entry["llama_extra_args"] == ["--ctx-size", "8192", "--top-k", "40"]
+
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("unsloth/B-GGUF", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+
+ _run_hook("unsloth/B-GGUF")
+ request = rec.calls[0]
+ assert request.max_seq_length == 32768
+ # The shadowing flag goes; the sampling flag beside it is nobody's first-class field.
+ assert request.llama_extra_args == ["--top-k", "40"]
+
+
+def test_load_kwargs_strip_only_the_shadow_groups_the_override_supplies():
+ # Same rule the /load route applies to inherited extras: one group per first-class
+ # field actually being sent, so a flag with nothing to shadow still passes through.
+ override = {
+ "llama_extra_args": [
+ "-c",
+ "8192",
+ "--cache-type-k",
+ "f16",
+ "--spec-type",
+ "ngram",
+ "--jinja",
+ "--split-mode",
+ "row",
+ "--top-p",
+ "0.9",
+ ],
+ "max_seq_length": 32768,
+ "kv_cache_dtype": "q8_0",
+ "speculative_type": "mtp",
+ "chat_template_override": "{{ bos_token }}",
+ "tensor_parallel": True,
+ }
+ stripped = settings.model_override_load_kwargs(override, is_gguf = True)
+ assert stripped["llama_extra_args"] == ["--top-p", "0.9"]
+
+ # Nothing is supplied to shadow them, so every flag survives.
+ kept = settings.model_override_load_kwargs(
+ {"llama_extra_args": override["llama_extra_args"]}, is_gguf = True
+ )
+ assert kept["llama_extra_args"] == override["llama_extra_args"]
+
+ # And one field strips one group.
+ ctx_only = settings.model_override_load_kwargs(
+ {"llama_extra_args": override["llama_extra_args"], "max_seq_length": 32768},
+ is_gguf = True,
+ )
+ assert ctx_only["llama_extra_args"] == override["llama_extra_args"][2:]
+
+
+def test_saved_parallel_slots_reach_an_api_load(monkeypatch):
+ # Parallel decode slots are a per-model setting the picker sends on every GGUF load.
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("unsloth/B-GGUF", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+ monkeypatch.setattr(settings, "get_model_override", lambda mid: {"n_parallel": 8})
+
+ _run_hook("unsloth/B-GGUF")
+ assert rec.calls[0].n_parallel == 8
+
+
+def test_parallel_slots_are_stored_and_gated_on_gguf():
+ override = settings.normalize_model_override({"n_parallel": 8})
+ assert override == {"n_parallel": 8}
+ # Blank, out of range and non-integer all mean "follow the server-wide default".
+ for bad in (None, 0, -1, settings.PARALLEL_SLOTS_MAX + 1, "many", True):
+ assert "n_parallel" not in settings.normalize_model_override({"n_parallel": bad})
+
+ gguf = settings.model_override_load_kwargs(override, is_gguf = True)
+ assert gguf["n_parallel"] == 8
+ # A safetensors load has no llama-server slots, exactly as the picker gates it.
+ assert "n_parallel" not in settings.model_override_load_kwargs(override, is_gguf = False)
+ LoadRequest(model_path = "unsloth/B-GGUF", **gguf)
+
+
+def test_override_route_persists_parallel_slots(override_store):
+ # The picker's mirror must carry the field, or a slot-count-only change saves as empty.
+ resp = _put("unsloth/B-GGUF:Q4_K_M", n_parallel = 8)
+ assert resp.overrides["unsloth/B-GGUF:Q4_K_M"] == {"n_parallel": 8}
+
+
+def test_eviction_cleanup_clears_mirrored_fields_but_keeps_launch_flags(override_store):
+ # Evicting a local entry for storage budget is not a forget, so cleanup sends remove=false.
+ settings.set_model_override(
+ "unsloth/B-GGUF:Q4_K_M",
+ llama_extra_args = ["--flash-attn"],
+ custom_context_length = 32768,
+ kv_cache_dtype = "q8_0",
+ )
+ resp = _put("unsloth/B-GGUF:Q4_K_M", remove = False)
+ assert resp.overrides["unsloth/B-GGUF:Q4_K_M"] == {"llama_extra_args": ["--flash-attn"]}
+
+ # Nothing server-owned left, so the row goes rather than lingering empty.
+ settings.set_model_override("unsloth/C-GGUF:Q4_K_M", custom_context_length = 32768)
+ gone = _put("unsloth/C-GGUF:Q4_K_M", remove = False)
+ assert "unsloth/C-GGUF:Q4_K_M" not in gone.overrides
+
+
+def test_auto_switch_prefers_variant_qualified_override(monkeypatch):
+ # Settings are per quant; the bare repo id is only the fallback.
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("unsloth/B-GGUF", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+ stored = {
+ "unsloth/B-GGUF": {"max_seq_length": 1024},
+ "unsloth/B-GGUF:Q4_K_M": {"max_seq_length": 8192, "gpu_layers": 20},
+ }
+ monkeypatch.setattr(settings, "get_model_override", lambda mid: stored.get(mid, {}))
+
+ _run_hook("unsloth/B-GGUF")
+ req = rec.calls[0]
+ assert req.max_seq_length == 8192
+ assert req.gpu_layers == 20
+
+
+def test_auto_switch_falls_back_to_bare_repo_override(monkeypatch):
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("unsloth/B-GGUF", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+ stored = {"unsloth/B-GGUF": {"max_seq_length": 1024}}
+ monkeypatch.setattr(settings, "get_model_override", lambda mid: stored.get(mid, {}))
+
+ _run_hook("unsloth/B-GGUF")
+ assert rec.calls[0].max_seq_length == 1024
+
+
+def test_override_route_preserves_launch_flags_across_a_settings_only_update(override_store):
+ # The settings page has no control for llama_extra_args, so it omits the field.
+ _put("unsloth/B-GGUF", llama_extra_args = ["--flash-attn"])
+ resp = _put("unsloth/B-GGUF", max_seq_length = 4096)
+ entry = resp.overrides["unsloth/B-GGUF"]
+ assert entry["llama_extra_args"] == ["--flash-attn"]
+ assert entry["max_seq_length"] == 4096
+
+ # An explicit empty list is the UI's "forget", and with no fields left the entry goes.
+ gone = _put("unsloth/B-GGUF", llama_extra_args = [])
+ assert "unsloth/B-GGUF" not in gone.overrides
+
+
+def test_override_found_under_a_concrete_path_with_variant(monkeypatch):
+ # A local folder resolves to repo id + path; settings saved against the path must be found.
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/models/local/Qwen3-8B-Q4_K_M.gguf", "Q4_K_M", "unsloth/Qwen3-8B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+ stored = {"/models/local/Qwen3-8B-Q4_K_M.gguf:Q4_K_M": {"max_seq_length": 8192}}
+ monkeypatch.setattr(settings, "get_model_override", lambda mid: stored.get(mid, {}))
+
+ _run_hook("unsloth/Qwen3-8B-GGUF")
+ assert rec.calls[0].max_seq_length == 8192
+
+
+def test_path_qualified_override_beats_repo_qualified(monkeypatch):
+ # Most specific first: the settings page keys a local row by the path being loaded,
+ # while the repo id is only the advertised alias. The row the user edited wins.
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/models/local/x.gguf", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+ stored = {
+ "unsloth/B-GGUF:Q4_K_M": {"max_seq_length": 8192},
+ "/models/local/x.gguf:Q4_K_M": {"max_seq_length": 1024},
+ }
+ monkeypatch.setattr(settings, "get_model_override", lambda mid: stored.get(mid, {}))
+
+ _run_hook("unsloth/B-GGUF")
+ assert rec.calls[0].max_seq_length == 1024
+
+
+def test_first_quant_save_keeps_legacy_bare_repo_launch_flags(override_store):
+ # Flags predating per-quant settings live under the bare repo id.
+ settings.set_model_override("unsloth/B-GGUF", llama_extra_args = ["--flash-attn"])
+
+ resp = _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 4096)
+ entry = resp.overrides["unsloth/B-GGUF:Q4_K_M"]
+ assert entry["max_seq_length"] == 4096
+ assert entry["llama_extra_args"] == ["--flash-attn"]
+
+
+def test_bare_repo_carry_over_does_not_split_a_windows_path(override_store):
+ # The colon in "C:\models\x.gguf" is not a variant separator: splitting looks up "C".
+ settings.set_model_override("C", llama_extra_args = ["--flash-attn"])
+
+ resp = _put(r"C:\models\x.gguf", max_seq_length = 4096)
+ assert "llama_extra_args" not in resp.overrides[r"C:\models\x.gguf"]
+
+
+def test_windows_path_with_quant_still_carries_over(override_store):
+ settings.set_model_override(r"C:\models\x.gguf", llama_extra_args = ["--flash-attn"])
+
+ resp = _put(r"C:\models\x.gguf:Q4_K_M", max_seq_length = 4096)
+ assert resp.overrides[r"C:\models\x.gguf:Q4_K_M"]["llama_extra_args"] == ["--flash-attn"]
+
+
+# The snapshot dir a repo cached outside the active HF cache loads from, which is what an
+# older release keyed that row by and what the loader still reads before the repo id.
+_LEGACY_SNAPSHOT = "/home/u/.cache/hub-alt/models--unsloth--B-GGUF/snapshots/2f1c9ab"
+
+
+def test_a_repo_save_retires_the_legacy_snapshot_path_entry(monkeypatch):
+ """The two spellings of one cached repo cannot both be stored, or the older wins.
+
+ The one-time backfill mirrors the pre-upgrade path-qualified key to the server, the
+ Settings page then keys the same row by its repo id, and the loader reads the load
+ path first: without retiring the leftover, every API load applies the settings the
+ user just replaced.
+ """
+ _mock_override_store(monkeypatch)
+ settings.set_model_override(f"{_LEGACY_SNAPSHOT}:Q4_K_M", max_seq_length = 4096)
+
+ resp = _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 32768)
+ assert resp.overrides["unsloth/B-GGUF:Q4_K_M"]["max_seq_length"] == 32768
+ assert f"{_LEGACY_SNAPSHOT}:Q4_K_M" not in resp.overrides
+
+ # End to end: the load the request triggers carries the saved value, not the retired one.
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = (_LEGACY_SNAPSHOT, "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+
+ _run_hook("unsloth/B-GGUF:Q4_K_M")
+ assert rec.calls[0].max_seq_length == 32768
+
+
+def test_the_retired_snapshot_path_entry_hands_over_its_launch_flags(override_store):
+ # The page can neither show nor restore llama_extra_args, so retiring the entry has to
+ # carry them, exactly as the bare repo id does on a first per-quant save.
+ settings.set_model_override(
+ f"{_LEGACY_SNAPSHOT}:Q4_K_M",
+ llama_extra_args = ["--flash-attn"],
+ max_seq_length = 4096,
+ )
+
+ resp = _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 32768)
+ entry = resp.overrides["unsloth/B-GGUF:Q4_K_M"]
+ assert entry["llama_extra_args"] == ["--flash-attn"]
+ assert entry["max_seq_length"] == 32768
+ assert f"{_LEGACY_SNAPSHOT}:Q4_K_M" not in resp.overrides
+
+
+def test_a_standalone_gguf_save_keeps_its_filename_label_launch_flags(override_store):
+ # An early build keyed a loose .gguf by the quant label from its filename, and the bare
+ # path the picker writes today is read before that key (see
+ # test_the_filename_label_key_no_longer_shadows_the_bare_path), so writing the bare entry
+ # without the legacy flags puts them out of reach of a page that cannot show or restore
+ # them. The forget path already consults the same derived key.
+ path = "/models/Qwen3-8B-Q4_K_M.gguf"
+ settings.set_model_override(
+ f"{path}:q4_k_m",
+ llama_extra_args = ["--flash-attn"],
+ max_seq_length = 4096,
+ )
+
+ resp = _put(path, max_seq_length = 32768)
+ entry = resp.overrides[path]
+ assert entry["llama_extra_args"] == ["--flash-attn"]
+ assert entry["max_seq_length"] == 32768
+
+
+def test_a_snapshot_path_save_retires_the_repo_id_entry(override_store):
+ # The same rule the other way round: a row the picker still keys by its path (an inactive
+ # cache reached as a local row) must not be shadowed, so the last spelling saved survives.
+ settings.set_model_override("unsloth/B-GGUF:Q4_K_M", max_seq_length = 32768)
+
+ resp = _put(f"{_LEGACY_SNAPSHOT}:Q4_K_M", max_seq_length = 4096)
+ assert resp.overrides[f"{_LEGACY_SNAPSHOT}:Q4_K_M"]["max_seq_length"] == 4096
+ assert "unsloth/B-GGUF:Q4_K_M" not in resp.overrides
+
+
+def test_forgetting_a_cached_repo_also_clears_its_snapshot_path_entry(override_store):
+ # Clearing only the repo id would leave the path entry applying what was forgotten.
+ settings.set_model_override(f"{_LEGACY_SNAPSHOT}:Q4_K_M", max_seq_length = 4096)
+ settings.set_model_override("unsloth/B-GGUF:Q4_K_M", max_seq_length = 32768)
+
+ resp = _put("unsloth/B-GGUF:Q4_K_M", remove = True, llama_extra_args = [])
+ assert resp.overrides == {}
+
+
+def test_retiring_a_spelling_leaves_every_other_entry_alone(override_store):
+ # Only the same repo and the same quant fold together: a ./models path is keyed by its path
+ # alone, another quant has its own settings, and a bare entry backs every quant.
+ settings.set_model_override("/models/local/x.gguf:Q4_K_M", max_seq_length = 1024)
+ settings.set_model_override(f"{_LEGACY_SNAPSHOT}:Q8_0", max_seq_length = 2048)
+ settings.set_model_override(_LEGACY_SNAPSHOT, max_seq_length = 4096)
+
+ resp = _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 32768)
+ assert resp.overrides["/models/local/x.gguf:Q4_K_M"]["max_seq_length"] == 1024
+ assert resp.overrides[f"{_LEGACY_SNAPSHOT}:Q8_0"]["max_seq_length"] == 2048
+ assert resp.overrides[_LEGACY_SNAPSHOT]["max_seq_length"] == 4096
+
+
+def test_the_one_time_fill_retires_nothing(override_store):
+ # fill_absent_fields only adds what is missing; the migration mirroring both spellings
+ # of one row must not have its own first write deleted by its second.
+ settings.set_model_override(f"{_LEGACY_SNAPSHOT}:Q4_K_M", max_seq_length = 4096)
+
+ resp = _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 32768, fill_absent_fields = True)
+ assert resp.overrides[f"{_LEGACY_SNAPSHOT}:Q4_K_M"]["max_seq_length"] == 4096
+ assert resp.overrides["unsloth/B-GGUF:Q4_K_M"]["max_seq_length"] == 32768
+
+
+def test_a_fill_never_creates_a_snapshot_path_key_over_a_repo_id_entry(override_store):
+ # A fill only adds, so it cannot retire the other spelling the way a save does. Creating
+ # the snapshot path key would leave two entries for one quant, and the loader reads the
+ # load path before the advertised repo id, so an upgraded browser's pre-upgrade copy would
+ # shadow the newer server config on every API load. Fill into the entry that is already
+ # there instead: nothing outranks it and the fields it lacks still arrive.
+ settings.set_model_override("unsloth/B-GGUF:Q4_K_M", max_seq_length = 32768)
+
+ resp = _put(
+ f"{_LEGACY_SNAPSHOT}:Q4_K_M",
+ max_seq_length = 2048,
+ kv_cache_dtype = "q8_0",
+ fill_absent_fields = True,
+ )
+ assert f"{_LEGACY_SNAPSHOT}:Q4_K_M" not in resp.overrides
+ entry = resp.overrides["unsloth/B-GGUF:Q4_K_M"]
+ assert entry["max_seq_length"] == 32768
+ assert entry["kv_cache_dtype"] == "q8_0"
+
+
+def test_stale_gpu_ids_are_dropped_not_fatal(monkeypatch):
+ # A two-GPU pin on a one-GPU box used to 400 the load; one dead field degrades to defaults.
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("unsloth/B-GGUF", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+ monkeypatch.setattr(
+ settings,
+ "get_model_override",
+ lambda mid: {"gpu_ids": [0, 1], "max_seq_length": 4096},
+ )
+
+ async def _unusable(ids):
+ return False
+
+ monkeypatch.setattr(inference_route, "_override_gpu_ids_still_resolve", _unusable)
+
+ _run_hook("unsloth/B-GGUF")
+ req = rec.calls[0]
+ assert not req.gpu_ids
+ # The rest of the config still applies.
+ assert req.max_seq_length == 4096
+
+
+def test_usable_gpu_ids_are_kept(monkeypatch):
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("unsloth/B-GGUF", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+ monkeypatch.setattr(settings, "get_model_override", lambda mid: {"gpu_ids": [0, 1]})
+
+ async def _usable(ids):
+ return True
+
+ monkeypatch.setattr(inference_route, "_override_gpu_ids_still_resolve", _usable)
+
+ _run_hook("unsloth/B-GGUF")
+ assert rec.calls[0].gpu_ids == [0, 1]
+
+
+def test_override_gpu_ids_probe_never_raises(monkeypatch):
+ # On the load path, so a hardware error must read as "unusable", not a 500.
+ import utils.hardware.hardware as hw
+
+ def boom(*args, **kwargs):
+ raise RuntimeError("driver exploded")
+
+ monkeypatch.setattr(hw, "resolve_requested_gpu_ids", boom)
+ assert asyncio.run(inference_route._override_gpu_ids_still_resolve([0])) is False
+
+
+def test_vulkan_ordinal_absent_from_the_probe_is_unusable(monkeypatch):
+ # resolve_requested_gpu_ids only rejects malformed ordinals; presence needs the ggml probe.
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda: True))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "/bin/llama-server")
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_get_gpu_memory", staticmethod(lambda binary: [(0, 8192)])
+ )
+ assert asyncio.run(inference_route._override_gpu_ids_still_resolve([0])) is True
+ assert asyncio.run(inference_route._override_gpu_ids_still_resolve([7])) is False
+ assert asyncio.run(inference_route._override_gpu_ids_still_resolve([0, 1])) is False
+
+
+def test_vulkan_probe_without_a_binary_does_not_block_the_load(monkeypatch):
+ # Nothing to probe with, and refusing would drop a valid pin on every load.
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda: True))
+ monkeypatch.setattr(LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: None))
+ assert asyncio.run(inference_route._override_gpu_ids_still_resolve([0])) is True
+
+
+def test_default_save_preserves_flags_instead_of_removing(override_store):
+ # All-default values send no fields, shape-identical to a removal; guessing wrong wipes flags.
+ settings.set_model_override("unsloth/B-GGUF", llama_extra_args = ["--flash-attn"])
+
+ resp = _put("unsloth/B-GGUF", remove = False)
+ assert resp.overrides["unsloth/B-GGUF"]["llama_extra_args"] == ["--flash-attn"]
+
+
+def test_explicit_remove_still_clears_everything(override_store):
+ settings.set_model_override(
+ "unsloth/B-GGUF", llama_extra_args = ["--flash-attn"], max_seq_length = 4096
+ )
+ resp = _put("unsloth/B-GGUF", remove = True, llama_extra_args = [])
+ assert "unsloth/B-GGUF" not in resp.overrides
+
+
+def test_bare_payload_without_remove_flag_still_removes(override_store):
+ # The original contract, kept for any caller that predates the flag.
+ settings.set_model_override("unsloth/B-GGUF", max_seq_length = 4096)
+ resp = _put("unsloth/B-GGUF")
+ assert "unsloth/B-GGUF" not in resp.overrides
+
+
+def test_remove_false_with_real_fields_saves_normally(override_store):
+ resp = _put("unsloth/B-GGUF", remove = False, max_seq_length = 8192)
+ assert resp.overrides["unsloth/B-GGUF"]["max_seq_length"] == 8192
+
+
+def test_override_lookup_falls_back_to_case_insensitive(override_store):
+ # The browser lowercases ids while the resolver asks for the repo's real casing.
+ settings.set_model_override("unsloth/qwen3-8b-gguf:q4_k_m", max_seq_length = 8192)
+ got = settings.get_model_override("unsloth/Qwen3-8B-GGUF:Q4_K_M")
+ assert got["max_seq_length"] == 8192
+
+
+def test_exact_override_match_beats_a_case_variant(override_store):
+ settings.set_model_override("/models/foo.gguf", max_seq_length = 1024)
+ settings.set_model_override("/models/Foo.gguf", max_seq_length = 8192)
+ assert settings.get_model_override("/models/Foo.gguf")["max_seq_length"] == 8192
+ assert settings.get_model_override("/models/foo.gguf")["max_seq_length"] == 1024
+
+
+def test_ambiguous_case_fallback_matches_nothing(override_store):
+ # Two POSIX paths differing only in case are two files; guessing applies the wrong settings.
+ settings.set_model_override("/models/foo.gguf", max_seq_length = 1024)
+ settings.set_model_override("/models/FOO.gguf", max_seq_length = 8192)
+ assert settings.get_model_override("/models/Foo.gguf") == {}
+
+
+def test_request_used_api_key_distinguishes_key_from_session():
+ from auth.authentication import API_KEY_PREFIX
+
+ class _Req:
+ def __init__(self, header):
+ self.headers = {"authorization": header} if header else {}
+
+ assert inference_route._request_used_api_key(_Req(f"Bearer {API_KEY_PREFIX}abc")) is True
+ assert inference_route._request_used_api_key(_Req(f"bearer {API_KEY_PREFIX}abc")) is True
+ assert inference_route._request_used_api_key(_Req("Bearer eyJhbGciOiJIUzI1NiJ9.x")) is False
+ assert inference_route._request_used_api_key(_Req("")) is False
+ assert inference_route._request_used_api_key(_Req(None)) is False
+ # Hot path: a malformed request object must read as "not an API key" rather than raise.
+ assert inference_route._request_used_api_key(object()) is False
+ # A stand-in whose headers answer with anything at all, which is how the load
+ # routes are driven in tests: a monitor label must never take a load down.
+ from unittest.mock import MagicMock
+
+ assert inference_route._request_used_api_key(MagicMock()) is False
+
+
+def test_case_fallback_never_applies_to_a_posix_path(override_store):
+ # Two casings are two models on Linux, so a near miss loads defaults, not the other's pin.
+ settings.set_model_override("/models/foo.gguf", max_seq_length = 8192, gpu_ids = [1])
+ assert settings.get_model_override("/models/Foo.gguf") == {}
+ assert settings.get_model_override("/models/foo.gguf")["max_seq_length"] == 8192
+
+
+def test_case_fallback_does_apply_to_a_windows_path(override_store):
+ # NTFS is case-insensitive: these name one file, and the browser folds drive paths.
+ settings.set_model_override(r"c:\models\foo.gguf", max_seq_length = 8192)
+ assert settings.get_model_override(r"C:\models\FOO.gguf")["max_seq_length"] == 8192
+ assert settings.get_model_override("C:/Models/Foo.gguf")["max_seq_length"] == 8192
+
+
+def test_case_fallback_applies_to_unc_and_wsl_drive_paths(override_store):
+ settings.set_model_override(r"\\server\share\foo.gguf", max_seq_length = 4096)
+ settings.set_model_override("/mnt/c/models/bar.gguf", max_seq_length = 2048)
+ assert settings.get_model_override(r"\\Server\Share\FOO.gguf")["max_seq_length"] == 4096
+ assert settings.get_model_override("/mnt/C/Models/Bar.gguf")["max_seq_length"] == 2048
+
+
+def test_a_plain_posix_path_under_mnt_stays_case_sensitive(override_store):
+ # Only /mnt/<letter> is a WSL drive mount; /mnt/data is an ordinary case-sensitive mount.
+ settings.set_model_override("/mnt/data/models/foo.gguf", max_seq_length = 8192)
+ assert settings.get_model_override("/mnt/data/models/Foo.gguf") == {}
+
+
+def test_an_ambiguous_windows_case_fallback_still_matches_nothing(override_store):
+ # Two keys folding to one has no single answer, so the load takes defaults.
+ settings.set_model_override(r"c:\models\foo.gguf", max_seq_length = 1024)
+ settings.set_model_override("C:/models/FOO.gguf", max_seq_length = 8192)
+ assert settings.get_model_override(r"C:\Models\Foo.gguf") == {}
+
+
+def test_case_fallback_still_covers_repo_ids(override_store):
+ # The migration case this fallback exists for.
+ settings.set_model_override("unsloth/qwen3-8b-gguf:q4_k_m", max_seq_length = 8192)
+ assert settings.get_model_override("unsloth/Qwen3-8B-GGUF:Q4_K_M")["max_seq_length"] == 8192
+
+
+def test_explicit_remove_is_not_blocked_by_stale_invalid_flags(override_store):
+ # remove is the operation discriminator: a rejected flag must not turn a forget into a 400.
+ settings.set_model_override("unsloth/B-GGUF", max_seq_length = 4096)
+ resp = _put("unsloth/B-GGUF", remove = True, llama_extra_args = ["--port", "1234"])
+ assert "unsloth/B-GGUF" not in resp.overrides
+
+
+def test_explicit_remove_wins_over_config_fields_in_the_same_payload(override_store):
+ # remove is the operation discriminator: a stale field beside it must not make it an update.
+ settings.set_model_override("unsloth/B-GGUF", max_seq_length = 4096)
+ resp = _put("unsloth/B-GGUF", remove = True, max_seq_length = 8192, tensor_parallel = True)
+ assert "unsloth/B-GGUF" not in resp.overrides
+
+
+def test_posix_colon_in_a_path_is_not_treated_as_a_quant(override_store):
+ # "/models/foo:bar.gguf" is one filename: splitting grafts /models/foo's flags onto it.
+ settings.set_model_override("/models/foo", llama_extra_args = ["--flash-attn"])
+ resp = _put("/models/foo:bar.gguf", max_seq_length = 4096)
+ assert "llama_extra_args" not in resp.overrides["/models/foo:bar.gguf"]
+
+
+def test_unknown_quant_label_on_a_gguf_still_carries_flags_over(override_store):
+ # A .gguf with no quant token is labelled by its stem, so the UI saves ":custom".
+ settings.set_model_override("/models/custom.gguf", llama_extra_args = ["--flash-attn"])
+ resp = _put("/models/custom.gguf:custom", max_seq_length = 4096)
+ assert resp.overrides["/models/custom.gguf:custom"]["llama_extra_args"] == ["--flash-attn"]
+
+
+def test_bpw_qualified_variants_still_carry_flags_over(override_store):
+ # model_config.py keeps a bits-per-weight modifier on the label, and that form reaches keys.
+ settings.set_model_override("unsloth/Repo-GGUF", llama_extra_args = ["--flash-attn"])
+ resp = _put("unsloth/Repo-GGUF:IQ4_XS-3.53bpw", max_seq_length = 4096)
+ assert resp.overrides["unsloth/Repo-GGUF:IQ4_XS-3.53bpw"]["llama_extra_args"] == [
+ "--flash-attn"
+ ]
+
+
+def test_a_posix_path_variant_folds_while_the_path_does_not(override_store):
+ # The browser lowercases the quant but keeps POSIX path casing.
+ settings.set_model_override("/models/Foo:q4_k_m", max_seq_length = 8192)
+ assert settings.get_model_override("/models/Foo:Q4_K_M")["max_seq_length"] == 8192
+ assert settings.get_model_override("/models/foo:Q4_K_M") == {}
+
+
+def test_an_unknown_gguf_label_is_reachable_in_either_casing(override_store):
+ # The stem-derived label is lowercased in storage while the scanner keeps filename casing.
+ settings.set_model_override("/models/CustomModel.gguf:custommodel", max_seq_length = 8192)
+ got = settings.get_model_override("/models/CustomModel.gguf:CustomModel")
+ assert got["max_seq_length"] == 8192
+ # The path itself is still case-sensitive on POSIX.
+ assert settings.get_model_override("/models/custommodel.gguf:CustomModel") == {}
+
+
+def test_a_posix_colon_filename_is_not_folded_as_a_variant(override_store):
+ # "/models/foo:Bar.gguf" is one filename: folding its tail reaches a different file.
+ settings.set_model_override("/models/foo:bar.gguf", max_seq_length = 8192)
+ assert settings.get_model_override("/models/foo:Bar.gguf") == {}
+
+
+def test_a_suffix_the_scanner_would_not_derive_carries_nothing_over(override_store):
+ # Only the scanner's exact label is accepted, so a stray colon suffix reaches nothing.
+ settings.set_model_override("/models/custom.gguf", llama_extra_args = ["--flash-attn"])
+ resp = _put("/models/custom.gguf:something-else", max_seq_length = 4096)
+ assert "llama_extra_args" not in resp.overrides["/models/custom.gguf:something-else"]
+
+
+def test_unknown_quant_label_carries_over_for_a_windows_path(override_store):
+ # Written on Windows, read back where a backslash is an ordinary filename character.
+ settings.set_model_override(r"C:\models\custom.gguf", llama_extra_args = ["--flash-attn"])
+ resp = _put(r"C:\models\custom.gguf:custom", max_seq_length = 4096)
+ assert resp.overrides[r"C:\models\custom.gguf:custom"]["llama_extra_args"] == ["--flash-attn"]
+
+
+def test_real_quant_suffix_on_a_path_still_carries_flags_over(override_store):
+ settings.set_model_override("/models/x.gguf", llama_extra_args = ["--flash-attn"])
+ resp = _put("/models/x.gguf:Q4_K_M", max_seq_length = 4096)
+ assert resp.overrides["/models/x.gguf:Q4_K_M"]["llama_extra_args"] == ["--flash-attn"]
+
+
+def test_load_retries_without_gpu_ids_when_the_loader_rejects_the_pin(monkeypatch):
+ # The pre-flight check can't mirror every loader rule, and a stale pin must not block a load.
+ from fastapi import HTTPException
+
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("unsloth/B-GGUF", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+ monkeypatch.setattr(
+ settings, "get_model_override", lambda mid: {"gpu_ids": [0], "max_seq_length": 4096}
+ )
+
+ async def _usable(ids):
+ return True
+
+ monkeypatch.setattr(inference_route, "_override_gpu_ids_still_resolve", _usable)
+
+ calls = {"n": 0}
+
+ async def _load(request, *args, **kwargs):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise HTTPException(
+ status_code = 400,
+ detail = "GPU selection (gpu_ids) is not supported for a DiffusionGemma GGUF",
+ )
+ return await rec(request, *args, **kwargs)
+
+ monkeypatch.setattr(inference_route, "_load_model_impl", _load)
+
+ _run_hook("unsloth/B-GGUF")
+ assert calls["n"] == 2
+ served = rec.calls[-1]
+ assert not served.gpu_ids
+ assert served.max_seq_length == 4096
+
+
+def test_a_non_gpu_load_failure_is_not_retried(monkeypatch):
+ from fastapi import HTTPException
+
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("unsloth/B-GGUF", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = rec,
+ )
+ monkeypatch.setattr(settings, "get_model_override", lambda mid: {"gpu_ids": [0]})
+
+ async def _usable(ids):
+ return True
+
+ monkeypatch.setattr(inference_route, "_override_gpu_ids_still_resolve", _usable)
+
+ calls = {"n": 0}
+
+ async def _load(request, *args, **kwargs):
+ calls["n"] += 1
+ raise HTTPException(status_code = 400, detail = "Corrupt GGUF header")
+
+ monkeypatch.setattr(inference_route, "_load_model_impl", _load)
+
+ with pytest.raises(HTTPException):
+ _run_hook("unsloth/B-GGUF")
+ assert calls["n"] == 1
+
+
+def test_removal_clears_the_entry_a_load_would_actually_resolve(override_store):
+ # A forget can carry a different casing; removing only the literal key leaves a live entry.
+ settings.set_model_override("unsloth/B-GGUF:Q4_K_M", max_seq_length = 8192)
+ assert settings.get_model_override("unsloth/b-gguf:q4_k_m")["max_seq_length"] == 8192
+
+ _put("unsloth/b-gguf:q4_k_m", remove = True)
+ assert settings.get_model_overrides() == {}
+ assert settings.get_model_override("unsloth/B-GGUF:Q4_K_M") == {}
+
+
+def test_save_updates_the_existing_case_variant_instead_of_forking_it(override_store):
+ # The backfill stores lowercase keys while a later UI save carries the catalog's casing.
+ settings.set_model_override("unsloth/b-gguf:q4_k_m", max_seq_length = 8192)
+ _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 4096)
+ assert list(settings.get_model_overrides()) == ["unsloth/b-gguf:q4_k_m"]
+ assert settings.get_model_override("Unsloth/B-GGUF:Q4_K_M")["max_seq_length"] == 4096
+
+
+def test_removal_of_a_path_still_only_touches_the_exact_key(override_store):
+ settings.set_model_override("/models/foo.gguf", max_seq_length = 8192)
+ _put("/models/Foo.gguf", remove = True)
+ # A different file must survive its neighbour being forgotten.
+ assert settings.get_model_override("/models/foo.gguf")["max_seq_length"] == 8192
+
+
+def test_forget_clears_the_filename_derived_key_a_load_still_reads(override_store):
+ # The picker once keyed a standalone .gguf by its filename quant label; backfill carries it.
+ settings.set_model_override(
+ "/models/Qwen3-8B-Q4_K_M.gguf:q4_k_m",
+ max_seq_length = 8192,
+ )
+ _put("/models/Qwen3-8B-Q4_K_M.gguf", remove = True)
+ assert settings.get_model_override("/models/Qwen3-8B-Q4_K_M.gguf:Q4_K_M") == {}
+ assert settings.get_model_overrides() == {}
+
+
+def test_forget_clears_the_bare_repo_entry_the_quant_inherited_from(override_store):
+ # A save under repo:QUANT copies the flags off a legacy bare entry and leaves it in place,
+ # and the loader falls back to it, so clearing only the qualified key hands them back.
+ settings.set_model_override(
+ "unsloth/B-GGUF",
+ llama_extra_args = ["--flash-attn"],
+ max_seq_length = 8192,
+ )
+ _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 4096)
+ _put("unsloth/B-GGUF:Q4_K_M", remove = True)
+ assert settings.get_model_override("unsloth/B-GGUF") == {}
+ assert settings.get_model_overrides() == {}
+
+
+def test_forget_keeps_a_bare_entry_another_quant_still_has_settings_under(override_store):
+ # The bare entry backs every quant with no entry of its own, so forgetting Q4 must not
+ # strip it while Q8 is still there: this forget is not the last word on the model.
+ settings.set_model_override("unsloth/B-GGUF", max_seq_length = 8192)
+ settings.set_model_override("unsloth/B-GGUF:Q8_0", max_seq_length = 2048)
+ _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 4096)
+ _put("unsloth/B-GGUF:Q4_K_M", remove = True)
+ assert settings.get_model_override("unsloth/B-GGUF") == {"max_seq_length": 8192}
+ assert settings.get_model_override("unsloth/B-GGUF:Q8_0") == {"max_seq_length": 2048}
+
+
+def test_forget_clears_every_spelling_of_one_model(override_store):
+ # Two spellings of one repo can coexist; clearing only the named one makes the survivor
+ # the sole fold match, so the next load reapplies what was just forgotten.
+ settings.set_model_override("unsloth/B-GGUF:Q4_K_M", max_seq_length = 8192)
+ settings.set_model_override("unsloth/b-gguf:q4_k_m", max_seq_length = 8192)
+ _put("unsloth/B-GGUF:Q4_K_M", remove = True)
+ assert settings.get_model_overrides() == {}
+ assert settings.get_model_override("unsloth/B-GGUF:Q4_K_M") == {}
+
+
+def test_forget_of_one_windows_spelling_clears_the_other(override_store):
+ # Windows paths fold, so two spellings are one file and both have to go.
+ settings.set_model_override(r"C:\Models\x.gguf", max_seq_length = 8192)
+ settings.set_model_override("c:/models/X.gguf", max_seq_length = 4096)
+ _put(r"C:\Models\x.gguf", remove = True)
+ assert settings.get_model_overrides() == {}
+
+
+def test_forget_of_a_posix_path_still_spares_its_case_sibling(override_store):
+ # POSIX paths do not fold: two casings are two files, so a forget spares the sibling.
+ settings.set_model_override("/models/foo.gguf", max_seq_length = 8192)
+ settings.set_model_override("/models/Foo.gguf", max_seq_length = 4096)
+ _put("/models/foo.gguf", remove = True)
+ assert list(settings.get_model_overrides()) == ["/models/Foo.gguf"]
+
+
+def test_forget_leaves_another_file_own_derived_key_alone(override_store):
+ # The derived key uses the forgotten file's own path, so a quant-sharing neighbour survives.
+ settings.set_model_override("/models/Other-Q4_K_M.gguf:q4_k_m", max_seq_length = 4096)
+ _put("/models/Qwen3-8B-Q4_K_M.gguf", remove = True)
+ assert settings.get_model_override("/models/Other-Q4_K_M.gguf:Q4_K_M")["max_seq_length"] == 4096
+
+
+def test_forget_of_a_repo_quant_key_derives_nothing(override_store):
+ # Only a bare .gguf path derives a label.
+ settings.set_model_override("unsloth/b-gguf:q4_k_m", max_seq_length = 8192)
+ _put("unsloth/B-GGUF", remove = True)
+ assert settings.get_model_override("unsloth/b-gguf:q4_k_m")["max_seq_length"] == 8192
+
+
def test_a_tag_that_names_no_quant_resolves_to_the_repo(monkeypatch):
# A downloaded but unloaded GGUF asked for as org/model:latest missed the resolver,
# so the switch could not load it (404ing on a quant that was never a quant with
@@ -4382,3 +5327,475 @@ def test_two_local_paths_differing_only_in_case_are_not_the_same_model(monkeypat
alias = _FakeBackend(loaded_id = "unsloth/Qwen3-4B-GGUF")
monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: alias)
assert inference_route._loaded_satisfies("unsloth/qwen3-4b-gguf") is True
+
+
+def test_abs_path_ids_are_recognised_in_either_platform_spelling():
+ """Path() follows the running OS, so a Windows host read "/home/me/x.gguf" as
+ relative and a POSIX host read "C:\\models\\x.gguf" the same way, and either
+ then reached /v1/models as a published host path. Ids outlive the machine
+ that wrote them (settings sync, WSL, a copied config), and the model-override
+ identity already folds both spellings."""
+ from types import SimpleNamespace
+
+ for spelling in ("/home/me/models/x.gguf", "C:\\models\\x.gguf", "//host/share/x.gguf"):
+ assert resolver._is_abs_path_id(spelling) is True, spelling
+ # An alias wins, and with none the path is stripped to a public id.
+ assert (
+ resolver._advertised_loader_id(
+ SimpleNamespace(id = spelling, model_id = "org/X-GGUF", display_name = "X")
+ )
+ == "org/X-GGUF"
+ )
+ advertised = resolver._advertised_loader_id(
+ SimpleNamespace(id = spelling, model_id = None, display_name = None)
+ )
+ assert advertised is not None
+ assert "/" not in advertised and "\\" not in advertised, advertised
+
+ # A repo id has no leading separator, drive or UNC prefix under either reading.
+ for repo_id in ("org/Repo-GGUF", "Repo", "org/Repo-GGUF:Q4_K_M"):
+ assert resolver._is_abs_path_id(repo_id) is False, repo_id
+
+
+def test_fill_absent_fields_put_never_replaces_a_newer_server_value(override_store):
+ """The one-time localStorage backfill reads the override map once and then
+ writes each model in turn, so a save by another tab during that pass was
+ overwritten by this browser's older copy. fill_absent_fields writes only what
+ the entry lacks, so every value already on the server wins."""
+ import routes.settings as settings_route
+
+ # The other tab's save lands first.
+ newer = settings_route.ModelOverridePayload(model_id = "unsloth/B-GGUF", max_seq_length = 8192)
+ settings_route.update_openai_auto_switch_override(newer, "tester")
+
+ # The backfill's write, carrying this browser's older localStorage value.
+ backfill = settings_route.ModelOverridePayload(
+ model_id = "unsloth/B-GGUF", max_seq_length = 2048, fill_absent_fields = True
+ )
+ resp = settings_route.update_openai_auto_switch_override(backfill, "tester")
+ assert resp.overrides["unsloth/B-GGUF"]["max_seq_length"] == 8192
+
+ # With nothing stored it still creates, or the migration would never run.
+ fresh = settings_route.ModelOverridePayload(
+ model_id = "unsloth/C-GGUF", max_seq_length = 2048, fill_absent_fields = True
+ )
+ resp2 = settings_route.update_openai_auto_switch_override(fresh, "tester")
+ assert resp2.overrides["unsloth/C-GGUF"]["max_seq_length"] == 2048
+
+
+def test_fill_absent_fields_carries_the_browser_only_settings_into_a_legacy_entry(monkeypatch):
+ """Codex P1: the override map shipped before the browser mirror did, storing only
+ llama_extra_args and max_seq_length. An upgraded install holds such an entry while
+ localStorage holds the context, KV cache, speculative and GPU settings, and an
+ entry-level skip would strand exactly what the migration exists to carry."""
+ import routes.settings as settings_route
+
+ store = _mock_override_store(monkeypatch)
+
+ legacy = settings_route.ModelOverridePayload(
+ model_id = "unsloth/B-GGUF:Q4_K_M",
+ llama_extra_args = ["--flash-attn"],
+ max_seq_length = 8192,
+ )
+ settings_route.update_openai_auto_switch_override(legacy, "tester")
+
+ backfill = settings_route.ModelOverridePayload(
+ model_id = "unsloth/B-GGUF:Q4_K_M",
+ # A field the server already has, plus the ones only the browser holds.
+ max_seq_length = 2048,
+ custom_context_length = 32768,
+ kv_cache_dtype = "q8_0",
+ speculative_type = "ngram",
+ gpu_ids = [0, 1],
+ fill_absent_fields = True,
+ )
+ resp = settings_route.update_openai_auto_switch_override(backfill, "tester")
+ entry = resp.overrides["unsloth/B-GGUF:Q4_K_M"]
+ # The server's own values survive untouched.
+ assert entry["max_seq_length"] == 8192
+ assert entry["llama_extra_args"] == ["--flash-attn"]
+ # The browser-only settings are now there, so an API load applies them.
+ assert entry["custom_context_length"] == 32768
+ assert entry["kv_cache_dtype"] == "q8_0"
+ assert entry["speculative_type"] == "ngram"
+ assert entry["gpu_ids"] == [0, 1]
+ # One entry, not two: the fill resolves onto the key a load reads.
+ assert list(store[settings.MODEL_OVERRIDES_SETTING_KEY]) == ["unsloth/B-GGUF:Q4_K_M"]
+
+ # An ordinary save is still a replacement, or an edit could never clear a field.
+ edit = settings_route.ModelOverridePayload(
+ model_id = "unsloth/B-GGUF:Q4_K_M", max_seq_length = 4096
+ )
+ resp2 = settings_route.update_openai_auto_switch_override(edit, "tester")
+ assert resp2.overrides["unsloth/B-GGUF:Q4_K_M"]["max_seq_length"] == 4096
+ assert "kv_cache_dtype" not in resp2.overrides["unsloth/B-GGUF:Q4_K_M"]
+
+
+def test_fill_absent_fields_matches_a_legacy_casing_and_never_deletes(override_store):
+ """The stored key can carry the casing an older install typed, and it must not
+ be duplicated or emptied by a fill for the folded spelling."""
+ import routes.settings as settings_route
+
+ stored = settings_route.ModelOverridePayload(
+ model_id = "Unsloth/B-GGUF:Q4_K_M", max_seq_length = 8192
+ )
+ settings_route.update_openai_auto_switch_override(stored, "tester")
+
+ folded = settings_route.ModelOverridePayload(
+ model_id = "unsloth/b-gguf:q4_k_m", max_seq_length = 2048, fill_absent_fields = True
+ )
+ resp = settings_route.update_openai_auto_switch_override(folded, "tester")
+ assert list(resp.overrides) == ["Unsloth/B-GGUF:Q4_K_M"]
+ assert resp.overrides["Unsloth/B-GGUF:Q4_K_M"]["max_seq_length"] == 8192
+
+ # An all-default fill is a no-op, not the "empty payload means forget" path.
+ empty = settings_route.ModelOverridePayload(
+ model_id = "Unsloth/B-GGUF:Q4_K_M", fill_absent_fields = True
+ )
+ resp2 = settings_route.update_openai_auto_switch_override(empty, "tester")
+ assert resp2.overrides["Unsloth/B-GGUF:Q4_K_M"]["max_seq_length"] == 8192
+
+ # A fill that is also a delete has no meaning.
+ with pytest.raises(HTTPException) as excinfo:
+ _put("Unsloth/B-GGUF:Q4_K_M", remove = True, fill_absent_fields = True)
+ assert excinfo.value.status_code == 400
+
+
+def test_fill_absent_fields_does_not_break_the_empty_payload_removal(override_store):
+ """fill_absent_fields is a write mode, not a saved field: leaving it in the dumped
+ payload would make every request look non-empty and silently retire the legacy
+ "a payload carrying only model_id forgets this model" contract."""
+ import routes.settings as settings_route
+
+ stored = settings_route.ModelOverridePayload(model_id = "unsloth/B-GGUF", max_seq_length = 4096)
+ settings_route.update_openai_auto_switch_override(stored, "tester")
+ empty = settings_route.ModelOverridePayload(model_id = "unsloth/B-GGUF")
+ resp = settings_route.update_openai_auto_switch_override(empty, "tester")
+ assert "unsloth/B-GGUF" not in resp.overrides
+
+
+def test_map_entry_fill_reads_and_writes_in_one_transaction(tmp_path, monkeypatch):
+ """The real store, not the in-memory stand-in: the read has to share the write's
+ transaction, or a concurrent writer still slips between them."""
+ import storage.studio_db as db
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.setattr(db, "_schema_ready", False)
+
+ key = "test_map_entry_create"
+ assert db.upsert_app_setting_map_entry(key, "a", {"v": 1}) == {"a": {"v": 1}}
+ # Present: the stored value stays, and a field it lacks is added.
+ assert db.upsert_app_setting_map_entry(key, "a", {"v": 2}, fill_absent_fields = True) == {
+ "a": {"v": 1}
+ }
+ assert db.get_app_setting(key) == {"a": {"v": 1}}
+ assert db.upsert_app_setting_map_entry(key, "a", {"v": 2, "w": 7}, fill_absent_fields = True) == {
+ "a": {"v": 1, "w": 7}
+ }
+ assert db.get_app_setting(key) == {"a": {"v": 1, "w": 7}}
+ # Absent: created.
+ assert db.upsert_app_setting_map_entry(key, "b", {"v": 3}, fill_absent_fields = True) == {
+ "a": {"v": 1, "w": 7},
+ "b": {"v": 3},
+ }
+ # A fill never deletes, even with nothing to store.
+ assert db.upsert_app_setting_map_entry(key, "a", None, fill_absent_fields = True) == {
+ "a": {"v": 1, "w": 7},
+ "b": {"v": 3},
+ }
+ # The ordinary write still replaces and still removes.
+ db.upsert_app_setting_map_entry(key, "a", {"v": 9})
+ db.upsert_app_setting_map_entry(key, "b", None)
+ assert db.get_app_setting(key) == {"a": {"v": 9}}
+
+
+def test_gpu_ids_dedupe_is_not_a_scan_of_the_list_being_built():
+ """gpu_ids arrives from an authenticated client and normalize_model_override
+ de-duplicates it. Testing membership against the growing list walks up to
+ MAX_GPU_ID entries per element; a set keeps the pass linear. Order, bounds and
+ the bool rejection all have to survive the change."""
+ import time
+
+ from utils.openai_auto_switch_settings import MAX_GPU_ID, normalize_model_override
+
+ assert normalize_model_override({"gpu_ids": [3, 1, 3, 0, 1, 2]})["gpu_ids"] == [3, 1, 0, 2]
+ # bool is an int subclass; [True, False] must not pin GPUs 1 and 0.
+ assert normalize_model_override({"gpu_ids": [True, False]}) == {}
+ assert normalize_model_override({"gpu_ids": [MAX_GPU_ID + 1, -1, 2]})["gpu_ids"] == [2]
+
+ ids = [index % (MAX_GPU_ID + 1) for index in range(200_000)]
+ started = time.perf_counter()
+ normalized = normalize_model_override({"gpu_ids": ids})
+ elapsed = time.perf_counter() - started
+ assert len(normalized["gpu_ids"]) == MAX_GPU_ID + 1
+ # The scan version took ~1s for this input on a dev box; a linear pass is ~50ms.
+ assert elapsed < 0.5, elapsed
+
+
+def test_gpu_ids_payload_is_bounded():
+ """A list longer than the number of ids the normalizer can store adds nothing
+ but work, so it is rejected at the boundary. A real device list is tiny."""
+ import pydantic
+
+ import routes.settings as settings_route
+ from utils.openai_auto_switch_settings import MAX_GPU_ID
+
+ assert settings_route.MAX_GPU_IDS == MAX_GPU_ID + 1
+ at_limit = settings_route.ModelOverridePayload(
+ model_id = "x", gpu_ids = list(range(settings_route.MAX_GPU_IDS))
+ )
+ assert len(at_limit.gpu_ids) == settings_route.MAX_GPU_IDS
+ with pytest.raises(pydantic.ValidationError):
+ settings_route.ModelOverridePayload(
+ model_id = "x", gpu_ids = [0] * (settings_route.MAX_GPU_IDS + 1)
+ )
+ # The ordinary case is untouched.
+ assert settings_route.ModelOverridePayload(model_id = "x", gpu_ids = [0, 1]).gpu_ids == [0, 1]
+
+
+# ── codex round: the concrete key beats the advertised alias ──────────
+
+
+def _switch_with_overrides(monkeypatch, resolves_to, stored, requested):
+ """Run the auto-switch hook against a real override map and return the load."""
+ backend = _FakeBackend(None)
+ rec = _LoadRecorder(backend)
+ _wire(monkeypatch, enabled = True, resolves_to = resolves_to, backend = backend, recorder = rec)
+ _mock_override_store(monkeypatch)
+ for key, max_seq_length in stored.items():
+ settings.set_model_override(key, max_seq_length = max_seq_length)
+ _run_hook(requested)
+ assert len(rec.calls) == 1
+ return rec.calls[0]
+
+
+def test_a_loose_gguf_prefers_its_path_keyed_settings_over_the_alias(monkeypatch):
+ """Codex: the settings UI keys a standalone .gguf by its bare path, while
+ override_id is the filename stem /v1/models advertises and an overrides PUT can
+ be written against. Reading the alias first let it shadow the saved settings for
+ good, so an API load kept applying the old flags."""
+ path = "/srv/models/Qwen3-8B-Q4_K_M.gguf"
+ alias = "Qwen3-8B-Q4_K_M"
+ req = _switch_with_overrides(
+ monkeypatch,
+ resolves_to = (path, None, alias),
+ stored = {alias: 2048, path: 32768},
+ requested = alias,
+ )
+ assert req.max_seq_length == 32768
+
+ # The alias is still read when it is the only key.
+ req2 = _switch_with_overrides(
+ monkeypatch,
+ resolves_to = (path, None, alias),
+ stored = {alias: 2048},
+ requested = alias,
+ )
+ assert req2.max_seq_length == 2048
+
+
+def test_the_filename_label_key_no_longer_shadows_the_bare_path(monkeypatch):
+ """An early build of this feature keyed a standalone .gguf by the quant label
+ derived from its filename. Those entries stay readable, but the bare path the
+ picker writes today comes first."""
+ path = "/srv/models/Qwen3-8B-Q4_K_M.gguf"
+ alias = "Qwen3-8B-Q4_K_M"
+ req = _switch_with_overrides(
+ monkeypatch,
+ resolves_to = (path, None, alias),
+ stored = {f"{path}:Q4_K_M": 2048, path: 32768},
+ requested = alias,
+ )
+ assert req.max_seq_length == 32768
+
+ req2 = _switch_with_overrides(
+ monkeypatch,
+ resolves_to = (path, None, alias),
+ stored = {f"{path}:Q4_K_M": 2048},
+ requested = alias,
+ )
+ assert req2.max_seq_length == 2048
+
+
+def test_a_variant_qualified_path_key_beats_the_same_quant_under_the_alias(monkeypatch):
+ """An LM Studio dir or a non-active HF cache is configured against its path, so
+ a same-quant entry under the repo id (another copy of the same repo, or a
+ hand-written PUT) must not win over the row the user actually edited."""
+ path = "/srv/lmstudio/publisher/Qwen3-8B-GGUF"
+ repo = "publisher/Qwen3-8B-GGUF"
+ req = _switch_with_overrides(
+ monkeypatch,
+ resolves_to = (path, "Q4_K_M", repo),
+ stored = {f"{repo}:Q4_K_M": 2048, f"{path}:Q4_K_M": 32768},
+ requested = f"{repo}:Q4_K_M",
+ )
+ assert req.max_seq_length == 32768
+
+
+def test_a_cached_repo_still_resolves_by_its_repo_id(monkeypatch):
+ """The Hub keys a cached repo row by its repo id, which is the advertised id,
+ and no path entry exists for it, so it still resolves on the second try."""
+ snapshot = "/mnt/old-cache/models--unsloth--Qwen3-8B-GGUF/snapshots/abc123"
+ repo = "unsloth/Qwen3-8B-GGUF"
+ req = _switch_with_overrides(
+ monkeypatch,
+ resolves_to = (snapshot, "Q4_K_M", repo),
+ stored = {f"{repo}:Q4_K_M": 32768},
+ requested = f"{repo}:Q4_K_M",
+ )
+ assert req.max_seq_length == 32768
+
+ # A bare entry under the repo id keeps working too.
+ req2 = _switch_with_overrides(
+ monkeypatch,
+ resolves_to = (snapshot, "Q4_K_M", repo),
+ stored = {repo: 16384},
+ requested = f"{repo}:Q4_K_M",
+ )
+ assert req2.max_seq_length == 16384
+
+
+def test_a_fill_does_not_replay_a_stored_flag_through_validation(monkeypatch):
+ """The migration now writes for entries it used to skip, and an omitted
+ llama_extra_args is normally carried over from the stored entry. Replaying a
+ flag that has been denylisted since it was saved would 400 the one-time
+ migration, which then retries on every start. A fill keeps the stored flags
+ without sending them back."""
+ import routes.settings as settings_route
+ from core.inference import llama_server_args
+
+ store = _mock_override_store(monkeypatch)
+ settings.set_model_override("unsloth/B-GGUF:Q4_K_M", llama_extra_args = ["--flash-attn"])
+
+ # The flag is refused from now on, as a later release's denylist would.
+ real_validate = llama_server_args.validate_extra_args
+
+ def _reject_flash_attn(args):
+ if args and "--flash-attn" in args:
+ raise ValueError("--flash-attn is managed by the server.")
+ return real_validate(args)
+
+ monkeypatch.setattr(llama_server_args, "validate_extra_args", _reject_flash_attn)
+
+ fill = settings_route.ModelOverridePayload(
+ model_id = "unsloth/B-GGUF:Q4_K_M", custom_context_length = 32768, fill_absent_fields = True
+ )
+ resp = settings_route.update_openai_auto_switch_override(fill, "tester")
+ entry = resp.overrides["unsloth/B-GGUF:Q4_K_M"]
+ assert entry["llama_extra_args"] == ["--flash-attn"]
+ assert entry["custom_context_length"] == 32768
+ assert list(store[settings.MODEL_OVERRIDES_SETTING_KEY]) == ["unsloth/B-GGUF:Q4_K_M"]
+
+ # An ordinary save still validates what it is handed.
+ with pytest.raises(HTTPException) as excinfo:
+ _put("unsloth/C-GGUF", llama_extra_args = ["--flash-attn"])
+ assert excinfo.value.status_code == 400
+
+
+def test_override_payload_rejects_booleans_for_numeric_fields():
+ """bool subclasses int and pydantic parses non-strictly, so `true` would
+ arrive as 1: `max_seq_length: true` becomes a one-token context and
+ `gpu_ids: [true]` pins GPU 1. _bounded_int rejects bools for exactly that
+ reason, but never sees one, because coercion happens at the route boundary
+ first. Reject them there so that guard is reachable through this path."""
+ import pytest
+ from pydantic import ValidationError
+ from routes.settings import ModelOverridePayload
+
+ for field, value in (
+ ("max_seq_length", True),
+ ("custom_context_length", True),
+ ("spec_draft_n_max", True),
+ ("n_parallel", True),
+ ("gpu_layers", False),
+ ("n_cpu_moe", True),
+ ("gpu_ids", [True]),
+ ("gpu_ids", [0, False, 2]),
+ ):
+ with pytest.raises(ValidationError):
+ ModelOverridePayload(model_id = "unsloth/x-GGUF:Q4_K_M", **{field: value})
+
+ # Only bools are rejected: real values, including real booleans, still validate.
+ ok = ModelOverridePayload(
+ model_id = "unsloth/x-GGUF:Q4_K_M",
+ max_seq_length = 4096,
+ gpu_layers = -1,
+ n_cpu_moe = 0,
+ gpu_ids = [0, 1],
+ tensor_parallel = True,
+ remove = True,
+ fill_absent_fields = True,
+ )
+ assert ok.max_seq_length == 4096
+ assert ok.gpu_ids == [0, 1]
+ assert ok.gpu_layers == -1
+ assert ok.tensor_parallel is True
+ assert ok.remove is True
+ assert ok.fill_absent_fields is True
+
+
+# ── codex round: the alias retirement has to be atomic with the write ──
+
+
+def test_two_spellings_of_one_cached_quant_do_not_delete_each_others_save(monkeypatch):
+ """A save writes its target key, then reads the map back to retire the other spelling
+ of the same cached repo, in a second transaction. This route is a plain `def`, so
+ FastAPI runs it in a threadpool: two clients saving one quant, one by repo id and one
+ by the snapshot path an upgraded install still holds, can both write before either
+ cleanup runs and then retire each other's row. Both calls return 200 and nothing is
+ stored. Whichever runs second must retire the first instead."""
+ import threading
+ import routes.settings as settings_route
+
+ _mock_override_store(monkeypatch)
+ repo = "unsloth/Qwen3-8B-GGUF:Q4_K_M"
+ snapshot = "/mnt/old-cache/models--unsloth--Qwen3-8B-GGUF/snapshots/abc123:Q4_K_M"
+
+ ready = threading.Barrier(2)
+ written = threading.Barrier(2)
+ write_lock = threading.Lock()
+ wrote = set()
+ real_set = settings_route.set_model_override
+
+ def _set_then_sync(model_id, *args, **kwargs):
+ # One write is one transaction in production (BEGIN IMMEDIATE), so keep the fake
+ # store's read-modify-write atomic too: only the gap between writes is on trial.
+ with write_lock:
+ result = real_set(model_id, *args, **kwargs)
+ ident = threading.get_ident()
+ if ident not in wrote:
+ wrote.add(ident)
+ try:
+ # Hold each save just after it stored its own key, so neither looks for
+ # aliases until both are there. Broken instead when the two are serialized:
+ # the second saver cannot reach this while the first is still inside.
+ written.wait(timeout = 1.0)
+ except threading.BrokenBarrierError:
+ pass
+ return result
+
+ monkeypatch.setattr(settings_route, "set_model_override", _set_then_sync)
+
+ failures = []
+
+ def _save(model_id, max_seq_length):
+ try:
+ ready.wait(timeout = 10.0)
+ _put(model_id, max_seq_length = max_seq_length)
+ except BaseException as exc: # noqa: BLE001 - re-reported below
+ failures.append(exc)
+
+ threads = [
+ threading.Thread(target = _save, args = (repo, 8192)),
+ threading.Thread(target = _save, args = (snapshot, 4096)),
+ ]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(timeout = 30.0)
+ assert not thread.is_alive()
+ assert not failures, failures
+
+ stored = settings.get_model_overrides()
+ assert list(stored) in ([repo], [snapshot]), stored
+ assert stored[list(stored)[0]]["max_seq_length"] in (4096, 8192)
diff --git a/studio/backend/tests/test_parallel_slots_per_load.py b/studio/backend/tests/test_parallel_slots_per_load.py
index f4f2d31c6f6..bd21eff480b 100644
--- a/studio/backend/tests/test_parallel_slots_per_load.py
+++ b/studio/backend/tests/test_parallel_slots_per_load.py
@@ -152,6 +152,12 @@ def test_frontend_mirror_matches_shared_bounds():
assert (int(low.group(1)), int(high.group(1))) == (PARALLEL_MIN, PARALLEL_MAX)
+def test_override_mirror_matches_shared_bounds():
+ # Mirrored, not imported: llama_server_args owns the allow-list that module stays out of.
+ from utils.openai_auto_switch_settings import PARALLEL_SLOTS_MAX, PARALLEL_SLOTS_MIN
+ assert (PARALLEL_SLOTS_MIN, PARALLEL_SLOTS_MAX) == (PARALLEL_MIN, PARALLEL_MAX)
+
+
def test_preset_model_reuses_shared_bounds():
# Bounds drifting from PARALLEL_MIN/MAX would 422 valid presets on every sync.
from routes.chat_history import ChatPresetLoadConfig
diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.py
index 95208462832..11f0b381a2c 100644
--- a/studio/backend/utils/openai_auto_switch_settings.py
+++ b/studio/backend/utils/openai_auto_switch_settings.py
@@ -27,6 +27,7 @@ per-request hot path; writes invalidate the cache.
from __future__ import annotations
import os
+import re
import threading
import time
from typing import Any, Optional
@@ -246,35 +247,508 @@ def set_openai_auto_switch(
)
+# --- Per-model launch config -------------------------------------------------
+#
+# An override is the server-side twin of the UI's per-model config, mirrored on every save
+# so an API load applies the same launch settings the picker would. Legacy entries hold just
+# {llama_extra_args, max_seq_length}. Every field is optional and absent means "app default";
+# a write replaces the fields it expresses, so the route carries `llama_extra_args` over.
+# Known gap: the picker's global fallbacks for GPU memory mode and speculative decoding live
+# in browser localStorage, so an API load of a model following the global gets the default.
+
+# Mirrors _valid_cache_types in core/inference/llama_cpp.py.
+VALID_KV_CACHE_DTYPES = frozenset(
+ {"f16", "bf16", "q8_0", "q4_0", "q4_1", "q5_0", "q5_1", "iq4_nl", "f32"}
+)
+# Canonical values plus the legacy spellings LoadRequest still accepts.
+VALID_SPECULATIVE_TYPES = frozenset(
+ {
+ "auto",
+ "mtp",
+ "ngram",
+ "mtp+ngram",
+ "off",
+ "default",
+ "draft-mtp",
+ "ngram-mod",
+ "ngram-simple",
+ }
+)
+# Only these consume spec_draft_n_max (mirrors MTP_SPECULATIVE_TYPES in the UI).
+MTP_SPECULATIVE_TYPES = frozenset({"mtp", "mtp+ngram", "draft-mtp"})
+VALID_GPU_MEMORY_MODES = frozenset({"auto", "manual"})
+
+# Mirrors PARALLEL_MIN/MAX in llama_server_args.py. Mirrored not imported: that module owns
+# the extra-args allow-list this one must stay out of.
+PARALLEL_SLOTS_MIN = 1
+PARALLEL_SLOTS_MAX = 64
+
+MAX_SEQ_LENGTH_CEILING = 1048576
+MAX_CHAT_TEMPLATE_OVERRIDE_BYTES = 65_536
+# Highest device index a gpu_ids entry may name; also bounds how many ids one entry holds.
+MAX_GPU_ID = 1024
+
+
+def _clean_str(value: Any, allowed: frozenset[str]) -> Optional[str]:
+ if not isinstance(value, str):
+ return None
+ normalized = value.strip().lower()
+ return normalized if normalized in allowed else None
+
+
+def _bounded_int(value: Any, *, minimum: int, maximum: int) -> Optional[int]:
+ # bool subclasses int, so `gpu_ids: [true, false]` would pin GPUs 1 and 0.
+ if isinstance(value, bool):
+ return None
+ # int(1.5) is 1, which would silently mangle a fractional context.
+ if isinstance(value, float) and not value.is_integer():
+ return None
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError, OverflowError):
+ # OverflowError is float("inf"), which json.loads accepts as `Infinity`.
+ return None
+ if parsed < minimum or parsed > maximum:
+ return None
+ return parsed
+
+
+def normalize_model_override(payload: dict[str, Any]) -> dict[str, Any]:
+ """Validate one per-model launch config, dropping anything unusable.
+
+ Silently drops rather than raising: an override is a convenience mirror of the
+ UI's config, so one stale field (a KV dtype this llama.cpp build lost, a GPU id
+ from another host) must not block persisting the rest or fail the API load that
+ reads it. ``validate_extra_args`` is the caller's job -- it lives in the
+ llama_server_args allow-list module, which this one must not import.
+ """
+ entry: dict[str, Any] = {}
+
+ extra_args = payload.get("llama_extra_args")
+ if isinstance(extra_args, (list, tuple)) and extra_args:
+ entry["llama_extra_args"] = [str(arg) for arg in extra_args]
+
+ # 0 / negative means "unset"; the loader reads absence as the app default.
+ for key in ("max_seq_length", "custom_context_length"):
+ parsed = _bounded_int(payload.get(key), minimum = 1, maximum = MAX_SEQ_LENGTH_CEILING)
+ if parsed:
+ entry[key] = parsed
+
+ kv_cache_dtype = _clean_str(payload.get("kv_cache_dtype"), VALID_KV_CACHE_DTYPES)
+ if kv_cache_dtype:
+ entry["kv_cache_dtype"] = kv_cache_dtype
+
+ speculative_type = _clean_str(payload.get("speculative_type"), VALID_SPECULATIVE_TYPES)
+ if speculative_type:
+ entry["speculative_type"] = speculative_type
+ # MTP-only; storing it otherwise shows an edit the loader ignores.
+ if speculative_type in MTP_SPECULATIVE_TYPES:
+ spec_draft_n_max = _bounded_int(payload.get("spec_draft_n_max"), minimum = 1, maximum = 16)
+ if spec_draft_n_max:
+ entry["spec_draft_n_max"] = spec_draft_n_max
+
+ # Blank or out of range means "follow the server-wide --parallel default".
+ n_parallel = _bounded_int(
+ payload.get("n_parallel"), minimum = PARALLEL_SLOTS_MIN, maximum = PARALLEL_SLOTS_MAX
+ )
+ if n_parallel:
+ entry["n_parallel"] = n_parallel
+
+ if _coerce_bool(payload.get("tensor_parallel")):
+ entry["tensor_parallel"] = True
+
+ template = payload.get("chat_template_override")
+ if isinstance(template, str) and template.strip():
+ # A lone surrogate from JSON breaks encode() and can never render, so drop it.
+ try:
+ template_bytes = len(template.encode("utf-8"))
+ except UnicodeEncodeError:
+ template_bytes = MAX_CHAT_TEMPLATE_OVERRIDE_BYTES + 1
+ if template_bytes <= MAX_CHAT_TEMPLATE_OVERRIDE_BYTES:
+ entry["chat_template_override"] = template
+
+ # Only "manual" is a real override: "auto" would stop the model following the global.
+ if _clean_str(payload.get("gpu_memory_mode"), VALID_GPU_MEMORY_MODES) == "manual":
+ entry["gpu_memory_mode"] = "manual"
+
+ # -1 is Auto (llama.cpp --fit), which is the default, so only >= 0 is stored.
+ gpu_layers = _bounded_int(payload.get("gpu_layers"), minimum = 0, maximum = 1024)
+ if gpu_layers is not None:
+ entry["gpu_layers"] = gpu_layers
+
+ n_cpu_moe = _bounded_int(payload.get("n_cpu_moe"), minimum = 1, maximum = 1024)
+ if n_cpu_moe:
+ entry["n_cpu_moe"] = n_cpu_moe
+
+ gpu_ids = payload.get("gpu_ids")
+ if isinstance(gpu_ids, (list, tuple)) and gpu_ids:
+ # De-duplicate, preserving order: resolve_requested_gpu_ids rejects a repeat, so
+ # [0, 0] would 400 every later load. A set, not a scan, keeps a long array linear.
+ cleaned_ids: list[int] = []
+ seen_ids: set[int] = set()
+ for gid in gpu_ids:
+ parsed = _bounded_int(gid, minimum = 0, maximum = MAX_GPU_ID)
+ if parsed is not None and parsed not in seen_ids:
+ seen_ids.add(parsed)
+ cleaned_ids.append(parsed)
+ if cleaned_ids:
+ entry["gpu_ids"] = cleaned_ids
+
+ return entry
+
+
+def resolve_fit_max_seq_length(override: dict[str, Any], *, is_gguf: bool) -> Optional[int]:
+ """The ``max_seq_length`` an API load should send for this override.
+
+ Mirrors resolveFitMaxSeqLength in the UI (features/chat/presets/preset-policy.ts):
+ under Manual GPU memory with Auto layers, llama.cpp's ``--fit`` owns context
+ sizing, so the load sends the explicit context pin (or 0 to hand sizing over)
+ rather than the stored max sequence length. Returns None to leave the field
+ at the loader's default.
+ """
+ manual_auto_layers = (
+ is_gguf
+ and override.get("gpu_memory_mode") == "manual"
+ and override.get("gpu_layers") is None
+ )
+ if manual_auto_layers:
+ return override.get("custom_context_length") or 0
+ # max_seq_length wins where both are set; they only collide in a legacy or hand-written entry.
+ return override.get("max_seq_length") or override.get("custom_context_length")
+
+
+def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> dict[str, Any]:
+ """Map a stored per-model config onto ``LoadRequest`` keyword arguments.
+
+ Mirrors the UI's load payload (features/chat/api/chat-adapter.ts) so an API
+ auto-switch load and a picker load of the same model produce the same command
+ line. GPU placement is GGUF-only there, so it is gated the same way here: a
+ safetensors model loads through HF auto-placement and must not inherit a
+ hidden GGUF GPU pin.
+ """
+ if not override:
+ return {}
+ kwargs: dict[str, Any] = {}
+
+ max_seq_length = resolve_fit_max_seq_length(override, is_gguf = is_gguf)
+ if max_seq_length is not None:
+ kwargs["max_seq_length"] = max_seq_length
+ for source, target in (
+ ("llama_extra_args", "llama_extra_args"),
+ ("kv_cache_dtype", "cache_type_kv"),
+ ("speculative_type", "speculative_type"),
+ ("spec_draft_n_max", "spec_draft_n_max"),
+ ("tensor_parallel", "tensor_parallel"),
+ ("chat_template_override", "chat_template_override"),
+ ):
+ if override.get(source) is not None:
+ kwargs[target] = override[source]
+
+ if is_gguf:
+ # Slots are a llama-server flag, and the picker sends them for GGUF only.
+ if override.get("n_parallel") is not None:
+ kwargs["n_parallel"] = override["n_parallel"]
+ if override.get("gpu_memory_mode") is not None:
+ kwargs["gpu_memory_mode"] = override["gpu_memory_mode"]
+ if override.get("gpu_layers") is not None:
+ kwargs["gpu_layers"] = override["gpu_layers"]
+ if override.get("n_cpu_moe") is not None:
+ kwargs["n_cpu_moe"] = override["n_cpu_moe"]
+ if override.get("gpu_ids") is not None:
+ kwargs["gpu_ids"] = override["gpu_ids"]
+
+ if kwargs.get("llama_extra_args"):
+ # One entry can hold a pass-through flag *and* the first-class field it shadows: the
+ # settings page has no control for flags, so a save carries the stored ones over
+ # (routes/settings.py) while writing the field just edited, and a legacy or
+ # API-authored entry can start out that way. Sending both explicitly puts the flag
+ # after Unsloth's own on the command line, where llama.cpp's last-wins parse hands it
+ # the load, so a stale "--ctx-size 8192" would quietly outrank a freshly saved 32768.
+ # The /load route strips exactly these groups off inherited extras
+ # (_resolve_inherited_extra_args); the stripper is imported rather than mirrored so
+ # the two paths cannot drift over which flag belongs to which group -- the allow-list
+ # this module stays out of is validate_extra_args, which remains the caller's job.
+ from core.inference.llama_server_args import strip_shadowing_flags
+ kwargs["llama_extra_args"] = strip_shadowing_flags(
+ kwargs["llama_extra_args"],
+ # Only the groups this override actually supplies, as the route gates on its
+ # request's set fields: a flag with no first-class field behind it is the user's
+ # only way to set that knob and still passes through.
+ strip_context = "max_seq_length" in kwargs,
+ strip_cache = "cache_type_kv" in kwargs,
+ strip_spec = "speculative_type" in kwargs or "spec_draft_n_max" in kwargs,
+ strip_template = "chat_template_override" in kwargs,
+ # Sent only when on, so it is always the Tensor Parallelism toggle overriding the
+ # flag; an override that leaves the toggle off keeps a row/none/layer split mode.
+ strip_split_mode = bool(kwargs.get("tensor_parallel")),
+ )
+ return kwargs
+
+
+def _looks_like_filesystem_path(model_id: str) -> bool:
+ """True for an absolute path id, as the ./models and LM Studio scanners emit."""
+ if model_id.startswith(("/", "\\")):
+ return True
+ # Windows drive letter, e.g. "C:\models\x.gguf".
+ return len(model_id) >= 3 and model_id[1] == ":" and model_id[2] in ("\\", "/")
+
+
+# The case-insensitive path shapes. Must stay in step with features/hub/lib/model-identity.ts,
+# which folds these before storing, or a stored key becomes unreachable.
+_WINDOWS_DRIVE_PATH = re.compile(r"^[A-Za-z]:[\\/]")
+_WSL_DRIVE_PATH = re.compile(r"^/mnt/[A-Za-z](?:/|$)")
+
+
+def _fold_case_insensitive_path(model_id: str) -> Optional[str]:
+ """``model_id`` folded for comparison, or None when the path is case-sensitive.
+
+ A Windows drive path, a UNC share and a WSL drive path all name one file
+ whatever the casing, and the separator is interchangeable on Windows. A
+ POSIX path is not: folding "/models/Foo.gguf" onto "/models/foo.gguf" would
+ replay another model's context and GPU pin.
+ """
+ slashed = model_id.replace("\\", "/")
+ if _WINDOWS_DRIVE_PATH.match(model_id):
+ minimum = 3
+ elif slashed.startswith("//"):
+ minimum = 2
+ elif _WSL_DRIVE_PATH.match(slashed):
+ minimum = 6
+ else:
+ return None
+ trimmed = slashed
+ while len(trimmed) > minimum and trimmed.endswith("/"):
+ trimmed = trimmed[:-1]
+ return trimmed.casefold()
+
+
+# A quant label may carry a bits-per-weight modifier ("IQ4_XS-3.53bpw"). The two label helpers
+# disagree on keeping it, so readers of a stored key must accept both forms.
+_BPW_SUFFIX = re.compile(r"-[0-9]+(?:\.[0-9]+)?bpw$", re.IGNORECASE)
+_MAX_QUANT_SUFFIX_LEN = 64
+
+
+def split_quant_suffix(value: str) -> Optional[tuple[str, str]]:
+ """``(head, quant)`` for a ``head:QUANT`` key, or None when there is none.
+
+ The suffix has to be a real quant label, so an ordinary colon inside a POSIX
+ filename is left alone: "/models/foo:bar.gguf" is one valid filename, and
+ splitting it would graft /models/foo's launch flags onto a different model.
+ """
+ from core.inference.llama_cpp import _GGUF_KNOWN_QUANT_RE
+ from hub.utils.gguf import extract_quant_label
+
+ head, sep, tail = value.rpartition(":")
+ if not sep or not head or not tail:
+ return None
+ if "/" in tail or "\\" in tail:
+ return None
+ if len(tail) <= _MAX_QUANT_SUFFIX_LEN and _GGUF_KNOWN_QUANT_RE.fullmatch(
+ _BPW_SUFFIX.sub("", tail)
+ ):
+ return head, tail
+ # A .gguf with no quant token is labelled by its stem, lowercased in storage while the
+ # scanner keeps filename casing. Requiring exactly that label keeps an ordinary colon out.
+ if not head.lower().endswith(".gguf"):
+ return None
+ filename = head.replace("\\", "/").rsplit("/", 1)[-1]
+ return (head, tail) if tail.casefold() == extract_quant_label(filename).casefold() else None
+
+
+def _fold_posix_path_variant(value: str) -> str:
+ """A POSIX path id with only its quant suffix folded.
+
+ The browser lowercases the variant but keeps the path casing, so a stored
+ "/models/Foo:q4_k_m" has to be reachable from "/models/Foo:Q4_K_M" without
+ also making "/models/Foo.gguf" reachable from "/models/foo.gguf".
+ """
+ split = split_quant_suffix(value)
+ if split is None:
+ return value
+ head, quant = split
+ return f"{head}:{quant.casefold()}"
+
+
def get_model_overrides() -> dict[str, dict]:
- """Per-model launch overrides keyed by model id ({llama_extra_args, max_seq_length})."""
+ """Per-model launch configs keyed by model id (see normalize_model_override)."""
raw = _cached_setting(MODEL_OVERRIDES_SETTING_KEY, None)
return raw if isinstance(raw, dict) else {}
def get_model_override(model_id: str) -> dict:
- """The launch override applied when auto-switch loads ``model_id`` (or empty)."""
- override = get_model_overrides().get(model_id)
+ """The launch override applied when auto-switch loads ``model_id`` (or empty).
+
+ Falls back to a case-insensitive match when nothing matches exactly. Repo ids
+ and quants are case-insensitive in practice ("Q4_K_M" and "q4_k_m" name one
+ file), and the browser normalizes them to lowercase before storing, so an
+ exact-only lookup misses entries written from that side. Exact still wins, and
+ an ambiguous fallback matches nothing, so two POSIX paths differing only in
+ case stay distinct.
+ """
+ key = resolve_model_override_key(model_id)
+ if key is None:
+ return {}
+ override = get_model_overrides().get(key)
return override if isinstance(override, dict) else {}
+def _folded_override_matches(model_id: str, overrides: dict) -> list[str]:
+ """Stored keys naming the same model as ``model_id``, by the folding rules.
+
+ One rule, so a reader and a remover can never fold differently.
+ """
+ if not isinstance(model_id, str):
+ return []
+ # POSIX paths are case-sensitive, so folding two casings would replay another model's
+ # settings. Windows drive, UNC and WSL paths do fold, and so does the browser before
+ # storing, so not folding them here strands them.
+ if _looks_like_filesystem_path(model_id):
+ folded = _fold_case_insensitive_path(model_id)
+ if folded is not None:
+
+ def fold(key: str) -> Optional[str]:
+ return _fold_case_insensitive_path(key)
+ else:
+ # POSIX: the path stays case-sensitive, but the browser lowercases the quant, so
+ # "/models/Foo:q4_k_m" must be reachable from the scanner's "/models/Foo:Q4_K_M".
+ folded = _fold_posix_path_variant(model_id)
+
+ def fold(key: str) -> Optional[str]:
+ # A path only ever folds onto another path.
+ if not _looks_like_filesystem_path(key):
+ return None
+ return None if _fold_case_insensitive_path(key) else _fold_posix_path_variant(key)
+ else:
+ folded = model_id.casefold()
+
+ def fold(key: str) -> Optional[str]:
+ # A path never folds onto a repo id: the shapes cannot collide.
+ return None if _looks_like_filesystem_path(key) else key.casefold()
+
+ return [
+ key
+ for key, value in overrides.items()
+ if isinstance(key, str) and fold(key) == folded and isinstance(value, dict)
+ ]
+
+
+def resolve_model_override_key(model_id: str) -> Optional[str]:
+ """The stored key an override lookup for ``model_id`` would actually hit.
+
+ Shared by read and remove so "what a load applies" and "what forgetting this
+ model clears" can never disagree. None when two keys fold together, since
+ guessing between them applies one model's settings to another.
+ """
+ overrides = get_model_overrides()
+ if isinstance(overrides.get(model_id), dict):
+ return model_id
+ matches = _folded_override_matches(model_id, overrides)
+ return matches[0] if len(matches) == 1 else None
+
+
+def resolve_model_override_keys(model_id: str) -> list[str]:
+ """Every stored key naming the same model, for a caller clearing all of them.
+
+ A lookup stops at one key, but forgetting cannot: an install upgraded from a
+ build whose setter stored the literal id can hold two spellings of one model,
+ and clearing only the one named leaves the survivor as the sole fold match, so
+ the next load applies the settings that were just forgotten. POSIX paths still
+ stand alone, so two files never clear each other.
+ """
+ overrides = get_model_overrides()
+ keys = [model_id] if isinstance(overrides.get(model_id), dict) else []
+ keys.extend(key for key in _folded_override_matches(model_id, overrides) if key not in keys)
+ return keys
+
+
+def _cached_repo_override_identity(model_id: str) -> Optional[tuple[str, str]]:
+ """``(repo id, quant)`` for a key naming one quant of an HF-cache repo, else None.
+
+ The two spellings of such a repo fold together here: the repo id the picker keys a
+ cached row by, and the ``models--org--name/snapshots/<rev>`` path the loader takes
+ (which an older release keyed the same row by). The repo id is recovered from the
+ path exactly as the scanner and the auto-switch index derive it, so the two sides
+ cannot disagree about which model a key names.
+
+ None for anything that names no quant (a bare entry backs every quant of the repo,
+ like the bare repo id, so it is nobody's duplicate) and for any other local path
+ (a ``./models`` folder or loose ``.gguf`` is keyed by its path and by nothing else).
+ """
+ split = split_quant_suffix(model_id)
+ if split is None:
+ return None
+ base, quant = split
+ from core.inference.model_ids import hf_cache_repo_id
+
+ repo = hf_cache_repo_id(base)
+ if repo is None:
+ if _looks_like_filesystem_path(base):
+ return None
+ repo = base
+ return repo.strip().casefold(), quant.strip().casefold()
+
+
+def cached_repo_alias_keys(model_id: str) -> list[str]:
+ """Stored keys that name the same cached quant as ``model_id`` under the other spelling.
+
+ The auto-switch loader reads the concrete load path before the advertised repo id,
+ so a snapshot-path entry left behind by an upgrade outranks the repo-id entry a
+ Settings save writes and keeps applying the pre-migration launch config. One entry
+ per model, as the casing folds already are: the writer clears what it supersedes.
+
+ Excludes every spelling of ``model_id`` itself, which the caller writes or clears
+ on its own.
+ """
+ identity = _cached_repo_override_identity(model_id)
+ if identity is None:
+ return []
+ own = {key.strip().casefold() for key in resolve_model_override_keys(model_id)}
+ own.add(model_id.strip().casefold())
+ return [
+ key
+ for key, value in get_model_overrides().items()
+ if isinstance(key, str)
+ and isinstance(value, dict)
+ and key.strip().casefold() not in own
+ and _cached_repo_override_identity(key) == identity
+ ]
+
+
def set_model_override(
model_id: str,
llama_extra_args: Optional[list[str]] = None,
max_seq_length: Optional[int] = None,
+ *,
+ fill_absent_fields: bool = False,
+ **config: Any,
) -> dict:
- """Upsert one model's launch override; an override with no fields removes it."""
+ """Upsert one model's launch config; a config with no usable fields removes it.
+
+ The two legacy parameters stay positional for existing callers; every other
+ per-model field is passed by keyword and normalized together.
+
+ ``fill_absent_fields`` writes only what is missing: an entry already stored
+ keeps every field it holds and gains only the ones it lacks. Returns the
+ normalized entry either way; read the map back to see what is actually stored.
+ """
if not model_id or not model_id.strip():
raise ValueError("model_id is required.")
- entry: dict[str, Any] = {}
- if llama_extra_args:
- entry["llama_extra_args"] = [str(arg) for arg in llama_extra_args]
- if max_seq_length:
- entry["max_seq_length"] = max(0, int(max_seq_length))
+ entry = normalize_model_override(
+ {
+ **config,
+ "llama_extra_args": llama_extra_args,
+ "max_seq_length": max_seq_length,
+ }
+ )
from storage.studio_db import upsert_app_setting_map_entry
# Atomic per-entry merge so two PUTs for different models can't drop each other.
- upsert_app_setting_map_entry(MODEL_OVERRIDES_SETTING_KEY, model_id.strip(), entry or None)
+ upsert_app_setting_map_entry(
+ MODEL_OVERRIDES_SETTING_KEY,
+ model_id.strip(),
+ entry or None,
+ fill_absent_fields = fill_absent_fields,
+ )
_invalidate(MODEL_OVERRIDES_SETTING_KEY)
return entry
diff --git a/studio/frontend/src/app/router.tsx b/studio/frontend/src/app/router.tsx
index 586c03d5df6..3dd8d2e8e02 100644
--- a/studio/frontend/src/app/router.tsx
+++ b/studio/frontend/src/app/router.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import { MascotImg } from "@/components/mascot-img";
import { useT } from "@/i18n";
import { Route as rootRoute } from "./routes/__root";
+import { Route as apiMonitorRoute } from "./routes/api";
import { Route as dataRecipesRoute } from "./routes/data-recipes";
import { Route as dataRecipeRoute } from "./routes/data-recipes.$recipeId";
import { Route as chatRoute } from "./routes/chat";
@@ -32,6 +33,7 @@ const routeTree = rootRoute.addChildren([
exportRoute,
dataRecipesRoute,
dataRecipeRoute,
+ apiMonitorRoute,
]);
function DefaultNotFound() {
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 9e72135bddf..d8d9a3a89d0 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -3,28 +3,27 @@
import { AppSidebar } from "@/components/app-sidebar";
import { Navbar } from "@/components/navbar";
-import { fetchDeviceType, usePlatformStore } from "@/config/env";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
-import {
- SettingsDialog,
- useSettingsDialogStore,
-} from "@/features/settings";
+import { fetchDeviceType, usePlatformStore } from "@/config/env";
+import { ApiMonitorOverlay } from "@/features/api-monitor/api-monitor-overlay";
+import { hasAuthToken } from "@/features/auth";
import {
ChatPage,
+ type ChatSearch,
clearNewChatDraft,
StopRunningChatsDialog,
useChatRuntimeStore,
- type ChatSearch,
} from "@/features/chat";
-import { RemoteCodeConsentDialog } from "@/features/security";
-import { HfTokenWarningDialog } from "@/features/hf-auth";
-import { TransformersUpgradeDialog } from "@/features/transformers-upgrade";
-import { useTrainingUnloadGuard } from "@/features/training";
import { useExportRuntimeLifecycle } from "@/features/export";
-import { hasAuthToken } from "@/features/auth";
+import { HfTokenWarningDialog } from "@/features/hf-auth";
+import { backfillModelOverrides } from "@/features/model-picker/api/migrate-model-overrides";
import { usePersonalizationSync } from "@/features/profile";
+import { RemoteCodeConsentDialog } from "@/features/security";
+import { SettingsDialog, useSettingsDialogStore } from "@/features/settings";
+import { useTrainingUnloadGuard } from "@/features/training";
+import { TransformersUpgradeDialog } from "@/features/transformers-upgrade";
import { useSidebarPin } from "@/hooks/use-sidebar-pin";
-import { useT, type TranslationKey } from "@/i18n";
+import { type TranslationKey, useT } from "@/i18n";
import {
Outlet,
createRootRoute,
@@ -34,13 +33,7 @@ import {
useRouterState,
} from "@tanstack/react-router";
import { AnimatePresence, motion } from "motion/react";
-import {
- Suspense,
- useEffect,
- useLayoutEffect,
- useMemo,
- useState,
-} from "react";
+import { Suspense, useEffect, useLayoutEffect, useMemo, useState } from "react";
import { AppProvider } from "../provider";
declare module "@tanstack/react-router" {
@@ -77,11 +70,15 @@ const CHAT_ONLY_ALLOWED = new Set([
// Export stays reachable on chat-only hosts so the page can show its own grayed-out reason
// instead of a silent redirect; it self-gates via export capability, so nothing runs.
"/export",
+ // Chat-only hosts serve the API like any other, so the monitor must be reachable there
+ // or the overlay's "Expand" and the Settings API card redirect to /chat.
+ "/api-monitor",
]);
function isChatOnlyAllowed(pathname: string): boolean {
if (CHAT_ONLY_ALLOWED.has(pathname)) return true;
- if (pathname === "/data-recipes" || pathname.startsWith("/data-recipes/")) return true;
+ if (pathname === "/data-recipes" || pathname.startsWith("/data-recipes/"))
+ return true;
return false;
}
@@ -177,6 +174,15 @@ function RootLayout() {
: DEFAULT_DOCUMENT_TITLE;
}, [documentTitle]);
+ // Settings predating the server override map live only here, so an API load would use
+ // app defaults. Backfill once, after auth.
+ useEffect(() => {
+ if (isAuthFlowRoute) {
+ return;
+ }
+ void backfillModelOverrides();
+ }, [isAuthFlowRoute]);
+
useEffect(() => {
if (isAuthFlowRoute) {
useSettingsDialogStore.getState().closeDialog();
@@ -225,6 +231,8 @@ function RootLayout() {
<AppProvider>
<PersonalizationSyncMount />
{!isAuthFlowRoute && <SettingsDialog />}
+ {/* Opens itself when API traffic arrives; hides on the full monitor page. */}
+ {!isAuthFlowRoute && <ApiMonitorOverlay />}
<HfTokenWarningDialog />
<RemoteCodeConsentDialog />
<TransformersUpgradeDialog />
@@ -244,7 +252,9 @@ function RootLayout() {
className="!min-h-0 h-[calc(100dvh-var(--studio-titlebar-height,0px))] overflow-hidden"
>
<AppSidebar />
- <SidebarInset className={isChatRoute ? "overflow-hidden" : "overflow-y-auto"}>
+ <SidebarInset
+ className={isChatRoute ? "overflow-hidden" : "overflow-y-auto"}
+ >
<Navbar />
<div
className={`relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col ${isChatRoute ? "overflow-hidden" : "overflow-visible"} ${isChatRoute ? "" : "pt-14 md:pt-[var(--studio-non-chat-content-top-inset,var(--studio-content-top-inset,0px))] md:[--studio-titlebar-height:var(--studio-non-chat-content-top-inset,var(--studio-content-top-inset,0px))]"}`}
diff --git a/studio/frontend/src/app/routes/api.tsx b/studio/frontend/src/app/routes/api.tsx
new file mode 100644
index 00000000000..1cf8b99efe9
--- /dev/null
+++ b/studio/frontend/src/app/routes/api.tsx
@@ -0,0 +1,20 @@
+// 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 { createRoute, lazyRouteComponent } from "@tanstack/react-router";
+import { requireAuth } from "../auth-guards";
+import { Route as rootRoute } from "./__root";
+
+const ApiMonitorPage = lazyRouteComponent(
+ () => import("@/features/api-monitor"),
+ "ApiMonitorPage",
+);
+
+export const Route = createRoute({
+ getParentRoute: () => rootRoute,
+ // Not "/api": the backend owns that prefix and its SPA fallback 404s those paths.
+ path: "/api-monitor",
+ staticData: { title: "API" },
+ beforeLoad: () => requireAuth(),
+ component: ApiMonitorPage,
+});
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
new file mode 100644
index 00000000000..d14fb2127a1
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
@@ -0,0 +1,394 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Floating API monitor: opens itself when API traffic arrives, summarises it
+// without taking over the window, and links through to the full page.
+
+import { getApiMonitor } from "@/features/chat/api/chat-api";
+import type { ApiMonitorEntry } from "@/features/chat/types/api";
+import { cn } from "@/lib/utils";
+import {
+ ArrowExpand01Icon,
+ DragDropVerticalIcon,
+ Globe02Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useNavigate, useRouterState } from "@tanstack/react-router";
+import { XIcon } from "lucide-react";
+import { AnimatePresence, motion, useDragControls } from "motion/react";
+import {
+ type PointerEvent,
+ type ReactElement,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { isLifecycleEntry, lifecycleLabel } from "./lifecycle";
+import {
+ type ApiMonitorWatch,
+ createWatch,
+ observeResponse,
+ rearmWatch,
+ standDownWatch,
+ startWatching,
+} from "./new-traffic";
+import { useApiMonitorOverlayStore } from "./overlay-store";
+import { computeStats } from "./use-api-monitor";
+
+// Live cadence while the panel is on screen.
+const OPEN_POLL_MS = 1500;
+// Closed, the poll only has to notice traffic started, so it backs off.
+const IDLE_POLL_MS = 5000;
+// Requests shown in the panel; the rest are one click away on the full page.
+const VISIBLE_ENTRIES = 4;
+// Quiet time before a dismissed panel re-arms.
+const REARM_QUIET_MS = 60_000;
+
+const API_INFERENCE_PREFIX_RE = /^\/api\/inference/;
+const V1_PREFIX_RE = /^\/v1\//;
+
+function compactEndpoint(endpoint: string): string {
+ return endpoint
+ .replace(API_INFERENCE_PREFIX_RE, "/api")
+ .replace(V1_PREFIX_RE, "/");
+}
+
+function formatDuration(value?: number | null): string {
+ if (value == null) {
+ return "live";
+ }
+ if (value < 1000) {
+ return `${Math.round(value)}ms`;
+ }
+ return `${(value / 1000).toFixed(value < 10000 ? 1 : 0)}s`;
+}
+
+function statusDotClass(status: ApiMonitorEntry["status"]): string {
+ switch (status) {
+ case "running":
+ return "bg-blue-500 animate-pulse";
+ case "error":
+ return "bg-red-500";
+ case "cancelled":
+ return "bg-amber-500";
+ default:
+ return "bg-emerald-500";
+ }
+}
+
+function StatCell({
+ label,
+ value,
+ tone,
+}: {
+ label: string;
+ value: string;
+ tone?: "error" | "active";
+}): ReactElement {
+ return (
+ <div className="flex min-w-0 flex-col items-center gap-0.5 px-1">
+ <span
+ className={cn(
+ "truncate text-ui-15 font-semibold tabular-nums leading-none tracking-[-0.01em]",
+ tone === "error" && "text-red-600 dark:text-red-400",
+ tone === "active" && "text-blue-600 dark:text-blue-400",
+ !tone && "text-nav-fg",
+ )}
+ >
+ {value}
+ </span>
+ {/* Sentence case: metric rows read as words, not headers. */}
+ <span className="truncate text-ui-11 tracking-nav text-muted-foreground">
+ {label}
+ </span>
+ </div>
+ );
+}
+
+export function ApiMonitorOverlay(): ReactElement | null {
+ const { isOpen, suppressed, autoOpen, open, close, setAutoOpen } =
+ useApiMonitorOverlayStore();
+ const navigate = useNavigate();
+ const pathname = useRouterState({ select: (s) => s.location.pathname });
+ const onFullPage = pathname === "/api-monitor";
+
+ const [data, setData] = useState<Awaited<
+ ReturnType<typeof getApiMonitor>
+ > | null>(null);
+
+ // What this session has already shown, and when it started watching.
+ const watchRef = useRef<ApiMonitorWatch>(createWatch(0));
+ const lastNewEntryAtRef = useRef(0);
+
+ // One loop for both jobs: panel contents while open, traffic watch while closed.
+ // Stands down on the full page, which polls itself.
+ useEffect(() => {
+ // Opted out and closed: nothing to open or show, so polling is pure load.
+ if (onFullPage || (!autoOpen && !isOpen)) {
+ // Standing down for the opt out leaves the same backlog behind it as the full page
+ // does, so write it off the same way: turning automatic opening back on waits for
+ // the next call rather than popping with the burst that ran while it was off.
+ if (!onFullPage) {
+ standDownWatch(watchRef.current);
+ }
+ return;
+ }
+ let cancelled = false;
+ let timer: number | undefined;
+ const intervalMs = isOpen ? OPEN_POLL_MS : IDLE_POLL_MS;
+
+ // Anchor the watch here, not at mount: the first snapshot can arrive much later
+ // (a hidden tab skips its poll), and everything terminal would read as history.
+ startWatching(watchRef.current, performance.now());
+
+ function schedule(): void {
+ timer = window.setTimeout(poll, intervalMs);
+ }
+
+ function poll(): void {
+ // A hidden tab has nobody to show the panel to.
+ if (document.hidden) {
+ schedule();
+ return;
+ }
+ getApiMonitor()
+ .then((next) => {
+ if (!cancelled) setData(next);
+ })
+ .catch(() => {
+ // An unreachable server is the full page's story to tell.
+ if (!cancelled) setData(null);
+ })
+ .finally(() => {
+ if (!cancelled) schedule();
+ });
+ }
+
+ poll();
+ return () => {
+ cancelled = true;
+ if (timer !== undefined) window.clearTimeout(timer);
+ };
+ }, [isOpen, onFullPage, autoOpen]);
+
+ const entries = useMemo(() => data?.entries ?? [], [data]);
+ const stats = useMemo(() => computeStats(entries), [entries]);
+
+ useEffect(() => {
+ if (data == null) {
+ return;
+ }
+ const hasNewTraffic = observeResponse(
+ watchRef.current,
+ data,
+ performance.now(),
+ );
+ if (!hasNewTraffic) {
+ return;
+ }
+ const now = Date.now();
+ const quietFor = now - lastNewEntryAtRef.current;
+ lastNewEntryAtRef.current = now;
+ if (!autoOpen || isOpen) {
+ return;
+ }
+ // A dismissal holds for the burst and re-arms only once the API goes quiet.
+ if (suppressed && quietFor < REARM_QUIET_MS) {
+ return;
+ }
+ open();
+ }, [data, autoOpen, suppressed, isOpen, open]);
+
+ // The backlog built while the poll stood down is not new traffic. The watch re-anchors
+ // when the poll stands back up, not here, or the panel pops with rows just read.
+ useEffect(() => {
+ if (onFullPage) {
+ rearmWatch(watchRef.current);
+ }
+ }, [onFullPage]);
+
+ const [constraintsElement, setConstraintsElement] =
+ useState<HTMLDivElement | null>(null);
+ const constraintsRef = useMemo(
+ () => ({ current: constraintsElement }),
+ [constraintsElement],
+ );
+ const dragControls = useDragControls();
+
+ function startDrag(event: PointerEvent<HTMLDivElement>): void {
+ event.preventDefault();
+ dragControls.start(event);
+ }
+
+ const visible = isOpen && !onFullPage;
+ const serverStatus = data?.status ?? "idle";
+
+ return (
+ <AnimatePresence>
+ {visible && (
+ <div
+ ref={setConstraintsElement}
+ className="pointer-events-none fixed inset-0 z-50"
+ >
+ <motion.div
+ drag={true}
+ dragControls={dragControls}
+ dragListener={false}
+ dragConstraints={constraintsRef}
+ dragElastic={0}
+ dragMomentum={false}
+ initial={{ opacity: 0, scale: 0.94 }}
+ animate={{ opacity: 1, scale: 1 }}
+ exit={{ opacity: 0, scale: 0.94 }}
+ /* Panel language from the sidebar menu: soft surface, 20px corner, heading font. */
+ className="menu-soft-surface pointer-events-auto fixed bottom-4 right-4 flex w-[400px] max-w-[calc(100vw-2rem)] cursor-default select-none resize flex-col overflow-hidden rounded-[20px] border-0 p-2.5 font-heading ring-0"
+ >
+ <div className="flex items-center justify-between gap-2 px-1.5 pb-2 pt-0.5">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <HugeiconsIcon
+ icon={Globe02Icon}
+ strokeWidth={1.75}
+ className="size-icon shrink-0 text-nav-fg"
+ />
+ <span className="truncate text-ui-13p5 font-semibold tracking-[0.025em] text-nav-fg dark:tracking-[0.04em]">
+ API monitor
+ </span>
+ <span
+ className={cn(
+ "size-1.5 shrink-0 rounded-full",
+ serverStatus === "generating"
+ ? "animate-pulse bg-blue-500"
+ : serverStatus === "ready"
+ ? "bg-emerald-500"
+ : "bg-muted-foreground",
+ )}
+ aria-hidden={true}
+ />
+ </div>
+ <div className="flex shrink-0 items-center gap-0.5">
+ <div
+ onPointerDown={startDrag}
+ className="flex size-7 touch-none cursor-grab items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-nav-surface-hover hover:text-foreground active:cursor-grabbing"
+ >
+ <HugeiconsIcon
+ icon={DragDropVerticalIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </div>
+ <button
+ type="button"
+ onClick={close}
+ title="Close"
+ aria-label="Close API monitor"
+ className="flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-nav-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <XIcon className="size-3.5" strokeWidth={1.75} />
+ </button>
+ </div>
+ </div>
+
+ <p className="truncate px-1.5 pb-2.5 text-ui-11p5 tracking-nav text-muted-foreground">
+ {data?.active_model ?? "No model loaded"}
+ </p>
+
+ {/* Soft tile, as the Hub and Train pages group readouts. */}
+ <div className="grid grid-cols-4 rounded-[14px] bg-muted/45 py-2.5 dark:bg-background/45">
+ <StatCell
+ label="Live"
+ value={stats.active.toLocaleString()}
+ tone={stats.active > 0 ? "active" : undefined}
+ />
+ <StatCell label="Requests" value={stats.total.toLocaleString()} />
+ <StatCell
+ label="Errors"
+ value={stats.errors.toLocaleString()}
+ tone={stats.errors > 0 ? "error" : undefined}
+ />
+ <StatCell
+ label="Avg"
+ value={
+ stats.avgDurationMs == null
+ ? "--"
+ : formatDuration(stats.avgDurationMs)
+ }
+ />
+ </div>
+
+ {/* Borderless rows on 12px hover pills, as in the sidebar. */}
+ <div className="flex flex-col pb-1 pt-1.5">
+ {entries.length === 0 ? (
+ <p className="px-1.5 py-4 text-center text-ui-11p5 tracking-nav text-muted-foreground">
+ No requests yet.
+ </p>
+ ) : (
+ entries.slice(0, VISIBLE_ENTRIES).map((entry) => (
+ <div
+ key={entry.id}
+ className="flex h-9 min-w-0 items-center gap-2.5 rounded-[12px] px-3 transition-colors hover:bg-nav-surface-hover"
+ >
+ <span
+ className={cn(
+ "size-1.5 shrink-0 rounded-full",
+ statusDotClass(entry.status),
+ )}
+ aria-hidden={true}
+ />
+ <span className="shrink-0 truncate text-ui-12p5 font-medium tracking-nav text-nav-fg">
+ {isLifecycleEntry(entry)
+ ? lifecycleLabel(entry)
+ : compactEndpoint(entry.endpoint)}
+ </span>
+ <span
+ className={cn(
+ "min-w-0 flex-1 truncate text-ui-11p5 tracking-nav",
+ entry.error
+ ? "text-red-600 dark:text-red-400"
+ : "text-muted-foreground",
+ )}
+ >
+ {entry.error ? entry.error : entry.model}
+ </span>
+ <span className="shrink-0 text-ui-11 tabular-nums text-muted-foreground">
+ {formatDuration(entry.duration_ms)}
+ </span>
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Through to payloads, filters and per request tokens. */}
+ <button
+ type="button"
+ onClick={() => {
+ close();
+ void navigate({ to: "/api-monitor" });
+ }}
+ className="mt-1 flex h-[33px] w-full items-center justify-center gap-[8.5px] rounded-full bg-muted/60 text-ui-13p5 font-medium tracking-nav text-nav-fg transition-colors hover:bg-nav-surface-hover focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:bg-background/50"
+ >
+ <HugeiconsIcon
+ icon={ArrowExpand01Icon}
+ strokeWidth={1.75}
+ className="size-icon shrink-0"
+ />
+ Expand to full monitor
+ </button>
+
+ {/* Closing silences this burst; this is the permanent off. */}
+ <button
+ type="button"
+ onClick={() => {
+ setAutoOpen(false);
+ close();
+ }}
+ className="mt-1.5 w-full rounded-[12px] py-1 text-ui-11 tracking-nav text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ Stop opening this automatically
+ </button>
+ </motion.div>
+ </div>
+ )}
+ </AnimatePresence>
+ );
+}
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
new file mode 100644
index 00000000000..d3cd58019a8
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
@@ -0,0 +1,923 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Full-page monitor for Unsloth's OpenAI-compatible API server. Settings still owns
+// configuration (keys, auto-switch, examples); this page owns observability.
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Skeleton } from "@/components/ui/skeleton";
+import { usePlatformStore } from "@/config/env";
+import { getInferenceStatus, unloadModel } from "@/features/chat/api/chat-api";
+import { resolveInferenceCheckpointId } from "@/features/chat/lib/apply-inference-status-to-store";
+import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import type { ApiMonitorEntry } from "@/features/chat/types/api";
+import { isExternalModelId } from "@/features/chat/external-providers";
+import { modelIdsMatch } from "@/features/hub/lib/model-identity";
+import { useSettingsDialogStore } from "@/features/settings";
+import { getApiBase, isTauri } from "@/lib/api-base";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { Tick02Icon } from "@/lib/tick-icon";
+import { cn } from "@/lib/utils";
+import {
+ Copy01Icon,
+ Delete02Icon,
+ Globe02Icon,
+ PauseIcon,
+ PlayIcon,
+ PowerSocket01Icon,
+ RefreshIcon,
+ Settings02Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { type ReactElement, useEffect, useMemo, useRef, useState } from "react";
+import { SavedModelSettingsPanel } from "./components/saved-model-settings";
+import { isLifecycleEntry, lifecycleLabel } from "./lifecycle";
+import { unloadResident } from "./unload-resident";
+import {
+ type MonitorStatusFilter,
+ filterEntries,
+ useApiMonitor,
+} from "./use-api-monitor";
+
+const API_INFERENCE_PREFIX_RE = /^\/api\/inference/;
+const V1_PREFIX_RE = /^\/v1\//;
+// Bounded because the usual failure is an entry aged out of the ring buffer.
+const DETAIL_FETCH_ATTEMPTS = 3;
+
+const STATUS_FILTERS: { value: MonitorStatusFilter; label: string }[] = [
+ { value: "all", label: "All requests" },
+ { value: "running", label: "In flight" },
+ { value: "completed", label: "Completed" },
+ { value: "error", label: "Errors" },
+ { value: "cancelled", label: "Cancelled" },
+];
+
+function formatTime(value: number): string {
+ return new Date(value * 1000).toLocaleTimeString([], {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ });
+}
+
+function formatDuration(value?: number | null): string {
+ if (value == null) {
+ return "running";
+ }
+ if (value < 1000) {
+ return `${Math.round(value)} ms`;
+ }
+ return `${(value / 1000).toFixed(value < 10000 ? 1 : 0)} s`;
+}
+
+function formatCount(value: number): string {
+ return value.toLocaleString();
+}
+
+function compactEndpoint(endpoint: string): string {
+ return endpoint
+ .replace(API_INFERENCE_PREFIX_RE, "/api")
+ .replace(V1_PREFIX_RE, "/");
+}
+
+function statusDotClass(status: ApiMonitorEntry["status"]): string {
+ switch (status) {
+ case "running":
+ return "bg-blue-500 animate-pulse";
+ case "error":
+ return "bg-red-500";
+ case "cancelled":
+ return "bg-amber-500";
+ default:
+ return "bg-emerald-500";
+ }
+}
+
+function statusTextClass(status: ApiMonitorEntry["status"]): string {
+ switch (status) {
+ case "running":
+ return "text-blue-600 dark:text-blue-400";
+ case "error":
+ return "text-red-600 dark:text-red-400";
+ case "cancelled":
+ return "text-amber-600 dark:text-amber-500";
+ default:
+ return "text-emerald-600 dark:text-emerald-500";
+ }
+}
+
+function StatCard({
+ label,
+ value,
+ hint,
+ tone,
+}: {
+ label: string;
+ value: string;
+ hint?: string;
+ tone?: "default" | "error" | "active";
+}): ReactElement {
+ return (
+ <div className="flex min-w-0 flex-col gap-1 rounded-xl border border-border/60 bg-card px-4 py-3">
+ <span className="truncate text-ui-11 font-medium uppercase tracking-wider text-muted-foreground">
+ {label}
+ </span>
+ <span
+ className={cn(
+ "truncate text-ui-22 font-semibold leading-tight tracking-[-0.02em]",
+ tone === "error" && "text-red-600 dark:text-red-400",
+ tone === "active" && "text-blue-600 dark:text-blue-400",
+ )}
+ >
+ {value}
+ </span>
+ {hint ? (
+ <span className="truncate text-ui-11 text-muted-foreground">
+ {hint}
+ </span>
+ ) : null}
+ </div>
+ );
+}
+
+function CopyButton({
+ value,
+ label,
+}: {
+ value: string;
+ label: string;
+}): ReactElement {
+ const [copied, setCopied] = useState(false);
+ // Cancel on cleanup, or navigating away mid-flash sets state after unmount.
+ const timerRef = useRef<number | undefined>(undefined);
+ useEffect(
+ () => () => {
+ if (timerRef.current !== undefined) window.clearTimeout(timerRef.current);
+ },
+ [],
+ );
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={label}
+ onClick={async () => {
+ if (await copyToClipboard(value)) {
+ setCopied(true);
+ if (timerRef.current !== undefined) {
+ window.clearTimeout(timerRef.current);
+ }
+ timerRef.current = window.setTimeout(() => setCopied(false), 1800);
+ }
+ }}
+ className="h-7 shrink-0 gap-1.5 px-2 text-ui-11"
+ >
+ <HugeiconsIcon
+ icon={copied ? Tick02Icon : Copy01Icon}
+ strokeWidth={1.75}
+ className={cn(
+ "size-3.5",
+ copied && "text-emerald-600 dark:text-emerald-500",
+ )}
+ />
+ {copied ? "Copied" : "Copy"}
+ </Button>
+ );
+}
+
+function ContextUsageBar({
+ value,
+}: { value?: number | null }): ReactElement | null {
+ if (value == null) {
+ return null;
+ }
+ const pct = Math.max(0, Math.min(100, Math.round(value * 100)));
+ return (
+ <div className="flex items-center gap-2">
+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
+ <div
+ className={cn(
+ "h-full rounded-full transition-[width]",
+ // Near-full context is the usual cause of truncated replies.
+ pct >= 90
+ ? "bg-red-500"
+ : pct >= 75
+ ? "bg-amber-500"
+ : "bg-control-accent",
+ )}
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ <span className="shrink-0 text-ui-11 tabular-nums text-muted-foreground">
+ {pct}%
+ </span>
+ </div>
+ );
+}
+
+function RequestRow({
+ entry,
+ selected,
+ onSelect,
+}: {
+ entry: ApiMonitorEntry;
+ selected: boolean;
+ onSelect: () => void;
+}): ReactElement {
+ const preview =
+ entry.error ||
+ entry.reply_preview ||
+ entry.prompt_preview ||
+ (entry.status === "running" ? "Waiting for output…" : "No preview");
+ // A lifecycle row has no payload, so it reads as a status line.
+ if (isLifecycleEntry(entry)) {
+ return (
+ <div className="flex w-full min-w-0 flex-col gap-1 border-b border-border/50 bg-muted/25 px-4 py-3 last:border-b-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className={cn(
+ "size-2 shrink-0 rounded-full",
+ statusDotClass(entry.status),
+ )}
+ aria-hidden={true}
+ />
+ <span className="truncate text-ui-13 font-medium text-foreground">
+ {lifecycleLabel(entry)}
+ </span>
+ <span className="ml-auto shrink-0 text-ui-11 tabular-nums text-muted-foreground">
+ {formatTime(entry.started_at)}
+ </span>
+ </div>
+ <div className="min-w-0 truncate pl-4 text-ui-11 text-muted-foreground">
+ {entry.model}
+ </div>
+ {entry.error ? (
+ <div className="min-w-0 break-words pl-4 text-ui-11 text-red-600 dark:text-red-400">
+ {entry.error}
+ </div>
+ ) : null}
+ </div>
+ );
+ }
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ aria-current={selected}
+ className={cn(
+ "flex w-full min-w-0 flex-col gap-1 border-b border-border/50 px-4 py-3 text-left transition-colors last:border-b-0",
+ selected ? "bg-muted/70" : "hover:bg-muted/40",
+ )}
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className={cn(
+ "size-2 shrink-0 rounded-full",
+ statusDotClass(entry.status),
+ )}
+ aria-hidden={true}
+ />
+ <span className="truncate text-ui-13 font-medium text-foreground">
+ {compactEndpoint(entry.endpoint)}
+ </span>
+ <span className="ml-auto shrink-0 text-ui-11 tabular-nums text-muted-foreground">
+ {formatDuration(entry.duration_ms)}
+ </span>
+ </div>
+ <div className="flex min-w-0 items-center gap-2 pl-4">
+ <span className="truncate text-ui-11 text-muted-foreground">
+ {entry.model}
+ </span>
+ <span className="ml-auto shrink-0 text-ui-11 tabular-nums text-muted-foreground">
+ {formatTime(entry.started_at)}
+ </span>
+ </div>
+ <p
+ className={cn(
+ "line-clamp-2 pl-4 text-ui-11 leading-[1.45]",
+ entry.error
+ ? "text-red-600 dark:text-red-400"
+ : "text-muted-foreground",
+ )}
+ >
+ {preview}
+ </p>
+ </button>
+ );
+}
+
+function PayloadBlock({
+ title,
+ body,
+ truncated,
+ loading,
+ tone,
+}: {
+ title: string;
+ body: string;
+ truncated?: boolean;
+ loading?: boolean;
+ tone?: "error";
+}): ReactElement {
+ return (
+ <section className="flex min-w-0 flex-col gap-1.5">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-ui-11 font-semibold uppercase tracking-wider text-muted-foreground">
+ {title}
+ </h3>
+ <div className="flex items-center gap-1">
+ {truncated ? (
+ <span className="text-ui-10 text-muted-foreground">
+ preview only
+ </span>
+ ) : null}
+ {body ? (
+ <CopyButton value={body} label={`Copy ${title.toLowerCase()}`} />
+ ) : null}
+ </div>
+ </div>
+ <pre
+ className={cn(
+ "max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-muted/50 p-3 text-ui-11 leading-[1.55]",
+ tone === "error" && "bg-red-500/5 text-red-700 dark:text-red-400",
+ )}
+ >
+ {loading && !body ? "Loading…" : body || "–"}
+ </pre>
+ </section>
+ );
+}
+
+function RequestDetail({
+ entry,
+ detail,
+ loading,
+}: {
+ entry: ApiMonitorEntry;
+ detail?: ApiMonitorEntry;
+ loading: boolean;
+}): ReactElement {
+ // The detail fetch can describe an older state of a streaming entry, so prefer it
+ // only once it is as fresh as the list row, or the panel rewinds.
+ const detailIsCurrent =
+ detail != null &&
+ detail.status === entry.status &&
+ detail.updated_at >= entry.updated_at;
+ const prompt = detail?.prompt ?? entry.prompt_preview;
+ const reply = detailIsCurrent
+ ? (detail.reply ?? entry.reply_preview)
+ : entry.reply_preview;
+
+ return (
+ <div className="flex min-w-0 flex-col gap-5 p-5">
+ <header className="flex min-w-0 flex-col gap-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className={cn(
+ "size-2 shrink-0 rounded-full",
+ statusDotClass(entry.status),
+ )}
+ aria-hidden={true}
+ />
+ <span
+ className={cn(
+ "text-ui-11 font-semibold uppercase tracking-wider",
+ statusTextClass(entry.status),
+ )}
+ >
+ {entry.status}
+ </span>
+ <span className="ml-auto shrink-0 font-mono text-ui-10 text-muted-foreground">
+ {entry.id}
+ </span>
+ </div>
+ <h2 className="min-w-0 break-all font-mono text-ui-13 font-medium text-foreground">
+ {entry.method} {entry.endpoint}
+ </h2>
+ <p className="min-w-0 break-all text-ui-11 text-muted-foreground">
+ {entry.model}
+ </p>
+ </header>
+
+ <dl className="grid grid-cols-2 gap-x-4 gap-y-3 rounded-xl border border-border/60 bg-card px-4 py-3 sm:grid-cols-3">
+ {[
+ { label: "Started", value: formatTime(entry.started_at) },
+ { label: "Duration", value: formatDuration(entry.duration_ms) },
+ {
+ label: "Prompt tokens",
+ value:
+ entry.prompt_tokens != null
+ ? formatCount(entry.prompt_tokens)
+ : "–",
+ },
+ {
+ label: "Completion tokens",
+ value:
+ entry.completion_tokens != null
+ ? formatCount(entry.completion_tokens)
+ : "–",
+ },
+ {
+ label: "Total tokens",
+ value:
+ entry.total_tokens != null
+ ? formatCount(entry.total_tokens)
+ : "–",
+ },
+ {
+ label: "Context",
+ value:
+ entry.context_length != null
+ ? formatCount(entry.context_length)
+ : "–",
+ },
+ ].map((item) => (
+ <div key={item.label} className="flex min-w-0 flex-col gap-0.5">
+ <dt className="truncate text-ui-10 font-medium uppercase tracking-wider text-muted-foreground">
+ {item.label}
+ </dt>
+ <dd className="truncate text-ui-13 tabular-nums text-foreground">
+ {item.value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+
+ {entry.context_usage != null ? (
+ <div className="flex flex-col gap-1.5">
+ <span className="text-ui-11 font-semibold uppercase tracking-wider text-muted-foreground">
+ Context used
+ </span>
+ <ContextUsageBar value={entry.context_usage} />
+ </div>
+ ) : null}
+
+ {entry.error ? (
+ <PayloadBlock title="Error" body={entry.error} tone="error" />
+ ) : null}
+
+ <PayloadBlock
+ title="Prompt"
+ body={prompt}
+ truncated={entry.prompt_truncated && detail?.prompt == null}
+ loading={loading}
+ />
+ <PayloadBlock
+ title="Reply"
+ body={reply}
+ truncated={entry.reply_truncated && !detailIsCurrent}
+ loading={loading}
+ />
+ </div>
+ );
+}
+
+export function ApiMonitorPage(): ReactElement {
+ const {
+ data,
+ entries,
+ stats,
+ error,
+ loading,
+ refreshing,
+ paused,
+ setPaused,
+ refresh,
+ clear,
+ details,
+ loadingDetails,
+ requestDetail,
+ } = useApiMonitor();
+ const serverUrl = usePlatformStore((s) => s.serverUrl);
+ const [unloading, setUnloading] = useState(false);
+ const [unloadError, setUnloadError] = useState<string | null>(null);
+
+ // Manual release so VRAM frees without the idle timer. /unload matches on the
+ // internal id, which the monitor does not carry, so read status. unloadResident owns
+ // the read/unload/recheck sequence: this page's own feature (an API auto-switch) can
+ // swap the model out from under the read, and /unload naming a replaced model is a
+ // successful no-op, so one pass would report success over the model still resident.
+ const unloadActiveModel = async (): Promise<void> => {
+ setUnloading(true);
+ try {
+ const { unloadedAliases, stillResident } = await unloadResident({
+ readResident: async () => {
+ const status = await getInferenceStatus();
+ const checkpoint = resolveInferenceCheckpointId(status);
+ if (!checkpoint) {
+ return null;
+ }
+ // Both spellings, since status reports the load path while the store may
+ // hold the advertised repo id.
+ return {
+ checkpoint,
+ aliases: [checkpoint, status.active_model].filter(
+ (alias): alias is string => alias != null,
+ ),
+ };
+ },
+ unload: (checkpoint) => unloadModel({ model_path: checkpoint }),
+ });
+ // As in the chat eject flow, but only when the store holds a model just unloaded: chat
+ // can have an external provider selected while a local model stays resident, and
+ // clearCheckpoint would delete a selection this button never touched.
+ const store = useChatRuntimeStore.getState();
+ const selected = store.params.checkpoint;
+ if (
+ selected &&
+ !isExternalModelId(selected) &&
+ unloadedAliases.some((alias) => modelIdsMatch(selected, alias))
+ ) {
+ store.clearCheckpoint();
+ }
+ setUnloadError(
+ stillResident
+ ? `The API loaded "${stillResident}" while unloading, so it is still using memory. Unload again to release it.`
+ : null,
+ );
+ refresh();
+ } catch (err: unknown) {
+ setUnloadError(
+ err instanceof Error ? err.message : "Failed to unload the model",
+ );
+ } finally {
+ setUnloading(false);
+ }
+ };
+ const [statusFilter, setStatusFilter] = useState<MonitorStatusFilter>("all");
+ const [query, setQuery] = useState("");
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+
+ const visible = useMemo(
+ () => filterEntries(entries, statusFilter, query),
+ [entries, statusFilter, query],
+ );
+ const selected = useMemo(
+ () => visible.find((entry) => entry.id === selectedId) ?? null,
+ [visible, selectedId],
+ );
+
+ // Refetch the selected entry while it streams. Keyed on identity and revision, never
+ // on `details`: the fetch rewrites it on success, so depending on it loops.
+ const selectedId_ = selected?.id ?? null;
+ const selectedUpdatedAt = selected?.updated_at ?? null;
+ const selectedIsMissing = selectedId_ != null && details[selectedId_] == null;
+ const lastFetchedRef = useRef<string | null>(null);
+ const attemptsRef = useRef<{ revision: string; count: number }>({
+ revision: "",
+ count: 0,
+ });
+ const [retryTick, setRetryTick] = useState(0);
+ // Flips as a fetch settles either way, which is what lets a failure be noticed.
+ const detailInFlight = selectedId_ != null && loadingDetails.has(selectedId_);
+ useEffect(() => {
+ if (selectedId_ == null || detailInFlight) {
+ return;
+ }
+ // `updated_at` advances per poll and settles when terminal; a missing payload
+ // always retries, covering a fetch that failed late.
+ const revision = `${selectedId_}@${selectedUpdatedAt ?? ""}`;
+ if (!selectedIsMissing && lastFetchedRef.current === revision) {
+ return;
+ }
+ // A terminal row's revision never advances, so a failed fetch had nothing to re-run
+ // this effect. `loadingDetails` settling is the trigger; the count bounds it.
+ if (attemptsRef.current.revision !== revision) {
+ attemptsRef.current = { revision, count: 0 };
+ }
+ if (attemptsRef.current.count >= DETAIL_FETCH_ATTEMPTS) {
+ return;
+ }
+ attemptsRef.current.count += 1;
+ // Only when a fetch started: the guard can refuse, and recording it anyway skips
+ // that revision for good.
+ if (requestDetail(selectedId_)) {
+ lastFetchedRef.current = revision;
+ setRetryTick(0);
+ } else {
+ // Refused: an older fetch is running and no dep changes when it settles.
+ const timer = window.setTimeout(() => setRetryTick((n) => n + 1), 250);
+ return () => window.clearTimeout(timer);
+ }
+ }, [
+ selectedId_,
+ selectedUpdatedAt,
+ selectedIsMissing,
+ requestDetail,
+ retryTick,
+ detailInFlight,
+ ]);
+
+ // The desktop webview's origin is tauri://, and the packaged app picks its port
+ // dynamically. Same source as the Agents tab.
+ const origin = typeof window === "undefined" ? "" : window.location.origin;
+ const baseUrl = `${isTauri ? (serverUrl ?? getApiBase()) : origin}/v1`;
+ const serverStatus = data?.status ?? "idle";
+ // Older backends omit the field; only an explicit `false` means recording is off.
+ const loggingDisabled = data?.logging_enabled === false;
+ const statusCopy =
+ serverStatus === "generating"
+ ? "Serving requests"
+ : serverStatus === "ready"
+ ? "Ready"
+ : "No model loaded";
+
+ return (
+ <main className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-6 pb-10 pt-12 font-heading sm:px-10">
+ <header className="flex flex-wrap items-start justify-between gap-4">
+ <div className="flex min-w-0 flex-col gap-1">
+ <h1 className="text-ui-30 font-semibold leading-[1.04] tracking-[-0.028em] text-foreground sm:text-ui-34">
+ API
+ </h1>
+ <p className="text-sm text-muted-foreground">
+ Live traffic through Unsloth&apos;s OpenAI-compatible server.
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setPaused(!paused)}
+ className="h-9 gap-1.5 rounded-full"
+ >
+ <HugeiconsIcon
+ icon={paused ? PlayIcon : PauseIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ {paused ? "Resume" : "Pause"}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => void unloadActiveModel()}
+ disabled={unloading || !data?.active_model}
+ title={
+ data?.active_model
+ ? `Unload ${data.active_model} and free its VRAM`
+ : "No model is loaded"
+ }
+ className="h-9 gap-1.5 rounded-full"
+ >
+ <HugeiconsIcon
+ icon={PowerSocket01Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ {unloading ? "Unloading" : "Unload"}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={refresh}
+ disabled={refreshing}
+ className="h-9 gap-1.5 rounded-full"
+ >
+ <HugeiconsIcon
+ icon={RefreshIcon}
+ strokeWidth={1.75}
+ className={cn("size-4", refreshing && "animate-spin")}
+ />
+ Refresh
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={entries.length === 0}
+ onClick={() => {
+ setSelectedId(null);
+ void clear();
+ }}
+ className="h-9 gap-1.5 rounded-full"
+ >
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ Clear log
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ useSettingsDialogStore.getState().openDialog("api-keys")
+ }
+ className="h-9 gap-1.5 rounded-full"
+ >
+ <HugeiconsIcon
+ icon={Settings02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ API settings
+ </Button>
+ </div>
+ </header>
+
+ {/* Checked first when a client can't reach the API: base URL and what is loaded. */}
+ <section className="flex flex-wrap items-center gap-x-6 gap-y-3 rounded-xl border border-border/60 bg-card px-4 py-3">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-border/60 bg-muted/40">
+ <HugeiconsIcon
+ icon={Globe02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </span>
+ <div className="flex min-w-0 flex-col">
+ <span className="text-ui-10 font-medium uppercase tracking-wider text-muted-foreground">
+ Base URL
+ </span>
+ <span className="truncate font-mono text-ui-12 text-foreground">
+ {baseUrl}
+ </span>
+ </div>
+ <CopyButton value={baseUrl} label="Copy API base URL" />
+ </div>
+ <div className="flex min-w-0 flex-col">
+ <span className="text-ui-10 font-medium uppercase tracking-wider text-muted-foreground">
+ Status
+ </span>
+ <span className="flex items-center gap-1.5 text-ui-12 text-foreground">
+ <span
+ className={cn(
+ "size-2 rounded-full",
+ serverStatus === "generating"
+ ? "bg-blue-500 animate-pulse"
+ : serverStatus === "ready"
+ ? "bg-emerald-500"
+ : "bg-muted-foreground",
+ )}
+ aria-hidden={true}
+ />
+ {statusCopy}
+ </span>
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="text-ui-10 font-medium uppercase tracking-wider text-muted-foreground">
+ Loaded model
+ </span>
+ <span className="truncate text-ui-12 text-foreground">
+ {data?.active_model ?? "None"}
+ {data?.context_length
+ ? ` · ${formatCount(data.context_length)} ctx`
+ : ""}
+ </span>
+ </div>
+ {paused ? (
+ <span className="rounded-full border border-amber-500/40 bg-amber-500/10 px-2.5 py-1 text-ui-11 font-medium text-amber-700 dark:text-amber-500">
+ Paused
+ </span>
+ ) : null}
+ </section>
+
+ {error || unloadError ? (
+ <div className="rounded-xl border border-red-500/40 bg-red-500/5 px-4 py-3 text-sm text-red-600 dark:text-red-400">
+ {error || unloadError}
+ </div>
+ ) : null}
+
+ <section className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
+ <StatCard
+ label="In flight"
+ value={formatCount(stats.active)}
+ tone={stats.active > 0 ? "active" : "default"}
+ />
+ <StatCard
+ label="Requests"
+ value={formatCount(stats.total)}
+ hint={loggingDisabled ? "recording off" : "recent window"}
+ />
+ <StatCard label="Completed" value={formatCount(stats.completed)} />
+ <StatCard
+ label="Errors"
+ value={formatCount(stats.errors)}
+ tone={stats.errors > 0 ? "error" : "default"}
+ hint={
+ stats.errorRate != null
+ ? `${Math.round(stats.errorRate * 100)}% of finished`
+ : undefined
+ }
+ />
+ <StatCard
+ label="Avg latency"
+ value={
+ stats.avgDurationMs == null
+ ? "–"
+ : formatDuration(stats.avgDurationMs)
+ }
+ hint={
+ stats.maxDurationMs != null
+ ? `max ${formatDuration(stats.maxDurationMs)}`
+ : undefined
+ }
+ />
+ <StatCard
+ label="Throughput"
+ value={
+ stats.tokensPerSecond == null
+ ? "–"
+ : `${stats.tokensPerSecond.toFixed(1)} tok/s`
+ }
+ hint={`${formatCount(stats.totalTokens)} tokens`}
+ />
+ </section>
+
+ <section className="flex min-h-0 flex-col overflow-hidden rounded-xl border border-border/60 bg-card">
+ <div className="flex flex-wrap items-center gap-2 border-b border-border/60 px-4 py-3">
+ <Input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder="Search model, endpoint, preview or error"
+ aria-label="Search API requests"
+ className="h-9 w-full min-w-0 flex-1 rounded-full border-none bg-muted shadow-none dark:bg-background sm:w-64 sm:flex-none"
+ />
+ <Select
+ value={statusFilter}
+ onValueChange={(value) =>
+ setStatusFilter(value as MonitorStatusFilter)
+ }
+ >
+ <SelectTrigger
+ aria-label="Filter by status"
+ className="h-9 w-[150px] rounded-full border-none bg-muted shadow-none dark:bg-background"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {STATUS_FILTERS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <span className="ml-auto shrink-0 text-ui-11 text-muted-foreground">
+ {formatCount(visible.length)} of {formatCount(entries.length)}
+ </span>
+ </div>
+
+ <div className="grid min-h-0 grid-cols-1 lg:grid-cols-[minmax(0,380px)_minmax(0,1fr)]">
+ <div className="max-h-[560px] min-h-[220px] overflow-y-auto border-b border-border/60 lg:border-b-0 lg:border-r">
+ {loading ? (
+ <div className="flex flex-col gap-3 p-4">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-16 w-full rounded-lg" />
+ ))}
+ </div>
+ ) : visible.length === 0 ? (
+ <p className="px-4 py-10 text-center text-sm text-muted-foreground">
+ {entries.length > 0
+ ? "No requests match this filter."
+ : loggingDisabled
+ ? "Recording is off: UNSLOTH_STUDIO_DISABLE_API_MONITOR is set. Requests and model loads still run normally, they are just not listed here. Unset the variable and restart Studio to re-enable."
+ : "No API traffic yet. Point a client at the base URL above to see requests here."}
+ </p>
+ ) : (
+ visible.map((entry) => (
+ <RequestRow
+ key={entry.id}
+ entry={entry}
+ selected={entry.id === selectedId}
+ onSelect={() => setSelectedId(entry.id)}
+ />
+ ))
+ )}
+ </div>
+
+ <div className="max-h-[560px] min-h-[220px] overflow-y-auto">
+ {selected ? (
+ <RequestDetail
+ entry={selected}
+ detail={details[selected.id]}
+ loading={loadingDetails.has(selected.id)}
+ />
+ ) : (
+ <p className="flex h-full items-center justify-center px-6 py-10 text-center text-sm text-muted-foreground">
+ Select a request to inspect its prompt, reply, tokens and
+ errors.
+ </p>
+ )}
+ </div>
+ </div>
+ </section>
+
+ <SavedModelSettingsPanel />
+ </main>
+ );
+}
diff --git a/studio/frontend/src/features/api-monitor/clear-monitor.ts b/studio/frontend/src/features/api-monitor/clear-monitor.ts
new file mode 100644
index 00000000000..6b799e0605d
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/clear-monitor.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// What the monitor's "Clear log" button runs. Its own plain module because the hook it
+// belongs to imports React and cannot be loaded by the node --test suite.
+
+export type ClearMonitorDeps = {
+ /** One DELETE /api/inference/monitor. Rejects when the server refuses or is unreachable. */
+ clearRemote: () => Promise<void>;
+ /** Drops the cached full payloads, whose rows the clear just deleted. */
+ resetDetails: () => void;
+ /** One refetch, so the emptied log is what the page renders. Settles either way. */
+ reload: () => Promise<void>;
+ /** The monitor's error banner. */
+ onError: (message: string) => void;
+};
+
+/** Shown when the DELETE rejects with something that is not an Error. */
+export const CLEAR_MONITOR_FAILED = "Failed to clear the monitor";
+
+export async function clearMonitor(deps: ClearMonitorDeps): Promise<void> {
+ try {
+ await deps.clearRemote();
+ } catch (err: unknown) {
+ // The click handler discards this promise, so rethrowing is an unhandled rejection and
+ // the page shows a cleared selection over an unchanged log with nothing said. Nothing
+ // was deleted, so the cached details and the current snapshot both still stand.
+ deps.onError(err instanceof Error ? err.message : CLEAR_MONITOR_FAILED);
+ return;
+ }
+ deps.resetDetails();
+ await deps.reload();
+}
diff --git a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
new file mode 100644
index 00000000000..17173812818
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// What a remote load will apply, otherwise unanswerable from outside the process. Read
+// only: the model's settings page is the only place that owns this and the local store.
+
+import { Skeleton } from "@/components/ui/skeleton";
+import {
+ type ApiModelOverride,
+ type ApiModelOverrides,
+ fetchModelOverrides,
+} from "@/features/model-picker/api/model-overrides";
+import { type ReactElement, useCallback, useEffect, useState } from "react";
+
+/** Summary of the fields the loader will apply, in load order. */
+function describeOverride(override: ApiModelOverride): string[] {
+ const parts: string[] = [];
+ if (override.custom_context_length) {
+ parts.push(`${override.custom_context_length.toLocaleString()} context`);
+ }
+ if (override.max_seq_length) {
+ parts.push(`${override.max_seq_length.toLocaleString()} max seq`);
+ }
+ if (override.kv_cache_dtype) {
+ parts.push(`KV ${override.kv_cache_dtype}`);
+ }
+ if (override.speculative_type) {
+ parts.push(
+ override.spec_draft_n_max
+ ? `spec ${override.speculative_type} ×${override.spec_draft_n_max}`
+ : `spec ${override.speculative_type}`,
+ );
+ }
+ if (override.n_parallel) {
+ parts.push(`${override.n_parallel} parallel slots`);
+ }
+ if (override.tensor_parallel) {
+ parts.push("tensor parallel");
+ }
+ if (override.gpu_memory_mode === "manual") {
+ parts.push("manual GPU memory");
+ }
+ if (override.gpu_layers != null) {
+ parts.push(`${override.gpu_layers} GPU layers`);
+ }
+ if (override.n_cpu_moe) {
+ parts.push(`${override.n_cpu_moe} MoE layers on CPU`);
+ }
+ if (override.gpu_ids?.length) {
+ parts.push(`GPU ${override.gpu_ids.join(", ")}`);
+ }
+ if (override.chat_template_override) {
+ parts.push("custom chat template");
+ }
+ if (override.llama_extra_args?.length) {
+ parts.push(override.llama_extra_args.join(" "));
+ }
+ return parts;
+}
+
+export function SavedModelSettingsPanel(): ReactElement {
+ const [overrides, setOverrides] = useState<ApiModelOverrides | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ try {
+ setOverrides(await fetchModelOverrides());
+ setError(null);
+ } catch (err: unknown) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : "Could not load saved model settings",
+ );
+ }
+ }, []);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const entries = Object.entries(overrides ?? {});
+
+ return (
+ <section className="flex flex-col gap-3">
+ <div className="flex flex-col gap-1">
+ <h2 className="text-ui-16 font-semibold tracking-[-0.01em] text-foreground">
+ Settings applied on API load
+ </h2>
+ <p className="text-sm text-muted-foreground">
+ When a request names one of these models, Unsloth loads it with these
+ settings, the same ones you saved in the model&apos;s settings page.
+ Models without an entry load with app defaults. Edit or forget an
+ entry from that model&apos;s settings, which keeps this list and the
+ picker in step.
+ </p>
+ </div>
+
+ {error ? (
+ <div className="rounded-xl border border-red-500/40 bg-red-500/5 px-4 py-3 text-sm text-red-600 dark:text-red-400">
+ {error}
+ </div>
+ ) : overrides == null ? (
+ <div className="flex flex-col gap-2">
+ {[0, 1].map((i) => (
+ <Skeleton key={i} className="h-14 w-full rounded-xl" />
+ ))}
+ </div>
+ ) : entries.length === 0 ? (
+ <p className="rounded-xl border border-border/60 bg-card px-4 py-6 text-center text-sm text-muted-foreground">
+ No saved model settings yet. Open a model&apos;s settings, turn on
+ &quot;Remember for this model&quot;, and it will be applied to API
+ loads too.
+ </p>
+ ) : (
+ <ul className="flex flex-col gap-2">
+ {entries.map(([modelId, override]) => {
+ const summary = describeOverride(override);
+ return (
+ <li
+ key={modelId}
+ className="flex min-w-0 items-start gap-3 rounded-xl border border-border/60 bg-card px-4 py-3"
+ >
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <span className="min-w-0 break-all font-mono text-ui-12 font-medium text-foreground">
+ {modelId}
+ </span>
+ <span className="min-w-0 break-words text-ui-11 text-muted-foreground">
+ {summary.length > 0 ? summary.join(" · ") : "App defaults"}
+ </span>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/studio/frontend/src/features/api-monitor/index.ts b/studio/frontend/src/features/api-monitor/index.ts
new file mode 100644
index 00000000000..28b01def8bb
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/index.ts
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export { ApiMonitorPage } from "./api-monitor-page";
+export { ApiMonitorOverlay } from "./api-monitor-overlay";
+export { useApiMonitorOverlayStore } from "./overlay-store";
+export {
+ computeStats,
+ filterEntries,
+ useApiMonitor,
+ type MonitorStats,
+ type MonitorStatusFilter,
+} from "./use-api-monitor";
diff --git a/studio/frontend/src/features/api-monitor/lifecycle.ts b/studio/frontend/src/features/api-monitor/lifecycle.ts
new file mode 100644
index 00000000000..6c2c3a178f6
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/lifecycle.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Labels for model load/unload/download rows, shared by the overlay and the page. Their own
+// module because the overlay mounts from __root.tsx: importing them from the page would pull it
+// into the eager bundle and undo the route's lazyRouteComponent.
+
+import type { ApiMonitorEntry } from "@/features/chat/types/api";
+
+// A lifecycle row carries an event and reason instead of a prompt, so nothing expands.
+export function isLifecycleEntry(entry: ApiMonitorEntry): boolean {
+ return entry.kind === "lifecycle";
+}
+
+export function lifecycleLabel(entry: ApiMonitorEntry): string {
+ if (entry.event === "unload") {
+ return entry.reason === "idle" ? "Model unloaded (idle)" : "Model unloaded";
+ }
+ if (entry.event === "download") {
+ if (entry.status === "running") {
+ const pct = entry.progress;
+ return typeof pct === "number"
+ ? `Downloading model (${Math.round(pct)}%)`
+ : "Downloading model";
+ }
+ if (entry.status === "completed") {
+ return "Model downloaded";
+ }
+ // A cancel is deliberate, so calling it a failure misreads the user's action.
+ return entry.status === "cancelled"
+ ? "Model download cancelled"
+ : "Model download failed";
+ }
+ if (entry.status === "running") {
+ return "Loading model";
+ }
+ if (entry.status === "completed") {
+ return "Model loaded";
+ }
+ return "Model load failed";
+}
diff --git a/studio/frontend/src/features/api-monitor/new-traffic.ts b/studio/frontend/src/features/api-monitor/new-traffic.ts
new file mode 100644
index 00000000000..e8ef72cdb3c
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/new-traffic.ts
@@ -0,0 +1,143 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Which rows of a monitor snapshot are traffic this session has not shown yet.
+// Split out of the overlay so it can be driven without a browser.
+
+import type { ApiMonitorEntry } from "@/features/chat/types/api";
+
+export type WatchedEntry = Pick<
+ ApiMonitorEntry,
+ "id" | "status" | "via_api_key" | "started_at"
+>;
+
+export interface WatchedResponse {
+ entries: readonly WatchedEntry[];
+ // biome-ignore lint/style/useNamingConvention: API schema
+ server_time?: number | null;
+}
+
+export interface ApiMonitorWatch {
+ /** The first snapshot has been folded in and its backlog written off. */
+ seeded: boolean;
+ /** Ids already shown. A set, not "the newest id": finishing moves an entry to the
+ * front, so the head flips without any new traffic. */
+ seenIds: Set<string>;
+ /** performance.now() when this watch began; monotonic, so a clock step cannot move it. */
+ watchStartedAt: number;
+ /** This seed follows a stay on the full page rather than starting a session. */
+ resumed: boolean;
+ /** The snapshot already folded in. The overlay's observer re-runs on any store change,
+ * not only on a new poll, and a second fold would spend a pending re-arm on a snapshot
+ * from before the stand down. */
+ lastFolded: WatchedResponse | null;
+}
+
+export function createWatch(nowMs: number): ApiMonitorWatch {
+ return {
+ seeded: false,
+ seenIds: new Set(),
+ watchStartedAt: nowMs,
+ resumed: false,
+ lastFolded: null,
+ };
+}
+
+/**
+ * Re-anchor as the poll stands up, and only while unseeded: the first snapshot can land
+ * long after mount (a hidden tab issues no fetch), and dating the backlog from mount
+ * would write that whole gap off as history.
+ */
+export function startWatching(watch: ApiMonitorWatch, nowMs: number): void {
+ if (!watch.seeded) {
+ watch.watchStartedAt = nowMs;
+ }
+}
+
+/** The full page took over; what it showed is not new traffic on the way back. */
+export function rearmWatch(watch: ApiMonitorWatch): void {
+ watch.seeded = false;
+ watch.resumed = true;
+}
+
+/**
+ * The poll also stands down for the auto-open opt out, and calls still land behind it.
+ * By the time the user turns automatic opening back on those are backlog, not a reason to
+ * pop the panel over the composer, so write them off exactly as a stay on the full page
+ * does. An unseeded watch has no backlog to write off: re-arming it would silence the
+ * first snapshot of a session that merely started out opted out.
+ */
+export function standDownWatch(watch: ApiMonitorWatch): void {
+ if (!watch.seeded) {
+ return;
+ }
+ rearmWatch(watch);
+}
+
+/**
+ * When this watch began, on the server's clock. Server ``time.time()`` minus a browser
+ * *duration*, never minus a browser timestamp, so a clock disagreeing with the server's cancels
+ * instead of skewing the answer. Null on a backend with no clock field.
+ */
+function historyCutoff(
+ watch: ApiMonitorWatch,
+ response: WatchedResponse,
+ nowMs: number,
+): number | null {
+ const serverTime = response.server_time;
+ if (typeof serverTime !== "number" || !Number.isFinite(serverTime)) {
+ return null;
+ }
+ return serverTime - Math.max(0, nowMs - watch.watchStartedAt) / 1000;
+}
+
+function isHistory(entry: WatchedEntry, cutoff: number | null): boolean {
+ // Still running at the first snapshot: it started while Studio loaded, so it is unseen.
+ if (entry.status === "running") {
+ return false;
+ }
+ if (cutoff == null || !Number.isFinite(entry.started_at)) {
+ return true;
+ }
+ // Finished before the first snapshot is not the same as started before we did: a call
+ // made while the tab was hidden is already terminal when the poll finally runs.
+ return entry.started_at <= cutoff;
+}
+
+/** Fold a snapshot in and report whether it holds API-key traffic not shown yet. */
+export function observeResponse(
+ watch: ApiMonitorWatch,
+ response: WatchedResponse,
+ nowMs: number,
+): boolean {
+ // Fold each snapshot once. The observer re-runs when the store changes, with the same
+ // snapshot in hand; folding it again would seed a re-arm from before the stand down and
+ // leave the backlog that landed behind it counting as new traffic.
+ if (watch.lastFolded === response) {
+ return false;
+ }
+ watch.lastFolded = response;
+ const { entries } = response;
+ if (!watch.seeded) {
+ watch.seeded = true;
+ const { resumed } = watch;
+ watch.resumed = false;
+ const cutoff = historyCutoff(watch, response, nowMs);
+ // A rearm is not a fresh watch. isHistory keeps a running row on purpose: at a first
+ // snapshot nobody has seen it. Off the full page the opposite holds, since that page
+ // was showing this same feed, so mark everything it could show as read.
+ watch.seenIds = new Set(
+ entries
+ .filter((entry) => resumed || isHistory(entry, cutoff))
+ .map((e) => e.id),
+ );
+ }
+ const seen = watch.seenIds;
+ // Only API-key traffic counts: Studio's own chat uses these same endpoints.
+ const hasNewTraffic = entries.some(
+ (entry) => entry.via_api_key && !seen.has(entry.id),
+ );
+ // Re-seed each poll so the set stays bounded by the server's ring buffer.
+ watch.seenIds = new Set(entries.map((entry) => entry.id));
+ return hasNewTraffic;
+}
diff --git a/studio/frontend/src/features/api-monitor/overlay-store.ts b/studio/frontend/src/features/api-monitor/overlay-store.ts
new file mode 100644
index 00000000000..88810f42dac
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/overlay-store.ts
@@ -0,0 +1,76 @@
+// 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 { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+
+/**
+ * localStorage that cannot throw: private browsing, blocked cookies and opaque webview
+ * origins all throw on access. Losing the preference is fine; losing the panel is not.
+ */
+const safeStorage = {
+ getItem: (name: string): string | null => {
+ try {
+ return window.localStorage.getItem(name);
+ } catch {
+ return null;
+ }
+ },
+ setItem: (name: string, value: string): void => {
+ try {
+ window.localStorage.setItem(name, value);
+ } catch {
+ // Quota exceeded or denied; the preference stays session-only.
+ }
+ },
+ removeItem: (name: string): void => {
+ try {
+ window.localStorage.removeItem(name);
+ } catch {
+ // Same.
+ }
+ },
+};
+
+interface ApiMonitorOverlayState {
+ /** Whether the floating panel is on screen right now. Session state. */
+ isOpen: boolean;
+ /** Set on close so the panel does not pop back in the same burst. */
+ suppressed: boolean;
+ /** Persisted opt out: when false the panel never opens itself. */
+ autoOpen: boolean;
+ open: () => void;
+ close: () => void;
+ setAutoOpen: (autoOpen: boolean) => void;
+}
+
+/** Only `autoOpen` persists; a dismissal lasts the sitting, not forever. */
+export const useApiMonitorOverlayStore = create<ApiMonitorOverlayState>()(
+ persist(
+ (set) => ({
+ isOpen: false,
+ suppressed: false,
+ autoOpen: true,
+ open: () => set({ isOpen: true, suppressed: false }),
+ close: () => set({ isOpen: false, suppressed: true }),
+ setAutoOpen: (autoOpen) => set({ autoOpen }),
+ }),
+ {
+ name: "unsloth_api_monitor_overlay",
+ version: 1,
+ storage: createJSONStorage(() => safeStorage),
+ partialize: (state) => ({ autoOpen: state.autoOpen }),
+ // Without this a version bump discards the payload and revives a disabled popup.
+ migrate: (persisted) => persisted,
+ // Explicit merge so an older stored payload cannot resurrect `isOpen`.
+ merge: (persisted, current) => ({
+ ...current,
+ autoOpen:
+ typeof (persisted as { autoOpen?: unknown } | null)?.autoOpen ===
+ "boolean"
+ ? (persisted as { autoOpen: boolean }).autoOpen
+ : current.autoOpen,
+ }),
+ },
+ ),
+);
diff --git a/studio/frontend/src/features/api-monitor/unload-resident.ts b/studio/frontend/src/features/api-monitor/unload-resident.ts
new file mode 100644
index 00000000000..b289b8639b8
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/unload-resident.ts
@@ -0,0 +1,51 @@
+// 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 monitor's Unload button releases whatever the backend has resident. /unload matches
+// on the internal id, which the monitor rows do not carry, so the id has to be read from
+// the status first. Its own plain module because the page is .tsx (router, motion, icons)
+// and cannot be imported by the node --test suite.
+
+/** The model the backend has resident right now, as the Unload button needs it. */
+export type ResidentModel = {
+ /** The id POST /api/inference/unload matches on. */
+ checkpoint: string;
+ /** Every spelling of that same model (load path, advertised repo id), for the store clear. */
+ aliases: string[];
+};
+
+export type UnloadResidentDeps = {
+ /** One GET /api/inference/status, resolved to the resident model or null. */
+ readResident: () => Promise<ResidentModel | null>;
+ /** One POST /api/inference/unload naming that id. */
+ unload: (checkpoint: string) => Promise<void>;
+};
+
+export type UnloadResidentResult = {
+ /** Aliases of every model this run really unloaded, in the order they were unloaded. */
+ unloadedAliases: string[];
+ /** A model still resident when the run ended, or null once nothing is loaded. */
+ stillResident: string | null;
+};
+
+// One retry. An API auto-switch can replace the model between the status read and the
+// unload reaching the backend's lifecycle gate, and /unload naming a model a load already
+// replaced is a documented 200 no-op, so a single pass reports success with the new model
+// still holding the VRAM. A model that arrives after the retry is a fresh load rather than
+// this click's target, so the run names it instead of chasing it.
+export const UNLOAD_RESIDENT_PASSES = 2;
+
+export async function unloadResident(
+ deps: UnloadResidentDeps,
+ passes: number = UNLOAD_RESIDENT_PASSES,
+): Promise<UnloadResidentResult> {
+ const unloadedAliases: string[] = [];
+ let resident = await deps.readResident();
+ for (let pass = 0; pass < passes && resident !== null; pass += 1) {
+ await deps.unload(resident.checkpoint);
+ unloadedAliases.push(...resident.aliases);
+ // Re-read rather than assume: only the backend knows whether that id matched.
+ resident = await deps.readResident();
+ }
+ return { unloadedAliases, stillResident: resident?.checkpoint ?? null };
+}
diff --git a/studio/frontend/src/features/api-monitor/use-api-monitor.ts b/studio/frontend/src/features/api-monitor/use-api-monitor.ts
new file mode 100644
index 00000000000..45c2b6904a6
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/use-api-monitor.ts
@@ -0,0 +1,310 @@
+// 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 {
+ clearApiMonitor,
+ getApiMonitor,
+ getApiMonitorEntry,
+} from "@/features/chat/api/chat-api";
+import type {
+ ApiMonitorEntry,
+ ApiMonitorResponse,
+} from "@/features/chat/types/api";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { clearMonitor } from "./clear-monitor";
+
+/** Poll cadence while live. Matches the settings console it replaces. */
+const POLL_INTERVAL_MS = 1500;
+
+export type MonitorStatusFilter =
+ | "all"
+ | "running"
+ | "completed"
+ | "error"
+ | "cancelled";
+
+export interface MonitorStats {
+ active: number;
+ total: number;
+ completed: number;
+ errors: number;
+ cancelled: number;
+ /** Mean duration over finished requests, or null when none have finished. */
+ avgDurationMs: number | null;
+ /** Slowest finished request, for spotting a pathological call. */
+ maxDurationMs: number | null;
+ totalTokens: number;
+ /** Share of finished requests that failed, 0-1. Null when nothing finished. */
+ errorRate: number | null;
+ /** Mean completion tokens per second over requests that reported both. */
+ tokensPerSecond: number | null;
+}
+
+function isTerminal(entry: ApiMonitorEntry): boolean {
+ return entry.status !== "running";
+}
+
+function completionTokens(entry: ApiMonitorEntry): number | null {
+ if (entry.completion_tokens != null) {
+ return entry.completion_tokens;
+ }
+ // Some providers report only a total, so subtract the prompt to estimate generated.
+ if (entry.total_tokens != null && entry.prompt_tokens != null) {
+ return Math.max(0, entry.total_tokens - entry.prompt_tokens);
+ }
+ return null;
+}
+
+function entryTokens(entry: ApiMonitorEntry): number {
+ if (entry.total_tokens != null) {
+ return entry.total_tokens;
+ }
+ return (entry.prompt_tokens ?? 0) + (entry.completion_tokens ?? 0);
+}
+
+export function computeStats(entries: ApiMonitorEntry[]): MonitorStats {
+ let active = 0;
+ let completed = 0;
+ let errors = 0;
+ let cancelled = 0;
+ let totalTokens = 0;
+ let durationSum = 0;
+ let durationCount = 0;
+ let maxDurationMs: number | null = null;
+ // Total tokens over total time: averaging rates lets one tiny request outweigh a long one.
+ let generatedTokens = 0;
+ let generatedDurationMs = 0;
+
+ let requests = 0;
+
+ for (const entry of entries) {
+ // A load, unload or download is not an HTTP call: it reads as "running" throughout, so
+ // counting it invents an in-flight request. The backend leaves these out of active_count.
+ if (entry.kind === "lifecycle") {
+ continue;
+ }
+ requests += 1;
+ totalTokens += entryTokens(entry);
+ if (entry.status === "running") {
+ active += 1;
+ } else if (entry.status === "error") {
+ errors += 1;
+ } else if (entry.status === "cancelled") {
+ cancelled += 1;
+ } else {
+ completed += 1;
+ }
+ const duration = entry.duration_ms;
+ if (duration != null && isTerminal(entry)) {
+ durationSum += duration;
+ durationCount += 1;
+ maxDurationMs =
+ maxDurationMs == null ? duration : Math.max(maxDurationMs, duration);
+ const generated = completionTokens(entry);
+ // A sub-millisecond duration divides into a meaningless rate.
+ if (generated != null && generated > 0 && duration > 0) {
+ generatedTokens += generated;
+ generatedDurationMs += duration;
+ }
+ }
+ }
+
+ const finished = completed + errors + cancelled;
+ return {
+ active,
+ total: requests,
+ completed,
+ errors,
+ cancelled,
+ avgDurationMs: durationCount > 0 ? durationSum / durationCount : null,
+ maxDurationMs,
+ totalTokens,
+ errorRate: finished > 0 ? errors / finished : null,
+ tokensPerSecond:
+ generatedDurationMs > 0
+ ? generatedTokens / (generatedDurationMs / 1000)
+ : null,
+ };
+}
+
+export function filterEntries(
+ entries: ApiMonitorEntry[],
+ status: MonitorStatusFilter,
+ query: string,
+): ApiMonitorEntry[] {
+ const needle = query.trim().toLowerCase();
+ return entries.filter((entry) => {
+ if (status !== "all" && entry.status !== status) {
+ return false;
+ }
+ if (!needle) {
+ return true;
+ }
+ // The fields a debugging session keys off. Coerced, not trusted: these arrive over
+ // the network, and one malformed entry throwing here would blank the whole log.
+ return [
+ entry.model,
+ entry.endpoint,
+ entry.prompt_preview,
+ entry.reply_preview,
+ entry.error,
+ ].some((field) =>
+ String(field ?? "")
+ .toLowerCase()
+ .includes(needle),
+ );
+ });
+}
+
+interface UseApiMonitorResult {
+ data: ApiMonitorResponse | null;
+ entries: ApiMonitorEntry[];
+ stats: MonitorStats;
+ error: string | null;
+ /** True until the first response lands, so skeletons show once. */
+ loading: boolean;
+ refreshing: boolean;
+ paused: boolean;
+ setPaused: (paused: boolean) => void;
+ refresh: () => void;
+ clear: () => Promise<void>;
+ /** Full prompt/reply for expanded entries, keyed by entry id. */
+ details: Record<string, ApiMonitorEntry>;
+ loadingDetails: ReadonlySet<string>;
+ requestDetail: (id: string) => boolean;
+}
+
+/**
+ * Live view of the server's OpenAI-compatible API traffic. Polls rather than streams because the
+ * backing monitor is a ring buffer with no change feed. Polling self-reschedules (never
+ * overlapping), and pausing stops it so reading a payload is not fighting a reordering list.
+ * `intervalMs` trades freshness for cost: the closed overlay slows right down.
+ */
+export function useApiMonitor({
+ intervalMs = POLL_INTERVAL_MS,
+}: { intervalMs?: number } = {}): UseApiMonitorResult {
+ const [data, setData] = useState<ApiMonitorResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [refreshing, setRefreshing] = useState(false);
+ const [paused, setPaused] = useState(false);
+ const [details, setDetails] = useState<Record<string, ApiMonitorEntry>>({});
+ const [loadingDetails, setLoadingDetails] = useState<Set<string>>(
+ () => new Set(),
+ );
+ // Mirrors `loadingDetails` outside React state so the guard sees same-tick writes.
+ const inFlightDetails = useRef<Set<string>>(new Set());
+
+ const load = useCallback(async (): Promise<void> => {
+ setRefreshing(true);
+ try {
+ const next = await getApiMonitor();
+ setData(next);
+ setError(null);
+ } catch (err: unknown) {
+ setError(err instanceof Error ? err.message : "Monitor unavailable");
+ } finally {
+ setRefreshing(false);
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (paused) {
+ return;
+ }
+ let cancelled = false;
+ let timer: number | undefined;
+
+ function poll(): void {
+ getApiMonitor()
+ .then((next) => {
+ if (cancelled) return;
+ setData(next);
+ setError(null);
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ setError(err instanceof Error ? err.message : "Monitor unavailable");
+ })
+ .finally(() => {
+ if (cancelled) return;
+ setLoading(false);
+ timer = window.setTimeout(poll, intervalMs);
+ });
+ }
+
+ poll();
+ return () => {
+ cancelled = true;
+ if (timer !== undefined) {
+ window.clearTimeout(timer);
+ }
+ };
+ }, [paused, intervalMs]);
+
+ // Returns whether a fetch started: recording "fetched revision N" when the guard
+ // refused would skip that revision once updated_at settles.
+ const requestDetail = useCallback((id: string): boolean => {
+ if (inFlightDetails.current.has(id)) {
+ return false;
+ }
+ inFlightDetails.current.add(id);
+ setLoadingDetails((prev) => new Set(prev).add(id));
+ getApiMonitorEntry(id)
+ .then((entry) => {
+ setDetails((prev) => ({ ...prev, [id]: entry }));
+ })
+ .catch(() => {
+ // Aged out of the ring buffer: drop the stale copy so the row previews show.
+ setDetails((prev) => {
+ if (!(id in prev)) return prev;
+ const next = { ...prev };
+ delete next[id];
+ return next;
+ });
+ })
+ .finally(() => {
+ inFlightDetails.current.delete(id);
+ setLoadingDetails((prev) => {
+ const next = new Set(prev);
+ next.delete(id);
+ return next;
+ });
+ });
+ return true;
+ }, []);
+
+ // The Clear log button discards this promise, so a failed DELETE has to land in the
+ // error banner here: rethrowing leaves an unhandled rejection and a log that silently
+ // did not clear. Sequence lives in a plain module so the node --test suite can drive it.
+ const clear = useCallback(
+ (): Promise<void> =>
+ clearMonitor({
+ clearRemote: clearApiMonitor,
+ resetDetails: () => setDetails({}),
+ reload: load,
+ onError: setError,
+ }),
+ [load],
+ );
+
+ const entries = useMemo(() => data?.entries ?? [], [data]);
+ const stats = useMemo(() => computeStats(entries), [entries]);
+
+ return {
+ data,
+ entries,
+ stats,
+ error,
+ loading,
+ refreshing,
+ paused,
+ setPaused,
+ refresh: () => void load(),
+ clear,
+ details,
+ loadingDetails,
+ requestDetail,
+ };
+}
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 66e2f835f21..c6a383861ca 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -161,6 +161,13 @@ export async function getApiMonitorEntry(id: string): Promise<ApiMonitorEntry> {
return parseJsonOrThrow<ApiMonitorEntry>(response);
}
+export async function clearApiMonitor(): Promise<void> {
+ const response = await authFetch("/api/inference/monitor", {
+ method: "DELETE",
+ });
+ await parseJsonOrThrow<{ cleared: boolean }>(response);
+}
+
export interface ActiveGenerationsResponse {
count: number;
/** Conversations with a generation in flight. Shorter than `count` when a
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index dbe88de6f9b..739254bb2b2 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -35,6 +35,10 @@ export type {
GgufVariantDetail,
InferenceStatusResponse,
} from "./types/api";
+export {
+ applyActiveModelStatusToStore,
+ resolveInferenceCheckpointId,
+} from "./lib/apply-inference-status-to-store";
export {
ChatSettingsPanel,
ParamSlider,
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 28a9711d312..fedb0fa9c46 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
@@ -3,7 +3,7 @@
// Barrel import (lint rule); the model-picker cycle is fine because the call
// happens at runtime, not module eval.
-import { resolveInitialConfig } from "@/features/model-picker";
+import { resolveResidentInitialConfig } from "@/features/model-picker";
import { getInferenceStatus } from "../api/chat-api";
import {
mergeBackendRecommendedInference,
@@ -25,6 +25,7 @@ import {
} from "../types/api";
import type { ChatModelSummary } from "../types/runtime";
import { sameGpuSelection } from "@/hooks/gpu-selection";
+import { resolveChatTemplateSeed } from "./resolve-chat-template-seed";
type LocalReasoningEffort = Extract<ReasoningEffort, "low" | "medium" | "high">;
@@ -215,11 +216,14 @@ export function applyActiveModelStatusToStore(
hydratingExistingModel && !options.readoptingSameModel;
// 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
+ // snapshot path a cached repo loaded from, while its settings are keyed by the
+ // repo id, and the plain lookup misses that record.
const slotsUnseeded =
prevState.loadedNParallel === null && prevState.nParallel === null;
const remembered =
status.is_gguf && (slotsUnseeded || slotsModelChanged)
- ? resolveInitialConfig(checkpointId, status.gguf_variant ?? null)
+ ? resolveResidentInitialConfig(checkpointId, status.gguf_variant ?? null)
: null;
const rememberedNParallel = remembered?.remembered
? (remembered.config.nParallel ?? null)
@@ -397,12 +401,20 @@ export function applyActiveModelStatusToStore(
hydratingExistingModel ||
gpuStatusChanged) &&
gpuStatusFields),
- ...(status.chat_template_override !== undefined &&
- prevState.loadedChatTemplateOverride === null &&
- prevState.chatTemplateOverride === null && {
- chatTemplateOverride: status.chat_template_override,
- loadedChatTemplateOverride: status.chat_template_override,
- }),
+ // The one load param that only ever seeded from null, so a switch left the previous model's
+ // template in the store, which the Hub settings page reads as the new model's loaded config:
+ // Apply then saves A's template under B. A same-model reload from another client moves it
+ // too, so the seed also follows a changed status the way the GPU group above does: baseline
+ // always, control only while it still sits on that baseline. See resolveChatTemplateSeed.
+ ...resolveChatTemplateSeed({
+ incoming: status.chat_template_override,
+ previous: {
+ chatTemplateOverride: prevState.chatTemplateOverride,
+ loadedChatTemplateOverride: prevState.loadedChatTemplateOverride,
+ },
+ hydratingExistingModel,
+ seedLoadParams,
+ }),
});
ensureActiveModelInStoreList(status, checkpointId);
diff --git a/studio/frontend/src/features/chat/lib/resolve-chat-template-seed.ts b/studio/frontend/src/features/chat/lib/resolve-chat-template-seed.ts
new file mode 100644
index 00000000000..8b13d7ea9ee
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/resolve-chat-template-seed.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// What a fresh /api/inference/status does to the chat-template override pair. Its own
+// module, importing neither the store nor a barrel, so the rules are testable off a browser.
+
+export interface ChatTemplateSeedState {
+ /** The editable control: what the next load or Apply would send. */
+ chatTemplateOverride: string | null;
+ /** What the resident server was launched with, as this tab last saw it. */
+ loadedChatTemplateOverride: string | null;
+}
+
+/** The subset of the pair to write back; empty means leave the store alone. */
+export type ChatTemplateSeed = Partial<ChatTemplateSeedState>;
+
+/** Blank and absent are the same template: /load normalises "" to null before launching. */
+function sameTemplate(a: string | null, b: string | null): boolean {
+ return (a?.trim() ? a : null) === (b?.trim() ? b : null);
+}
+
+export function resolveChatTemplateSeed(options: {
+ /** ``status.chat_template_override``; undefined on a backend that omits the field. */
+ incoming: string | null | undefined;
+ previous: ChatTemplateSeedState;
+ /** A different model or quant is being adopted, so both fields are stale. */
+ hydratingExistingModel: boolean;
+ /** No load of this tab's own is in flight (``!modelLoading``). */
+ seedLoadParams: boolean;
+}): ChatTemplateSeed {
+ const { incoming, previous, hydratingExistingModel, seedLoadParams } =
+ options;
+ // While a load is in flight performLoad owns the load params, and an older backend
+ // omitting the field says nothing about the template.
+ if (incoming === undefined || !seedLoadParams) {
+ return {};
+ }
+ const unseeded =
+ previous.loadedChatTemplateOverride === null &&
+ previous.chatTemplateOverride === null;
+ if (hydratingExistingModel || unseeded) {
+ return {
+ chatTemplateOverride: incoming,
+ loadedChatTemplateOverride: incoming,
+ };
+ }
+ // Same checkpoint and quant, steady template: an ordinary poll must not touch the
+ // control, or it would overwrite a staged edit every refresh.
+ if (sameTemplate(incoming, previous.loadedChatTemplateOverride)) {
+ return {};
+ }
+ // The resident template moved under this tab -- another tab or an API caller reloaded
+ // the same checkpoint with a different override. The baseline is a fact about the
+ // running server, so it always advances (the rollback resends it). The control follows
+ // only while it still sits on the old baseline; a genuinely dirty one keeps its intent,
+ // exactly as the GPU group above preserves an unapplied placement edit.
+ const controlIsDirty = !sameTemplate(
+ previous.chatTemplateOverride,
+ previous.loadedChatTemplateOverride,
+ );
+ return {
+ loadedChatTemplateOverride: incoming,
+ ...(controlIsDirty ? {} : { chatTemplateOverride: incoming }),
+ };
+}
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 2c545009a15..c45d12eb3ed 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -304,6 +304,8 @@ export interface ApiMonitorEntry {
model: string;
prompt?: string;
reply?: string;
+ // True for API-key callers, not UI sessions: the panel auto-opens off this.
+ via_api_key: boolean;
prompt_preview: string;
reply_preview: string;
prompt_truncated: boolean;
@@ -329,6 +331,9 @@ export interface ApiMonitorEntry {
export interface ApiMonitorResponse {
status: "idle" | "ready" | "generating";
+ // Server wall clock (seconds) at snapshot, so started_at can be dated without trusting
+ // the browser's clock. Absent on a backend older than the field.
+ server_time?: number;
active_model?: string | null;
context_length?: number | null;
active_requests: number;
diff --git a/studio/frontend/src/features/hub/catalog/download-card.tsx b/studio/frontend/src/features/hub/catalog/download-card.tsx
index 8016a9406d2..cf767c7903d 100644
--- a/studio/frontend/src/features/hub/catalog/download-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/download-card.tsx
@@ -23,6 +23,7 @@ import {
ArrowReloadHorizontalIcon,
Delete02Icon,
Download01Icon,
+ Settings02Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
@@ -82,6 +83,39 @@ export function CardDivider() {
);
}
+export function CardSettingsButton({
+ label,
+ onClick,
+}: {
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ aria-label={label}
+ onClick={(e) => {
+ e.stopPropagation();
+ onClick();
+ }}
+ className="inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-foreground/[0.06] hover:text-foreground focus-visible:opacity-100 group-hover/dl:opacity-100 dark:hover:bg-white/[0.08]"
+ >
+ <HugeiconsIcon
+ icon={Settings02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="tooltip-compact">
+ {label}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
export function CardDeleteButton({
label,
onClick,
diff --git a/studio/frontend/src/features/hub/catalog/hub-model-settings-view.tsx b/studio/frontend/src/features/hub/catalog/hub-model-settings-view.tsx
new file mode 100644
index 00000000000..baf86d2f3bf
--- /dev/null
+++ b/studio/frontend/src/features/hub/catalog/hub-model-settings-view.tsx
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Full-page settings for one model, opened from the Hub. The same controls exist in the
+// chat picker's popover, but a popover is a poor place to work through every knob.
+
+import {
+ ModelConfigPage,
+ type ModelPickTarget,
+ modelConfigInstanceKey,
+} from "@/features/model-picker";
+import type { PerModelConfig } from "@/features/model-picker";
+import { cn } from "@/lib/utils";
+import { ArrowLeft01Icon, Globe02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useEffect, useRef, useState } from "react";
+
+export function HubModelSettingsView({
+ target,
+ loadedConfig = null,
+ loadedContextLength = null,
+ onBack,
+ onRun,
+ compact = false,
+}: {
+ target: ModelPickTarget;
+ /** Non-null when this model is loaded, so the page can show live values. */
+ loadedConfig?: PerModelConfig | null;
+ loadedContextLength?: number | null;
+ onBack: () => void;
+ /** Apply + load with these settings. */
+ onRun: (config: PerModelConfig) => void;
+ compact?: boolean;
+}) {
+ const scrollRef = useRef<HTMLDivElement | null>(null);
+ const [scrolled, setScrolled] = useState(false);
+ // Mirrors HubDetailView so this view sits at the Hub's measure.
+ const measure = compact
+ ? "mx-auto w-full max-w-[860px] px-5 sm:px-5"
+ : "mx-auto w-full max-w-[1100px] px-5 sm:px-8";
+
+ useEffect(() => {
+ const el = scrollRef.current;
+ if (!el) return;
+ const onScroll = () => {
+ const next = el.scrollTop > 0;
+ setScrolled((current) => (current === next ? current : next));
+ };
+ onScroll();
+ el.addEventListener("scroll", onScroll, { passive: true });
+ return () => el.removeEventListener("scroll", onScroll);
+ }, []);
+
+ return (
+ <div className="relative flex min-h-0 flex-1 flex-col">
+ <div
+ aria-hidden="true"
+ data-scrolled={scrolled || undefined}
+ className="hub-scroll-fade pointer-events-none absolute inset-x-0 top-0 z-10 h-7"
+ />
+ <div
+ ref={scrollRef}
+ data-hub-scroll="true"
+ className={cn(
+ "min-h-0 flex-1 overflow-x-hidden overflow-y-auto [overflow-anchor:none] [scrollbar-width:thin]",
+ compact
+ ? "mr-2 [scrollbar-gutter:stable]"
+ : "[scrollbar-gutter:stable_both-edges]",
+ )}
+ >
+ <div
+ className="hub-detail-bar sticky top-0 z-20"
+ data-scrolled={scrolled || undefined}
+ >
+ <div className={`${measure} py-3`}>
+ <button
+ type="button"
+ onClick={onBack}
+ className="-ml-1.5 inline-flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-full pl-1.5 pr-2.5 text-ui-12p5 font-medium text-muted-foreground transition-colors hover:bg-foreground/[0.05] hover:text-foreground dark:hover:bg-white/[0.06]"
+ >
+ <HugeiconsIcon
+ icon={ArrowLeft01Icon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ Back to Hub
+ </button>
+ </div>
+ </div>
+
+ <div className={cn(measure, "pb-20")}>
+ <header className="flex flex-col gap-1 pb-5">
+ <h1 className="min-w-0 break-words text-ui-24 font-semibold leading-[1.1] tracking-[-0.022em] text-foreground">
+ {target.displayName}
+ </h1>
+ <p className="min-w-0 break-all text-ui-12 text-muted-foreground">
+ {target.id}
+ {target.ggufVariant ? ` · ${target.ggufVariant}` : ""}
+ </p>
+ </header>
+
+ <div className="mb-5 flex items-start gap-2.5 rounded-xl border border-border/60 bg-card px-4 py-3">
+ <span className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-lg border border-border/60 bg-muted/40">
+ <HugeiconsIcon
+ icon={Globe02Icon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </span>
+ <p className="min-w-0 text-ui-12 leading-[1.5] text-muted-foreground">
+ {/* Only what auto-switch reaches: it indexes GGUFs and skips Ollama. */}
+ {(target.apiLoadable ?? target.isGguf)
+ ? "Saved settings apply everywhere this model loads, including when an OpenAI-compatible API request asks for it."
+ : "Saved settings apply everywhere Studio loads this model."}{" "}
+ Turn on{" "}
+ <span className="font-medium text-foreground">
+ Remember for this model
+ </span>{" "}
+ below to keep them.
+ </p>
+ </div>
+
+ <div className="rounded-xl border border-border/60 bg-card px-4 py-4">
+ <ModelConfigPage
+ // Keyed on the live config too, like the sidebar entry: ModelConfigPage
+ // reads loadedConfig once, so opening before status hydrates would leave
+ // the editor on saved values that Apply then writes back over.
+ key={modelConfigInstanceKey(
+ target.id,
+ target.ggufVariant,
+ loadedConfig,
+ )}
+ target={target}
+ onRun={onRun}
+ loadedConfig={loadedConfig}
+ loadedContextLength={loadedContextLength}
+ variant="page"
+ // The page heading already names the model; "Run settings" would repeat it.
+ showHeader={false}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
index 8f2672a706a..dba89a018e6 100644
--- a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
@@ -58,6 +58,7 @@ import { useHfTokenStore } from "../stores/hf-token-store";
import { DotTag } from "./dot-tag";
import {
CardDeleteButton,
+ CardSettingsButton,
CardUpdateButton,
DeleteConfirmDialog,
UpdateConfirmDialog,
@@ -104,6 +105,12 @@ interface LocalOnDeviceCardProps {
onEject?: () => void;
onTrain?: () => void;
onChange?: () => void;
+ /**
+ * Open settings for the quant this card is showing. ``quantIsUserPicked`` says whether
+ * it came from this card's selector or was derived from the resident model, which
+ * decides whether a fresher status read may override it.
+ */
+ onOpenSettings?: (ggufVariant: string | null, quantIsUserPicked: boolean) => void;
}
function formatAdapterLabel(
@@ -225,6 +232,7 @@ export function LocalOnDeviceCard({
onEject,
onTrain,
onChange,
+ onOpenSettings,
}: LocalOnDeviceCardProps) {
const [deleteOpen, setDeleteOpen] = useState(false);
const [updateOpen, setUpdateOpen] = useState(false);
@@ -367,6 +375,13 @@ export function LocalOnDeviceCard({
)?.quant ??
sortedVariants?.[0]?.quant ??
null);
+ // Only the first branch is a choice; the rest read the store, which can be stale.
+ const quantIsUserPicked = Boolean(
+ selectedVariantOverride &&
+ sortedVariants?.some((variant) =>
+ ggufVariantsMatch(variant.quant, selectedVariantOverride),
+ ),
+ );
const selectedVariant =
sortedVariants?.find((variant) =>
ggufVariantsMatch(variant.quant, selectedQuant),
@@ -578,6 +593,15 @@ export function LocalOnDeviceCard({
)}
</span>
<div className="ml-auto flex items-center gap-0.5">
+ {onOpenSettings && (
+ <CardSettingsButton
+ label={`Settings for ${repoId}`}
+ // The quant this card resolved, so settings edits what is on screen.
+ onClick={() =>
+ onOpenSettings(selectedQuant ?? null, quantIsUserPicked)
+ }
+ />
+ )}
{canUpdate && (
<CardUpdateButton
label={`Update ${repoId}`}
diff --git a/studio/frontend/src/features/hub/catalog/model-inspector.tsx b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
index 79e69e2f273..757ab0e2c93 100644
--- a/studio/frontend/src/features/hub/catalog/model-inspector.tsx
+++ b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
@@ -403,6 +403,8 @@ export type ModelInspectorActions = {
onTrain?: () => void;
onInventoryChange?: () => void;
onSearchHub?: (query: string) => void;
+ /** Open settings with the quant the card resolved. */
+ onOpenSettings?: (ggufVariant: string | null) => void;
};
export const ModelInspector = memo(function ModelInspector({
@@ -444,6 +446,7 @@ export const ModelInspector = memo(function ModelInspector({
onTrain,
onInventoryChange,
onSearchHub,
+ onOpenSettings,
} = actions;
const deviceType = usePlatformStore((s) => s.deviceType);
const chatOnly = usePlatformStore((s) => s.isChatOnly());
@@ -714,6 +717,7 @@ export const ModelInspector = memo(function ModelInspector({
model.isDownloaded && canTrainModel ? onTrain : undefined
}
onChange={onInventoryChange}
+ onOpenSettings={onOpenSettings}
/>
) : (
<DownloadSection
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
index cbae1080063..cd209e496a8 100644
--- a/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
@@ -263,6 +263,7 @@ export function DownloadedList({
compact = false,
sort,
onInventoryChange,
+ onOpenModelSettings,
}: {
cachedRows: CachedInventoryRow[];
localRows: LocalInventoryRow[];
@@ -284,6 +285,7 @@ export function DownloadedList({
compact?: boolean;
sort: InventorySort;
onInventoryChange?: () => void;
+ onOpenModelSettings?: (row: CachedInventoryRow | LocalInventoryRow) => void;
}) {
// Pinned repos surface first regardless of the active sort; the chosen sort
// still orders rows within the pinned and unpinned groups.
@@ -383,6 +385,7 @@ export function DownloadedList({
compact={compact}
onSelect={onSelect}
onChange={onInventoryChange}
+ onOpenSettings={onOpenModelSettings}
/>
);
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
index 5236c0be744..38c8661d7df 100644
--- a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx
@@ -573,6 +573,7 @@ export const InventoryRow = memo(function InventoryRow({
compact = false,
onSelect,
onChange,
+ onOpenSettings,
}: {
row: CachedInventoryRow | LocalInventoryRow;
selected: boolean;
@@ -585,6 +586,8 @@ export const InventoryRow = memo(function InventoryRow({
compact?: boolean;
onSelect: (id: string) => void;
onChange?: () => void;
+ /** Open this model's settings page. Omitted for datasets. */
+ onOpenSettings?: (row: CachedInventoryRow | LocalInventoryRow) => void;
}) {
const rowModelId =
row.kind === "cache"
@@ -732,30 +735,38 @@ export const InventoryRow = memo(function InventoryRow({
const rowPinned =
cacheDeletableRepoId != null &&
pinnedKeys.includes(pinKey(cacheDeletableRepoId));
+ // Settings applies to any downloaded model, not just deletable ones, so the menu renders
+ // when either action applies. `deletableRepoId` keeps the delete closures' narrowing.
+ const settingsAction =
+ !isDataset && onOpenSettings ? { onOpen: () => onOpenSettings(row) } : undefined;
+ const deletableRepoId = canDelete ? cacheDeletableRepoId : null;
const deleteAction =
- canDelete && cacheDeletableRepoId ? (
+ deletableRepoId || settingsAction ? (
<ModelRowMenu
- ariaLabel={`More options for ${cacheDeletableRepoId}`}
+ ariaLabel={`More options for ${deletableRepoId ?? rowModelId}`}
buttonClassName="pointer-events-auto hub-modal-pe-guard p-2 opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 [@media(pointer:coarse)]:opacity-100"
iconClassName="size-4"
+ settings={settingsAction}
pin={
- isDataset
+ isDataset || !deletableRepoId
? undefined
: {
pinned: rowPinned,
pinLabel: "Pin to top",
unpinLabel: "Unpin",
- onToggle: () => togglePinned(cacheDeletableRepoId),
+ onToggle: () => togglePinned(deletableRepoId),
}
}
- cachePath={isDataset ? undefined : { repoId: cacheDeletableRepoId }}
- del={{
+ cachePath={
+ isDataset || !deletableRepoId ? undefined : { repoId: deletableRepoId }
+ }
+ del={deletableRepoId ? {
title: isDataset ? "Delete cached dataset?" : "Delete cached model?",
description: (
<>
This will remove{" "}
<span className="font-medium text-foreground">
- {cacheDeletableRepoId}
+ {deletableRepoId}
</span>{" "}
{isDataset
? "and its downloaded files"
@@ -766,17 +777,17 @@ export const InventoryRow = memo(function InventoryRow({
disk. You can re-download it later.
</>
),
- successMessage: `Deleted ${cacheDeletableRepoId}`,
+ successMessage: `Deleted ${deletableRepoId}`,
onConfirm: async () => {
// Delete only the copy this row shows: cache rows carry the owning
// cache path, so pass it through and leave other caches untouched.
const rowCachePath =
row.kind === "cache" ? (row.cachePath ?? undefined) : undefined;
if (isDataset) {
- await deleteCachedDataset(cacheDeletableRepoId, rowCachePath);
+ await deleteCachedDataset(deletableRepoId, rowCachePath);
} else {
await deleteCachedModel(
- cacheDeletableRepoId,
+ deletableRepoId,
undefined,
undefined,
rowCachePath,
@@ -787,11 +798,11 @@ export const InventoryRow = memo(function InventoryRow({
usePinnedModelsStore.getState();
for (const key of pinned) {
if (
- key === pinKey(cacheDeletableRepoId) ||
- key.startsWith(`${cacheDeletableRepoId}::`)
+ key === pinKey(deletableRepoId) ||
+ key.startsWith(`${deletableRepoId}::`)
) {
toggle(
- cacheDeletableRepoId,
+ deletableRepoId,
key.includes("::")
? key.slice(key.indexOf("::") + 2)
: undefined,
@@ -801,7 +812,7 @@ export const InventoryRow = memo(function InventoryRow({
}
},
onDeleted: onChange,
- }}
+ } : undefined}
/>
) : null;
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog.tsx b/studio/frontend/src/features/hub/catalog/models-catalog.tsx
index 02b9b62fce0..e67954d2674 100644
--- a/studio/frontend/src/features/hub/catalog/models-catalog.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-catalog.tsx
@@ -16,6 +16,7 @@ import {
import type {
CachedInventoryRow,
DiscoverRow,
+ InventoryRow,
LocalInventoryRow,
ModelsTab,
} from "../types";
@@ -70,6 +71,7 @@ export interface ModelsCatalogHandlers {
onRetry: () => void;
onInventoryChange?: () => void;
onSwitchDevice?: () => void;
+ onOpenModelSettings?: (row: InventoryRow) => void;
}
function assignRef<T>(ref: RefObject<T | null>, value: T | null) {
@@ -128,6 +130,7 @@ export const ModelsCatalog = memo(function ModelsCatalog({
onRetry,
onInventoryChange,
onSwitchDevice,
+ onOpenModelSettings,
} = handlers;
const [scrolled, setScrolled] = useState(false);
const [streamingActive, setStreamingActive] = useState(false);
@@ -483,6 +486,7 @@ export const ModelsCatalog = memo(function ModelsCatalog({
columns={discoverView === "two" ? 2 : 1}
sort={inventorySort}
onInventoryChange={onInventoryChange}
+ onOpenModelSettings={onOpenModelSettings}
/>
</div>
) : (
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
index 36879097d08..519d94467bb 100644
--- a/studio/frontend/src/features/hub/hub-page.tsx
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -3,33 +3,31 @@
import { usePlatformStore } from "@/config/env";
import {
- isChannelEntryFresh,
- useHubFeedStore,
-} from "./stores/hub-feed-store";
-import {
+ applyActiveModelStatusToStore,
getInferenceStatus,
isExternalModelId,
+ listGgufVariants,
+ resolveInferenceCheckpointId,
useChatModelRuntime,
useChatRuntimeStore,
} from "@/features/chat";
-import { useHubInventory } from "./inventory";
-import type {
- HfModelSearchChannel,
- HfSortDirection,
- HfSortKey,
-} from "./hooks/use-hub-model-search";
import { useOnlineStatus } from "@/features/hub";
import { useHubInfiniteScroll } from "@/features/hub";
-import { ggufVariantsMatch, modelIdsMatch } from "./lib/model-identity";
-import { hfApiToken, useHfTokenStore } from "./stores/hf-token-store";
import {
+ type ModelPickTarget,
+ type PerModelConfig,
+ adoptLegacyConfigKey,
applyModelLoadConfigToRuntime,
+ applyPerModelConfigToRuntime,
currentRuntimePerModelConfig,
hfModelFitsDevice,
resolveInitialConfig,
+ useActiveModelConfig,
} from "@/features/model-picker";
+import { loadOpenAIAutoSwitchSettings } from "@/features/settings";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useGpuInfo, useInferenceGpuInfo } from "@/hooks/use-gpu-info";
+import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { useNavigate, useSearch } from "@tanstack/react-router";
import {
@@ -43,6 +41,7 @@ import {
import { ExternalLinkConfirmDialog } from "./catalog/external-link-confirm-dialog";
import { HubDetailView } from "./catalog/hub-detail-view";
import { HubFeed } from "./catalog/hub-feed";
+import { HubModelSettingsView } from "./catalog/hub-model-settings-view";
import { HubTopBar } from "./catalog/hub-top-bar";
import {
ModelsCatalog,
@@ -66,8 +65,23 @@ import { useDiscoverSearch } from "./hooks/use-discover-search";
import { useFeedWriteBack } from "./hooks/use-feed-write-back";
import { useHiddenEmbeddingModelIds } from "./hooks/use-hidden-embedding-models";
import { useHubFeed } from "./hooks/use-hub-feed";
+import type {
+ HfModelSearchChannel,
+ HfSortDirection,
+ HfSortKey,
+} from "./hooks/use-hub-model-search";
import { useHubModelVram } from "./hooks/use-hub-model-vram";
import { useModelsSelection } from "./hooks/use-models-selection";
+import { useHubInventory } from "./inventory";
+import { LOCAL_MODEL_SOURCE } from "./inventory/constants";
+import { settingsGgufVariantForRow } from "./inventory/settings-identity";
+import { adoptResidentModelStatus } from "./lib/adopt-inference-status";
+import { subscribeResidentStatusRefresh } from "./lib/resident-status-refresh";
+import {
+ type RefreshSupersession,
+ registerRefresh,
+ supersedingRefresh,
+} from "./lib/superseded-refresh";
import {
CHANNEL_TO_SECTION,
type ChannelId,
@@ -82,6 +96,11 @@ import {
isHiddenModelId,
} from "./lib/hidden-models";
import { inventoryRowMatches, tokenizeQuery } from "./lib/inventory-search";
+import {
+ ggufVariantsMatch,
+ modelIdsMatch,
+ residentModelIdMatches,
+} from "./lib/model-identity";
import {
type ModelTypeFilter,
matchesModelType,
@@ -95,6 +114,8 @@ import {
matchesCapability,
matchesFormat,
} from "./lib/view-models";
+import { hfApiToken, useHfTokenStore } from "./stores/hf-token-store";
+import { isChannelEntryFresh, useHubFeedStore } from "./stores/hub-feed-store";
import type {
CachedInventoryRow,
CapabilityFilter,
@@ -104,8 +125,24 @@ import type {
ModelsTab,
ResourceTypeFilter,
SelectedModelView,
+ SelectedResourceRef,
} from "./types";
+// What per-model settings are keyed by, which is not always what the loader is handed: a repo
+// cached outside the active HF cache loads by snapshot path while the picker and the auto-switch
+// index key it by repo id, so saving under the path strands them. The row decides that, not the
+// view it is shown in (a cache row is reachable from Discover too); `hub_cache` marks exactly
+// those, while a local row in the active cache stays on its run id.
+function modelConfigIdentity(
+ kind: SelectedModelView["kind"],
+ resource: SelectedResourceRef,
+): string {
+ if (kind !== "cache" && resource.source !== "hub_cache") {
+ return resource.runId;
+ }
+ return resource.repoId ?? resource.runId;
+}
+
const MODELS_TAB_STORAGE_KEY = "unsloth.hub.modelsTab";
const ALL_MODELS_VIEW_STORAGE_KEY = "unsloth.hub.allModelsView";
const INVENTORY_SORT_STORAGE_KEY = "unsloth.hub.inventorySort";
@@ -348,32 +385,104 @@ export function ModelsPage() {
const activeCheckpoint =
checkpoint && !isExternalModelId(checkpoint) ? checkpoint : null;
const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
+ const activeGgufContextLength = useChatRuntimeStore(
+ (s) => s.ggufContextLength,
+ );
+ // Live settings of the loaded model, so its page shows what it is running with.
+ const { config: activeModelConfig } = useActiveModelConfig();
// Shared with the chat model selector: list only models sized for this device.
const fitOnDeviceOnly = useChatRuntimeStore((s) => s.fitOnDeviceOnly);
const setFitOnDeviceOnly = useChatRuntimeStore((s) => s.setFitOnDeviceOnly);
- useEffect(() => {
- let cancelled = false;
- void getInferenceStatus()
- .then((status) => {
- if (cancelled || !status.active_model) return;
+ // Drops a response that lands after a newer read started, or after unmount.
+ const residentStatusSeq = useRef(0);
+ // The newest read started, so a dropped response can resolve with that instead of with
+ // nothing. A caller awaits a settled store, and the settings handlers' own guard counts
+ // settings opens only: a focus or visibilitychange refresh supersedes one without bumping it.
+ const residentStatusSupersession = useRef<RefreshSupersession>({
+ latest: null,
+ });
+ // /status cannot say whether an empty answer is an idle eviction that will reload or a real
+ // unload, and only this endpoint knows. Read alongside every status read rather than cached,
+ // since the idle timeout is editable from Settings while this page stays mounted, and awaited
+ // with it, since the first read is the one most likely to land on an evicted model.
+ // Last answer wins on failure, not the default: "disarmed" is the side that clears the
+ // checkpoint, so a transient failure would discard a selection the idle loop is bringing
+ // back. Before any successful read it is false, the setting's own default.
+ const idleUnloadArmed = useRef(false);
+ const readIdleUnloadArmed = useCallback(
+ (): Promise<boolean> =>
+ loadOpenAIAutoSwitchSettings()
+ .then((settings) => {
+ idleUnloadArmed.current = settings.idleUnloadActive;
+ return idleUnloadArmed.current;
+ })
+ .catch(() => idleUnloadArmed.current),
+ [],
+ );
+ // Returns the read so a caller that needs the answer first can wait for it.
+ const refreshResidentModelStatus = useCallback((): Promise<void> => {
+ const seq = ++residentStatusSeq.current;
+ const read = Promise.all([getInferenceStatus(), readIdleUnloadArmed()])
+ .then(([status, idleUnloadArmed]) => {
+ // A newer read owns the store, so this writes nothing; resolving with the refresh
+ // that took it over keeps an awaiting caller from reading the store it has not
+ // written yet, which is the pre-switch store the await was there to replace.
+ if (seq !== residentStatusSeq.current)
+ return supersedingRefresh(residentStatusSupersession.current, seq);
const store = useChatRuntimeStore.getState();
- if (
- !isExternalModelId(store.params.checkpoint) &&
- (!modelIdsMatch(store.params.checkpoint, status.active_model) ||
- !ggufVariantsMatch(
- store.activeGgufVariant,
- status.gguf_variant ?? null,
- ))
- ) {
- store.setCheckpoint(status.active_model, status.gguf_variant ?? null);
- }
+ adoptResidentModelStatus(
+ {
+ // The loadable identifier, as every other status reader records it: a GGUF off
+ // disk loads by path, and two files sharing a stem collapse onto one public id.
+ checkpointId: resolveInferenceCheckpointId(status),
+ ggufVariant: status.gguf_variant ?? null,
+ },
+ {
+ checkpoint: store.params.checkpoint,
+ checkpointIsExternal: isExternalModelId(store.params.checkpoint),
+ activeGgufVariant: store.activeGgufVariant,
+ modelLoading: store.modelLoading,
+ idleUnloadArmed,
+ },
+ {
+ setCheckpoint: (checkpointId, ggufVariant) => {
+ store.setCheckpoint(checkpointId, ggufVariant);
+ },
+ clearCheckpoint: () => {
+ store.clearCheckpoint();
+ },
+ // Landing here is the one entry point that has applied no status yet, so the
+ // settings page would read the live config off a store holding defaults.
+ applyStatus: (previous) => {
+ applyActiveModelStatusToStore(status, {
+ previousCheckpoint: previous.checkpoint ?? undefined,
+ previousGgufVariant: previous.ggufVariant,
+ });
+ },
+ },
+ );
})
.catch(() => undefined);
+ // In start order, synchronously with the sequence number, so a dropped response always
+ // finds the read that took the store over rather than one older than itself.
+ registerRefresh(residentStatusSupersession.current, seq, read);
+ return read;
+ }, [readIdleUnloadArmed]);
+
+ // Mount, then again whenever this tab could have missed an API-driven switch. Re-reading is
+ // safe: adoptResidentModelStatus stands down for an external selection and this tab's loads.
+ useEffect(() => {
+ void refreshResidentModelStatus();
+ const unsubscribe = subscribeResidentStatusRefresh(
+ refreshResidentModelStatus,
+ );
return () => {
- cancelled = true;
+ // A response still in flight adopts nothing once the Hub is gone.
+ residentStatusSeq.current += 1;
+ unsubscribe();
};
- }, []);
+ }, [refreshResidentModelStatus]);
const { tab, setTab: setModelsTab } = useModelsTabState();
const [query, setQuery] = useState("");
@@ -660,11 +769,7 @@ export function ModelsPage() {
const visibleResults =
results.length === 0 &&
liveListChannel &&
- isChannelEntryFresh(
- cachedListEntry,
- liveListChannel.id,
- tokenFingerprint,
- )
+ isChannelEntryFresh(cachedListEntry, liveListChannel.id, tokenFingerprint)
? (cachedListEntry?.results ?? results)
: results;
@@ -1187,7 +1292,17 @@ export function ModelsPage() {
(opts: ModelLoadOptions, isDownloaded: boolean) => {
if (!selectedModel) return;
const runId = selectedModel.resource.runId;
- const resolvedConfig = resolveInitialConfig(runId, opts.ggufVariant);
+ const configIdentity = modelConfigIdentity(
+ selectedModel.kind,
+ selectedModel.resource,
+ );
+ // A cached repo used to be keyed by the snapshot path it loads from, which is its
+ // runId. Move that record over before reading, or an upgrade reads as unremembered.
+ adoptLegacyConfigKey(configIdentity, runId, opts.ggufVariant);
+ const resolvedConfig = resolveInitialConfig(
+ configIdentity,
+ opts.ggufVariant,
+ );
const rememberedConfig = resolvedConfig.remembered
? resolvedConfig.config
: null;
@@ -1221,6 +1336,151 @@ export function ModelsPage() {
runSelectedModel(opts, selectedModel?.isDownloaded ?? true),
[runSelectedModel, selectedModel],
);
+
+ // Full-page per-model settings, opened from a downloaded row's menu. Local state, not a
+ // URL param: a deep link would need the row re-resolved against an unloaded inventory.
+ const [settingsTarget, setSettingsTarget] = useState<ModelPickTarget | null>(
+ null,
+ );
+ // Opening settings is where a stale read costs something: the editor is seeded once and Apply
+ // reloads with what it seeded, so this covers a switch that landed while the window kept
+ // focus. Resolving a target is openModelSettings' own read; this is for ready-made targets.
+ useEffect(() => {
+ if (settingsTarget) void refreshResidentModelStatus();
+ }, [settingsTarget, refreshResidentModelStatus]);
+ // Bumped per open so a slow lookup for an abandoned row cannot land on the chosen one.
+ const settingsOpenSeq = useRef(0);
+ const openModelSettings = useCallback(
+ async (row: CachedInventoryRow | LocalInventoryRow) => {
+ const openSeq = ++settingsOpenSeq.current;
+ // Before anything reads the store: the status effect watches settingsTarget, so it
+ // cannot run until the target exists. Every path out of here seeds the editor from the
+ // store and Apply reloads with that, so a pre-switch read would launch wrong settings.
+ await refreshResidentModelStatus();
+ if (settingsOpenSeq.current !== openSeq) return;
+ // loadId is what the loader accepts; repoId is only a display/API alias.
+ const id = row.loadId;
+ // Every name this row answers to.
+ const rowAliases =
+ row.kind === "local"
+ ? [id, row.repoId, row.path]
+ : [id, row.repoId, row.cachePath];
+ // Cached repo rows never carry a quant, and a null variant keys the config to `repo::`
+ // while the loader reads `repo::Q4_K_M`, so resolve one as the on-device card does.
+ let ggufVariant = settingsGgufVariantForRow(row);
+ if (!ggufVariant && row.isGguf && row.capabilities.requiresVariant) {
+ // A local row only carries a repo id inside the HF cache, so a plain folder of quants
+ // has none while still needing one. The listing scans a path in the same position, as
+ // the on-device card does; without it this menu entry only reaches the error toast.
+ const repoId =
+ row.kind === "cache" ? row.repoId : (row.repoId ?? row.path ?? null);
+ if (repoId) {
+ try {
+ const res = await listGgufVariants(repoId, hfApiToken(hfToken), {
+ preferLocalCache: true,
+ localPath:
+ row.kind === "local" ? row.path : (row.cachePath ?? null),
+ });
+ const downloaded = res.variants.filter((v) => v.downloaded);
+ // Re-read after this await too: the lookup hits the network, and a switch during
+ // it would leave the branch below on the displaced model's quant. Against the
+ // server, not the store: nothing pushes an API switch into this tab, so the store
+ // is as old as the read above.
+ await refreshResidentModelStatus();
+ if (settingsOpenSeq.current !== openSeq) return;
+ const settled = useChatRuntimeStore.getState();
+ const settledCheckpoint =
+ settled.params.checkpoint &&
+ !isExternalModelId(settled.params.checkpoint)
+ ? settled.params.checkpoint
+ : null;
+ const settledIsActive = rowAliases.some((alias) =>
+ modelIdsMatch(alias, settledCheckpoint),
+ );
+ ggufVariant =
+ // Loaded quant, then repo default, then whatever is on disk, mirroring
+ // LocalOnDeviceCard. Loaded row only: Q4_K_M exists in most repos.
+ (settledIsActive
+ ? downloaded.find((v) =>
+ ggufVariantsMatch(v.quant, settled.activeGgufVariant),
+ )?.quant
+ : undefined) ??
+ downloaded.find((v) =>
+ ggufVariantsMatch(v.quant, res.default_variant),
+ )?.quant ??
+ downloaded[0]?.quant ??
+ null;
+ } catch {
+ ggufVariant = null;
+ }
+ }
+ if (!ggufVariant) {
+ // A model needing a quant cannot be configured without one: the picker matches
+ // variants exactly and would never find the config, while the API would.
+ toast.error("Couldn't determine which quant to configure.", {
+ description:
+ "Settings for this model are per quant. Check the connection or the model's cache, then try again.",
+ });
+ return;
+ }
+ }
+ // The lookup is async: without this, whichever call finished last would win.
+ if (settingsOpenSeq.current !== openSeq) {
+ return;
+ }
+ // A repo in a previous cache loads by snapshot path, so `id` ends in the revision
+ // hash; name the row by what the user calls it instead.
+ const configId = row.kind === "cache" ? row.repoId : id;
+ const leaf = configId.split(/[\\/]/).filter(Boolean).pop() ?? configId;
+ setSettingsTarget({
+ id,
+ configId,
+ displayName: ggufVariant ? `${leaf} · ${ggufVariant}` : leaf,
+ ggufVariant,
+ isGguf: row.isGguf,
+ apiLoadable:
+ row.isGguf &&
+ (row.kind !== "local" || row.source !== LOCAL_MODEL_SOURCE.OLLAMA),
+ meta: {
+ source: "local",
+ isLora: row.modelFormat === "adapter",
+ ggufVariant: ggufVariant ?? undefined,
+ isGguf: row.isGguf,
+ // A partial opens settings too; claiming complete would skip download progress.
+ isDownloaded: !row.partial,
+ // Not on inventory rows; ModelConfigPage reads the GGUF header itself.
+ contextLength: null,
+ },
+ });
+ },
+ [activeCheckpoint, activeGgufVariant, hfToken, refreshResidentModelStatus],
+ );
+ // Applying loads the model with exactly these settings, which ModelConfigPage has already
+ // persisted locally and, with "remember" on, to the server, so an API load matches.
+ const runSettingsTarget = useCallback(
+ (config: PerModelConfig) => {
+ const target = settingsTarget;
+ if (!target) return;
+ const previousConfig = currentRuntimePerModelConfig({
+ includeMaxSeqLength: true,
+ });
+ applyPerModelConfigToRuntime(config);
+ setSettingsTarget(null);
+ void selectModel({
+ id: target.id,
+ source: "local",
+ ggufVariant: target.ggufVariant ?? undefined,
+ isGguf: target.isGguf,
+ // A partial row opens settings too; claiming complete would skip download progress.
+ isDownloaded: target.meta.isDownloaded,
+ isLora: target.meta.isLora,
+ keepSpeculative: true,
+ forceReload: true,
+ previousConfig,
+ }).catch(() => undefined);
+ },
+ [selectModel, settingsTarget],
+ );
const handleLoadLocal = useCallback(
(opts: ModelLoadOptions = {}) => runSelectedModel(opts, true),
[runSelectedModel],
@@ -1228,6 +1488,95 @@ export function ModelsPage() {
const handleTrain = useCallback(() => {
// Hub → train integration ships in a later PR.
}, []);
+ // Opened from the on-device card, which passes in the quant it already resolved.
+ const openSelectedModelSettings = useCallback(
+ async (ggufVariant: string | null, quantIsUserPicked = false) => {
+ if (!selectedModel) return;
+ // Shared with openModelSettings: another row's pending lookup must not land here.
+ const openSeq = ++settingsOpenSeq.current;
+ // Unconditional, as in openModelSettings: the editor is seeded from the store and
+ // Apply reloads with what it seeded.
+ await refreshResidentModelStatus();
+ if (settingsOpenSeq.current !== openSeq) return;
+ let variant = ggufVariant;
+ // The card derived this quant from the store's active variant, now settled by the
+ // read above. A user-picked quant stands; a derived one defers to what is loaded.
+ if (!quantIsUserPicked) {
+ const settled = useChatRuntimeStore.getState();
+ const settledCheckpoint =
+ settled.params.checkpoint &&
+ !isExternalModelId(settled.params.checkpoint)
+ ? settled.params.checkpoint
+ : null;
+ // Every name this model answers to, as the row menu path matches them.
+ const aliases = [
+ selectedModel.resource.runId,
+ selectedModel.resource.repoId,
+ selectedModel.resource.localPath,
+ ];
+ if (
+ settled.activeGgufVariant &&
+ aliases.some((alias) => modelIdsMatch(alias, settledCheckpoint))
+ ) {
+ variant = settled.activeGgufVariant;
+ }
+ }
+ // The card passes null while its lookup is pending or after it failed, so this needs
+ // the same guard openModelSettings applies.
+ if (!variant && selectedModel.isGguf && selectedModel.requiresVariant) {
+ toast.error("Couldn't determine which quant to configure.", {
+ description:
+ "Settings for this model are per quant. Check the connection or the model's cache, then try again.",
+ });
+ return;
+ }
+ const id = selectedModel.resource.runId;
+ const configId = modelConfigIdentity(
+ selectedModel.kind,
+ selectedModel.resource,
+ );
+ // As in runSelectedModel: the editor seeds from this key, so the move has to happen
+ // before it reads or the page opens on defaults and Apply writes them back.
+ adoptLegacyConfigKey(configId, id, variant);
+ const leaf = configId.split(/[\\/]/).filter(Boolean).pop() ?? configId;
+ setSettingsTarget({
+ id,
+ configId,
+ displayName: variant ? `${leaf} · ${variant}` : leaf,
+ ggufVariant: variant,
+ isGguf: selectedModel.isGguf,
+ apiLoadable:
+ selectedModel.isGguf &&
+ selectedModel.localSource !== LOCAL_MODEL_SOURCE.OLLAMA,
+ meta: {
+ source: "local",
+ isLora: selectedModel.modelFormat === "adapter",
+ ggufVariant: variant ?? undefined,
+ isGguf: selectedModel.isGguf,
+ isDownloaded: selectedModel.isDownloaded,
+ contextLength: null,
+ },
+ });
+ },
+ [selectedModel, refreshResidentModelStatus],
+ );
+ // Whether the settings page is open on the loaded model, so it can show the live launch
+ // config. A GGUF off disk loads by path but is reported by its public id, so the row's path
+ // and its settings identity are both offered as aliases. A loose .gguf carries no variant while
+ // the loader derives one from its filename, so the two can never be required to agree.
+ const settingsTargetIsStandaloneFile =
+ settingsTarget !== null &&
+ settingsTarget.ggufVariant == null &&
+ settingsTarget.id.toLowerCase().endsWith(".gguf");
+ const settingsTargetIsResident =
+ settingsTarget !== null &&
+ residentModelIdMatches(
+ activeCheckpoint,
+ settingsTarget.id,
+ settingsTarget.configId,
+ ) &&
+ (settingsTargetIsStandaloneFile ||
+ ggufVariantsMatch(activeGgufVariant, settingsTarget.ggufVariant));
const handleSearchHub = useCallback(
(next: string) => {
const trimmed = next.trim();
@@ -1290,6 +1639,7 @@ export function ModelsPage() {
onTrain: handleTrain,
onInventoryChange: refreshInventory,
onSearchHub: handleSearchHub,
+ onOpenSettings: openSelectedModelSettings,
}),
[
handleLoad,
@@ -1299,48 +1649,17 @@ export function ModelsPage() {
handleTrain,
handleSearchHub,
refreshInventory,
+ openSelectedModelSettings,
],
);
- const catalogState = useMemo<ModelsCatalogState>(
- () => {
- const typeFilterActive =
- !isDatasetMode && inventoryTypeFilter !== "all";
- return {
- tab,
- discoverRows: listRows,
- cachedRows: filteredCachedRows,
- localRows: filteredLocalRows,
- selectedId,
- isLoading,
- downloadedReady,
- inventoryError,
- inventoryWarning,
- query,
- activeCheckpoint,
- activeGgufVariant,
- searchError,
- online,
- isDataset: isDatasetMode,
- inventoryTokens,
- scannedCount,
- loadingIntentCount: discoverFetchIntent,
- hasMore,
- manualFetchAvailable: discoverManualFetchAvailable,
- hasActiveFilters:
- !isFeedMode &&
- (deferredFormatFilter !== "all" ||
- deferredCapabilityFilter !== "all" ||
- (tab === "downloaded" && typeFilterActive)),
- typeFilterActive,
- };
- },
- [
+ const catalogState = useMemo<ModelsCatalogState>(() => {
+ const typeFilterActive = !isDatasetMode && inventoryTypeFilter !== "all";
+ return {
tab,
- isFeedMode,
- listRows,
- filteredCachedRows,
- filteredLocalRows,
+ discoverRows: listRows,
+ cachedRows: filteredCachedRows,
+ localRows: filteredLocalRows,
selectedId,
isLoading,
downloadedReady,
@@ -1351,17 +1670,45 @@ export function ModelsPage() {
activeGgufVariant,
searchError,
online,
- isDatasetMode,
+ isDataset: isDatasetMode,
inventoryTokens,
scannedCount,
- discoverFetchIntent,
+ loadingIntentCount: discoverFetchIntent,
hasMore,
- discoverManualFetchAvailable,
- deferredFormatFilter,
- deferredCapabilityFilter,
- inventoryTypeFilter,
- ],
- );
+ manualFetchAvailable: discoverManualFetchAvailable,
+ hasActiveFilters:
+ !isFeedMode &&
+ (deferredFormatFilter !== "all" ||
+ deferredCapabilityFilter !== "all" ||
+ (tab === "downloaded" && typeFilterActive)),
+ typeFilterActive,
+ };
+ }, [
+ tab,
+ isFeedMode,
+ listRows,
+ filteredCachedRows,
+ filteredLocalRows,
+ selectedId,
+ isLoading,
+ downloadedReady,
+ inventoryError,
+ inventoryWarning,
+ query,
+ activeCheckpoint,
+ activeGgufVariant,
+ searchError,
+ online,
+ isDatasetMode,
+ inventoryTokens,
+ scannedCount,
+ discoverFetchIntent,
+ hasMore,
+ discoverManualFetchAvailable,
+ deferredFormatFilter,
+ deferredCapabilityFilter,
+ inventoryTypeFilter,
+ ]);
const catalogPagination = useMemo<ModelsCatalogPagination>(
() => ({
@@ -1380,6 +1727,7 @@ export function ModelsPage() {
onRetry: handleRetrySearch,
onInventoryChange: refreshInventory,
onSwitchDevice: handleSwitchDevice,
+ onOpenModelSettings: openModelSettings,
}),
[
handleSelect,
@@ -1388,6 +1736,7 @@ export function ModelsPage() {
handleRetrySearch,
refreshInventory,
handleSwitchDevice,
+ openModelSettings,
],
);
@@ -1530,6 +1879,8 @@ export function ModelsPage() {
const detailOpen = urlModel !== null;
const splitMode = allModelsView === "split";
+ // Unreachable under an opaque overlay: the detail view (full-page only) or settings.
+ const catalogCovered = (detailOpen && !splitMode) || settingsTarget !== null;
return (
<div className="hub-page flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden bg-background">
@@ -1585,9 +1936,12 @@ export function ModelsPage() {
splitMode
? "flex-1 lg:w-[460px] lg:max-w-[44%] lg:flex-none lg:shrink-0 lg:border-r lg:border-border/60"
: "flex-1",
- detailOpen && !splitMode && "pointer-events-none",
+ // A full-bleed opaque overlay, so the catalog leaves the tab order; without
+ // this, tabbing out of the form walks into the rows behind it.
+ catalogCovered && "pointer-events-none",
)}
- aria-hidden={(detailOpen && !splitMode) || undefined}
+ aria-hidden={catalogCovered || undefined}
+ inert={catalogCovered || undefined}
>
<ModelsCatalog
state={catalogState}
@@ -1603,7 +1957,10 @@ export function ModelsPage() {
{splitMode ? (
detailOpen ? (
- <div className="hub-canvas z-20 flex min-h-0 flex-col max-lg:absolute max-lg:inset-0 lg:relative lg:min-w-0 lg:flex-1">
+ <div
+ className="hub-canvas z-20 flex min-h-0 flex-col max-lg:absolute max-lg:inset-0 lg:relative lg:min-w-0 lg:flex-1"
+ inert={settingsTarget !== null || undefined}
+ >
<HubDetailView
model={selectedModel}
preferredGgufFile={preferredGgufFile}
@@ -1625,7 +1982,10 @@ export function ModelsPage() {
)
) : (
detailOpen && (
- <div className="hub-canvas absolute inset-0 z-20 flex min-h-0 flex-col">
+ <div
+ className="hub-canvas absolute inset-0 z-20 flex min-h-0 flex-col"
+ inert={settingsTarget !== null || undefined}
+ >
<HubDetailView
model={selectedModel}
preferredGgufFile={preferredGgufFile}
@@ -1641,6 +2001,22 @@ export function ModelsPage() {
</div>
)
)}
+
+ {/* Above the detail overlay (z-30), so settings do not stack behind a preview. */}
+ {settingsTarget && (
+ <div className="hub-canvas absolute inset-0 z-30 flex min-h-0 flex-col">
+ <HubModelSettingsView
+ target={settingsTarget}
+ loadedConfig={settingsTargetIsResident ? activeModelConfig : null}
+ loadedContextLength={
+ settingsTargetIsResident ? activeGgufContextLength : null
+ }
+ onBack={() => setSettingsTarget(null)}
+ onRun={runSettingsTarget}
+ compact={splitMode}
+ />
+ </div>
+ )}
</div>
<OnDeviceFoldersDialog
diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.ts
index 7d9e5b74aa6..c2925f5790b 100644
--- a/studio/frontend/src/features/hub/index.ts
+++ b/studio/frontend/src/features/hub/index.ts
@@ -41,8 +41,11 @@ export { looksLikeLocalPath } from "./lib/local-path";
export { hubTokenHeader } from "./lib/hub-token-header";
export {
ggufVariantsMatch,
+ isOllamaLinkPath,
normalizeGgufVariantIdentity,
normalizeModelIdentity,
+ publicModelId,
+ residentModelIdMatches,
} from "./lib/model-identity";
export { formatBytes, formatRelativeShort } from "./lib/format";
export { ggufVariantDisplayLabel } from "./lib/gguf-variant-sort";
diff --git a/studio/frontend/src/features/hub/inventory/settings-identity.ts b/studio/frontend/src/features/hub/inventory/settings-identity.ts
new file mode 100644
index 00000000000..bf054f6cf58
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/settings-identity.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
+
+// How an inventory row maps onto the identity its saved settings are keyed by.
+
+import type { CachedInventoryRow, LocalInventoryRow } from "./types";
+
+/**
+ * The GGUF variant a settings page keys this row's config by, before any per-repo lookup. A
+ * standalone `.gguf` has no quant to choose between, but the inventory still labels it from its
+ * filename, and adopting that label would key its settings to `<path>:Q4_K_M` while every other
+ * surface uses the bare path, leaving two configs for one file.
+ */
+export function settingsGgufVariantForRow(
+ row: CachedInventoryRow | LocalInventoryRow,
+): string | null {
+ if (row.kind === "local" && row.path.toLowerCase().endsWith(".gguf")) {
+ return null;
+ }
+ return row.formatVariant?.trim() || null;
+}
diff --git a/studio/frontend/src/features/hub/lib/adopt-inference-status.ts b/studio/frontend/src/features/hub/lib/adopt-inference-status.ts
new file mode 100644
index 00000000000..9f053ce3dff
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/adopt-inference-status.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Adopting the resident model into the chat runtime store from the Hub. Landing straight on /hub
+// is the one entry point where nothing has applied /api/inference/status yet, and pinning only
+// the checkpoint leaves every other useActiveModelConfig field at its default, which the settings
+// page would pass on as the live config. So adoption applies the whole status, as chat does.
+
+import { ggufVariantsMatch, modelIdsMatch } from "./model-identity.ts";
+
+/** The parts of the chat runtime store adoption has to look at. */
+export interface ResidentAdoptionState {
+ checkpoint: string | null;
+ /** Whether that checkpoint names an external provider's model. */
+ checkpointIsExternal: boolean;
+ activeGgufVariant: string | null;
+ /** ``modelLoading``: a load this tab started still owns the store. */
+ modelLoading: boolean;
+ /** Whether the idle-unload loop will actually free the model. From
+ * ``/openai-auto-switch``; ``/status`` says nothing about it. */
+ idleUnloadArmed: boolean;
+}
+
+/** What ``/api/inference/status`` says is resident, already resolved. */
+export interface ResidentStatusFacts {
+ /** ``resolveInferenceCheckpointId(status)``; null when nothing is loaded. */
+ checkpointId: string | null;
+ ggufVariant: string | null;
+}
+
+export interface ResidentAdoptionActions {
+ /** Re-pin ``params.checkpoint`` onto the resident model. */
+ setCheckpoint: (checkpointId: string, ggufVariant: string | null) => void;
+ /** Drop a checkpoint the server has genuinely unloaded. Optional, so a caller
+ * that only wants the pinning half can leave it out. */
+ clearCheckpoint?: () => void;
+ /**
+ * Apply the rest of the status. Receives the store values from BEFORE ``setCheckpoint`` ran,
+ * which is how applyActiveModelStatusToStore tells a hydration from steady state.
+ */
+ applyStatus: (previous: {
+ checkpoint: string | null;
+ ggufVariant: string | null;
+ }) => void;
+}
+
+/**
+ * Adopt the resident model reported by ``/api/inference/status``. Returns whether anything was
+ * adopted. Never loads or unloads: it only mirrors what the server already has.
+ */
+export function adoptResidentModelStatus(
+ status: ResidentStatusFacts,
+ state: ResidentAdoptionState,
+ actions: ResidentAdoptionActions,
+): boolean {
+ const { checkpointId } = status;
+ // An external selection has no local mirror, so the resident GGUF's settings would
+ // describe a model the user is not talking to.
+ if (state.checkpointIsExternal) {
+ return false;
+ }
+ // A load this tab started applies its own status when it settles, and owns the params
+ // meanwhile. Adopting underneath it would fight both.
+ if (state.modelLoading) {
+ return false;
+ }
+ if (!checkpointId) {
+ // An empty status means one of two things and /status cannot say which. Armed, the idle
+ // loop frees the model but keeps a stash the next request reloads, so clearing would drop
+ // a selection that is coming back. Disarmed, nothing brings it back, and leaving the row
+ // resident seeds the settings editor from a launch config nothing is running.
+ if (state.idleUnloadArmed) {
+ return false;
+ }
+ if (state.checkpoint) {
+ actions.clearCheckpoint?.();
+ return true;
+ }
+ return false;
+ }
+ const previous = {
+ checkpoint: state.checkpoint,
+ ggufVariant: state.activeGgufVariant,
+ };
+ const alreadyPinned =
+ modelIdsMatch(previous.checkpoint, checkpointId) &&
+ ggufVariantsMatch(previous.ggufVariant, status.ggufVariant);
+ if (!alreadyPinned) {
+ actions.setCheckpoint(checkpointId, status.ggufVariant);
+ }
+ // Unconditional, even when the checkpoint matched: a persisted checkpoint rehydrates
+ // from localStorage without the fields saying how the model was launched.
+ actions.applyStatus(previous);
+ return true;
+}
diff --git a/studio/frontend/src/features/hub/lib/model-identity.ts b/studio/frontend/src/features/hub/lib/model-identity.ts
index 488502ae287..98724bbc57d 100644
--- a/studio/frontend/src/features/hub/lib/model-identity.ts
+++ b/studio/frontend/src/features/hub/lib/model-identity.ts
@@ -63,3 +63,135 @@ export function ggufVariantsMatch(
normalizeGgufVariantIdentity(left) === normalizeGgufVariantIdentity(right)
);
}
+
+// Mirrors core/inference/model_ids.py _looks_like_path.
+const PUBLIC_ID_PATH_PREFIX_RE = /^(?:[/\\]|\.{1,2}[\\/]|~)/;
+const GGUF_SUFFIX_RE = /\.gguf$/i;
+const BACKSLASHES_RE = /\\/g;
+const TRAILING_SLASHES_RE = /\/+$/;
+
+function looksLikeModelPath(identifier: string): boolean {
+ if (GGUF_SUFFIX_RE.test(identifier)) {
+ return true;
+ }
+ if (PUBLIC_ID_PATH_PREFIX_RE.test(identifier)) {
+ return true;
+ }
+ if (identifier.length >= 2 && identifier[1] === ":") {
+ return true;
+ }
+ return identifier.split("/").length - 1 >= 2 || identifier.includes("\\");
+}
+
+/** `.../models--org--name/snapshots/<sha>` -> `org/name`, else null. */
+function hfCacheRepoId(path: string): string | null {
+ const parts = path.replace(BACKSLASHES_RE, "/").split("/");
+ for (let index = 0; index < parts.length; index += 1) {
+ const part = parts[index];
+ if (part.startsWith("models--") && parts[index + 1] === "snapshots") {
+ return part.slice("models--".length).replaceAll("--", "/");
+ }
+ }
+ return 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``:
+ * an HF cache snapshot becomes its repo id, any other local GGUF its filename stem, and a repo
+ * id or clean name comes back unchanged.
+ */
+export function publicModelId(identifier: string): string {
+ const trimmed = identifier.trim();
+ if (!(trimmed && looksLikeModelPath(trimmed))) {
+ return trimmed;
+ }
+ const repoId = hfCacheRepoId(trimmed);
+ if (repoId) {
+ return repoId;
+ }
+ const slashPath = trimmed
+ .replace(BACKSLASHES_RE, "/")
+ .replace(TRAILING_SLASHES_RE, "");
+ const name = slashPath.slice(slashPath.lastIndexOf("/") + 1);
+ return name.replace(GGUF_SUFFIX_RE, "") || trimmed;
+}
+
+/**
+ * Whether the model the backend reports as loaded is one of *candidates*.
+ *
+ * A GGUF from an inactive HF cache loads by path, so a caller holding only the public id would
+ * read an exact comparison as "not loaded": candidates are compared literally first, then by
+ * public id. That second pass only accepts an identity naming one model, since an HF snapshot
+ * collapses onto its unique repo id while every other path collapses onto a stem two models can
+ * share, and accepting a stem would save one model's live config under another's key.
+ */
+export function residentModelIdMatches(
+ activeModelId: string | null | undefined,
+ ...candidates: (string | null | undefined)[]
+): boolean {
+ if (candidates.some((candidate) => modelIdsMatch(activeModelId, candidate))) {
+ return true;
+ }
+ const active = activeModelId?.trim();
+ // A path-shaped active id is the raw identifier, which the literal pass covered.
+ if (!active || looksLikeModelPath(active)) {
+ return false;
+ }
+ return candidates.some((candidate) => {
+ const trimmed = candidate?.trim();
+ if (!trimmed) {
+ return false;
+ }
+ const publicId = publicModelId(trimmed);
+ // Unambiguous only when the collapse produced a namespaced repo id.
+ return publicId.includes("/") && modelIdsMatch(active, publicId);
+ });
+}
+
+// Ollama's blobs reach the picker through a symlink dir that local_model_resolver.py
+// refuses to index, so the API can never load one and mirroring its settings would
+// advertise a load that cannot happen.
+const OLLAMA_LINK_SEGMENTS = new Set([".studio_links", "ollama_links"]);
+
+export function isOllamaLinkPath(modelId: string | null | undefined): boolean {
+ if (!modelId) {
+ return false;
+ }
+ return modelId
+ .replace(BACKSLASHES_RE, "/")
+ .split("/")
+ .some((segment) => OLLAMA_LINK_SEGMENTS.has(segment));
+}
+
+// A dropped or file-picked GGUF is the API's second unreachable identity: /status withholds the
+// host path for a lease-backed load, so the browser keys settings by the bare file name echoed
+// back, which _build_index (path and stem only) never uses as an index key. Anything the API can
+// load is keyed by a path or a repo id, both of which carry a separator.
+const NATIVE_FILE_LABEL_RE = /^[^/\\]+\.gguf$/i;
+
+export function isNativeFileLabel(modelId: string | null | undefined): boolean {
+ return modelId != null && NATIVE_FILE_LABEL_RE.test(modelId);
+}
+
+// A scanned standalone .gguf, keyed by its on-disk path with no variant: it has no quant to
+// choose between, and adopting the filename label would key one file's config two ways
+// (settings-identity.ts applies the same rule to a Hub row). The suffix alone does not say that:
+// repo ids ending in .gguf are real on the Hub, an iMat repo among them, and those hold every
+// quant, so reading one as a single file would collapse Q4 and Q8 onto the same key. The id has
+// to name something on this machine too, which a repo id never does.
+export function isStandaloneGgufPath(
+ modelId: string | null | undefined,
+): boolean {
+ if (modelId == null || !GGUF_SUFFIX_RE.test(modelId)) {
+ return false;
+ }
+ return (
+ PUBLIC_ID_PATH_PREFIX_RE.test(modelId) ||
+ // A drive letter, or more separators than the single one a repo id carries.
+ (modelId.length >= 2 && modelId[1] === ":") ||
+ modelId.includes("\\") ||
+ modelId.split("/").length - 1 >= 2 ||
+ isNativeFileLabel(modelId)
+ );
+}
diff --git a/studio/frontend/src/features/hub/lib/resident-status-refresh.ts b/studio/frontend/src/features/hub/lib/resident-status-refresh.ts
new file mode 100644
index 00000000000..2fb0fe14466
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/resident-status-refresh.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// When the Hub has to re-read /api/inference/status. An API request can auto-switch the resident
+// model at any moment and nothing else on /hub reads status, so a mount-only read leaves every
+// "loaded" marker (and the settings page's live config) pinned to whatever was resident when the
+// Hub opened. A background timer would keep asking a server that usually has not changed, so
+// re-read only on the moments this tab could have missed a switch.
+
+/** The event targets to listen on; injected so this is testable off a browser. */
+export interface ResidentStatusRefreshTargets {
+ window: Pick<EventTarget, "addEventListener" | "removeEventListener">;
+ document: Pick<EventTarget, "addEventListener" | "removeEventListener"> & {
+ readonly hidden: boolean;
+ };
+}
+
+function browserTargets(): ResidentStatusRefreshTargets {
+ return { window, document };
+}
+
+/**
+ * Call ``refresh`` whenever this tab returns to the foreground: coming back from the
+ * client that made the API call is when the resident model may have moved.
+ */
+export function subscribeResidentStatusRefresh(
+ refresh: () => void,
+ targets: ResidentStatusRefreshTargets = browserTargets(),
+): () => void {
+ const onFocus = () => refresh();
+ // Focus alone misses a backgrounded tab, visibility alone a window that never hid;
+ // a redundant pair of reads is cheaper than a missed switch.
+ const onVisibility = () => {
+ if (!targets.document.hidden) refresh();
+ };
+ targets.window.addEventListener("focus", onFocus);
+ targets.document.addEventListener("visibilitychange", onVisibility);
+ return () => {
+ targets.window.removeEventListener("focus", onFocus);
+ targets.document.removeEventListener("visibilitychange", onVisibility);
+ };
+}
diff --git a/studio/frontend/src/features/hub/lib/superseded-refresh.ts b/studio/frontend/src/features/hub/lib/superseded-refresh.ts
new file mode 100644
index 00000000000..2c68333939e
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/superseded-refresh.ts
@@ -0,0 +1,45 @@
+// 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 caller that awaits a status refresh is waiting for the store to be settled, not for one
+// particular HTTP response. Refreshes are sequenced so the newest read owns the store, and a
+// response that lands after a newer read started writes nothing. Resolving that dropped
+// response's promise anyway releases its caller onto the store the newer read has not written
+// yet, which is exactly the pre-read store the await was there to replace: the Hub's settings
+// handlers would then resolve a quant from the model an API switch already displaced and bake
+// it into the settings target, and Apply reloads and persists under whatever the target names.
+// A settings open is guarded against a newer settings open, but nothing bumps that guard for a
+// focus or visibilitychange refresh, so those are the reads that can supersede one unnoticed.
+//
+// So a dropped response resolves with the refresh that superseded it instead of with nothing.
+
+/** The newest refresh started, so a superseded one can hand its caller that promise. */
+export interface RefreshSupersession {
+ latest: { seq: number; settled: Promise<void> } | null;
+}
+
+/**
+ * Record `settled` as what callers of refresh `seq` are holding. Call it in start order,
+ * synchronously with the sequence number, so `latest` always names the newest read.
+ */
+export function registerRefresh(
+ supersession: RefreshSupersession,
+ seq: number,
+ settled: Promise<void>,
+): void {
+ supersession.latest = { seq, settled };
+}
+
+/**
+ * What the dropped response of refresh `seq` should resolve with: the refresh that superseded
+ * it, so its caller still comes back to a settled store. `undefined` once nothing newer is
+ * registered, which is how a sequence bump that starts no read (unmount) ends the chain rather
+ * than handing a promise back to itself, where it would wait forever.
+ */
+export function supersedingRefresh(
+ supersession: RefreshSupersession,
+ seq: number,
+): Promise<void> | undefined {
+ const { latest } = supersession;
+ return latest && latest.seq > seq ? latest.settled : undefined;
+}
diff --git a/studio/frontend/src/features/model-picker/api/migrate-model-overrides.ts b/studio/frontend/src/features/model-picker/api/migrate-model-overrides.ts
new file mode 100644
index 00000000000..270a266d393
--- /dev/null
+++ b/studio/frontend/src/features/model-picker/api/migrate-model-overrides.ts
@@ -0,0 +1,155 @@
+// 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-time backfill of per-model settings into the server override map. Settings used to live
+// only in this browser, so on upgrade an already-configured model still shows as remembered
+// while an API load uses app defaults.
+
+import {
+ isNativeFileLabel,
+ isOllamaLinkPath,
+ normalizeGgufVariantIdentity,
+ normalizeModelIdentity,
+ splitQuantSuffix,
+} from "../model-config/model-identity";
+import {
+ isDefaultConfig,
+ listPerModelConfigs,
+} from "../model-config/per-model-config";
+import type { ApiModelOverride } from "./model-overrides";
+import {
+ fetchModelOverrides,
+ modelOverrideKey,
+ putModelOverride,
+ toApiOverride,
+} from "./model-overrides";
+
+const DONE_FLAG = "unsloth_model_overrides_backfilled_v1";
+
+function alreadyRan(): boolean {
+ try {
+ return window.localStorage.getItem(DONE_FLAG) === "1";
+ } catch {
+ // Storage denied: treat as done rather than re-running on every mount.
+ return true;
+ }
+}
+
+function markRan(): void {
+ try {
+ window.localStorage.setItem(DONE_FLAG, "1");
+ } catch {
+ // Nothing to do; the backfill is idempotent anyway.
+ }
+}
+
+/**
+ * A server key under the same identity this browser stores. `app_settings` has no schema
+ * version, so an old install holds keys the backend resolves to this model while an exact lookup
+ * calls them missing and overwrites them. The split folds repo ids and leaves POSIX paths alone.
+ */
+function normalizedOverrideKey(key: string): string {
+ const split = splitQuantSuffix(key);
+ if (!split) {
+ return modelOverrideKey(normalizeModelIdentity(key));
+ }
+ return modelOverrideKey(
+ normalizeModelIdentity(split[0]),
+ normalizeGgufVariantIdentity(split[1]),
+ );
+}
+
+/**
+ * The fields *config* would contribute that the stored entry does not hold. A malformed entry
+ * (nothing constrains what an older install wrote) counts as holding nothing.
+ */
+function absentFields(
+ stored: ApiModelOverride,
+ config: Parameters<typeof toApiOverride>[0],
+): string[] {
+ const fields = Object.keys(toApiOverride(config));
+ if (typeof stored !== "object" || stored === null) {
+ return fields;
+ }
+ return fields.filter((field) => !(field in stored));
+}
+
+/**
+ * Push local settings the server does not hold. Never deletes and never overwrites: a value
+ * already there is the newer authority. Field by field, not entry by entry, since a legacy entry
+ * holds only llama_extra_args and max_seq_length, so treating the key as done would skip exactly
+ * the settings this migration exists to carry.
+ */
+export async function backfillModelOverrides(): Promise<void> {
+ if (alreadyRan()) {
+ return;
+ }
+ const local = listPerModelConfigs().filter(
+ // A quant means GGUF, the only thing auto-switch resolves. A standalone .gguf is
+ // stored with a null variant, so it needs the extra test or stays browser-only. An
+ // Ollama blob sits behind a link dir the resolver skips, and a bare file name is a
+ // dropped file's label, which the resolver never keys.
+ (entry) =>
+ (entry.ggufVariant != null ||
+ entry.modelId.toLowerCase().endsWith(".gguf")) &&
+ !isOllamaLinkPath(entry.modelId) &&
+ !isNativeFileLabel(entry.modelId) &&
+ !isDefaultConfig(entry.config),
+ );
+ if (local.length === 0) {
+ markRan();
+ return;
+ }
+
+ let existing: Awaited<ReturnType<typeof fetchModelOverrides>>;
+ try {
+ existing = await fetchModelOverrides();
+ } catch {
+ // Offline or not authenticated yet: leave the flag unset so the next start retries.
+ return;
+ }
+
+ const known = new Map<string, ApiModelOverride>();
+ for (const [storedKey, storedEntry] of Object.entries(existing)) {
+ known.set(normalizedOverrideKey(storedKey), storedEntry);
+ }
+
+ let failed = false;
+ for (const entry of local) {
+ // Folded here too: the older `id::variant` keys hold the casing that was typed.
+ const key = normalizedOverrideKey(
+ modelOverrideKey(entry.modelId, entry.ggufVariant),
+ );
+ // Re-read rather than trusting the pre-fetch snapshot: this write commits last, so a
+ // save or forget during the round trip would be undone by it.
+ const current = listPerModelConfigs().find(
+ (candidate) =>
+ normalizedOverrideKey(
+ modelOverrideKey(candidate.modelId, candidate.ggufVariant),
+ ) === key,
+ );
+ if (!current || isDefaultConfig(current.config)) {
+ continue;
+ }
+ const stored = known.get(key);
+ // Nothing this browser could add, so skip the round trip entirely.
+ if (stored && absentFields(stored, current.config).length === 0) {
+ continue;
+ }
+ try {
+ // Fills the gaps only. `known` predates this loop, so another tab's save is
+ // invisible here; the server reads and writes together instead.
+ await putModelOverride(
+ current.modelId,
+ current.ggufVariant,
+ current.config,
+ { fillAbsentFields: true },
+ );
+ } catch {
+ failed = true;
+ }
+ }
+ if (!failed) {
+ markRan();
+ }
+}
diff --git a/studio/frontend/src/features/model-picker/api/model-overrides.ts b/studio/frontend/src/features/model-picker/api/model-overrides.ts
new file mode 100644
index 00000000000..b8fae42cd46
--- /dev/null
+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts
@@ -0,0 +1,237 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Server-side mirror of the per-model config. ../model-config/per-model-config.ts lives in
+// browser localStorage, so an API auto-switch load (no browser in the loop) came up with none of
+// the user's settings. routes/inference.py reads this map and rebuilds the picker's LoadRequest.
+
+import { authFetch } from "@/features/auth";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+import {
+ normalizeGgufVariantIdentity,
+ normalizeModelIdentity,
+} from "../model-config/model-identity";
+import type { PerModelConfig } from "../model-config/per-model-config";
+
+const OVERRIDES_URL = "/api/settings/openai-auto-switch/overrides";
+
+/** One model's stored launch config, as the backend persists it. */
+export interface ApiModelOverride {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ llama_extra_args?: string[];
+ // biome-ignore lint/style/useNamingConvention: API schema
+ max_seq_length?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ custom_context_length?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ kv_cache_dtype?: string;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ speculative_type?: string;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ spec_draft_n_max?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ n_parallel?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ tensor_parallel?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ chat_template_override?: string;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ gpu_memory_mode?: "auto" | "manual";
+ // biome-ignore lint/style/useNamingConvention: API schema
+ gpu_layers?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ n_cpu_moe?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ gpu_ids?: number[];
+}
+
+export type ApiModelOverrides = Record<string, ApiModelOverride>;
+
+/**
+ * The key one model's config is stored under: the `repo:VARIANT` form an OpenAI
+ * request names a quant by, so two quants of one repo keep separate configs and the
+ * backend matches the requested name directly. Bare id when there is no variant.
+ */
+export function modelOverrideKey(
+ modelId: string,
+ ggufVariant?: string | null,
+): string {
+ return ggufVariant ? `${modelId}:${ggufVariant}` : modelId;
+}
+
+export async function fetchModelOverrides(): Promise<ApiModelOverrides> {
+ const res = await authFetch(OVERRIDES_URL);
+ if (!res.ok) {
+ throw new Error(
+ await readFastApiError(res, "Failed to load saved model settings"),
+ );
+ }
+ const body = (await res.json()) as { overrides?: ApiModelOverrides };
+ return body.overrides ?? {};
+}
+
+/**
+ * Translate the UI's per-model config into the backend's schema. Only fields the user set are
+ * sent: an absent field reads as "app default", so nulls would pin defaults and stop the model
+ * following later global changes. A `null` config clears the entry. Exported so the backfill
+ * can compare it against the stored entry.
+ */
+export function toApiOverride(config: PerModelConfig | null): ApiModelOverride {
+ if (!config) {
+ return {};
+ }
+ const payload: ApiModelOverride = {};
+ if (config.maxSeqLength && config.maxSeqLength > 0) {
+ payload.max_seq_length = config.maxSeqLength;
+ }
+ if (config.customContextLength && config.customContextLength > 0) {
+ payload.custom_context_length = config.customContextLength;
+ }
+ if (config.kvCacheDtype) {
+ payload.kv_cache_dtype = config.kvCacheDtype;
+ }
+ if (config.speculativeType) {
+ payload.speculative_type = config.speculativeType;
+ }
+ if (config.specDraftNMax && config.specDraftNMax > 0) {
+ payload.spec_draft_n_max = config.specDraftNMax;
+ }
+ // Blank follows the server-wide --parallel default, which is the app default here.
+ if (config.nParallel && config.nParallel > 0) {
+ payload.n_parallel = config.nParallel;
+ }
+ if (config.tensorParallel) {
+ payload.tensor_parallel = true;
+ }
+ if (config.chatTemplateOverride?.trim()) {
+ payload.chat_template_override = config.chatTemplateOverride;
+ }
+ // Only "manual" is a real override; "auto" is the follow-the-global default.
+ if (config.gpuMemoryMode === "manual") {
+ payload.gpu_memory_mode = "manual";
+ }
+ // gpuLayers < 0 is Auto, which is also the default.
+ if (typeof config.gpuLayers === "number" && config.gpuLayers >= 0) {
+ payload.gpu_layers = config.gpuLayers;
+ }
+ if (typeof config.nCpuMoe === "number" && config.nCpuMoe > 0) {
+ payload.n_cpu_moe = config.nCpuMoe;
+ }
+ // Only a physical pin travels. The same integers are a Vulkan ordinal under Vulkan and a
+ // CUDA/ROCm index elsewhere, and the override carries no namespace, so after a backend change
+ // the server would pin a different device with ids its availability check accepts. An absent
+ // kind predates the field, which was physical-only. Dropping the pin leaves auto placement.
+ const gpuIndexKind = config.selectedGpuIndexKind ?? "physical";
+ if (
+ config.selectedGpuIds &&
+ config.selectedGpuIds.length > 0 &&
+ gpuIndexKind === "physical"
+ ) {
+ payload.gpu_ids = config.selectedGpuIds;
+ }
+ return payload;
+}
+
+// One in-flight write per model, so writes commit in issue order: otherwise the older
+// response can land last and resurrect the entry the newer one replaced. Models overlap.
+const writesByKey = new Map<string, Promise<void>>();
+
+export interface PutModelOverrideOptions {
+ /**
+ * Fill in only what is missing: every value already on the server stays as it is. The backfill
+ * reads the map once then writes each model in turn, so another tab's save would be overwritten
+ * by this browser's older copy. Field level, so a legacy entry gains the browser-only fields.
+ */
+ fillAbsentFields?: boolean;
+ /**
+ * Clear the fields this UI mirrors but leave the server's own launch flags alone. Evicting a
+ * local entry for the storage budget is not a forget, so it must not take `llama_extra_args`
+ * the page can neither show nor restore. The route drops the row once nothing is left in it.
+ */
+ keepLaunchFlags?: boolean;
+}
+
+export async function putModelOverride(
+ modelId: string,
+ ggufVariant: string | null | undefined,
+ config: PerModelConfig | null,
+ options?: PutModelOverrideOptions,
+): Promise<void> {
+ // Keyed by the folded identity: the backend resolves a legacy casing and the
+ // normalized one to one row, so raw strings would open two queues and race again.
+ const key = modelOverrideKey(
+ normalizeModelIdentity(modelId),
+ normalizeGgufVariantIdentity(ggufVariant),
+ );
+ // Chain on the settled tail: a failed write must not cancel the next one.
+ const previous = writesByKey.get(key) ?? Promise.resolve();
+ const write = previous
+ .catch(() => {})
+ .then(() => sendModelOverride(modelId, ggufVariant, config, options));
+ writesByKey.set(key, write);
+ try {
+ await write;
+ } finally {
+ // Only the last writer clears the slot, so a queue still building keeps order.
+ if (writesByKey.get(key) === write) {
+ writesByKey.delete(key);
+ }
+ }
+}
+
+async function sendModelOverride(
+ modelId: string,
+ ggufVariant: string | null | undefined,
+ config: PerModelConfig | null,
+ options?: PutModelOverrideOptions,
+): Promise<void> {
+ const res = await authFetch(OVERRIDES_URL, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ // biome-ignore lint/style/useNamingConvention: API schema
+ model_id: modelOverrideKey(modelId, ggufVariant),
+ // Only sent when set, so an older backend is not handed an unknown key every save.
+ ...(options?.fillAbsentFields
+ ? // biome-ignore lint/style/useNamingConvention: API schema
+ { fill_absent_fields: true }
+ : {}),
+ // Say which operation this is: an all-default save carries no fields, shape-identical
+ // to a forget, and guessing wrong wipes flags the UI cannot show or restore.
+ remove: config === null && !options?.keepLaunchFlags,
+ // Flags have no UI control, so the backend preserves them when omitted; a forget
+ // means all of it, so that path sends an explicit [].
+ ...(config === null && !options?.keepLaunchFlags
+ ? // biome-ignore lint/style/useNamingConvention: API schema
+ { llama_extra_args: [] }
+ : {}),
+ ...toApiOverride(config),
+ }),
+ });
+ if (!res.ok) {
+ throw new Error(
+ await readFastApiError(res, "Failed to save model settings for the API"),
+ );
+ }
+}
+
+/**
+ * Mirror a per-model config save to the backend without blocking the UI. Best-effort: the
+ * localStorage write already happened, so a failed sync must not fail the save. Logged, not
+ * toasted: an API load falls back to defaults until the next save.
+ */
+export function syncModelOverride(
+ modelId: string,
+ ggufVariant: string | null | undefined,
+ config: PerModelConfig | null,
+ options?: PutModelOverrideOptions,
+): void {
+ void putModelOverride(modelId, ggufVariant, config, options).catch(
+ (error: unknown) => {
+ console.warn(
+ "Failed to mirror model settings to the server; an API load of this model will use defaults.",
+ error,
+ );
+ },
+ );
+}
diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
index 268e7ab212e..abcebb56b44 100644
--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
@@ -40,6 +40,7 @@ import {
useRef,
useState,
} from "react";
+import { syncModelOverride } from "../api/model-overrides";
import {
useDefaultChatTemplate,
useModelMaxPositionEmbeddings,
@@ -62,6 +63,7 @@ import {
floorMaxSeqLength,
isDefaultConfig,
normalizeMaxSeqLength,
+ normalizePerModelConfig,
resolveInitialConfig,
savePerModelConfig,
} from "../model-config/per-model-config";
@@ -699,6 +701,11 @@ interface ModelConfigPageProps {
initialConfig?: PerModelConfig | null;
isDiffusion?: boolean;
variant?: "page" | "sidebar";
+ /**
+ * Page variant only: render the built-in "Run settings" title block. A host that
+ * already shows the model name as its page heading turns this off.
+ */
+ showHeader?: boolean;
}
export function ModelConfigPage({
@@ -710,6 +717,7 @@ export function ModelConfigPage({
initialConfig = null,
isDiffusion = false,
variant = "page",
+ showHeader = true,
}: ModelConfigPageProps) {
const rememberId = useId();
const isActiveModel = loadedConfig != null;
@@ -723,9 +731,12 @@ export function ModelConfigPage({
const loadedMaxContextLength = useChatRuntimeStore(
(s) => s.ggufMaxContextLength,
);
+ // What settings are stored under, which is not always what loads. Every read, write
+ // and mirror uses it; the probes keep target.id, since they have to open the model.
+ const configId = target.configId ?? target.id;
const gpuDevices = useGpuDevices();
const resolveInitial = () => {
- const resolved = resolveInitialConfig(target.id, target.ggufVariant);
+ const resolved = resolveInitialConfig(configId, target.ggufVariant);
if (loadedConfig) {
return { config: loadedConfig, remembered: resolved.remembered };
}
@@ -1017,16 +1028,47 @@ export function ModelConfigPage({
const effectiveAtBaseline = perModelConfigsEqual(effectiveConfig, baseline);
const effectivePersistenceOnly =
isActiveModel && effectiveAtBaseline && rememberChanged;
- const defaultConfig = isDefaultConfig(effectiveRuntimeConfig);
+ // Judge what storage keeps: savePerModelConfig normalizes first, so judging the raw
+ // object reported saved while the write dropped it.
+ const normalizedRuntimeConfig = normalizePerModelConfig(
+ effectiveRuntimeConfig,
+ );
+ const defaultConfig = isDefaultConfig(normalizedRuntimeConfig);
let saveFailed = false;
+ const evicted: { modelId: string; ggufVariant: string | null }[] = [];
if (remember) {
saveFailed = !savePerModelConfig(
- target.id,
+ configId,
target.ggufVariant,
- effectiveRuntimeConfig,
+ normalizedRuntimeConfig,
+ evicted,
);
} else {
- saveFailed = !deletePerModelConfig(target.id, target.ggufVariant);
+ saveFailed = !deletePerModelConfig(configId, target.ggufVariant);
+ }
+ // Mirror to the server so an API load gets these settings, not app defaults. Best-effort:
+ // the localStorage write above already governs this browser, and it is skipped when that
+ // write failed, or the two would permanently disagree. Gated on auto-switch reach, not just
+ // GGUF-ness, since the resolver skips Ollama, and a native-path lease is the same case: the
+ // id is only the file's display name, which the resolver never keys.
+ if (
+ !saveFailed &&
+ (target.apiLoadable ?? target.isGguf) &&
+ !nativePathToken
+ ) {
+ syncModelOverride(
+ configId,
+ target.ggufVariant,
+ remember ? normalizedRuntimeConfig : null,
+ );
+ }
+ // Saving can push the local map over budget and drop other models, whose server
+ // entries would keep applying with nothing able to forget them. Not a Forget: only
+ // the mirrored fields go, and launch flags set through the API stay.
+ for (const dropped of evicted) {
+ syncModelOverride(dropped.modelId, dropped.ggufVariant, null, {
+ keepLaunchFlags: true,
+ });
}
if (effectivePersistenceOnly) {
if (saveFailed) {
@@ -1056,7 +1098,7 @@ export function ModelConfigPage({
return (
<div className="flex flex-col">
- {variant === "page" && (
+ {variant === "page" && showHeader && (
<div className="flex items-center gap-2.5 pb-4">
{onBack && (
<button
diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsx
index 32b6df238ed..743901fa18f 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx
@@ -34,6 +34,7 @@ import {
useRef,
useState,
} from "react";
+import { isOllamaLinkPath } from "../model-config/model-identity";
import {
type PerModelConfig,
resolveInitialConfig,
@@ -480,11 +481,15 @@ function ModelSelectorContent({
const visibleConfigTarget = open ? configTarget : null;
const openConfigPage = (id: string, meta: ModelSelectorChangeMeta) => {
const leaf = id.includes("/") ? id.slice(id.lastIndexOf("/") + 1) : id;
+ const isGguf = meta.isGguf ?? Boolean(meta.ggufVariant);
setConfigTarget({
id,
displayName: meta.ggufVariant ? `${leaf} · ${meta.ggufVariant}` : leaf,
ggufVariant: meta.ggufVariant ?? null,
- isGguf: meta.isGguf ?? Boolean(meta.ggufVariant),
+ isGguf,
+ // Ollama's models sit under a link dir the resolver skips, so mirroring their
+ // settings would advertise a load the API can never make.
+ apiLoadable: isGguf && !isOllamaLinkPath(id),
meta,
});
};
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx b/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx
index ee149d802f0..c807d8957fc 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx
@@ -28,6 +28,7 @@ import {
MoreVerticalIcon,
PinIcon,
PinOffIcon,
+ Settings02Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { RefreshCw } from "lucide-react";
@@ -73,11 +74,17 @@ interface ModelRowMenuCachePath {
variant?: string;
}
+/** The model's settings page: load config plus what the API will apply. */
+interface ModelRowMenuSettings {
+ onOpen: () => void;
+}
+
export function ModelRowMenu({
ariaLabel,
buttonClassName,
iconClassName,
cachePath,
+ settings,
pin,
update,
del,
@@ -87,6 +94,7 @@ export function ModelRowMenu({
iconClassName?: string;
/** Enables "Reveal in Finder" for cached repos. */
cachePath?: ModelRowMenuCachePath;
+ settings?: ModelRowMenuSettings;
pin?: ModelRowMenuPin;
update?: ModelRowMenuUpdate;
del?: ModelRowMenuDelete;
@@ -167,7 +175,7 @@ export function ModelRowMenu({
});
}, [cachePathRepoId, cachePathVariant]);
- if (!pin && !update && !del && !cachePath) return null;
+ if (!pin && !update && !del && !cachePath && !settings) return null;
return (
<>
@@ -195,6 +203,21 @@ export function ModelRowMenu({
sideOffset={2}
className="unsloth-plus-menu menu-flat-destructive w-48"
>
+ {settings && (
+ <DropdownMenuItem
+ onSelect={(e) => {
+ e.stopPropagation();
+ settings.onOpen();
+ }}
+ >
+ <HugeiconsIcon
+ icon={Settings02Icon}
+ strokeWidth={1.75}
+ className="size-icon"
+ />
+ <span>Settings</span>
+ </DropdownMenuItem>
+ )}
{pin && (
<DropdownMenuItem
onSelect={(e) => {
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/types.ts b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
index 59639157a65..a621c5134ad 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/types.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
@@ -51,6 +51,17 @@ export interface ModelPickTarget {
displayName: string;
ggufVariant?: string | null;
isGguf: boolean;
+ /**
+ * Whether an OpenAI-compatible request can actually load this model. Not the same as isGguf:
+ * local_model_resolver skips Ollama's scanner. Defaults to isGguf when unknown.
+ */
+ apiLoadable?: boolean;
+ /**
+ * Identity the saved settings are keyed by, when that is not what loads: a repo cached
+ * outside the active HF cache loads by snapshot path while its settings key on the repo
+ * id. Probes that must open the model keep using `id`.
+ */
+ configId?: string;
meta: ModelSelectorChangeMeta;
}
diff --git a/studio/frontend/src/features/model-picker/components/sidebar-model-config.tsx b/studio/frontend/src/features/model-picker/components/sidebar-model-config.tsx
index e8aa4b8c317..e252b54d349 100644
--- a/studio/frontend/src/features/model-picker/components/sidebar-model-config.tsx
+++ b/studio/frontend/src/features/model-picker/components/sidebar-model-config.tsx
@@ -2,7 +2,11 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useMemo } from "react";
-import { gpuFieldsSignature } from "../model-config/apply-per-model-config";
+import { modelConfigInstanceKey } from "../model-config/config-signature";
+import {
+ isOllamaLinkPath,
+ isStandaloneGgufPath,
+} from "../model-config/model-identity";
import type { PerModelConfig } from "../model-config/per-model-config";
import { ModelConfigPage } from "./model-config-page";
import type { ModelPickTarget } from "./model-selector/types";
@@ -29,30 +33,6 @@ function leafName(id: string): string {
return separator >= 0 ? trimmed.slice(separator + 1) : trimmed;
}
-function hashString(value: string): number {
- let hash = 5381;
- for (let i = 0; i < value.length; i += 1) {
- hash = (Math.imul(hash, 33) ^ value.charCodeAt(i)) >>> 0;
- }
- return hash;
-}
-
-function configSignature(config: PerModelConfig): string {
- return [
- config.customContextLength ?? "",
- config.maxSeqLength ?? "",
- config.kvCacheDtype ?? "",
- config.speculativeType ?? "",
- config.specDraftNMax ?? "",
- config.nParallel ?? "",
- config.tensorParallel ? "1" : "0",
- config.chatTemplateOverride == null
- ? ""
- : `${config.chatTemplateOverride.length}:${hashString(config.chatTemplateOverride)}`,
- gpuFieldsSignature(config),
- ].join("|");
-}
-
export function SidebarModelConfig({
modelId,
ggufVariant,
@@ -63,27 +43,34 @@ export function SidebarModelConfig({
loadedConfig,
onReload,
}: SidebarModelConfigProps) {
+ // A standalone .gguf has no quant to choose between, but the loader labels it from its
+ // filename and /status echoes that back. Keying settings by it would write "<path>:Q4_K_M"
+ // while every other surface uses the bare path, so one file would carry two configs. Same
+ // rule as settingsGgufVariantForRow.
+ const settingsGgufVariant = isStandaloneGgufPath(modelId) ? null : ggufVariant;
const target = useMemo<ModelPickTarget>(() => {
const leaf = leafName(modelId);
return {
id: modelId,
displayName: ggufVariant ? `${leaf} · ${ggufVariant}` : leaf,
- ggufVariant,
+ ggufVariant: settingsGgufVariant,
isGguf,
+ // An Ollama blob sits behind a link dir the resolver skips, so do not mirror it.
+ apiLoadable: isGguf && !isOllamaLinkPath(modelId),
meta: {
source: "local",
isLora: false,
- ggufVariant: ggufVariant ?? undefined,
+ ggufVariant: settingsGgufVariant ?? undefined,
isGguf,
isDownloaded: true,
contextLength: nativeContextLength,
},
};
- }, [modelId, ggufVariant, isGguf, nativeContextLength]);
+ }, [modelId, ggufVariant, settingsGgufVariant, isGguf, nativeContextLength]);
return (
<ModelConfigPage
- key={`${modelId}::${ggufVariant ?? ""}::${configSignature(loadedConfig)}`}
+ key={modelConfigInstanceKey(modelId, settingsGgufVariant, loadedConfig)}
target={target}
onRun={onReload}
loadedConfig={loadedConfig}
diff --git a/studio/frontend/src/features/model-picker/index.ts b/studio/frontend/src/features/model-picker/index.ts
index 383d441f09d..54a4ec618b4 100644
--- a/studio/frontend/src/features/model-picker/index.ts
+++ b/studio/frontend/src/features/model-picker/index.ts
@@ -15,7 +15,17 @@ export {
type NumericValueInputHandle,
snapToStep,
} from "./components/numeric-value-input";
+export { ModelConfigPage } from "./components/model-config-page";
export { SidebarModelConfig } from "./components/sidebar-model-config";
+export type { ModelPickTarget } from "./components/model-selector/types";
+export {
+ fetchModelOverrides,
+ modelOverrideKey,
+ putModelOverride,
+ syncModelOverride,
+ type ApiModelOverride,
+ type ApiModelOverrides,
+} from "./api/model-overrides";
export {
useActiveModelConfig,
} from "./hooks/use-active-model-config";
@@ -26,6 +36,7 @@ export type {
ModelOption,
ModelSelectorChangeMeta,
} from "./components/model-selector";
+export { modelConfigInstanceKey } from "./model-config/config-signature";
export {
applyModelLoadConfigToRuntime,
applyPerModelConfigToRuntime,
@@ -36,5 +47,7 @@ export {
DEFAULT_MAX_SEQ_LENGTH,
normalizeMaxSeqLength,
type PerModelConfig,
+ adoptLegacyConfigKey,
resolveInitialConfig,
+ resolveResidentInitialConfig,
} from "./model-config/per-model-config";
diff --git a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
index 1cddfbe796c..78a427724de 100644
--- a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
@@ -10,12 +10,16 @@ import {
reconcilePersistedGpuSelection,
useChatRuntimeStore,
} from "@/features/chat";
+// Its own module so hosts needing only the signature skip the chat runtime store.
+import { gpuFieldsSignature } from "./config-signature";
import {
DEFAULT_PER_MODEL_CONFIG,
type PerModelConfig,
normalizeMaxSeqLength,
} from "./per-model-config";
+export { gpuFieldsSignature };
+
function cleanTemplate(value: string | null | undefined): string | null {
return value?.trim() ? value : null;
}
@@ -132,27 +136,6 @@ export function perModelConfigsEqual(
);
}
-// Serialize the per-model GPU knobs with the same "absent == default"
-// coalescing the store applies: mode auto/absent, gpuLayers Auto (< 0) /
-// absent, nCpuMoe 0 / absent, and null / absent GPU picks as automatic.
-export function gpuFieldsSignature(config: PerModelConfig): string {
- const gpuSelection =
- config.selectedGpuIds == null
- ? "automatic"
- : [
- [...config.selectedGpuIds].sort((a, b) => a - b).join(","),
- config.selectedGpuIndexKind === undefined
- ? "physical"
- : (config.selectedGpuIndexKind ?? "deferred"),
- ].join("@");
- return [
- config.gpuMemoryMode ?? "auto",
- config.gpuLayers == null || config.gpuLayers < 0 ? -1 : config.gpuLayers,
- config.nCpuMoe ?? 0,
- gpuSelection,
- ].join("|");
-}
-
function gpuFieldsEqual(a: PerModelConfig, b: PerModelConfig): boolean {
return gpuFieldsSignature(a) === gpuFieldsSignature(b);
}
diff --git a/studio/frontend/src/features/model-picker/model-config/config-signature.ts b/studio/frontend/src/features/model-picker/model-config/config-signature.ts
new file mode 100644
index 00000000000..c914ca37afb
--- /dev/null
+++ b/studio/frontend/src/features/model-picker/model-config/config-signature.ts
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Identity of one ModelConfigPage editor instance. The page seeds its state from `loadedConfig`
+// in a useState initializer, so it reads that prop once per mount: a host that opens it before
+// status hydrates gets null first and the live config a moment later, and without the config in
+// the React key the instance survives that flip and keeps showing saved values, which Apply
+// then writes back over the running model.
+
+import type { PerModelConfig } from "./per-model-config";
+
+// Serialize the GPU knobs with the store's "absent == default" coalescing: mode auto,
+// gpuLayers Auto (< 0), nCpuMoe 0, and null / absent GPU picks as automatic.
+export function gpuFieldsSignature(config: PerModelConfig): string {
+ const gpuSelection =
+ config.selectedGpuIds == null
+ ? "automatic"
+ : [
+ [...config.selectedGpuIds].sort((a, b) => a - b).join(","),
+ config.selectedGpuIndexKind === undefined
+ ? "physical"
+ : (config.selectedGpuIndexKind ?? "deferred"),
+ ].join("@");
+ return [
+ config.gpuMemoryMode ?? "auto",
+ config.gpuLayers == null || config.gpuLayers < 0 ? -1 : config.gpuLayers,
+ config.nCpuMoe ?? 0,
+ gpuSelection,
+ ].join("|");
+}
+
+function hashString(value: string): number {
+ let hash = 5381;
+ for (let i = 0; i < value.length; i += 1) {
+ hash = (Math.imul(hash, 33) ^ value.charCodeAt(i)) >>> 0;
+ }
+ return hash;
+}
+
+/**
+ * Signature of the live config an editor was seeded from. `null` (not resident, or status has
+ * not answered yet) is its own value: the arrival of the live config must remount.
+ */
+export function loadedConfigSignature(
+ config: PerModelConfig | null | undefined,
+): string {
+ if (!config) {
+ return "none";
+ }
+ return [
+ config.customContextLength ?? "",
+ config.maxSeqLength ?? "",
+ config.kvCacheDtype ?? "",
+ config.speculativeType ?? "",
+ config.specDraftNMax ?? "",
+ config.nParallel ?? "",
+ config.tensorParallel ? "1" : "0",
+ config.chatTemplateOverride == null
+ ? ""
+ : `${config.chatTemplateOverride.length}:${hashString(config.chatTemplateOverride)}`,
+ gpuFieldsSignature(config),
+ ].join("|");
+}
+
+/**
+ * React key for one ModelConfigPage instance, so every host agrees on when the editor
+ * re-seeds: a different model, a different quant, or a change in the live config.
+ */
+export function modelConfigInstanceKey(
+ modelId: string,
+ ggufVariant: string | null | undefined,
+ loadedConfig: PerModelConfig | null | undefined,
+): string {
+ return `${modelId}::${ggufVariant ?? ""}::${loadedConfigSignature(loadedConfig)}`;
+}
diff --git a/studio/frontend/src/features/model-picker/model-config/model-identity.ts b/studio/frontend/src/features/model-picker/model-config/model-identity.ts
index 0caa7c1312b..5d2e1948e5d 100644
--- a/studio/frontend/src/features/model-picker/model-config/model-identity.ts
+++ b/studio/frontend/src/features/model-picker/model-config/model-identity.ts
@@ -1,15 +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
+// Straight from the module, not the hub barrel: the barrel also re-exports the download
+// manager and its React components, which these pure string helpers do not need.
import {
normalizeGgufVariantIdentity,
normalizeModelIdentity,
-} from "@/features/hub";
+} from "@/features/hub/lib/model-identity";
export {
+ isNativeFileLabel,
+ isOllamaLinkPath,
+ isStandaloneGgufPath,
normalizeGgufVariantIdentity,
normalizeModelIdentity,
-} from "@/features/hub";
+ publicModelId,
+} from "@/features/hub/lib/model-identity";
const MODEL_STORAGE_KEY_PREFIX = "v2:";
@@ -67,3 +73,82 @@ export function ggufVariantFromStorageKey(key: string): string | null {
const separator = key.lastIndexOf("::");
return separator >= 0 ? key.slice(separator + 2) : null;
}
+
+// Mirrors split_quant_suffix in studio/backend/utils/openai_auto_switch_settings.py.
+// The bpw modifier ("IQ4_XS-3.53bpw") is optional: the backend label helpers disagree.
+const BPW_SUFFIX = /-[0-9]+(?:\.[0-9]+)?bpw$/i;
+// One source for the anchored test and the scan below. Mirrors _GGUF_QUANT_RE in gguf.py.
+const QUANT_TOKEN_SOURCE =
+ "(UD-)?(MXFP[0-9]+(?:_[A-Z0-9]+)*|IQ[0-9]+_[A-Z]+(?:_[A-Z0-9]+)?|TQ[0-9]+_[0-9]+|Q[0-9]+_K_[A-Z]+|Q[0-9]+_[0-9]+|Q[0-9]+_K|BF16|F16|F32)";
+const KNOWN_QUANT = new RegExp(`^${QUANT_TOKEN_SOURCE}$`, "i");
+const QUANT_TOKEN = new RegExp(QUANT_TOKEN_SOURCE, "gi");
+const MAX_QUANT_SUFFIX_LEN = 64;
+// Mirrors _GGUF_SPLIT_SUFFIX_RE in studio/backend/hub/utils/gguf.py.
+const GGUF_SPLIT_SUFFIX = /-[0-9]{3,}-of-[0-9]{3,}/gi;
+const BACKSLASHES = /\\/g;
+// A float precision labels a file only when nothing sharper does, as _select_quant_match.
+const FLOAT_PRECISION_QUANTS: ReadonlySet<string> = new Set([
+ "BF16",
+ "F16",
+ "F32",
+]);
+
+/** Mirrors _gguf_stem in studio/backend/hub/utils/gguf.py, for a bare filename. */
+function ggufStem(filename: string): string {
+ const dot = filename.lastIndexOf(".");
+ const withoutExtension = dot >= 0 ? filename.slice(0, dot) : filename;
+ return withoutExtension.replace(GGUF_SPLIT_SUFFIX, "").trim();
+}
+
+/**
+ * Mirrors extract_quant_label in gguf.py, for a bare filename. The parent-directory pass
+ * cannot fire on a basename, so this is the stem's quant token or the stem itself.
+ */
+function ggufQuantLabel(filename: string): string {
+ const stem = ggufStem(filename);
+ let fallback: RegExpExecArray | null = null;
+ for (const match of stem.matchAll(QUANT_TOKEN)) {
+ if (FLOAT_PRECISION_QUANTS.has(match[2].toUpperCase())) {
+ fallback ??= match;
+ continue;
+ }
+ return `${match[1] ?? ""}${match[2]}`;
+ }
+ if (fallback) {
+ return `${fallback[1] ?? ""}${fallback[2]}`;
+ }
+ return stem || "gguf";
+}
+
+/**
+ * `[head, quant]` for a `head:QUANT` key, or null when the colon is not one. The suffix must
+ * look like a real quant, so an ordinary colon in a POSIX filename and a drive letter are left
+ * alone.
+ */
+export function splitQuantSuffix(value: string): [string, string] | null {
+ const separator = value.lastIndexOf(":");
+ if (separator <= 0 || separator === value.length - 1) {
+ return null;
+ }
+ const head = value.slice(0, separator);
+ const tail = value.slice(separator + 1);
+ if (tail.includes("/") || tail.includes("\\")) {
+ return null;
+ }
+ if (
+ tail.length <= MAX_QUANT_SUFFIX_LEN &&
+ KNOWN_QUANT.test(tail.replace(BPW_SUFFIX, ""))
+ ) {
+ return [head, tail];
+ }
+ // A .gguf with no quant is labelled by its stem; a non-.gguf head is a plain colon.
+ if (!head.toLowerCase().endsWith(".gguf")) {
+ return null;
+ }
+ // Exactly that label, as the backend requires: a colon is legal in a POSIX filename,
+ // so reading the suffix as a variant folds two real files onto one lowercased key.
+ const filename = head.replace(BACKSLASHES, "/").split("/").pop() ?? head;
+ return tail.toLowerCase() === ggufQuantLabel(filename).toLowerCase()
+ ? [head, tail]
+ : null;
+}
diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
index f3e077272d2..3687d21780d 100644
--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
@@ -7,6 +7,7 @@ import {
modelStorageKey,
normalizeGgufVariantIdentity,
normalizeModelIdentity,
+ publicModelId,
} from "./model-identity";
import type { GpuIndexKind } from "@/hooks/use-gpu-info";
@@ -237,6 +238,7 @@ function serializedMapEntrySize(key: string, value: StoredMap[string]): number {
function deleteOldestEvictableEntry(
map: StoredMap,
protectedKeys?: ReadonlySet<string>,
+ evicted?: string[],
): { key: string; value: StoredMap[string] } | null {
for (const key of Object.keys(map)) {
// Never evict a future-schema entry an older client cannot interpret.
@@ -248,6 +250,7 @@ function deleteOldestEvictableEntry(
}
const value = map[key];
delete map[key];
+ evicted?.push(key);
return { key, value };
}
return null;
@@ -256,17 +259,18 @@ function deleteOldestEvictableEntry(
function enforceStorageBudget(
map: StoredMap,
protectedKeys?: ReadonlySet<string>,
+ evicted?: string[],
): boolean {
let entryCount = Object.keys(map).length;
while (entryCount > MAX_ENTRIES) {
- if (!deleteOldestEvictableEntry(map, protectedKeys)) {
+ if (!deleteOldestEvictableEntry(map, protectedKeys, evicted)) {
return false;
}
entryCount -= 1;
}
let bytes = serializedMapSize(map);
while (bytes > MAX_PER_MODEL_CONFIG_STORAGE_BYTES) {
- const removed = deleteOldestEvictableEntry(map, protectedKeys);
+ const removed = deleteOldestEvictableEntry(map, protectedKeys, evicted);
if (!removed) {
return false;
}
@@ -438,7 +442,10 @@ function writeMap(map: StoredMap): boolean {
}
}
-function warnDroppedFields(raw: Record<string, unknown>, version: number): void {
+function warnDroppedFields(
+ raw: Record<string, unknown>,
+ version: number,
+): void {
if (!import.meta.env?.DEV) {
return;
}
@@ -458,7 +465,8 @@ function normalizeV1(partial: RawConfig): PerModelConfig {
typeof partial.speculativeType === "string"
? canonicalizeSpeculativeType(partial.speculativeType)
: null;
- const speculativeType = rawSpecType ?? DEFAULT_PER_MODEL_CONFIG.speculativeType;
+ const speculativeType =
+ rawSpecType ?? DEFAULT_PER_MODEL_CONFIG.speculativeType;
const specDraftNMax =
speculativeType != null &&
MTP_SPECULATIVE_TYPES.has(speculativeType) &&
@@ -498,6 +506,14 @@ function normalizeV1(partial: RawConfig): PerModelConfig {
};
}
+/**
+ * A config in the exact shape storage keeps it in: the UI carries sentinels storage does not
+ * (Speculative Decoding "auto" canonicalizes to null), which would read as non-default.
+ */
+export function normalizePerModelConfig(raw: unknown): PerModelConfig {
+ return normalize(raw);
+}
+
function normalize(raw: unknown): PerModelConfig {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
return normalizeV1({});
@@ -646,6 +662,12 @@ export function savePerModelConfig(
modelId: string,
ggufVariant: string | null | undefined,
config: PerModelConfig,
+ /**
+ * Receives models dropped to stay inside the storage budget. Eviction is silent and
+ * still reports success, so without this their server overrides would keep applying
+ * with nothing in the UI able to forget them.
+ */
+ evicted?: { modelId: string; ggufVariant: string | null }[],
): boolean {
if (
typeof config.chatTemplateOverride === "string" &&
@@ -669,10 +691,53 @@ export function savePerModelConfig(
const [key] = storageKeysForModelVariant(modelId, ggufVariant);
deleteConfigEntriesForModelVariant(map, modelId, ggufVariant);
map[key] = toStoredConfig(normalized);
- if (!enforceStorageBudget(map, new Set([key]))) {
+ const evictedKeys: string[] = [];
+ if (!enforceStorageBudget(map, new Set([key]), evictedKeys)) {
return false;
}
- return writeMap(map);
+ const written = writeMap(map);
+ if (written && evicted) {
+ for (const evictedKey of evictedKeys) {
+ const id = modelIdFromStorageKey(evictedKey);
+ if (!id) {
+ continue;
+ }
+ const variant = ggufVariantFromStorageKey(evictedKey);
+ evicted.push({ modelId: id, ggufVariant: variant ? variant : null });
+ }
+ }
+ return written;
+}
+
+/** Every saved per-model config, decoded back to the ids it was keyed by. */
+export function listPerModelConfigs(): {
+ modelId: string;
+ ggufVariant: string | null;
+ config: PerModelConfig;
+}[] {
+ const out: {
+ modelId: string;
+ ggufVariant: string | null;
+ config: PerModelConfig;
+ }[] = [];
+ for (const [key, raw] of Object.entries(readMap())) {
+ const modelId = modelIdFromStorageKey(key);
+ if (!modelId) {
+ continue;
+ }
+ // Never report a future-schema record: loadPerModelConfig refuses to apply one, so
+ // the backfill would persist this client's partial reading of it.
+ if (storedConfigVersion(raw) > STORAGE_SCHEMA_VERSION) {
+ continue;
+ }
+ const variant = ggufVariantFromStorageKey(key);
+ out.push({
+ modelId,
+ ggufVariant: variant ? variant : null,
+ config: normalize(raw),
+ });
+ }
+ return out;
}
export function deletePerModelConfig(
@@ -690,6 +755,70 @@ export function deletePerModelConfig(
return writeMap(map);
}
+/**
+ * Move a saved config from an id an older release keyed it by onto the current one.
+ *
+ * A repo cached outside the active HF cache is now keyed by its repo id, because that is
+ * what the picker and the auto-switch index use; it used to be keyed by the snapshot
+ * path it loads from. Nothing else migrates that: the server backfill only mirrors what
+ * is already stored, so without this the model reads as never remembered and comes up on
+ * defaults after an upgrade.
+ *
+ * The key is renamed in one write rather than saved and then deleted: holding both copies at once
+ * puts an already-full map over its budget, and the save then evicts the oldest unrelated model
+ * silently, with no eviction list to hand back, so that model's server override outlives anything
+ * the UI could forget. A rename cannot grow the entry count.
+ */
+export function adoptLegacyConfigKey(
+ modelId: string,
+ legacyModelId: string,
+ ggufVariant?: string | null,
+): boolean {
+ if (!legacyModelId || legacyModelId === modelId) {
+ return false;
+ }
+ const map = readMap();
+ const legacyKey = findConfigKeyForModelVariant(
+ map,
+ legacyModelId,
+ ggufVariant,
+ );
+ if (!legacyKey) {
+ return false;
+ }
+ // Never interpret, move or destroy a record a newer client wrote, on either id: the same
+ // guard loadPerModelConfig, savePerModelConfig and deletePerModelConfig each apply.
+ if (
+ storedConfigVersion(map[legacyKey]) > STORAGE_SCHEMA_VERSION ||
+ hasFutureConfigForModelVariant(map, legacyModelId, ggufVariant) ||
+ hasFutureConfigForModelVariant(map, modelId, ggufVariant)
+ ) {
+ return false;
+ }
+ const legacy = normalize(map[legacyKey]);
+ // What is already saved under modelId wins; the stale record still goes.
+ const alreadySaved =
+ findConfigKeyForModelVariant(map, modelId, ggufVariant) !== null;
+ const bytesBefore = serializedMapSize(map);
+ delete map[legacyKey];
+ deleteConfigEntriesForModelVariant(map, legacyModelId, ggufVariant);
+ if (!(alreadySaved || isDefaultConfig(legacy))) {
+ const [key] = storageKeysForModelVariant(modelId, ggufVariant);
+ map[key] = toStoredConfig(legacy);
+ }
+ // Only the key strings change length, and a repo id is normally shorter than the snapshot
+ // path it replaces. If it is not, and that tips the map past its byte cap, leave storage as
+ // it was: the stale record is still readable, where an eviction would not be undoable.
+ const bytesAfter = serializedMapSize(map);
+ if (
+ bytesAfter > bytesBefore &&
+ bytesAfter > MAX_PER_MODEL_CONFIG_STORAGE_BYTES
+ ) {
+ return false;
+ }
+ return writeMap(map);
+}
+
export function resolveInitialConfig(
modelId: string,
ggufVariant?: string | null,
@@ -700,3 +829,30 @@ export function resolveInitialConfig(
}
return { config: { ...DEFAULT_PER_MODEL_CONFIG }, remembered: false };
}
+
+/**
+ * Remembered settings for the identifier ``/api/inference/status`` reports as loaded.
+ *
+ * An API auto-switch hands the loader the concrete snapshot path (the resolver index only holds
+ * paths), so ``model_identifier`` names that path while this model's settings are keyed by its
+ * repo id -- what ``modelConfigIdentity`` writes for a cached repo, and what the backend's
+ * override lookup already tries alongside the path. Reading the raw identifier alone reports the
+ * resident model as unremembered, blanking a control it is running with, which the next save then
+ * writes back over the saved record. Only a namespaced collapse is adopted, the rule
+ * ``residentModelIdMatches`` applies: an HF snapshot collapses onto a repo id naming exactly one
+ * model, while every other path collapses onto a stem two models can share.
+ */
+export function resolveResidentInitialConfig(
+ modelId: string,
+ ggufVariant?: string | null,
+): { config: PerModelConfig; remembered: boolean } {
+ const direct = resolveInitialConfig(modelId, ggufVariant);
+ if (direct.remembered) {
+ return direct;
+ }
+ const alias = publicModelId(modelId);
+ if (alias === modelId || !alias.includes("/")) {
+ return direct;
+ }
+ return resolveInitialConfig(alias, ggufVariant);
+}
diff --git a/studio/frontend/src/features/settings/components/api-monitor-console.tsx b/studio/frontend/src/features/settings/components/api-monitor-console.tsx
deleted file mode 100644
index a9c89dbeffe..00000000000
--- a/studio/frontend/src/features/settings/components/api-monitor-console.tsx
+++ /dev/null
@@ -1,591 +0,0 @@
-// 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 { Button } from "@/components/ui/button";
-import { cn } from "@/lib/utils";
-import {
- ActivityIcon,
- ChevronDownIcon,
- CircleIcon,
- PowerOffIcon,
- RefreshCwIcon,
-} from "lucide-react";
-import {
- type ReactElement,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
-import {
- getApiMonitor,
- getApiMonitorEntry,
- getInferenceStatus,
- unloadModel,
-} from "../../chat/api/chat-api";
-import { resolveInferenceCheckpointId } from "../../chat/lib/apply-inference-status-to-store";
-import { useChatRuntimeStore } from "../../chat/stores/chat-runtime-store";
-import type { ApiMonitorEntry, ApiMonitorResponse } from "../../chat/types/api";
-
-const API_INFERENCE_PREFIX_RE = /^\/api\/inference/;
-const V1_PREFIX_RE = /^\/v1\//;
-const PAGE_SIZE = 5;
-
-function formatTime(value: number): string {
- return new Date(value * 1000).toLocaleTimeString([], {
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- });
-}
-
-function formatDuration(value?: number | null): string {
- if (value == null) {
- return "Running";
- }
- if (value < 1000) {
- return `${value} ms`;
- }
- return `${(value / 1000).toFixed(value < 10000 ? 1 : 0)} s`;
-}
-
-function formatTokens(entry: ApiMonitorEntry): string {
- if (entry.total_tokens != null) {
- return `${entry.total_tokens.toLocaleString()} tokens`;
- }
- if (entry.prompt_tokens != null || entry.completion_tokens != null) {
- const prompt = entry.prompt_tokens ?? 0;
- const completion = entry.completion_tokens ?? 0;
- return `${(prompt + completion).toLocaleString()} tokens`;
- }
- return "Tokens pending";
-}
-
-function compactEndpoint(endpoint: string): string {
- return endpoint
- .replace(API_INFERENCE_PREFIX_RE, "/api")
- .replace(V1_PREFIX_RE, "/");
-}
-
-function statusTone(status: ApiMonitorEntry["status"]): string {
- if (status === "running") {
- return "text-emerald-500";
- }
- if (status === "error") {
- return "text-destructive";
- }
- if (status === "cancelled") {
- return "text-amber-500";
- }
- return "text-muted-foreground";
-}
-
-function UsageBar({ value }: { value?: number | null }): ReactElement | null {
- if (value == null) {
- return null;
- }
- const pct = Math.max(0, Math.min(100, Math.round(value * 100)));
- return (
- <div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-muted">
- <div
- className="h-full rounded-full bg-control-accent"
- style={{ width: `${pct}%` }}
- />
- </div>
- );
-}
-
-function isLifecycle(entry: ApiMonitorEntry): boolean {
- return entry.kind === "lifecycle";
-}
-
-function lifecycleLabel(entry: ApiMonitorEntry): string {
- if (entry.event === "unload") {
- return entry.reason === "idle" ? "Model unloaded (idle)" : "Model unloaded";
- }
- if (entry.event === "download") {
- if (entry.status === "running") {
- const pct = entry.progress;
- return typeof pct === "number"
- ? `Downloading model (${Math.round(pct)}%)`
- : "Downloading model";
- }
- if (entry.status === "completed") return "Model downloaded";
- // A cancel is deliberate, so saying it failed misreads the user's own action.
- return entry.status === "cancelled"
- ? "Model download cancelled"
- : "Model download failed";
- }
- if (entry.status === "running") {
- return "Loading model";
- }
- if (entry.status === "completed") {
- return "Model loaded";
- }
- return "Model load failed";
-}
-
-// Load/unload rows: label, model and time. No prompt or detail, so nothing to expand.
-function LifecycleEntry({ entry }: { entry: ApiMonitorEntry }): ReactElement {
- return (
- <article className="min-w-0 rounded-lg border border-border/70 bg-muted/25">
- <div className="flex w-full min-w-0 items-start justify-between gap-3 p-3">
- <div className="min-w-0">
- <div className="flex min-w-0 items-center gap-2">
- <ActivityIcon
- className={cn("size-3.5 shrink-0", statusTone(entry.status))}
- />
- <span className="truncate text-xs font-medium">
- {lifecycleLabel(entry)}
- </span>
- </div>
- <div className="mt-1 truncate text-ui-11 text-muted-foreground">
- {entry.model}
- </div>
- </div>
- <div className="shrink-0 text-right text-ui-11 text-muted-foreground">
- <div>{formatTime(entry.started_at)}</div>
- {entry.event === "load" || entry.event === "download" ? (
- <div>{formatDuration(entry.duration_ms)}</div>
- ) : null}
- </div>
- </div>
- </article>
- );
-}
-
-function MonitorEntry({
- entry,
- detail,
- expanded,
- loading,
- onToggle,
-}: {
- entry: ApiMonitorEntry;
- detail?: ApiMonitorEntry;
- expanded: boolean;
- loading: boolean;
- onToggle: () => void;
-}): ReactElement {
- const hasCurrentDetail =
- detail &&
- detail.status === entry.status &&
- detail.updated_at >= entry.updated_at;
- const prompt = detail?.prompt ?? entry.prompt_preview;
- const replyText = hasCurrentDetail
- ? detail.error ?? detail.reply ?? entry.error ?? entry.reply_preview
- : entry.error ?? entry.reply_preview;
- const reply = replyText || (entry.status === "running" ? "Waiting..." : "No reply");
-
- return (
- <article className="min-w-0 rounded-lg border border-border/70 bg-background">
- <button
- type="button"
- onClick={onToggle}
- className="flex w-full min-w-0 items-start justify-between gap-3 p-3 text-left"
- aria-expanded={expanded}
- >
- <div className="min-w-0">
- <div className="flex min-w-0 items-center gap-2">
- <CircleIcon
- className={cn("size-2.5 fill-current", statusTone(entry.status))}
- />
- <span className="truncate text-xs font-medium">
- {compactEndpoint(entry.endpoint)}
- </span>
- </div>
- <div className="mt-1 truncate text-ui-11 text-muted-foreground">
- {entry.model}
- </div>
- <div className="mt-2 line-clamp-2 whitespace-pre-wrap break-words text-xs text-muted-foreground">
- {entry.error ||
- entry.reply_preview ||
- entry.prompt_preview ||
- (entry.status === "running" ? "Waiting..." : "No preview")}
- </div>
- </div>
- <div className="flex shrink-0 items-start gap-2 text-right text-ui-11 text-muted-foreground">
- <div>
- <div>{formatTime(entry.started_at)}</div>
- <div>{formatDuration(entry.duration_ms)}</div>
- </div>
- <ChevronDownIcon
- className={cn(
- "mt-0.5 size-3.5 transition-transform",
- expanded && "rotate-180",
- )}
- />
- </div>
- </button>
-
- {expanded ? (
- <div className="border-t border-border/60 p-3 pt-2">
- <div className="grid gap-2">
- <div>
- <div className="mb-1 flex items-center justify-between gap-2 text-ui-10 font-semibold uppercase text-muted-foreground">
- <span>Prompt</span>
- {entry.prompt_truncated && !detail ? <span>Preview</span> : null}
- </div>
- <pre className="max-h-44 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted/45 p-2 text-xs leading-5">
- {loading && !detail ? "Loading..." : prompt || "No prompt text"}
- </pre>
- </div>
- <div>
- <div className="mb-1 flex items-center justify-between gap-2 text-ui-10 font-semibold uppercase text-muted-foreground">
- <span>Reply</span>
- {entry.reply_truncated && !detail ? <span>Preview</span> : null}
- </div>
- <pre className="max-h-44 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted/45 p-2 text-xs leading-5">
- {loading && !detail ? "Loading..." : reply}
- </pre>
- </div>
- </div>
-
- <div className="mt-3 text-ui-11 text-muted-foreground">
- {formatTokens(entry)}
- {entry.context_length ? (
- <> / {entry.context_length.toLocaleString()} context</>
- ) : null}
- <UsageBar value={entry.context_usage} />
- </div>
- </div>
- ) : null}
- </article>
- );
-}
-
-export function ApiMonitorConsole(): ReactElement {
- const [data, setData] = useState<ApiMonitorResponse | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [refreshing, setRefreshing] = useState(false);
- const [unloading, setUnloading] = useState(false);
- const [expandedIds, setExpandedIds] = useState<Set<string>>(() => new Set());
- const [details, setDetails] = useState<Record<string, ApiMonitorEntry>>({});
- const [loadingDetails, setLoadingDetails] = useState<Set<string>>(
- () => new Set(),
- );
- const loadingDetailsRef = useRef<Set<string>>(new Set());
- const detailsRef = useRef<Record<string, ApiMonitorEntry>>({});
-
- const loadMonitor = useCallback(async (): Promise<void> => {
- setRefreshing(true);
- try {
- setData(await getApiMonitor());
- setError(null);
- } catch (err: unknown) {
- setError(err instanceof Error ? err.message : "Monitor unavailable");
- } finally {
- setRefreshing(false);
- }
- }, []);
-
- // /unload matches on the internal id, which the monitor omits, so read it from status.
- const unloadActiveModel = useCallback(async (): Promise<void> => {
- setUnloading(true);
- try {
- const status = await getInferenceStatus();
- const checkpoint = resolveInferenceCheckpointId(status);
- if (!checkpoint) {
- setError(null);
- return;
- }
- await unloadModel({ model_path: checkpoint });
- // Same as the chat eject flow: the store still holds the freed checkpoint.
- useChatRuntimeStore.getState().clearCheckpoint();
- setError(null);
- await loadMonitor();
- } catch (err: unknown) {
- setError(err instanceof Error ? err.message : "Failed to unload the model");
- } finally {
- setUnloading(false);
- }
- }, [loadMonitor]);
-
- useEffect(() => {
- let cancelled = false;
- let timer: number | undefined;
-
- function schedule(): void {
- timer = window.setTimeout(poll, 1500);
- }
-
- function poll(): void {
- getApiMonitor()
- .then((next) => {
- if (cancelled) {
- return;
- }
- setData(next);
- setError(null);
- })
- .catch((err: unknown) => {
- if (cancelled) {
- return;
- }
- setError(err instanceof Error ? err.message : "Monitor unavailable");
- })
- .finally(() => {
- if (!cancelled) {
- schedule();
- }
- });
- }
-
- poll();
- return () => {
- cancelled = true;
- if (timer !== undefined) {
- window.clearTimeout(timer);
- }
- };
- }, []);
-
- const statusLabel = data?.status ?? "idle";
- const hasActive = (data?.active_requests ?? 0) > 0;
- const entries = useMemo(() => data?.entries ?? [], [data]);
- // Older backends omit the field; only an explicit `false` means logging is off.
- const loggingDisabled = data?.logging_enabled === false;
-
- // Page 1 tracks the live list; paging back freezes the id order so history holds still.
- const [page, setPage] = useState(0);
- const [frozenIds, setFrozenIds] = useState<string[] | null>(null);
- const byId = useMemo(
- () => new Map(entries.map((entry) => [entry.id, entry])),
- [entries],
- );
- const ordered = useMemo(() => {
- if (frozenIds === null) {
- return entries;
- }
- return frozenIds.flatMap((id) => {
- const entry = byId.get(id);
- return entry ? [entry] : [];
- });
- }, [byId, entries, frozenIds]);
- const pageCount = Math.max(1, Math.ceil(ordered.length / PAGE_SIZE));
- const pageIndex = Math.min(page, pageCount - 1);
- const visible = ordered.slice(
- pageIndex * PAGE_SIZE,
- pageIndex * PAGE_SIZE + PAGE_SIZE,
- );
- const newerCount =
- frozenIds === null
- ? 0
- : entries.filter((entry) => !frozenIds.includes(entry.id)).length;
-
- const goToPage = useCallback(
- (next: number): void => {
- if (next <= 0) {
- setFrozenIds(null);
- setPage(0);
- return;
- }
- // Freeze on the way off page 1 so the history under the cursor holds still.
- setFrozenIds((prev) => prev ?? entries.map((entry) => entry.id));
- setPage(next);
- },
- [entries],
- );
-
- const loadDetail = useCallback(
- (id: string): void => {
- if (loadingDetailsRef.current.has(id)) {
- return;
- }
- loadingDetailsRef.current.add(id);
- setLoadingDetails((prev) => new Set(prev).add(id));
- getApiMonitorEntry(id)
- .then((entry) => {
- setDetails((prev) => {
- const next = { ...prev, [id]: entry };
- detailsRef.current = next;
- return next;
- });
- })
- .catch(() => {
- setDetails((prev) => {
- const next = { ...prev };
- delete next[id];
- detailsRef.current = next;
- return next;
- });
- })
- .finally(() => {
- loadingDetailsRef.current.delete(id);
- setLoadingDetails((prev) => {
- const next = new Set(prev);
- next.delete(id);
- return next;
- });
- });
- },
- [],
- );
-
- const toggleEntry = useCallback(
- (entry: ApiMonitorEntry): void => {
- setExpandedIds((prev) => {
- const next = new Set(prev);
- if (next.has(entry.id)) {
- next.delete(entry.id);
- } else {
- next.add(entry.id);
- loadDetail(entry.id);
- }
- return next;
- });
- },
- [loadDetail],
- );
-
- useEffect(() => {
- // Only rows on screen: an expanded row on another page would keep polling.
- for (const entry of visible) {
- if (isLifecycle(entry) || !expandedIds.has(entry.id)) {
- continue;
- }
- const cached = detailsRef.current[entry.id];
- if (!cached || cached.status !== entry.status || entry.status === "running") {
- loadDetail(entry.id);
- }
- }
- }, [visible, expandedIds, loadDetail]);
-
- return (
- <section className="flex min-w-0 flex-col rounded-lg border border-border/70 bg-background">
- <div className="flex min-w-0 items-start justify-between gap-3 border-b border-border/60 px-4 py-3">
- <div className="flex min-w-0 gap-3">
- <div className="relative mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md border border-border/70 bg-muted/40">
- <ActivityIcon className="size-4 text-foreground" />
- {hasActive ? (
- <span className="absolute right-1 top-1 size-2 rounded-full bg-emerald-500" />
- ) : null}
- </div>
- <div className="min-w-0">
- <h2 className="text-sm font-semibold text-foreground">
- API monitor
- </h2>
- <p className="truncate text-xs text-muted-foreground">
- {data?.active_model ?? "No model loaded"}
- </p>
- </div>
- </div>
- <div className="flex shrink-0 items-center gap-2">
- <div className="rounded-full border border-border px-2.5 py-1 text-xs capitalize text-muted-foreground">
- {statusLabel}
- </div>
- {/* Always rendered, disabled when idle: the only manual release must stay visible. */}
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => void unloadActiveModel()}
- disabled={unloading || !data?.active_model}
- title={
- data?.active_model
- ? "Unload the model and free its VRAM"
- : "No model is loaded"
- }
- >
- <PowerOffIcon className="size-3.5" />
- {unloading ? "Unloading" : "Unload"}
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => void loadMonitor()}
- disabled={refreshing}
- >
- <RefreshCwIcon
- className={cn("size-3.5", refreshing && "animate-spin")}
- />
- Refresh
- </Button>
- </div>
- </div>
-
- <div className="flex items-center justify-between border-b border-border/60 px-4 py-2 text-xs text-muted-foreground">
- <span>
- {(data?.active_requests ?? 0).toLocaleString()} active
- {loggingDisabled ? null : (
- <> / {entries.length.toLocaleString()} recent</>
- )}
- </span>
- {data?.context_length ? (
- <span>{data.context_length.toLocaleString()} context</span>
- ) : null}
- </div>
-
- <div className="max-h-[420px] min-h-24 overflow-y-auto p-3">
- {error ? (
- <div className="rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
- {error}
- </div>
- ) : loggingDisabled ? (
- <div className="rounded-lg border border-border/70 p-4 text-sm text-muted-foreground">
- The API monitor is disabled by{" "}
- <code className="rounded bg-muted/60 px-1 py-0.5 text-xs">
- UNSLOTH_STUDIO_DISABLE_API_MONITOR
- </code>
- . Requests and model loads still run normally, they are just not recorded
- here. Unset the variable and restart Studio to re-enable.
- </div>
- ) : entries.length === 0 ? (
- <div className="rounded-lg border border-border/70 p-4 text-sm text-muted-foreground">
- No API traffic yet
- </div>
- ) : (
- <div className="grid gap-3">
- {visible.map((entry) =>
- isLifecycle(entry) ? (
- <LifecycleEntry key={entry.id} entry={entry} />
- ) : (
- <MonitorEntry
- key={entry.id}
- entry={entry}
- detail={details[entry.id]}
- expanded={expandedIds.has(entry.id)}
- loading={loadingDetails.has(entry.id)}
- onToggle={() => toggleEntry(entry)}
- />
- ),
- )}
- </div>
- )}
- </div>
-
- {/* Also while frozen: retention can shrink that list below one page, and hiding the
- pager would strand the console on a stale snapshot. */}
- {ordered.length > PAGE_SIZE || frozenIds !== null ? (
- <div className="flex items-center justify-between gap-2 border-t border-border/60 px-4 py-2 text-xs text-muted-foreground">
- <span>
- Page {pageIndex + 1} of {pageCount}
- {newerCount > 0 ? ` (${newerCount.toLocaleString()} new)` : ""}
- </span>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="sm"
- className="h-7 px-2 text-xs"
- onClick={() => goToPage(pageIndex - 1)}
- disabled={pageIndex === 0 && frozenIds === null}
- >
- Newer
- </Button>
- <Button
- variant="ghost"
- size="sm"
- className="h-7 px-2 text-xs"
- onClick={() => goToPage(pageIndex + 1)}
- disabled={pageIndex >= pageCount - 1}
- >
- Older
- </Button>
- </div>
- </div>
- ) : null}
- </section>
- );
-}
diff --git a/studio/frontend/src/features/settings/components/monitor-link.tsx b/studio/frontend/src/features/settings/components/monitor-link.tsx
new file mode 100644
index 00000000000..ac6ea078fef
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/monitor-link.tsx
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The monitor has its own page, normally reached from the floating panel; this card is
+// the way in from Settings.
+
+import { Switch } from "@/components/ui/switch";
+// Direct path, not the barrel: the barrel re-exports the page, defeating its lazy route.
+import { useApiMonitorOverlayStore } from "@/features/api-monitor/overlay-store";
+import { getApiMonitor } from "@/features/chat/api/chat-api";
+import type { ApiMonitorResponse } from "@/features/chat/types/api";
+import { cn } from "@/lib/utils";
+import { ActivityIcon, ArrowRight02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useNavigate } from "@tanstack/react-router";
+import { type ReactElement, useEffect, useState } from "react";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+
+export function MonitorLink(): ReactElement {
+ const navigate = useNavigate();
+ const [data, setData] = useState<ApiMonitorResponse | null>(null);
+ const autoOpen = useApiMonitorOverlayStore((s) => s.autoOpen);
+ const setAutoOpen = useApiMonitorOverlayStore((s) => s.setAutoOpen);
+
+ // One snapshot, not a poll: the live view is the monitor page.
+ useEffect(() => {
+ let cancelled = false;
+ void getApiMonitor()
+ .then((next) => {
+ if (!cancelled) setData(next);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const active = data?.active_requests ?? 0;
+ const recent = data?.entries.length ?? 0;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <button
+ type="button"
+ onClick={() => {
+ useSettingsDialogStore.getState().closeDialog();
+ void navigate({ to: "/api-monitor" });
+ }}
+ className="flex w-full min-w-0 items-center gap-3 rounded-lg border border-border/70 bg-background px-4 py-3 text-left transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <span className="relative flex size-8 shrink-0 items-center justify-center rounded-md border border-border/70 bg-muted/40">
+ <HugeiconsIcon
+ icon={ActivityIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ {active > 0 ? (
+ <span className="absolute right-1 top-1 size-2 rounded-full bg-emerald-500" />
+ ) : null}
+ </span>
+ <span className="flex min-w-0 flex-col">
+ <span className="text-sm font-semibold text-foreground">
+ API monitor
+ </span>
+ <span className="truncate text-xs text-muted-foreground">
+ {data == null
+ ? "Live requests, errors and token usage"
+ : `${active.toLocaleString()} active · ${recent.toLocaleString()} recent · ${
+ data.active_model ?? "no model loaded"
+ }`}
+ </span>
+ </span>
+ <HugeiconsIcon
+ icon={ArrowRight02Icon}
+ strokeWidth={1.75}
+ className={cn("ml-auto size-4 shrink-0 text-muted-foreground")}
+ />
+ </button>
+
+ {/* Where the panel's own "stop opening this" gets turned back on. */}
+ <div className="flex items-center justify-between gap-3 rounded-lg px-1 py-1">
+ <span className="flex min-w-0 flex-col">
+ <span className="text-sm text-foreground">
+ Show the floating monitor automatically
+ </span>
+ <span className="text-xs text-muted-foreground">
+ Opens a small panel when API traffic arrives.
+ </span>
+ </span>
+ <Switch
+ checked={autoOpen}
+ onCheckedChange={setAutoOpen}
+ aria-label="Show the floating API monitor automatically"
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index 49d73dcfb3f..1b791a52ea6 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -3,6 +3,7 @@
export { SettingsDialog } from "./settings-dialog";
export { loadEmbeddingModelSettings } from "./api/embedding-model";
+export { loadOpenAIAutoSwitchSettings } from "./api/openai-auto-switch";
export {
loadHuggingFaceCacheSettings,
updateHuggingFaceCacheSettings,
diff --git a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
index 1743d784d7f..33aa900b5cc 100644
--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
@@ -14,7 +14,7 @@ import { translate, useT } from "@/i18n";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useCallback, useEffect, useState } from "react";
import { fetchApiKeys, revokeApiKey, type ApiKey } from "../api/api-keys";
-import { ApiMonitorConsole } from "../components/api-monitor-console";
+import { MonitorLink } from "../components/monitor-link";
import { ApiKeyRow } from "../components/api-key-row";
import { CreateKeyForm } from "../components/create-key-form";
import { ModelAutoSwitchSection } from "../components/model-auto-switch-section";
@@ -168,9 +168,9 @@ export function ApiKeysTab() {
)}
</section>
- <ModelAutoSwitchSection />
+ <MonitorLink />
- <ApiMonitorConsole />
+ <ModelAutoSwitchSection />
<UsageExamples apiKey={revealed} />
diff --git a/studio/frontend/tests/adopt-legacy-config-key.test.ts b/studio/frontend/tests/adopt-legacy-config-key.test.ts
new file mode 100644
index 00000000000..226b2f61558
--- /dev/null
+++ b/studio/frontend/tests/adopt-legacy-config-key.test.ts
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const {
+ adoptLegacyConfigKey,
+ listPerModelConfigs,
+ resolveInitialConfig,
+ savePerModelConfig,
+} = await import(
+ "../src/features/model-picker/model-config/per-model-config.ts"
+);
+
+// A snapshot path is what an older release keyed a repo cached outside the active HF cache
+// by; the repo id is what it is keyed by now.
+const LEGACY_ID = "/home/u/.cache/models/snapshots/2f1c9ab";
+const MODEL_ID = "unsloth/Repo-GGUF";
+
+function config(
+ maxSeqLength: number,
+ kvCacheDtype: string | null = null,
+ chatTemplateOverride: string | null = null,
+) {
+ return {
+ customContextLength: null,
+ maxSeqLength,
+ kvCacheDtype,
+ speculativeType: null,
+ specDraftNMax: null,
+ nParallel: null,
+ tensorParallel: false,
+ chatTemplateOverride,
+ };
+}
+
+// MAX_ENTRIES in per-model-config.ts, which does not export it.
+const MAX_ENTRIES = 500;
+// MAX_PER_MODEL_CONFIG_STORAGE_BYTES is 1 MiB, so a handful of models carrying a large
+// chat template override sits against the byte budget well before the entry budget.
+const BIG_TEMPLATE = "x".repeat(60_000);
+const TEMPLATE_MODELS = 16;
+
+// The values have to be asserted, not just the key. Passing the config where the quant goes
+// writes an all-defaults record and reports success, after which the legacy record is dropped
+// anyway, so a key-count or source-substring check still reads as a successful move.
+test("a legacy-keyed config moves to the current id with its values", () => {
+ store.clear();
+ savePerModelConfig(LEGACY_ID, "Q4_K_M", config(32768, "q8_0"));
+
+ assert.equal(adoptLegacyConfigKey(MODEL_ID, LEGACY_ID, "Q4_K_M"), true);
+
+ const adopted = resolveInitialConfig(MODEL_ID, "Q4_K_M");
+ assert.equal(adopted.remembered, true);
+ assert.equal(adopted.config.maxSeqLength, 32768);
+ assert.equal(adopted.config.kvCacheDtype, "q8_0");
+ // The stale record goes, so exactly one survives and nothing reads the old key.
+ assert.equal(listPerModelConfigs().length, 1);
+ assert.equal(resolveInitialConfig(LEGACY_ID, "Q4_K_M").remembered, false);
+});
+
+test("a config already saved under the current id wins and the stale one still goes", () => {
+ store.clear();
+ savePerModelConfig(LEGACY_ID, "Q4_K_M", config(4096));
+ savePerModelConfig(MODEL_ID, "Q4_K_M", config(131072, "q4_0"));
+
+ assert.equal(adoptLegacyConfigKey(MODEL_ID, LEGACY_ID, "Q4_K_M"), true);
+
+ const kept = resolveInitialConfig(MODEL_ID, "Q4_K_M");
+ assert.equal(kept.config.maxSeqLength, 131072);
+ assert.equal(kept.config.kvCacheDtype, "q4_0");
+ assert.equal(listPerModelConfigs().length, 1);
+ assert.equal(resolveInitialConfig(LEGACY_ID, "Q4_K_M").remembered, false);
+});
+
+test("adopting one quant leaves another quant of the same model alone", () => {
+ store.clear();
+ savePerModelConfig(LEGACY_ID, "Q4_K_M", config(32768));
+ savePerModelConfig(LEGACY_ID, "Q8_0", config(8192));
+
+ assert.equal(adoptLegacyConfigKey(MODEL_ID, LEGACY_ID, "Q4_K_M"), true);
+
+ assert.equal(
+ resolveInitialConfig(MODEL_ID, "Q4_K_M").config.maxSeqLength,
+ 32768,
+ );
+ assert.equal(
+ resolveInitialConfig(LEGACY_ID, "Q8_0").config.maxSeqLength,
+ 8192,
+ );
+ assert.equal(resolveInitialConfig(MODEL_ID, "Q8_0").remembered, false);
+ assert.equal(listPerModelConfigs().length, 2);
+});
+
+test("nothing to move is not a move", () => {
+ store.clear();
+ // No legacy record at all.
+ assert.equal(adoptLegacyConfigKey(MODEL_ID, LEGACY_ID, "Q4_K_M"), false);
+
+ savePerModelConfig(MODEL_ID, "Q4_K_M", config(32768));
+ // The two ids are the same, or there is no older id to move from, so the record the
+ // caller is about to read must be left exactly where it is.
+ assert.equal(adoptLegacyConfigKey(MODEL_ID, MODEL_ID, "Q4_K_M"), false);
+ assert.equal(adoptLegacyConfigKey(MODEL_ID, "", "Q4_K_M"), false);
+ assert.equal(
+ resolveInitialConfig(MODEL_ID, "Q4_K_M").config.maxSeqLength,
+ 32768,
+ );
+ assert.equal(listPerModelConfigs().length, 1);
+});
+
+// A save before the delete holds two copies at once, one entry over a full map, and
+// savePerModelConfig then evicts the oldest unrelated model silently. This path passes no
+// eviction list, so that model's server override outlives anything the UI could forget.
+test("moving a legacy key at the entry budget keeps every other model", () => {
+ store.clear();
+ // A full map, with the stale record saved partway through so it is not the oldest entry
+ // and so cannot be the one eviction happens to take.
+ const half = Math.floor(MAX_ENTRIES / 2);
+ for (let i = 0; i < half; i += 1) {
+ savePerModelConfig(`org/unrelated-${i}`, "Q4_K_M", config(4096 + i * 128));
+ }
+ savePerModelConfig(LEGACY_ID, "Q4_K_M", config(32768, "q8_0"));
+ for (let i = half; i < MAX_ENTRIES - 1; i += 1) {
+ savePerModelConfig(`org/unrelated-${i}`, "Q4_K_M", config(4096 + i * 128));
+ }
+ assert.equal(listPerModelConfigs().length, MAX_ENTRIES);
+
+ assert.equal(adoptLegacyConfigKey(MODEL_ID, LEGACY_ID, "Q4_K_M"), true);
+
+ const adopted = resolveInitialConfig(MODEL_ID, "Q4_K_M");
+ assert.equal(adopted.remembered, true);
+ assert.equal(adopted.config.maxSeqLength, 32768);
+ assert.equal(adopted.config.kvCacheDtype, "q8_0");
+ // The oldest entry is the first eviction would take, and every model is still there: the
+ // move traded one key for another rather than adding a second copy.
+ assert.equal(
+ resolveInitialConfig("org/unrelated-0", "Q4_K_M").remembered,
+ true,
+ );
+ assert.equal(resolveInitialConfig(LEGACY_ID, "Q4_K_M").remembered, false);
+ assert.equal(listPerModelConfigs().length, MAX_ENTRIES);
+});
+
+test("moving a legacy key at the byte budget keeps every other model", () => {
+ store.clear();
+ for (let i = 0; i < TEMPLATE_MODELS; i += 1) {
+ savePerModelConfig(
+ `org/template-${i}`,
+ "Q4_K_M",
+ config(4096, null, BIG_TEMPLATE),
+ );
+ }
+ savePerModelConfig(LEGACY_ID, "Q4_K_M", config(32768, null, BIG_TEMPLATE));
+ assert.equal(listPerModelConfigs().length, TEMPLATE_MODELS + 1);
+
+ assert.equal(adoptLegacyConfigKey(MODEL_ID, LEGACY_ID, "Q4_K_M"), true);
+
+ const adopted = resolveInitialConfig(MODEL_ID, "Q4_K_M");
+ assert.equal(adopted.remembered, true);
+ assert.equal(adopted.config.maxSeqLength, 32768);
+ assert.equal(adopted.config.chatTemplateOverride, BIG_TEMPLATE);
+ assert.equal(
+ resolveInitialConfig("org/template-0", "Q4_K_M").remembered,
+ true,
+ );
+ assert.equal(resolveInitialConfig(LEGACY_ID, "Q4_K_M").remembered, false);
+ assert.equal(listPerModelConfigs().length, TEMPLATE_MODELS + 1);
+});
diff --git a/studio/frontend/tests/api-monitor-clear-failure.test.ts b/studio/frontend/tests/api-monitor-clear-failure.test.ts
new file mode 100644
index 00000000000..7c1e61ad0d8
--- /dev/null
+++ b/studio/frontend/tests/api-monitor-clear-failure.test.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+// use-api-monitor.ts imports React, so it cannot be imported here. The Clear log sequence
+// lives in a plain module, which this drives directly.
+import {
+ CLEAR_MONITOR_FAILED,
+ type ClearMonitorDeps,
+ clearMonitor,
+} from "../src/features/api-monitor/clear-monitor.ts";
+
+type Trace = {
+ deps: ClearMonitorDeps;
+ errors: string[];
+ detailsReset: number;
+ reloads: number;
+};
+
+/** A monitor whose DELETE settles as `remote` says. */
+function trace(remote: () => Promise<void>): Trace {
+ const state: Trace = {
+ errors: [],
+ detailsReset: 0,
+ reloads: 0,
+ deps: {
+ clearRemote: remote,
+ resetDetails: () => {
+ state.detailsReset += 1;
+ },
+ // The hook's load() owns its own try/catch, so this never rejects.
+ reload: () => {
+ state.reloads += 1;
+ return Promise.resolve();
+ },
+ onError: (message) => {
+ state.errors.push(message);
+ },
+ },
+ };
+ return state;
+}
+
+test("a refused clear reports through the monitor's error state", async () => {
+ // The backend is up enough to answer but refuses the delete, so the poll keeps
+ // succeeding and nothing else would ever mention this.
+ const state = trace(() => Promise.reject(new Error("Monitor is read-only")));
+
+ // The click handler discards the promise, so a rejection here is unhandled and silent.
+ await assert.doesNotReject(() => clearMonitor(state.deps));
+
+ assert.deepEqual(state.errors, ["Monitor is read-only"]);
+ // Nothing was deleted, so the cached payloads and the on-screen snapshot both stand.
+ assert.equal(state.detailsReset, 0);
+ assert.equal(state.reloads, 0);
+});
+
+test("a rejection that is not an Error still reports", async () => {
+ const state = trace(() => Promise.reject("offline"));
+
+ await assert.doesNotReject(() => clearMonitor(state.deps));
+
+ assert.deepEqual(state.errors, [CLEAR_MONITOR_FAILED]);
+});
+
+test("a clear that lands drops the details and refetches", async () => {
+ const state = trace(() => Promise.resolve());
+
+ await clearMonitor(state.deps);
+
+ assert.deepEqual(state.errors, []);
+ assert.equal(state.detailsReset, 1);
+ // The refetch is what empties the rendered log, and it clears the error on success.
+ assert.equal(state.reloads, 1);
+});
diff --git a/studio/frontend/tests/api-monitor-new-traffic.test.ts b/studio/frontend/tests/api-monitor-new-traffic.test.ts
new file mode 100644
index 00000000000..eedd40820ae
--- /dev/null
+++ b/studio/frontend/tests/api-monitor-new-traffic.test.ts
@@ -0,0 +1,181 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+// The overlay .tsx pulls in motion, hugeicons and the router, so it cannot be imported
+// here. Its new-traffic decision lives in a plain module, which this drives directly.
+import {
+ type WatchedEntry,
+ type WatchedResponse,
+ createWatch,
+ observeResponse,
+ rearmWatch,
+ startWatching,
+} from "../src/features/api-monitor/new-traffic.ts";
+
+// The server's clock: entry timestamps are its time.time(), never a browser instant.
+const SERVER_NOW = 1_000_000;
+// performance.now() when the poll stood up.
+const WATCH_AT = 1_000;
+
+function entry(
+ id: string,
+ status: WatchedEntry["status"],
+ startedAt: number,
+ viaApiKey = true,
+): WatchedEntry {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ return { id, status, via_api_key: viaApiKey, started_at: startedAt };
+}
+
+function snapshot(
+ entries: WatchedEntry[],
+ serverTime: number | null = SERVER_NOW,
+): WatchedResponse {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ return { entries, server_time: serverTime };
+}
+
+function watchFrom(startedAtMs: number) {
+ const watch = createWatch(0);
+ startWatching(watch, startedAtMs);
+ return watch;
+}
+
+test("a call that finished before the first snapshot arrived is new traffic", () => {
+ // The tab was hidden for 4s, so poll() issued no fetch. The first curl ran 2s into
+ // that gap and was done when the snapshot landed: terminal, but not history.
+ const opened = observeResponse(
+ watchFrom(WATCH_AT),
+ snapshot([entry("apireq_new", "completed", SERVER_NOW - 2)]),
+ WATCH_AT + 4_000,
+ );
+ assert.equal(opened, true);
+});
+
+test("traffic from before the watch began stays history", () => {
+ const opened = observeResponse(
+ watchFrom(WATCH_AT),
+ snapshot([entry("apireq_old", "completed", SERVER_NOW - 90)]),
+ WATCH_AT + 4_000,
+ );
+ assert.equal(opened, false);
+});
+
+test("a request still running at the first snapshot is live traffic", () => {
+ const opened = observeResponse(
+ watchFrom(WATCH_AT),
+ snapshot([entry("apireq_live", "running", SERVER_NOW - 90)]),
+ WATCH_AT + 10,
+ );
+ assert.equal(opened, true);
+});
+
+test("a fresh id in a later snapshot opens the panel", () => {
+ const watch = watchFrom(WATCH_AT);
+ const backlog = [entry("apireq_old", "completed", SERVER_NOW - 90)];
+ assert.equal(observeResponse(watch, snapshot(backlog), WATCH_AT + 10), false);
+ const opened = observeResponse(
+ watch,
+ snapshot(
+ [entry("apireq_next", "completed", SERVER_NOW + 4), ...backlog],
+ SERVER_NOW + 5,
+ ),
+ WATCH_AT + 5_010,
+ );
+ assert.equal(opened, true);
+});
+
+test("Studio's own chat never opens the panel", () => {
+ const opened = observeResponse(
+ watchFrom(WATCH_AT),
+ snapshot([entry("uireq", "completed", SERVER_NOW - 2, false)]),
+ WATCH_AT + 4_000,
+ );
+ assert.equal(opened, false);
+});
+
+test("a backend with no clock field keeps the old terminal-is-history seed", () => {
+ const opened = observeResponse(
+ watchFrom(WATCH_AT),
+ snapshot([entry("apireq_new", "completed", SERVER_NOW - 2)], null),
+ WATCH_AT + 4_000,
+ );
+ assert.equal(opened, false);
+});
+
+test("a browser clock disagreeing with the server's does not replay the backlog", () => {
+ // The cutoff is the server's clock minus a browser DURATION, never minus a browser
+ // timestamp, so a wall clock minutes off still dates the backlog correctly.
+ const opened = observeResponse(
+ watchFrom(WATCH_AT),
+ snapshot([
+ entry("apireq_a", "completed", SERVER_NOW - 300),
+ entry("apireq_b", "completed", SERVER_NOW - 120),
+ ]),
+ WATCH_AT + 20,
+ );
+ assert.equal(opened, false);
+});
+
+test("coming back from the full page does not replay the rows it showed", () => {
+ const watch = watchFrom(WATCH_AT);
+ const backlog = [entry("apireq_old", "completed", SERVER_NOW - 90)];
+ observeResponse(watch, snapshot(backlog), WATCH_AT + 10);
+ // 60s on /api-monitor reading those rows, then back to chat.
+ rearmWatch(watch);
+ startWatching(watch, WATCH_AT + 60_000);
+ const opened = observeResponse(
+ watch,
+ snapshot(backlog, SERVER_NOW + 60),
+ WATCH_AT + 60_010,
+ );
+ assert.equal(opened, false);
+});
+
+test("a request still running when the full page is left does not reopen the overlay", () => {
+ // /api-monitor was open on a long generation, then left for chat: that row was on
+ // screen the whole time.
+ const watch = watchFrom(WATCH_AT);
+ const live = entry("apireq_live", "running", SERVER_NOW - 5);
+ observeResponse(watch, snapshot([live]), WATCH_AT + 10);
+ rearmWatch(watch);
+ startWatching(watch, WATCH_AT + 60_000);
+ const opened = observeResponse(
+ watch,
+ snapshot([live], SERVER_NOW + 60),
+ WATCH_AT + 60_010,
+ );
+ assert.equal(opened, false);
+});
+
+test("a rearm writes off only the snapshot it comes back to", () => {
+ // The write-off is one seed, not a mode: a later call is still new traffic.
+ const watch = watchFrom(WATCH_AT);
+ const live = entry("apireq_live", "running", SERVER_NOW - 5);
+ observeResponse(watch, snapshot([live]), WATCH_AT + 10);
+ rearmWatch(watch);
+ startWatching(watch, WATCH_AT + 60_000);
+ observeResponse(watch, snapshot([live], SERVER_NOW + 60), WATCH_AT + 60_010);
+ const opened = observeResponse(
+ watch,
+ snapshot(
+ [entry("apireq_next", "running", SERVER_NOW + 61), live],
+ SERVER_NOW + 62,
+ ),
+ WATCH_AT + 62_010,
+ );
+ assert.equal(opened, true);
+});
+
+test("a fresh watch still reports a request that was already running", () => {
+ // The rearm write-off must not seed a session that never saw the full page.
+ const opened = observeResponse(
+ watchFrom(WATCH_AT),
+ snapshot([entry("apireq_live", "running", SERVER_NOW - 90)]),
+ WATCH_AT + 10,
+ );
+ assert.equal(opened, true);
+});
diff --git a/studio/frontend/tests/api-monitor-opt-out-rearm.test.ts b/studio/frontend/tests/api-monitor-opt-out-rearm.test.ts
new file mode 100644
index 00000000000..80c15df0307
--- /dev/null
+++ b/studio/frontend/tests/api-monitor-opt-out-rearm.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
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+// The overlay .tsx pulls in motion, hugeicons and the router, so it cannot be imported
+// here. These drive its watch through the exact call order its effects use.
+import {
+ type ApiMonitorWatch,
+ type WatchedEntry,
+ type WatchedResponse,
+ createWatch,
+ observeResponse,
+ standDownWatch,
+ startWatching,
+} from "../src/features/api-monitor/new-traffic.ts";
+
+// The server's clock: entry timestamps are its time.time(), never a browser instant.
+const SERVER_NOW = 1_000_000;
+// performance.now() when the poll first stood up.
+const WATCH_AT = 1_000;
+// An hour spent with automatic opening switched off.
+const OPT_OUT_MS = 3_600_000;
+
+function entry(
+ id: string,
+ status: WatchedEntry["status"],
+ startedAt: number,
+ viaApiKey = true,
+): WatchedEntry {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ return { id, status, via_api_key: viaApiKey, started_at: startedAt };
+}
+
+function snapshot(
+ entries: WatchedEntry[],
+ serverTime: number = SERVER_NOW,
+): WatchedResponse {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ return { entries, server_time: serverTime };
+}
+
+/**
+ * The overlay as its effects run it. `standDown` is the poll effect returning early for the
+ * opt out; `standUp` is it running again; `observe` is the observer effect, which re-runs on
+ * any store change and so sees the snapshot already in hand as well as each fresh one.
+ */
+function overlay(): {
+ watch: ApiMonitorWatch;
+ standDown: () => void;
+ standUp: (nowMs: number) => void;
+ observe: (response: WatchedResponse, nowMs: number) => boolean;
+} {
+ const watch = createWatch(0);
+ return {
+ watch,
+ standDown: () => standDownWatch(watch),
+ standUp: (nowMs) => startWatching(watch, nowMs),
+ observe: (response, nowMs) => observeResponse(watch, response, nowMs),
+ };
+}
+
+test("turning automatic opening back on does not pop the panel for the opt-out backlog", () => {
+ const ui = overlay();
+ const backlog = [entry("apireq_old", "completed", SERVER_NOW - 90)];
+ const first = snapshot(backlog);
+ ui.standUp(WATCH_AT);
+ assert.equal(ui.observe(first, WATCH_AT + 10), false);
+
+ // "Stop opening this automatically": the poll stands down with that snapshot in hand.
+ ui.standDown();
+ assert.equal(ui.observe(first, WATCH_AT + 20), false);
+
+ // An hour of curl against the API key, none of it polled for.
+ const during = [
+ entry("apireq_curl_b", "completed", SERVER_NOW + 900),
+ entry("apireq_curl_a", "completed", SERVER_NOW + 300),
+ ...backlog,
+ ];
+
+ // The switch in settings goes back on: the poll stands up and the observer re-runs with
+ // the stale snapshot before the first fetch of the new watch resolves.
+ ui.standUp(WATCH_AT + OPT_OUT_MS);
+ assert.equal(ui.observe(first, WATCH_AT + OPT_OUT_MS + 1), false);
+ const opened = ui.observe(
+ snapshot(during, SERVER_NOW + 3600),
+ WATCH_AT + OPT_OUT_MS + 10,
+ );
+ assert.equal(opened, false);
+});
+
+test("the snapshot in hand at the stand down cannot spend the opt-out re-arm", () => {
+ // Same run, one effect at a time: the re-arm has to survive the observer re-running on
+ // the autoOpen change itself, both when it goes off and when it comes back.
+ const ui = overlay();
+ const first = snapshot([entry("apireq_old", "completed", SERVER_NOW - 90)]);
+ ui.standUp(WATCH_AT);
+ ui.observe(first, WATCH_AT + 10);
+ ui.standDown();
+ assert.equal(ui.watch.seeded, false);
+ ui.observe(first, WATCH_AT + 20);
+ assert.equal(ui.watch.seeded, false, "a re-fold must not seed the re-arm");
+ ui.standUp(WATCH_AT + OPT_OUT_MS);
+ ui.observe(first, WATCH_AT + OPT_OUT_MS + 1);
+ assert.equal(
+ ui.watch.seeded,
+ false,
+ "still owed to the first fresh snapshot",
+ );
+});
+
+test("a call made after automatic opening is back on still opens the panel", () => {
+ const ui = overlay();
+ const backlog = [entry("apireq_old", "completed", SERVER_NOW - 90)];
+ ui.standUp(WATCH_AT);
+ ui.observe(snapshot(backlog), WATCH_AT + 10);
+ ui.standDown();
+ const during = [
+ entry("apireq_curl", "completed", SERVER_NOW + 300),
+ ...backlog,
+ ];
+ ui.standUp(WATCH_AT + OPT_OUT_MS);
+ ui.observe(snapshot(during, SERVER_NOW + 3600), WATCH_AT + OPT_OUT_MS + 10);
+ const opened = ui.observe(
+ snapshot(
+ [entry("apireq_next", "running", SERVER_NOW + 3605), ...during],
+ SERVER_NOW + 3606,
+ ),
+ WATCH_AT + OPT_OUT_MS + 1_510,
+ );
+ assert.equal(opened, true);
+});
+
+test("a session that starts opted out still reports its first snapshot", () => {
+ // Nothing has been folded in, so there is no backlog to write off; the persisted opt out
+ // must not turn into a permanent silence once the switch goes back on.
+ const ui = overlay();
+ ui.standDown();
+ assert.equal(ui.watch.resumed, false);
+ ui.standUp(WATCH_AT);
+ const opened = ui.observe(
+ snapshot([entry("apireq_live", "running", SERVER_NOW - 5)]),
+ WATCH_AT + 10,
+ );
+ assert.equal(opened, true);
+});
+
+test("an opt out with nothing behind it leaves the retained ids read", () => {
+ // The ids held at the stand down were already diffed away, re-arm or not.
+ const ui = overlay();
+ const backlog = [entry("apireq_old", "completed", SERVER_NOW - 90)];
+ ui.standUp(WATCH_AT);
+ ui.observe(snapshot(backlog), WATCH_AT + 10);
+ ui.standDown();
+ ui.standUp(WATCH_AT + OPT_OUT_MS);
+ const opened = ui.observe(
+ snapshot(backlog, SERVER_NOW + 3600),
+ WATCH_AT + OPT_OUT_MS + 10,
+ );
+ assert.equal(opened, false);
+});
diff --git a/studio/frontend/tests/api-monitor-unload-resident.test.ts b/studio/frontend/tests/api-monitor-unload-resident.test.ts
new file mode 100644
index 00000000000..34a9385d794
--- /dev/null
+++ b/studio/frontend/tests/api-monitor-unload-resident.test.ts
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+// The page .tsx pulls in the router, motion and hugeicons, so it cannot be imported here.
+// Its Unload sequence lives in a plain module, which this drives directly.
+import {
+ type ResidentModel,
+ type UnloadResidentDeps,
+ unloadResident,
+} from "../src/features/api-monitor/unload-resident.ts";
+
+function resident(checkpoint: string, advertised?: string): ResidentModel {
+ return {
+ checkpoint,
+ aliases: advertised ? [checkpoint, advertised] : [checkpoint],
+ };
+}
+
+/** A backend whose resident model follows `timeline`, one entry consumed per status read,
+ * so an entry after the first is a model an API auto-switch put there under the click.
+ *
+ * `unload` lands after the status read that preceded it, on whatever the switch left
+ * behind, and frees VRAM only when the id it names is that model: the route treats an id
+ * a concurrent load already replaced as a successful no-op (routes/inference.py:7153 ->
+ * orchestrator.py:1386-1391), so a stale name returns 200 and evicts nothing. */
+function backend(timeline: (ResidentModel | null)[]): UnloadResidentDeps & {
+ readonly sent: string[];
+ readonly reads: number;
+ peek: () => string | null;
+} {
+ let index = 0;
+ let reads = 0;
+ const sent: string[] = [];
+ const at = (i: number) => timeline[Math.min(i, timeline.length - 1)] ?? null;
+ return {
+ readResident: async () => {
+ reads += 1;
+ return at(index++);
+ },
+ unload: async (checkpoint: string) => {
+ sent.push(checkpoint);
+ const landsOn = at(index);
+ if (landsOn && landsOn.checkpoint === checkpoint) {
+ // A real eviction: nothing is resident from here on.
+ timeline.splice(index, timeline.length - index, null);
+ }
+ },
+ get sent() {
+ return sent;
+ },
+ get reads() {
+ return reads;
+ },
+ // What is still occupying VRAM once the run ends.
+ peek: () => at(index)?.checkpoint ?? null,
+ };
+}
+
+test("unloads the resident model and reports nothing left", async () => {
+ const b = backend([resident("/models/a.gguf", "org/a"), null]);
+ const result = await unloadResident(b);
+ assert.deepEqual(b.sent, ["/models/a.gguf"]);
+ assert.deepEqual(result.unloadedAliases, ["/models/a.gguf", "org/a"]);
+ assert.equal(result.stillResident, null);
+ assert.equal(b.peek(), null);
+});
+
+test("nothing loaded: no unload is sent", async () => {
+ const b = backend([null]);
+ const result = await unloadResident(b);
+ assert.deepEqual(b.sent, []);
+ assert.deepEqual(result.unloadedAliases, []);
+ assert.equal(result.stillResident, null);
+});
+
+test("an API auto-switch under the click does not leave the new model resident", async () => {
+ // The switch replaces A with B between the status read and the unload reaching the
+ // lifecycle gate, so the /unload naming A is a 200 no-op. Without a recheck the button
+ // reports success while B keeps the VRAM.
+ const b = backend([resident("/models/a.gguf"), resident("/models/b.gguf")]);
+ const result = await unloadResident(b);
+ assert.equal(b.peek(), null, "B must not stay resident");
+ assert.deepEqual(b.sent, ["/models/a.gguf", "/models/b.gguf"]);
+ assert.deepEqual(result.unloadedAliases, [
+ "/models/a.gguf",
+ "/models/b.gguf",
+ ]);
+ assert.equal(result.stillResident, null);
+});
+
+test("a switch the recheck cannot catch is reported, not swallowed", async () => {
+ // Bounded: a model that arrives after the recheck is a fresh load, not this click's
+ // target, so the run names it instead of claiming a free backend.
+ const b = backend([
+ resident("/models/a.gguf"),
+ resident("/models/b.gguf"),
+ resident("/models/c.gguf"),
+ ]);
+ const result = await unloadResident(b);
+ assert.deepEqual(b.sent, ["/models/a.gguf", "/models/b.gguf"]);
+ assert.equal(result.stillResident, "/models/c.gguf");
+});
+
+test("the steady-state click costs one extra status read, never an extra unload", async () => {
+ const b = backend([resident("/models/a.gguf"), null]);
+ await unloadResident(b);
+ assert.equal(b.sent.length, 1);
+ assert.equal(b.reads, 2);
+});
diff --git a/studio/frontend/tests/bundler-resolver.mjs b/studio/frontend/tests/bundler-resolver.mjs
new file mode 100644
index 00000000000..beb32b44d34
--- /dev/null
+++ b/studio/frontend/tests/bundler-resolver.mjs
@@ -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
+
+// The two resolution rules vite and tsconfig's "bundler" mode give the app that bare node
+// does not: the "@/*" path alias, and a relative import written without its extension.
+// Register this from a test that imports a src module using either.
+import { existsSync } from "node:fs";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const SRC = fileURLToPath(new URL("../src/", import.meta.url));
+
+function firstExisting(base) {
+ for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {
+ if (existsSync(candidate)) {
+ return pathToFileURL(candidate).href;
+ }
+ }
+ return null;
+}
+
+export function resolve(specifier, context, next) {
+ if (specifier.startsWith("@/")) {
+ const resolved = firstExisting(SRC + specifier.slice(2));
+ return next(resolved ?? specifier, context);
+ }
+ if (specifier.startsWith(".") && context.parentURL?.startsWith("file:")) {
+ const resolved = firstExisting(
+ fileURLToPath(new URL(specifier, context.parentURL)),
+ );
+ if (resolved) {
+ return next(resolved, context);
+ }
+ }
+ return next(specifier, context);
+}
diff --git a/studio/frontend/tests/chat-template-status-seed.test.ts b/studio/frontend/tests/chat-template-status-seed.test.ts
new file mode 100644
index 00000000000..4a019f8a4df
--- /dev/null
+++ b/studio/frontend/tests/chat-template-status-seed.test.ts
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// How /api/inference/status moves the chat-template override pair. The control is what the
+// next load or Apply sends and what the Hub settings page presents as the live config; the
+// loaded baseline is what the resident server is running and what a rollback resends.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+
+import type {
+ ChatTemplateSeed,
+ ChatTemplateSeedState,
+} from "../src/features/chat/lib/resolve-chat-template-seed.ts";
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { resolveChatTemplateSeed } = await import(
+ "../src/features/chat/lib/resolve-chat-template-seed.ts"
+);
+
+/** The applier must route the pair through the resolver, not re-inline the old guard. */
+const DELEGATES_TO_RESOLVER = /resolveChatTemplateSeed\(\{/;
+
+const OLD = "{{ bos_token }}{% for m in messages %}A{% endfor %}";
+const NEW = "{{ bos_token }}{% for m in messages %}B{% endfor %}";
+const STAGED = "{{ bos_token }}{% for m in messages %}C{% endfor %}";
+
+function seed(
+ incoming: string | null | undefined,
+ previous: ChatTemplateSeedState,
+ options: {
+ hydratingExistingModel?: boolean;
+ seedLoadParams?: boolean;
+ } = {},
+): ChatTemplateSeed {
+ return resolveChatTemplateSeed({
+ incoming,
+ previous,
+ hydratingExistingModel: options.hydratingExistingModel ?? false,
+ seedLoadParams: options.seedLoadParams ?? true,
+ });
+}
+
+function pair(
+ chatTemplateOverride: string | null,
+ loadedChatTemplateOverride: string | null,
+): ChatTemplateSeedState {
+ return { chatTemplateOverride, loadedChatTemplateOverride };
+}
+
+test("a same-model reload from another client advances an undirty pair", () => {
+ // Another tab, or an OpenAI-compatible caller whose auto-switch load applied this
+ // model's saved override, relaunched the same checkpoint and quant on NEW.
+ assert.deepEqual(seed(NEW, pair(OLD, OLD)), {
+ chatTemplateOverride: NEW,
+ loadedChatTemplateOverride: NEW,
+ });
+});
+
+test("a same-model reload that drops the override is adopted too", () => {
+ assert.deepEqual(seed(null, pair(OLD, OLD)), {
+ chatTemplateOverride: null,
+ loadedChatTemplateOverride: null,
+ });
+});
+
+test("a genuinely dirty control survives, while its baseline advances", () => {
+ // A staged Apply put STAGED on the control and no load is in flight yet.
+ const result = seed(NEW, pair(STAGED, OLD));
+ assert.equal(result.loadedChatTemplateOverride, NEW);
+ assert.ok(
+ !("chatTemplateOverride" in result),
+ "a staged edit must not be overwritten by a status refresh",
+ );
+});
+
+test("a control the user blanked is not re-pinned", () => {
+ const result = seed(NEW, pair(null, OLD));
+ assert.equal(result.loadedChatTemplateOverride, NEW);
+ assert.ok(!("chatTemplateOverride" in result));
+});
+
+test("a steady poll touches neither field", () => {
+ assert.deepEqual(seed(OLD, pair(OLD, OLD)), {});
+ assert.deepEqual(seed(OLD, pair(STAGED, OLD)), {});
+ // Blank and absent are the same template, so neither is a spurious change.
+ assert.deepEqual(seed(null, pair("", "")), {});
+ assert.deepEqual(seed("", pair(null, null)), {
+ chatTemplateOverride: "",
+ loadedChatTemplateOverride: "",
+ });
+});
+
+test("a load in flight keeps its own params", () => {
+ assert.deepEqual(seed(NEW, pair(OLD, OLD), { seedLoadParams: false }), {});
+ assert.deepEqual(
+ seed(NEW, pair(OLD, OLD), {
+ seedLoadParams: false,
+ hydratingExistingModel: true,
+ }),
+ {},
+ );
+});
+
+test("a model or quant switch adopts the new model's template outright", () => {
+ assert.deepEqual(
+ seed(null, pair(OLD, OLD), { hydratingExistingModel: true }),
+ {
+ chatTemplateOverride: null,
+ loadedChatTemplateOverride: null,
+ },
+ );
+ assert.deepEqual(
+ seed(NEW, pair(STAGED, OLD), { hydratingExistingModel: true }),
+ { chatTemplateOverride: NEW, loadedChatTemplateOverride: NEW },
+ );
+});
+
+test("a fresh store seeds from status, an older backend changes nothing", () => {
+ assert.deepEqual(seed(OLD, pair(null, null)), {
+ chatTemplateOverride: OLD,
+ loadedChatTemplateOverride: OLD,
+ });
+ assert.deepEqual(seed(undefined, pair(null, null)), {});
+ assert.deepEqual(seed(undefined, pair(OLD, OLD)), {});
+});
+
+test("the status applier delegates to the seed resolver", () => {
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ const source = readFileSync(
+ path.join(
+ here,
+ "../src/features/chat/lib/apply-inference-status-to-store.ts",
+ ),
+ "utf8",
+ );
+ assert.match(source, DELEGATES_TO_RESOLVER);
+ assert.ok(
+ !source.includes("prevState.loadedChatTemplateOverride === null"),
+ "the inline chat-template guard must not survive alongside the resolver",
+ );
+});
diff --git a/studio/frontend/tests/helpers/kit.ts b/studio/frontend/tests/helpers/kit.ts
new file mode 100644
index 00000000000..40d3b0e151e
--- /dev/null
+++ b/studio/frontend/tests/helpers/kit.ts
@@ -0,0 +1,131 @@
+// 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 { register } from "node:module";
+
+import type { ResidentAdoptionState } from "../../src/features/hub/lib/adopt-inference-status.ts";
+import type { ResidentStatusRefreshTargets } from "../../src/features/hub/lib/resident-status-refresh.ts";
+
+/**
+ * Teach the loader the two resolution rules vite and tsconfig's "bundler" mode give the
+ * app. Call before dynamically importing any src module that resolves that way.
+ */
+export function registerBundlerResolver(): void {
+ register("../bundler-resolver.mjs", import.meta.url);
+}
+
+export type StorageFake = {
+ getItem: (key: string) => string | null;
+ setItem: (key: string, value: string) => void;
+ removeItem: (key: string) => void;
+};
+
+/**
+ * An in-memory localStorage, installed on globalThis under both names the app reads it
+ * by. The returned map is the backing store, so a test can stage records before import.
+ */
+export function installLocalStorageFake(): {
+ store: Map<string, string>;
+ storage: StorageFake;
+} {
+ const store = new Map<string, string>();
+ const storage: StorageFake = {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ store.set(key, value);
+ },
+ removeItem: (key: string) => {
+ store.delete(key);
+ },
+ };
+ Object.assign(globalThis, {
+ window: { localStorage: storage },
+ localStorage: storage,
+ });
+ return { store, storage };
+}
+
+/** The chat-runtime store as it stands before anything has hydrated it. */
+export function emptyStore(
+ overrides: Partial<ResidentAdoptionState> = {},
+): ResidentAdoptionState {
+ return {
+ checkpoint: null,
+ checkpointIsExternal: false,
+ activeGgufVariant: null,
+ modelLoading: false,
+ // Off by default, as the setting is, so a test opts in to the stash case.
+ idleUnloadArmed: false,
+ ...overrides,
+ };
+}
+
+/** Records the store actions adoptResidentModelStatus takes, in order. */
+export function spies() {
+ const calls: string[] = [];
+ const previouslySeen: { checkpoint: string | null; ggufVariant: string | null }[] =
+ [];
+ return {
+ calls,
+ previouslySeen,
+ actions: {
+ setCheckpoint(checkpointId: string, ggufVariant: string | null) {
+ calls.push(`setCheckpoint:${checkpointId}:${ggufVariant ?? ""}`);
+ },
+ applyStatus(previous: {
+ checkpoint: string | null;
+ ggufVariant: string | null;
+ }) {
+ calls.push("applyStatus");
+ previouslySeen.push(previous);
+ },
+ },
+ };
+}
+
+/** A window/document pair whose events and visibility a test drives by hand. */
+export function fakeTargets(): ResidentStatusRefreshTargets & {
+ hidden: boolean;
+ fire: (target: "window" | "document", type: string) => void;
+ listenerCount: () => number;
+} {
+ const listeners = new Map<string, Set<EventListenerOrEventListenerObject>>();
+ const key = (target: string, type: string) => `${target}:${type}`;
+ const make = (target: "window" | "document") => ({
+ addEventListener(type: string, fn: EventListenerOrEventListenerObject) {
+ const set = listeners.get(key(target, type)) ?? new Set();
+ set.add(fn);
+ listeners.set(key(target, type), set);
+ },
+ removeEventListener(type: string, fn: EventListenerOrEventListenerObject) {
+ listeners.get(key(target, type))?.delete(fn);
+ },
+ });
+ const visibility = { hidden: false };
+ const state = {
+ get hidden() {
+ return visibility.hidden;
+ },
+ set hidden(next: boolean) {
+ visibility.hidden = next;
+ },
+ window: make("window"),
+ document: {
+ ...make("document"),
+ get hidden() {
+ return visibility.hidden;
+ },
+ },
+ fire(target: "window" | "document", type: string) {
+ for (const fn of listeners.get(key(target, type)) ?? []) {
+ (fn as EventListener)(new Event(type));
+ }
+ },
+ listenerCount() {
+ let total = 0;
+ for (const set of listeners.values()) total += set.size;
+ return total;
+ },
+ };
+ return state as never;
+}
diff --git a/studio/frontend/tests/hub-resident-status.test.ts b/studio/frontend/tests/hub-resident-status.test.ts
new file mode 100644
index 00000000000..90d2045c594
--- /dev/null
+++ b/studio/frontend/tests/hub-resident-status.test.ts
@@ -0,0 +1,303 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { adoptResidentModelStatus } from "../src/features/hub/lib/adopt-inference-status.ts";
+import {
+ ggufVariantsMatch,
+ residentModelIdMatches,
+} from "../src/features/hub/lib/model-identity.ts";
+import { subscribeResidentStatusRefresh } from "../src/features/hub/lib/resident-status-refresh.ts";
+import { emptyStore, fakeTargets, spies } from "./helpers/kit.ts";
+
+const RESIDENT = {
+ checkpointId: "unsloth/Qwen3-8B-GGUF",
+ ggufVariant: "Q4_K_M",
+};
+
+/**
+ * Store actions that refuse to be called. Each message names what must not happen, so a
+ * test states its rule by the action it declines to forbid.
+ */
+function refusing(messages: {
+ setCheckpoint?: string;
+ clearCheckpoint?: string;
+ applyStatus?: string;
+}) {
+ const refuse = (message = "unreachable") => {
+ return () => {
+ throw new Error(message);
+ };
+ };
+ return {
+ setCheckpoint: refuse(messages.setCheckpoint),
+ clearCheckpoint: refuse(messages.clearCheckpoint),
+ applyStatus: refuse(messages.applyStatus),
+ };
+}
+
+test("landing on the Hub applies the whole status, not just the checkpoint", () => {
+ // Nothing else on /hub hydrates the runtime store, so pinning only the checkpoint
+ // leaves useActiveModelConfig at its defaults and the settings page offers those.
+ const { calls, actions } = spies();
+ const adopted = adoptResidentModelStatus(RESIDENT, emptyStore(), actions);
+ assert.equal(adopted, true);
+ assert.deepEqual(calls, [
+ "setCheckpoint:unsloth/Qwen3-8B-GGUF:Q4_K_M",
+ "applyStatus",
+ ]);
+});
+
+test("a checkpoint that already matches is still hydrated", () => {
+ // A reload rehydrates the checkpoint without the fields saying how it launched.
+ const { calls, actions } = spies();
+ adoptResidentModelStatus(
+ RESIDENT,
+ emptyStore({
+ checkpoint: "unsloth/Qwen3-8B-GGUF",
+ activeGgufVariant: "Q4_K_M",
+ }),
+ actions,
+ );
+ assert.deepEqual(calls, ["applyStatus"]);
+});
+
+test("an API auto-switch under the tab re-pins the model and the quant", () => {
+ for (const stale of [
+ { checkpoint: "unsloth/Llama-3.1-8B-GGUF", activeGgufVariant: "Q4_K_M" },
+ { checkpoint: "unsloth/Qwen3-8B-GGUF", activeGgufVariant: "Q8_0" },
+ ]) {
+ const { calls, actions } = spies();
+ adoptResidentModelStatus(RESIDENT, emptyStore(stale), actions);
+ assert.deepEqual(calls, [
+ "setCheckpoint:unsloth/Qwen3-8B-GGUF:Q4_K_M",
+ "applyStatus",
+ ]);
+ }
+});
+
+test("the status applied is the one from before the checkpoint moved", () => {
+ // applyActiveModelStatusToStore tells a hydration from steady state by the previous
+ // checkpoint/quant, so reading it after setCheckpoint keeps the old quant's baselines.
+ const { previouslySeen, actions } = spies();
+ adoptResidentModelStatus(
+ RESIDENT,
+ emptyStore({
+ checkpoint: "unsloth/Qwen3-8B-GGUF",
+ activeGgufVariant: "Q8_0",
+ }),
+ actions,
+ );
+ assert.deepEqual(previouslySeen, [
+ { checkpoint: "unsloth/Qwen3-8B-GGUF", ggufVariant: "Q8_0" },
+ ]);
+});
+
+test("nothing is adopted when no model is loaded", () => {
+ const { calls, actions } = spies();
+ const adopted = adoptResidentModelStatus(
+ { checkpointId: null, ggufVariant: null },
+ emptyStore(),
+ actions,
+ );
+ assert.equal(adopted, false);
+ assert.deepEqual(calls, []);
+});
+
+test("an external-provider selection is left alone", () => {
+ // No local mirror, so the resident GGUF's settings would describe the wrong model.
+ const { calls, actions } = spies();
+ const adopted = adoptResidentModelStatus(
+ RESIDENT,
+ emptyStore({
+ checkpoint: "openai/gpt-5",
+ checkpointIsExternal: true,
+ }),
+ actions,
+ );
+ assert.equal(adopted, false);
+ assert.deepEqual(calls, []);
+});
+
+test("a load in flight is not fought", () => {
+ // The load applies its own status when it settles, and owns the params meanwhile.
+ const { calls, actions } = spies();
+ const adopted = adoptResidentModelStatus(
+ RESIDENT,
+ emptyStore({ modelLoading: true }),
+ actions,
+ );
+ assert.equal(adopted, false);
+ assert.deepEqual(calls, []);
+});
+
+test("an empty status drops the checkpoint when idle unload is disarmed", () => {
+ // Nothing will bring the model back, so it really is gone. Leaving the row resident would
+ // seed the settings editor from a launch config nothing is running.
+ const cleared: string[] = [];
+ const adopted = adoptResidentModelStatus(
+ { checkpointId: null, ggufVariant: null },
+ emptyStore({ checkpoint: "/models/llama.gguf", activeGgufVariant: "Q4_K_M" }),
+ {
+ ...refusing({
+ setCheckpoint: "nothing is resident, so nothing may be pinned",
+ applyStatus: "there is no status to apply",
+ }),
+ clearCheckpoint: () => {
+ cleared.push("cleared");
+ },
+ },
+ );
+ assert.equal(adopted, true);
+ assert.deepEqual(cleared, ["cleared"]);
+});
+
+test("an empty status leaves the checkpoint pinned while idle unload is armed", () => {
+ // An empty status is not the model going away: an idle unload frees it but keeps a stash the
+ // next request reloads, and /status cannot tell the two apart, so this must not clear it.
+ const adopted = adoptResidentModelStatus(
+ { checkpointId: null, ggufVariant: null },
+ emptyStore({
+ checkpoint: "/models/llama.gguf",
+ activeGgufVariant: "Q4_K_M",
+ idleUnloadArmed: true,
+ }),
+ refusing({
+ setCheckpoint: "nothing is resident, so nothing may be pinned",
+ clearCheckpoint: "the stash will reload exactly this model",
+ applyStatus: "there is no status to apply",
+ }),
+ );
+ assert.equal(adopted, false);
+});
+
+test("an empty status leaves an external pick alone", () => {
+ const adopted = adoptResidentModelStatus(
+ { checkpointId: null, ggufVariant: null },
+ emptyStore({
+ checkpoint: "gemini/gemini-2.5-pro",
+ checkpointIsExternal: true,
+ }),
+ refusing({
+ setCheckpoint: "an external pick is not a local model",
+ applyStatus: "the resident GGUF's status describes another model",
+ }),
+ );
+ assert.equal(adopted, false);
+});
+
+test("an empty status does not fight a load this tab started", () => {
+ const adopted = adoptResidentModelStatus(
+ { checkpointId: null, ggufVariant: null },
+ emptyStore({
+ checkpoint: "/models/llama.gguf",
+ modelLoading: true,
+ }),
+ refusing({ setCheckpoint: "the load owns the store until it settles" }),
+ );
+ assert.equal(adopted, false);
+});
+
+test("coming back to the window re-reads inference status", () => {
+ // An API request auto-switches at any time, and the Hub's only other read is its mount
+ // effect, so without this the catalog keeps describing the previous model.
+ const targets = fakeTargets();
+ let reads = 0;
+ subscribeResidentStatusRefresh(() => {
+ reads += 1;
+ }, targets);
+
+ assert.equal(reads, 0, "subscribing must not read on its own");
+ targets.fire("window", "focus");
+ assert.equal(reads, 1);
+ targets.fire("document", "visibilitychange");
+ assert.equal(reads, 2);
+});
+
+test("a tab going hidden does not read", () => {
+ // visibilitychange fires on the way out too, and a hidden tab has nothing to correct.
+ const targets = fakeTargets();
+ let reads = 0;
+ subscribeResidentStatusRefresh(() => {
+ reads += 1;
+ }, targets);
+
+ targets.hidden = true;
+ targets.fire("document", "visibilitychange");
+ assert.equal(reads, 0);
+
+ targets.hidden = false;
+ targets.fire("document", "visibilitychange");
+ assert.equal(reads, 1);
+});
+
+test("an auto-switch under a mounted Hub stops hiding the live config", () => {
+ // End to end: an API request swaps the resident model under a mounted Hub. Without a second
+ // read settingsTargetIsResident says it is not resident, so the editor seeds from saved
+ // values that Apply then reloads over the API's choice.
+ const store = emptyStore({
+ checkpoint: "unsloth/Qwen3-8B-GGUF",
+ activeGgufVariant: "Q4_K_M",
+ });
+ // What the server reports once the API request has switched it.
+ let serverStatus = {
+ checkpointId: "unsloth/Llama-3.1-8B-Instruct-GGUF",
+ ggufVariant: "Q8_0",
+ };
+ const readStatusAndAdopt = () => {
+ adoptResidentModelStatus(
+ serverStatus,
+ { ...store },
+ {
+ setCheckpoint: (checkpointId, ggufVariant) => {
+ store.checkpoint = checkpointId;
+ store.activeGgufVariant = ggufVariant;
+ },
+ applyStatus: () => undefined,
+ },
+ );
+ };
+
+ // hub-page.tsx's settingsTargetIsResident, for the model the API just loaded.
+ const settingsTargetIsResident = () =>
+ residentModelIdMatches(store.checkpoint, serverStatus.checkpointId) &&
+ ggufVariantsMatch(store.activeGgufVariant, serverStatus.ggufVariant);
+
+ const targets = fakeTargets();
+ subscribeResidentStatusRefresh(readStatusAndAdopt, targets);
+
+ assert.equal(
+ settingsTargetIsResident(),
+ false,
+ "precondition: the mount-time read predates the switch",
+ );
+ targets.fire("window", "focus");
+ assert.equal(settingsTargetIsResident(), true);
+
+ // A load this tab started owns the store until it settles, so a mid-switch refresh
+ // must not re-pin the model being moved away from.
+ store.modelLoading = true;
+ serverStatus = {
+ checkpointId: "unsloth/Qwen3-8B-GGUF",
+ ggufVariant: "Q4_K_M",
+ };
+ targets.fire("window", "focus");
+ assert.equal(store.checkpoint, "unsloth/Llama-3.1-8B-Instruct-GGUF");
+});
+
+test("unsubscribing stops the reads and leaves no listener behind", () => {
+ const targets = fakeTargets();
+ let reads = 0;
+ const unsubscribe = subscribeResidentStatusRefresh(() => {
+ reads += 1;
+ }, targets);
+
+ assert.equal(targets.listenerCount(), 2);
+ unsubscribe();
+ assert.equal(targets.listenerCount(), 0);
+ targets.fire("window", "focus");
+ targets.fire("document", "visibilitychange");
+ assert.equal(reads, 0);
+});
diff --git a/studio/frontend/tests/hub-superseded-refresh.test.ts b/studio/frontend/tests/hub-superseded-refresh.test.ts
new file mode 100644
index 00000000000..390d6334e6a
--- /dev/null
+++ b/studio/frontend/tests/hub-superseded-refresh.test.ts
@@ -0,0 +1,189 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ type RefreshSupersession,
+ registerRefresh,
+ supersedingRefresh,
+} from "../src/features/hub/lib/superseded-refresh.ts";
+
+interface Status {
+ checkpoint: string;
+ ggufVariant: string;
+}
+
+/** What the store holds before an API request switches the resident model under the tab. */
+const STALE: Status = {
+ checkpoint: "unsloth/Qwen3-8B-GGUF",
+ ggufVariant: "Q8_0",
+};
+/** What every read of /api/inference/status answers once the switch has landed. */
+const SWITCHED: Status = {
+ checkpoint: "unsloth/Llama-3.1-8B-Instruct-GGUF",
+ ggufVariant: "Q4_K_M",
+};
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+
+/** Let every pending microtask run, so "did not resolve" means it really has not. */
+const flush = () => new Promise((r) => setTimeout(r, 0));
+
+/**
+ * hub-page.tsx's refreshResidentModelStatus, with the status read held open so a test can
+ * choose the order responses land in. `coalesce` is the fix: whether a dropped response
+ * resolves with the refresh that superseded it or with nothing.
+ */
+function hubPageRefresh(coalesce: boolean) {
+ let seq = 0;
+ const supersession: RefreshSupersession = { latest: null };
+ const store: Status = { ...STALE };
+ const inFlight: Array<(status: Status) => void> = [];
+
+ const refresh = (): Promise<void> => {
+ const mine = ++seq;
+ const read = deferred<Status>();
+ inFlight.push(read.resolve);
+ const settled = read.promise
+ .then((status) => {
+ // hub-page.tsx:417, the drop: a newer read owns the store, so this writes nothing.
+ if (mine !== seq) {
+ return coalesce ? supersedingRefresh(supersession, mine) : undefined;
+ }
+ store.checkpoint = status.checkpoint;
+ store.ggufVariant = status.ggufVariant;
+ })
+ .catch(() => undefined);
+ if (coalesce) registerRefresh(supersession, mine, settled);
+ return settled;
+ };
+
+ return {
+ refresh,
+ store,
+ /** Deliver the status response for the nth refresh started. */
+ deliver: (n: number, status: Status = SWITCHED) => inFlight[n](status),
+ /** The unmount cleanup: invalidate everything in flight without starting a read. */
+ unmount: () => {
+ seq += 1;
+ },
+ };
+}
+
+/** Resolves to true only if `promise` settles before the microtask queue drains. */
+async function settledEarly(promise: Promise<void>): Promise<boolean> {
+ let done = false;
+ void promise.then(() => {
+ done = true;
+ });
+ await flush();
+ return done;
+}
+
+test("a settings open waits out the focus refresh that superseded its own read", async () => {
+ // openModelSettings awaits a status read before it resolves a quant and builds the settings
+ // target. A window focus refresh started while that read was out takes the sequence number,
+ // so the settings read's response is dropped without writing the store.
+ const hub = hubPageRefresh(true);
+ const settingsRead = hub.refresh();
+ hub.refresh();
+
+ hub.deliver(0);
+ assert.equal(
+ await settledEarly(settingsRead),
+ false,
+ "a dropped response must not release the settings open",
+ );
+ assert.deepEqual(
+ hub.store,
+ STALE,
+ "precondition: the dropped response wrote nothing, so the store is still pre-switch",
+ );
+
+ hub.deliver(1);
+ await settingsRead;
+ assert.deepEqual(hub.store, SWITCHED);
+});
+
+test("without it the dropped response opens settings on the displaced model", async () => {
+ // The failure this guards: the settings handler's own sequence guard only counts settings
+ // opens, so a focus refresh supersedes it silently and it proceeds on the pre-switch store,
+ // naming the displaced model's quant in a target that Apply then loads and saves under.
+ const hub = hubPageRefresh(false);
+ const settingsRead = hub.refresh();
+ hub.refresh();
+
+ hub.deliver(0);
+ assert.equal(await settledEarly(settingsRead), true);
+ assert.deepEqual(hub.store, STALE);
+});
+
+test("every dropped response in a chain waits for the one read that wins", async () => {
+ // Focus and visibilitychange fire as a pair, so more than one refresh can pile up behind
+ // the settings read, and each one in turn is dropped.
+ const hub = hubPageRefresh(true);
+ const settingsRead = hub.refresh();
+ hub.refresh();
+ hub.refresh();
+
+ hub.deliver(0);
+ hub.deliver(1);
+ assert.equal(await settledEarly(settingsRead), false);
+ assert.deepEqual(hub.store, STALE);
+
+ hub.deliver(2);
+ await settingsRead;
+ assert.deepEqual(hub.store, SWITCHED);
+});
+
+test("responses that land out of order still leave the store on the newest read", async () => {
+ const hub = hubPageRefresh(true);
+ const settingsRead = hub.refresh();
+ hub.refresh();
+
+ // The newest read answers first and writes the store; the older response is dropped and
+ // finds its superseder already settled.
+ hub.deliver(1);
+ hub.deliver(0);
+ await settingsRead;
+ assert.deepEqual(hub.store, SWITCHED);
+});
+
+test("an unmount strands nobody, since it bumps the sequence without starting a read", async () => {
+ // hub-page.tsx's cleanup only invalidates. The newest refresh is then its own superseder,
+ // and handing it its own promise would leave every caller waiting forever.
+ const hub = hubPageRefresh(true);
+ const read = hub.refresh();
+ hub.unmount();
+ hub.deliver(0);
+
+ const timeout = new Promise<"hung">((r) => setTimeout(() => r("hung"), 50));
+ assert.notEqual(
+ await Promise.race([read.then(() => "settled" as const), timeout]),
+ "hung",
+ );
+ assert.deepEqual(hub.store, STALE, "an unmounted Hub adopts nothing");
+});
+
+test("a superseder is only ever a strictly newer refresh", () => {
+ const supersession: RefreshSupersession = { latest: null };
+ assert.equal(supersedingRefresh(supersession, 1), undefined);
+
+ const settled = Promise.resolve();
+ registerRefresh(supersession, 2, settled);
+ assert.equal(supersedingRefresh(supersession, 1), settled);
+ assert.equal(
+ supersedingRefresh(supersession, 2),
+ undefined,
+ "a refresh may not be handed its own promise",
+ );
+ assert.equal(supersedingRefresh(supersession, 3), undefined);
+});
diff --git a/studio/frontend/tests/model-config-instance-key.test.ts b/studio/frontend/tests/model-config-instance-key.test.ts
new file mode 100644
index 00000000000..f8d12a646b9
--- /dev/null
+++ b/studio/frontend/tests/model-config-instance-key.test.ts
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { modelConfigInstanceKey } from "../src/features/model-picker/model-config/config-signature.ts";
+import type { PerModelConfig } from "../src/features/model-picker/model-config/per-model-config.ts";
+
+const MODEL = "unsloth/Qwen3-8B-GGUF";
+const VARIANT = "Q4_K_M";
+
+// What the model is actually running with, as useActiveModelConfig reports it.
+const LIVE: PerModelConfig = {
+ customContextLength: 16384,
+ maxSeqLength: null,
+ kvCacheDtype: "q8_0",
+ speculativeType: "ngram",
+ specDraftNMax: 6,
+ nParallel: 4,
+ tensorParallel: true,
+ chatTemplateOverride: null,
+ gpuMemoryMode: "manual",
+ gpuLayers: 24,
+ nCpuMoe: 3,
+ selectedGpuIds: [0, 1],
+};
+
+// What ModelConfigPage would fall back to before the live config lands.
+const SAVED: PerModelConfig = {
+ customContextLength: null,
+ maxSeqLength: null,
+ kvCacheDtype: null,
+ speculativeType: "auto",
+ specDraftNMax: null,
+ nParallel: null,
+ tensorParallel: false,
+ chatTemplateOverride: null,
+ gpuMemoryMode: "auto",
+ gpuLayers: -1,
+ nCpuMoe: 0,
+ selectedGpuIds: null,
+};
+
+/**
+ * ModelConfigPage reads `loadedConfig` in a useState initializer, so it seeds once per
+ * MOUNTED instance, and React keeps that instance while the key is unchanged.
+ */
+function renderEditor(
+ previous: { key: string; editing: PerModelConfig } | null,
+ key: string,
+ loadedConfig: PerModelConfig | null,
+): { key: string; editing: PerModelConfig } {
+ if (previous && previous.key === key) {
+ return previous;
+ }
+ return { key, editing: loadedConfig ?? SAVED };
+}
+
+test("the settings editor re-seeds when the live config arrives after mount", () => {
+ // Opened before status answered: loadedConfig is null first and live on the next render.
+ let editor = renderEditor(
+ null,
+ modelConfigInstanceKey(MODEL, VARIANT, null),
+ null,
+ );
+ assert.deepEqual(editor.editing, SAVED);
+
+ editor = renderEditor(
+ editor,
+ modelConfigInstanceKey(MODEL, VARIANT, LIVE),
+ LIVE,
+ );
+ // Without the live config in the key the editor would still hold SAVED, and Apply
+ // would reload the model over what it is running with.
+ assert.deepEqual(editor.editing, LIVE);
+});
+
+test("a repeated status poll keeps the same editor instance", () => {
+ const first = renderEditor(
+ null,
+ modelConfigInstanceKey(MODEL, VARIANT, LIVE),
+ LIVE,
+ );
+ // An equal config from the next poll must not remount and discard what was typed.
+ const again = renderEditor(
+ first,
+ modelConfigInstanceKey(MODEL, VARIANT, { ...LIVE }),
+ LIVE,
+ );
+ assert.equal(again, first);
+});
+
+test("every mirrored setting moves the instance key", () => {
+ const base = modelConfigInstanceKey(MODEL, VARIANT, LIVE);
+ const changes: PerModelConfig[] = [
+ { ...LIVE, customContextLength: 8192 },
+ { ...LIVE, maxSeqLength: 4096 },
+ { ...LIVE, kvCacheDtype: "f16" },
+ { ...LIVE, speculativeType: "off" },
+ { ...LIVE, specDraftNMax: 4 },
+ { ...LIVE, nParallel: 1 },
+ { ...LIVE, tensorParallel: false },
+ { ...LIVE, chatTemplateOverride: "{{ bos_token }}" },
+ { ...LIVE, gpuMemoryMode: "auto" },
+ { ...LIVE, gpuLayers: 20 },
+ { ...LIVE, nCpuMoe: 0 },
+ { ...LIVE, selectedGpuIds: [0] },
+ ];
+ for (const changed of changes) {
+ assert.notEqual(modelConfigInstanceKey(MODEL, VARIANT, changed), base);
+ }
+ // The GPU pick is a set, not an order.
+ assert.equal(
+ modelConfigInstanceKey(MODEL, VARIANT, { ...LIVE, selectedGpuIds: [1, 0] }),
+ base,
+ );
+});
+
+test("the model and its quant still key the editor", () => {
+ const base = modelConfigInstanceKey(MODEL, VARIANT, LIVE);
+ assert.notEqual(modelConfigInstanceKey("unsloth/Other-GGUF", VARIANT, LIVE), base);
+ assert.notEqual(modelConfigInstanceKey(MODEL, "Q8_0", LIVE), base);
+ // A loose .gguf carries no quant; null and undefined are the same absence.
+ assert.equal(
+ modelConfigInstanceKey(MODEL, null, LIVE),
+ modelConfigInstanceKey(MODEL, undefined, LIVE),
+ );
+});
diff --git a/studio/frontend/tests/model-identity.test.ts b/studio/frontend/tests/model-identity.test.ts
new file mode 100644
index 00000000000..80fd3efedbe
--- /dev/null
+++ b/studio/frontend/tests/model-identity.test.ts
@@ -0,0 +1,360 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { settingsGgufVariantForRow } from "../src/features/hub/inventory/settings-identity.ts";
+import type {
+ CachedInventoryRow,
+ LocalInventoryRow,
+} from "../src/features/hub/inventory/types.ts";
+import {
+ isOllamaLinkPath,
+ isStandaloneGgufPath,
+ modelIdsMatch,
+ publicModelId,
+ residentModelIdMatches,
+} from "../src/features/hub/lib/model-identity.ts";
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store, storage } = installLocalStorageFake();
+
+const REPO_KEY = 'v2:["unsloth/repo-gguf","q4_k_m"]';
+
+// The legacy import runs once on the first read, so it must be staged before the import.
+store.set(
+ "unsloth_model_configs",
+ JSON.stringify({ [REPO_KEY]: { version: 1, maxSeqLength: 32768 } }),
+);
+store.set(
+ "unsloth_load_settings",
+ JSON.stringify({ "Unsloth/Repo-GGUF::Q4_K_M": { contextLength: 8192 } }),
+);
+
+const { listPerModelConfigs, resolveInitialConfig, savePerModelConfig } =
+ await import("../src/features/model-picker/model-config/per-model-config.ts");
+const { modelStorageKey, splitQuantSuffix } = await import(
+ "../src/features/model-picker/model-config/model-identity.ts"
+);
+
+function config(maxSeqLength: number, kvCacheDtype: string | null = null) {
+ return {
+ customContextLength: null,
+ maxSeqLength,
+ kvCacheDtype,
+ speculativeType: null,
+ specDraftNMax: null,
+ nParallel: null,
+ tensorParallel: false,
+ chatTemplateOverride: null,
+ };
+}
+
+function storedKeys(): string[] {
+ return Object.keys(
+ JSON.parse(storage.getItem("unsloth_model_configs") ?? "{}"),
+ );
+}
+
+test("publicModelId mirrors what /status reports for a path-loaded model", () => {
+ // Mirrors public_model_id in studio/backend/core/inference/model_ids.py.
+ assert.equal(
+ publicModelId("/srv/models/Qwen3-8B-Q4_K_M.gguf"),
+ "Qwen3-8B-Q4_K_M",
+ );
+ assert.equal(
+ publicModelId(
+ "/home/u/.cache/huggingface/hub/models--unsloth--Qwen3-8B-GGUF/snapshots/abc123",
+ ),
+ "unsloth/Qwen3-8B-GGUF",
+ );
+ assert.equal(publicModelId("C:\\models\\Foo-Q4_K_M.gguf"), "Foo-Q4_K_M");
+ assert.equal(publicModelId("~/models/Foo.gguf"), "Foo");
+ assert.equal(publicModelId("/srv/models/repo/"), "repo");
+ // A repo id and an already-clean name come back untouched.
+ assert.equal(publicModelId("unsloth/Qwen3-8B-GGUF"), "unsloth/Qwen3-8B-GGUF");
+ assert.equal(publicModelId("Qwen3-8B-Q4_K_M"), "Qwen3-8B-Q4_K_M");
+ // "models--" alone is not the cache layout; only the snapshots sibling is.
+ assert.equal(publicModelId("models--only--nosnapshots/blobs/x"), "x");
+});
+
+test("a resident path-loaded model is matched by the id /status reports", () => {
+ // A loose .gguf: the row is keyed by path and the Hub records the loadable
+ // identifier, so the literal pass answers.
+ assert.equal(
+ modelIdsMatch("Qwen3-8B-Q4_K_M", "/srv/models/Qwen3-8B-Q4_K_M.gguf"),
+ false,
+ );
+ assert.equal(
+ residentModelIdMatches(
+ "/srv/models/Qwen3-8B-Q4_K_M.gguf",
+ "/srv/models/Qwen3-8B-Q4_K_M.gguf",
+ "/srv/models/Qwen3-8B-Q4_K_M.gguf",
+ ),
+ true,
+ );
+ // A repo in an inactive cache keeps the repo id as its settings identity.
+ assert.equal(
+ residentModelIdMatches(
+ "unsloth/Qwen3-8B-GGUF",
+ "/mnt/old-cache/models--unsloth--Qwen3-8B-GGUF/snapshots/abc123",
+ "unsloth/Qwen3-8B-GGUF",
+ ),
+ true,
+ );
+ // The raw identifier is still matched literally.
+ assert.equal(
+ residentModelIdMatches(
+ "/srv/models/Qwen3-8B-Q4_K_M.gguf",
+ "/srv/models/Qwen3-8B-Q4_K_M.gguf",
+ null,
+ ),
+ true,
+ );
+ // Another model is still not the loaded one.
+ assert.equal(
+ residentModelIdMatches(
+ "Qwen3-8B-Q4_K_M",
+ "/srv/models/Llama-3-8B-Q4_K_M.gguf",
+ null,
+ ),
+ false,
+ );
+ assert.equal(
+ residentModelIdMatches(
+ "unsloth/Qwen3-8B-GGUF",
+ "/mnt/old-cache/models--unsloth--Llama-3-GGUF/snapshots/abc123",
+ "unsloth/Llama-3-GGUF",
+ ),
+ false,
+ );
+ assert.equal(residentModelIdMatches(null, "/srv/models/x.gguf"), false);
+ assert.equal(residentModelIdMatches("Qwen3-8B-Q4_K_M"), false);
+});
+
+test("a shared filename or folder name never marks a row resident", () => {
+ // Same filename in two folders collapses onto one public id, so a stem cannot say which.
+ const loaded = "/srv/models/alpha/model.gguf";
+ const other = "/srv/models/beta/model.gguf";
+ assert.equal(publicModelId(loaded), publicModelId(other));
+ assert.equal(residentModelIdMatches(publicModelId(loaded), other, other), false);
+ // The loadable identifier names exactly one of them.
+ assert.equal(residentModelIdMatches(loaded, loaded, loaded), true);
+ assert.equal(residentModelIdMatches(loaded, other, other), false);
+
+ // Same collapse one level up: two model directories sharing a basename.
+ const loadedDir = "/srv/lmstudio/publisher-a/Llama-3-8B-GGUF";
+ const otherDir = "/srv/models/publisher-b/Llama-3-8B-GGUF";
+ assert.equal(publicModelId(loadedDir), publicModelId(otherDir));
+ assert.equal(
+ residentModelIdMatches(publicModelId(loadedDir), otherDir, otherDir),
+ false,
+ );
+
+ // A cache snapshot still collapses onto its repo id, which names one model.
+ assert.equal(
+ residentModelIdMatches(
+ "unsloth/Qwen3-8B-GGUF",
+ "/mnt/old-cache/models--unsloth--Qwen3-8B-GGUF/snapshots/abc123",
+ null,
+ ),
+ true,
+ );
+});
+
+test("Ollama link paths are recognised the way the resolver excludes them", () => {
+ // core/inference/local_model_resolver.py refuses any path with these segments.
+ assert.equal(
+ isOllamaLinkPath("/home/u/.ollama/models/.studio_links/q/qwen3-Q4_K_M.gguf"),
+ true,
+ );
+ assert.equal(
+ isOllamaLinkPath("/home/u/.cache/unsloth/ollama_links/ab12/llama3.gguf"),
+ true,
+ );
+ assert.equal(
+ isOllamaLinkPath("C:\\Users\\u\\.ollama\\models\\.studio_links\\q\\a.gguf"),
+ true,
+ );
+ // Only those exact segments, not a directory that merely contains the name.
+ assert.equal(isOllamaLinkPath("/srv/studio_links_backup/a.gguf"), false);
+ assert.equal(isOllamaLinkPath("/srv/models/Qwen3-8B-Q4_K_M.gguf"), false);
+ assert.equal(isOllamaLinkPath("unsloth/Qwen3-8B-GGUF"), false);
+ assert.equal(isOllamaLinkPath(null), false);
+});
+
+test("a standalone gguf keeps one settings identity across surfaces", () => {
+ const loose = {
+ kind: "local",
+ path: "/srv/models/Qwen3-8B-Q4_K_M.gguf",
+ // What hub/services/models/common.py emits for a single scanned file.
+ formatVariant: "Q4_K_M",
+ } as LocalInventoryRow;
+ // The Chat picker opens the same file with no variant, so adopting the filename
+ // label would leave the two editing different configs.
+ assert.equal(settingsGgufVariantForRow(loose), null);
+
+ // A GGUF directory still has a variant slot for the quant lookup to fill.
+ const repoDir = {
+ kind: "local",
+ path: "/srv/models/Qwen3-8B-GGUF",
+ formatVariant: null,
+ } as LocalInventoryRow;
+ assert.equal(settingsGgufVariantForRow(repoDir), null);
+ const lmStudioDir = {
+ kind: "local",
+ path: "/srv/lmstudio/Qwen3-8B-GGUF",
+ formatVariant: "Q8_0",
+ } as LocalInventoryRow;
+ assert.equal(settingsGgufVariantForRow(lmStudioDir), "Q8_0");
+
+ // Cached repo rows are unaffected (cache_inventory.py never sets one).
+ const cached = { kind: "cache", formatVariant: null } as CachedInventoryRow;
+ assert.equal(settingsGgufVariantForRow(cached), null);
+});
+
+// The backfill matches on the folded identity, which is only unambiguous because storage
+// holds one record per model. These pin that rule rather than the backfill.
+test("importing the legacy load settings never doubles up a model", () => {
+ // The legacy casing names the model the v2 record already holds, so the import must
+ // leave it alone rather than add a second record.
+ assert.deepEqual(listPerModelConfigs().length, 1);
+ assert.deepEqual(storedKeys(), [REPO_KEY]);
+ assert.equal(
+ resolveInitialConfig("unsloth/repo-gguf", "q4_k_m").config
+ .customContextLength,
+ null,
+ );
+});
+
+test("two spellings of one model id keep a single stored record", () => {
+ store.clear();
+ savePerModelConfig("Unsloth/Repo-GGUF", "Q4_K_M", config(4096));
+ savePerModelConfig("unsloth/repo-gguf", "q4_k_m", config(32768, "q8_0"));
+
+ assert.deepEqual(storedKeys(), [REPO_KEY]);
+ const listed = listPerModelConfigs();
+ assert.equal(listed.length, 1);
+ assert.equal(listed[0]?.config.maxSeqLength, 32768);
+ // What the picker applies and the only thing the backfill can see agree.
+ assert.equal(
+ resolveInitialConfig("Unsloth/Repo-GGUF", "Q4_K_M").config.maxSeqLength,
+ 32768,
+ );
+});
+
+test("two spellings of one Windows path keep a single stored record", () => {
+ store.clear();
+ savePerModelConfig("C:\\Models\\Foo.gguf", null, config(4096));
+ savePerModelConfig("c:/models/foo.gguf", null, config(32768, "q8_0"));
+
+ assert.deepEqual(storedKeys(), ['v2:["c:/models/foo.gguf",""]']);
+ assert.equal(listPerModelConfigs().length, 1);
+});
+
+test("a POSIX path is case sensitive, so its two spellings stay separate", () => {
+ store.clear();
+ savePerModelConfig("/models/Foo.gguf", null, config(4096));
+ savePerModelConfig("/models/foo.gguf", null, config(32768, "q8_0"));
+
+ assert.equal(storedKeys().length, 2);
+ assert.equal(
+ resolveInitialConfig("/models/Foo.gguf", null).config.maxSeqLength,
+ 4096,
+ );
+});
+
+// Every answer below is the one the backend's split_quant_suffix gives. The backfill folds a
+// stored key with this before comparing, so a disagreement collapses two models onto one key.
+const CASES: [string, [string, string] | null][] = [
+ // A known quant label, with and without the optional bpw modifier.
+ ["org/Repo-GGUF:Q4_K_M", ["org/Repo-GGUF", "Q4_K_M"]],
+ ["org/Repo-GGUF:IQ4_XS-3.53bpw", ["org/Repo-GGUF", "IQ4_XS-3.53bpw"]],
+ ["org/Repo-GGUF:UD-Q4_K_XL", ["org/Repo-GGUF", "UD-Q4_K_XL"]],
+ // A .gguf with no quant token is labelled by its stem, lowercased in storage while
+ // the scanner keeps the filename's casing.
+ ["/models/CustomModel.gguf:custommodel", ["/models/CustomModel.gguf", "custommodel"]],
+ ["/models/CustomModel.gguf:CustomModel", ["/models/CustomModel.gguf", "CustomModel"]],
+ ["C:\\models\\CustomModel.gguf:custommodel", ["C:\\models\\CustomModel.gguf", "custommodel"]],
+ // A shard suffix is not part of the label.
+ [
+ "/models/Custom-00001-of-00003.gguf:custom",
+ ["/models/Custom-00001-of-00003.gguf", "custom"],
+ ],
+ ["/models/Custom-00001-of-00003.gguf:custom-00001-of-00003", null],
+ // An extensionless .gguf still has a label.
+ ["/models/.gguf:gguf", ["/models/.gguf", "gguf"]],
+ // A quant token inside the filename wins over the stem.
+ ["/models/tinyllama-Q4_K_M.gguf:q4_k_m", ["/models/tinyllama-Q4_K_M.gguf", "q4_k_m"]],
+ ["/models/tinyllama-Q4_K_M.gguf:tinyllama-q4_k_m", null],
+ // Only the basename is labelled, never the directories above it.
+ [
+ "/models/dir/CustomModel.gguf:custommodel",
+ ["/models/dir/CustomModel.gguf", "custommodel"],
+ ],
+ ["/models/dir/CustomModel.gguf:dir/custommodel", null],
+ // A colon is legal in a POSIX filename: reading it as a variant folds two real files.
+ ["/models/foo:Bar.gguf", null],
+ ["/models/foo:bar.gguf", null],
+ ["/models/llama.gguf:Bar.gguf", null],
+ ["/models/llama.gguf:bar.gguf", null],
+ ["/models/CustomModel.gguf:othermodel", null],
+ ["/models/model.gguf:notalabel", null],
+ ["/models/plain.gguf:plain:extra", null],
+ // A Windows drive letter is not a separator either.
+ ["C:\\models\\foo.gguf", null],
+ ["C:/models/foo.gguf", null],
+ // Nothing to split.
+ ["org/Repo-GGUF", null],
+ ["/models/foo.gguf", null],
+ ["org/Repo:", null],
+ [":Q4_K_M", null],
+];
+
+test("splitQuantSuffix answers exactly as the backend's split_quant_suffix", () => {
+ for (const [value, expected] of CASES) {
+ assert.deepEqual(splitQuantSuffix(value), expected, value);
+ }
+});
+
+test("a .gguf filename carrying a colon is not folded into a variant", () => {
+ // Two real, distinct files: POSIX allows a colon and is case sensitive. The variant
+ // half of a key is stored lowercased, so folding these strands one file's settings.
+ const upper = "/models/llama.gguf:Bar.gguf";
+ const lower = "/models/llama.gguf:bar.gguf";
+ assert.equal(splitQuantSuffix(upper), null);
+ assert.equal(splitQuantSuffix(lower), null);
+ assert.notEqual(modelStorageKey(upper, null), modelStorageKey(lower, null));
+});
+
+// Repo ids ending in .gguf are real on the Hub, an iMat repo among them, and those hold every
+// quant. Reading one as a single file drops the variant, so Q4 and Q8 save under one key.
+const STANDALONE_GGUF_CASES: [string, boolean][] = [
+ ["/models/llama.gguf", true],
+ ["/mnt/c/models/llama.gguf", true],
+ ["C:\\models\\llama.gguf", true],
+ ["\\\\server\\share\\llama.gguf", true],
+ ["./models/llama.gguf", true],
+ ["~/models/llama.gguf", true],
+ // A dropped or picked file, which /status echoes back by bare name.
+ ["llama.gguf", true],
+ // Repo ids: one separator, no anchor. These are repos, not files.
+ ["lex-au/Orpheus-3b-FT-Q8_0.gguf", false],
+ ["NexesQuants/TeeZee_Kyllene-Yi-34B-v1.1-iMat.GGUF", false],
+ ["Joshua65535/qwen2.5-1.5b-instruct-q4_k_m.gguf", false],
+ ["unsloth/Qwen3-8B-GGUF", false],
+ ["", false],
+];
+
+test("only a file on this machine counts as a standalone gguf", () => {
+ for (const [modelId, expected] of STANDALONE_GGUF_CASES) {
+ assert.equal(isStandaloneGgufPath(modelId), expected, modelId);
+ }
+ assert.equal(isStandaloneGgufPath(null), false);
+ assert.equal(isStandaloneGgufPath(undefined), false);
+});
diff --git a/studio/frontend/tests/resident-remembered-config.test.ts b/studio/frontend/tests/resident-remembered-config.test.ts
new file mode 100644
index 00000000000..e534ef1372f
--- /dev/null
+++ b/studio/frontend/tests/resident-remembered-config.test.ts
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const {
+ resolveInitialConfig,
+ resolveResidentInitialConfig,
+ savePerModelConfig,
+} = await import(
+ "../src/features/model-picker/model-config/per-model-config.ts"
+);
+
+// What /api/inference/status reports as model_identifier after an API auto-switch: the concrete
+// snapshot path the resolver index handed the loader. The repo id is what the Hub keys this
+// model's settings by (modelConfigIdentity) and what status.active_model reports.
+const SNAPSHOT_PATH =
+ "/home/u/.cache/huggingface/hub/models--unsloth--Repo-GGUF/snapshots/2f1c9ab";
+const REPO_ID = "unsloth/Repo-GGUF";
+
+function config(nParallel: number | null, maxSeqLength: number | null = null) {
+ return {
+ customContextLength: null,
+ maxSeqLength,
+ kvCacheDtype: null,
+ speculativeType: null,
+ specDraftNMax: null,
+ nParallel,
+ tensorParallel: false,
+ chatTemplateOverride: null,
+ };
+}
+
+test("the resident model's repo-keyed slots are found through its snapshot path", () => {
+ store.clear();
+ savePerModelConfig(REPO_ID, "Q4_K_M", config(4));
+
+ // The plain lookup is what status adoption used to do, and it misses.
+ assert.equal(resolveInitialConfig(SNAPSHOT_PATH, "Q4_K_M").remembered, false);
+
+ const resolved = resolveResidentInitialConfig(SNAPSHOT_PATH, "Q4_K_M");
+ assert.equal(resolved.remembered, true);
+ // Without this the control blanks on the model change and the next save writes the
+ // blank back over the saved record (locally and through the server mirror).
+ assert.equal(resolved.config.nParallel, 4);
+});
+
+test("a record under the raw identifier still wins over the repo alias", () => {
+ store.clear();
+ savePerModelConfig(SNAPSHOT_PATH, "Q4_K_M", config(2));
+ savePerModelConfig(REPO_ID, "Q4_K_M", config(8));
+
+ assert.equal(
+ resolveResidentInitialConfig(SNAPSHOT_PATH, "Q4_K_M").config.nParallel,
+ 2,
+ );
+});
+
+test("the quant still separates two variants of one cached repo", () => {
+ store.clear();
+ savePerModelConfig(REPO_ID, "Q4_K_M", config(4));
+
+ assert.equal(
+ resolveResidentInitialConfig(SNAPSHOT_PATH, "Q8_0").remembered,
+ false,
+ );
+});
+
+test("a stem two models can share is never read as an alias", () => {
+ store.clear();
+ // A standalone GGUF is keyed by its own path; "Repo-Q4_K_M" is the stem both of these
+ // files collapse onto, so adopting it would apply one file's settings to the other.
+ savePerModelConfig("Repo-Q4_K_M", null, config(4));
+
+ assert.equal(
+ resolveResidentInitialConfig("/srv/models/a/Repo-Q4_K_M.gguf", null)
+ .remembered,
+ false,
+ );
+ assert.equal(
+ resolveResidentInitialConfig("/srv/models/b/Repo-Q4_K_M.gguf", null)
+ .remembered,
+ false,
+ );
+});
+
+test("a repo id resolves exactly as before", () => {
+ store.clear();
+ savePerModelConfig(REPO_ID, "Q4_K_M", config(4));
+
+ assert.equal(
+ resolveResidentInitialConfig(REPO_ID, "Q4_K_M").config.nParallel,
+ 4,
+ );
+ assert.equal(
+ resolveResidentInitialConfig("unsloth/Other-GGUF", "Q4_K_M").remembered,
+ false,
+ );
+});
diff --git a/studio/frontend/tsconfig.test.json b/studio/frontend/tsconfig.test.json
index da6cdcc9ba1..be53907fc7f 100644
--- a/studio/frontend/tsconfig.test.json
+++ b/studio/frontend/tsconfig.test.json
@@ -3,7 +3,9 @@
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
- "types": ["node"],
+ // vite/client so a test may import a src module that (transitively) reads
+ // import.meta.env; without it those reads fail to typecheck here only.
+ "types": ["node", "vite/client"],
"skipLibCheck": true,
"moduleResolution": "bundler",
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index f13e3e0e1e1..0af3017a1fd 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -190,9 +190,9 @@ def test_diffusion_capability_labeled_image_generation():
def test_active_model_config_round_trips_gpu_fields():
- """The active model's config must carry the GPU Memory knobs (GGUF only) so
- a sidebar/hub-gear reload cannot silently reset manual GPU settings, and
- "Remember settings" cannot persist a GPU-less config over a saved one."""
+ """The active model's config must carry the GPU Memory knobs (GGUF only) so a
+ sidebar/hub-gear reload cannot silently reset manual GPU settings, and "Remember
+ settings" cannot persist a GPU-less config over a saved one."""
src = _read("features/model-picker/hooks/use-active-model-config.ts")
for field in (
"gpuMemoryMode",
@@ -208,10 +208,19 @@ def test_active_model_config_round_trips_gpu_fields():
"features/hub/catalog/sampling-settings-dialog.tsx",
):
assert "useActiveModelConfig(" in _read(rel), rel
- signature = _read("features/model-picker/components/sidebar-model-config.tsx")
- assert "gpuFieldsSignature(config)" in signature
- shared = _read("features/model-picker/model-config/apply-per-model-config.ts")
+ # The GPU knobs are in the editor's instance key, so a reload re-seeds instead of keeping.
+ shared = _read("features/model-picker/model-config/config-signature.ts")
assert "export function gpuFieldsSignature" in shared
+ assert "gpuFieldsSignature(config)," in shared
+ assert "export function modelConfigInstanceKey" in shared
+ for rel in (
+ "features/model-picker/components/sidebar-model-config.tsx",
+ "features/hub/catalog/hub-model-settings-view.tsx",
+ ):
+ assert "modelConfigInstanceKey(" in _read(rel), rel
+ # apply-per-model-config re-exports it, so its own callers are unchanged.
+ reexport = _read("features/model-picker/model-config/apply-per-model-config.ts")
+ assert "export { gpuFieldsSignature };" in reexport
def test_deferred_gpu_pick_keeps_its_index_namespace():
@@ -222,8 +231,11 @@ def test_deferred_gpu_pick_keeps_its_index_namespace():
apply = _read("features/model-picker/model-config/apply-per-model-config.ts")
assert "selectedGpuIndexKind: s.selectedGpuIndexKind" in apply
- assert "config.selectedGpuIndexKind === undefined" in apply
- assert 'config.selectedGpuIndexKind ?? "physical"' not in apply
+ # gpuFieldsSignature moved to config-signature.ts so the editor's instance key can
+ # read it without importing the runtime applier; the namespace rule moved with it.
+ signature = _read("features/model-picker/model-config/config-signature.ts")
+ assert "config.selectedGpuIndexKind === undefined" in signature
+ assert 'config.selectedGpuIndexKind ?? "physical"' not in signature
runtime = _read("features/chat/hooks/use-chat-model-runtime.ts")
assert "stateBeforeUnload.selectedGpuIndexKind," in runtime
@@ -351,10 +363,7 @@ def test_variant_expander_refreshes_after_delete():
def test_local_picker_rows_require_chat_capability():
- """Local inventory rows can be classified non-chat (canChat false, e.g. a
- folder with only config.json). The picker must filter those out, or selecting
- one loads a weightless path; toLocalModelInfo drops capabilities so the memo
- is the only place the guard can live."""
+ """Local inventory rows can be classified non-chat (canChat false, e.g."""
src = _read("features/model-picker/inventory/use-chat-picker-inventory.ts")
memo = re.search(r"const localModels = useMemo\(.*?\[inventory\.localRows\]", src, re.S)
assert memo, "localModels memo not found"
@@ -380,12 +389,10 @@ def test_model_picker_toolbar_reflows_before_crossing_picker_edge():
def test_native_picked_gguf_template_read_through_lease():
- """A native (picked / drag-drop) GGUF's path lives only in its signed lease,
- and the picker chat-template GET has no lease plumbing, so the default
- template must be read through the lease-aware validate probe: mint a
- validate-model lease and post include_chat_template. The native token also
- has to reach the fetch (threaded through the hook) and be part of the cache
- key so two picks of the same basename don't share a template."""
+ """A native (picked / drag-drop) GGUF's path lives only in its signed lease, and the
+ picker chat-template GET has no lease plumbing, so the default template must be read
+ through the lease-aware validate probe: mint a validate-model lease and post
+ include_chat_template."""
api = _read("features/model-picker/api/templates.ts")
assert 'consumeNativePathToken(nativePathToken, "validate-model")' in api
assert "include_chat_template: true" in api
@@ -408,23 +415,17 @@ def test_model_load_guard_is_cross_instance():
def test_partial_safetensors_download_keeps_delete_menu():
- """A stopped partial safetensors download must keep its options menu (the
- Delete affordance) like the GGUF card does, or partial downloads can only
- be cleaned up by finishing or leaving them. During an ACTIVE download the
- menu stays hidden (every item would be disabled: no Copy path while not
- downloaded, no Delete while downloading, pin suppressed in the run bar)."""
+ """A stopped partial safetensors download must keep its options menu (the Delete
+ affordance) like the GGUF card does, or partial downloads can only be cleaned up by
+ finishing or leaving them."""
src = _read("features/hub/catalog/safetensors-download-card.tsx")
assert "(isDownloaded || (isPartial && !downloading))" in src
def test_pinned_validation_uses_cached_local_variant_listing():
- """Pinned-quant validation must use the TTL-cached hub client with
- preferLocalCache (downloaded-ness is local state) instead of one uncached
- round-trip per pinned repo on every picker open. Picker deletes must go
- through the hub inventory client, whose delete invalidates both the
- variants TTL cache and the server-side HF cache scan (the legacy
- /api/models/delete-cached route invalidates neither, so a post-delete
- inventory refresh would resurrect the deleted row until the scan TTL)."""
+ """Pinned-quant validation must use the TTL-cached hub client with preferLocalCache
+ (downloaded-ness is local state) instead of one uncached round-trip per pinned repo
+ on every picker open."""
src = _read("features/model-picker/components/model-selector/pickers.tsx")
assert "listGgufVariantsCached(" in src
assert "preferLocalCache: true" in src
@@ -546,11 +547,8 @@ def test_fixed_layer_gguf_pins_displayed_context():
def test_fixed_layer_pin_recomputed_after_committing_gpu_layers():
- """pinFixedLayerContext is computed from the render-time config, before a
- same-click GPU Layers draft is committed. handleRun must recompute it from the
- committed effectiveConfig; otherwise typing a positive GPU Layers value on an
- auto-fit GGUF and clicking Reload saves customContextLength: null, so a later
- fresh load sends the native context with fixed layers (the OOM the pin avoids)."""
+ """pinFixedLayerContext is computed from the render-time config, before a same-click
+ GPU Layers draft is committed."""
src = _read("features/model-picker/components/model-config-page.tsx")
assert "const effectivePinFixedLayerContext =" in src
assert 'effectiveConfig.gpuMemoryMode === "manual"' in src
@@ -561,11 +559,7 @@ def test_fixed_layer_pin_recomputed_after_committing_gpu_layers():
def test_blur_cache_cleared_on_every_settled_render():
"""The lastBlurCommittedRef bridge is valid only across the single synchronous
- same-click gesture that set it. Keying its clear on [value] missed a Reset (or
- external edit) that restores the shown value unchanged after the blur dispatched
- onChange: value nets back to its prior number, the effect never re-ran, and a
- later Load/Save replayed the override Reset removed. Clear it on every settled
- render instead."""
+ same-click gesture that set it."""
src = _read("features/model-picker/components/numeric-value-input.tsx")
# The clearing effect must run on every commit, not be gated on [value] alone.
assert not re.search(r"lastBlurCommittedRef\.current = null;\s*\}, \[value\]\);", src)
@@ -659,11 +653,8 @@ def test_initial_load_uses_staged_config_payload():
def test_same_click_commit_covers_all_numeric_inputs():
- """The same-click blur bridge must flush every NumericValueInput-backed
- setting, not just Context Length. Max Seq Length (non-GGUF), GPU Layers and
- MoE Layers (GGUF) also stage their draft only on blur, so handleRun must
- imperatively commit each and fold the value into the staged load config;
- otherwise a value the user typed right before clicking Load/Reload is lost."""
+ """The same-click blur bridge must flush every NumericValueInput-backed setting, not
+ just Context Length."""
page = _read("features/model-picker/components/model-config-page.tsx")
# Each numeric input owns an imperative handle that handleRun commits, and the
# handle is forwarded down to the actual NumericValueInput.
@@ -696,10 +687,8 @@ def test_context_commit_rechecks_persistence_only_shortcut():
def test_reset_enabled_for_explicit_context_pin_at_native():
- """An explicit customContextLength that equals the native ceiling is still a
- user override, so contextAtDefault must require customContextLength == null.
- The buggy form treated `contextValue === native` alone as default, wedging
- the Reset button disabled for a deliberate pin-to-native."""
+ """An explicit customContextLength that equals the native ceiling is still a user
+ override, so contextAtDefault must require customContextLength == null."""
src = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())
assert (
"const contextAtDefault = !target.isGguf || "
@@ -882,13 +871,10 @@ def test_diffusion_picker_hides_and_clears_unsupported_memory_modes():
def test_legacy_migration_is_idempotent_and_non_destructive():
- """The v1->v2 localStorage migration (unsloth_load_settings ->
- unsloth_model_configs) is invoked on every store read, so it must be
- idempotent: repeated reads, browser reloads, and Studio restarts must never
- re-migrate, duplicate records, or overwrite a newer per-model config. This
- was the class of regression that reverted the predecessor PR, so pin all
- three idempotency layers at source level; dropping any of them reddens here.
- """
+ """The v1->v2 localStorage migration (unsloth_load_settings -> unsloth_model_configs)
+ is invoked on every store read, so it must be idempotent: repeated reads, browser
+ reloads, and Studio restarts must never re-migrate, duplicate records, or overwrite
+ a newer per-model config."""
raw = _read("features/model-picker/model-config/per-model-config.ts")
src = " ".join(raw.split())
# Migration runs from readMap (every store read), so it must be safe to repeat.
@@ -901,10 +887,7 @@ def test_legacy_migration_is_idempotent_and_non_destructive():
assert "let legacyMigrationChecked = false;" in src
assert "if (legacyMigrationChecked || !canUseStorage()) {" in src
assert "legacyMigrationChecked = true;" in src
- # Layer 2: persistent cross-session flag so a completed migration is never
- # redone. Set in every terminal branch (malformed data, nothing to migrate,
- # successful write); a failed quota write leaves it unset so the next session
- # retries. Three set-sites encode exactly that.
+ # Layer 2: persistent cross-session flag so a completed migration is never redone.
assert 'const LEGACY_MIGRATION_FLAG = "unsloth_model_configs_migrated";' in src
assert "if (localStorage.getItem(LEGACY_MIGRATION_FLAG)) {" in src
assert src.count('localStorage.setItem(LEGACY_MIGRATION_FLAG, "1");') >= 3
@@ -914,10 +897,10 @@ def test_legacy_migration_is_idempotent_and_non_destructive():
def test_parallel_slots_setting_wired_end_to_end():
- """The per-load Parallel Slots knob (llama-server --parallel) must flow from
- the run-settings form through persistence, every /load builder, the validate
- preflight and the cross-model reset; a lost hop silently reverts the model to
- the server-wide slot default."""
+ """The per-load Parallel Slots knob (llama-server --parallel) must flow from the
+ run-settings form through persistence, every /load builder, the validate preflight
+ and the cross-model reset; a lost hop silently reverts the model to the server-wide
+ slot default."""
config = _read("features/model-picker/model-config/per-model-config.ts")
# Persisted per model, clamped on every read/write, and null (= server
# default) counts as default so blank configs are not stored.
@@ -955,22 +938,41 @@ def test_parallel_slots_setting_wired_end_to_end():
# the control would pin a blank "server default" to a number.
assert "loadedNParallel: status.requested_parallel_slots," in status
assert "nParallel: status.requested_parallel_slots," not in status
- sidebar = _read("features/model-picker/components/sidebar-model-config.tsx")
# The sidebar form remounts when an external change lands.
- assert 'config.nParallel ?? "",' in sidebar
+ signature = _read("features/model-picker/model-config/config-signature.ts")
+ assert 'config.nParallel ?? "",' in signature
+ sidebar = " ".join(_read("features/model-picker/components/sidebar-model-config.tsx").split())
+ assert "key={modelConfigInstanceKey(modelId, settingsGgufVariant, loadedConfig)}" in sidebar
+
+
+def test_parallel_slots_reach_an_api_load_through_the_server_mirror():
+ """The server mirror is the hop an OpenAI-compatible auto-switch load reads, and it is
+ the browser's only way to express a per-model setting to a load no browser makes."""
+ api = " ".join(_read("features/model-picker/api/model-overrides.ts").split())
+ assert "n_parallel?: number;" in api
+ assert (
+ "if (config.nParallel && config.nParallel > 0) { payload.n_parallel = config.nParallel; }"
+ in api
+ )
+ # The monitor lists what a remote load applies, so slots-only must not read as "App defaults".
+ monitor = " ".join(_read("features/api-monitor/components/saved-model-settings.tsx").split())
+ assert "if (override.n_parallel) {" in monitor
+
+ route = _read_backend("routes/settings.py")
+ assert "n_parallel: Optional[int] = Field(" in route
+ assert "n_parallel = payload.n_parallel," in route
+ store = _read_backend("utils/openai_auto_switch_settings.py")
+ assert 'entry["n_parallel"] = n_parallel' in store
+ # GGUF-only, like the picker: a safetensors load has no llama-server slots.
+ gguf_block = store.split(" if is_gguf:", 1)[1]
+ assert 'kwargs["n_parallel"] = override["n_parallel"]' in gguf_block
def test_parallel_slots_control_cleared_when_the_load_never_sent_them():
- """`nParallel` is the editable control ("blank = follow the server default")
- and `loadedNParallel` the rollback baseline. A success path that sends no
- slot count must blank the control, or a value staged for another model shows
- as applied, is persisted into this model's config (`isDefaultConfig` keys on
- nParallel) and is re-sent by the next Apply. Each assertion below is the only
- thing pinning one such path."""
+ """`nParallel` is the editable control ("blank = follow the server default") and
+ `loadedNParallel` the rollback baseline."""
status = " ".join(_read("features/chat/lib/apply-inference-status-to-store.ts").split())
- # A model/variant swap underneath this tab must reset the control like
- # performLoad's cross-model reset, or model A's count follows onto model B.
- # Narrowly gated -- see test_hydration_keeps_the_slot_control_when_readopting_the_running_model.
+ # A swap under this tab must reset the control, or model A's count follows onto model B.
assert "...(seedLoadParams && slotsModelChanged && { nParallel: null })," in status
# ... while still never adopting the RESOLVED echo into the control.
assert "nParallel: status.requested_parallel_slots," not in status
@@ -986,8 +988,7 @@ def test_parallel_slots_control_cleared_when_the_load_never_sent_them():
# The cached-GGUF branch keeps the remembered override via the gated local...
assert "nParallel: committedSlots," in gguf_branch
assert "nParallel: null," not in gguf_branch
- # ... the safetensors fallback sends no slots, so it clears both, or the count
- # survives on a model whose form does not even render the field.
+ # ...
assert "nParallel: null," in non_gguf_branch
assert "loadedNParallel: null," in non_gguf_branch
@@ -1002,10 +1003,8 @@ def test_parallel_slots_control_cleared_when_the_load_never_sent_them():
def test_hydration_clears_the_slot_baseline_for_a_slotless_model():
- """The baseline is what a rollback re-sends and what preset capture reads, so
- a model that cannot have slots must not inherit the previous GGUF's count.
- /status omits the echo for non-GGUF and sends an explicit null for diffusion;
- an absent field on a GGUF is an older backend and must NOT wipe it."""
+ """The baseline is what a rollback re-sends and what preset capture reads, so a model
+ that cannot have slots must not inherit the previous GGUF's count."""
src = _read("features/chat/lib/apply-inference-status-to-store.ts")
assert (
"(status.is_gguf === false || status.requested_parallel_slots === null) && {" in src
@@ -1017,17 +1016,10 @@ def test_hydration_clears_the_slot_baseline_for_a_slotless_model():
def test_hydration_keeps_the_slot_control_when_readopting_the_running_model():
- """`hydratingExistingModel` is true whenever the incoming status disagrees
- with what this tab last recorded, which includes RE-ADOPTING a model the tab
- never lost: the resident-adopt branch restores the model's own per-model
- config and only then hydrates, passing the EXTERNAL id as
- `previousCheckpoint`. An ungated clear there wipes the slot count that branch
- just restored, and the blank persists into `savePerModelConfig`, so a Save
- the user reads as a no-op erases their remembered override.
-
- Only that branch knows the model is unchanged, so it says so explicitly.
- Slot counts cannot stand in: the echo falls back to the server-wide default,
- so a genuine A->B swap can echo exactly A's explicit count."""
+ """`hydratingExistingModel` is true whenever the incoming status disagrees with what
+ this tab last recorded, which includes RE-ADOPTING a model the tab never lost: the
+ resident-adopt branch restores the model's own per-model config and only then
+ hydrates, passing the EXTERNAL id as `previousCheckpoint`."""
status = " ".join(_read("features/chat/lib/apply-inference-status-to-store.ts").split())
assert (
"const slotsModelChanged = hydratingExistingModel && !options.readoptingSameModel;"
@@ -1061,14 +1053,7 @@ def test_hydration_keeps_the_slot_control_when_readopting_the_running_model():
def test_parallel_slots_are_never_recorded_for_a_diffusion_load():
"""A DiffusionGemma GGUF answers ``is_gguf: true``, but its runner ignores
- ``--parallel``, so ``_parallel_slot_echo`` reports null slots for it. The
- three load success paths must gate on ``is_diffusion`` too, or they record a
- click-time count the load never committed.
-
- That phantom does not stay put: ``capturePresetLoadConfig`` snapshots
- ``nParallel`` with no model gate and a preset carries no model identity, so
- applying it over a TEXT GGUF sends the count as a real ``n_parallel``.
- """
+ ``--parallel``, so ``_parallel_slot_echo`` reports null slots for it."""
runtime = " ".join(_read("features/chat/hooks/use-chat-model-runtime.ts").split())
# One gated local feeds the control and the baseline, so they cannot drift.
assert "(loadResponse.is_gguf ?? false) && !(loadResponse.is_diffusion ?? false)" in runtime
@@ -1090,21 +1075,13 @@ def test_parallel_slots_are_never_recorded_for_a_diffusion_load():
def test_hydration_restores_a_remembered_slot_override():
- """The control is never seeded from the status echo, so a model running on a
- remembered override shows a BLANK slot control after a browser reload or a
- tab move to another GGUF. `ModelConfigPage.resolveInitial` prefers the live
- store for the active model, so that blank is what the form edits: the next
- Apply reloads at the server default and a Save writes the blank over the
- remembered count.
-
- The seed is deliberately narrow: storage is read only on a fresh store or a
- model change, never on a steady poll, and the value is adopted only when the
- server already runs that exact count, which proves it is this model's own.
- """
+ """The control is never seeded from the status echo, so a model running on a remembered
+ override shows a BLANK slot control after a browser reload or a tab move to another
+ GGUF."""
src = _read("features/chat/lib/apply-inference-status-to-store.ts")
status = " ".join(src.split())
assert (
- "resolveInitialConfig(checkpointId, status.gguf_variant ?? null)" in status
+ "resolveResidentInitialConfig(checkpointId, status.gguf_variant ?? null)" in status
), "the remembered override comes from per-model storage, not the echo"
assert (
"const slotsUnseeded = prevState.loadedNParallel === null && "
@@ -1127,17 +1104,44 @@ def test_hydration_restores_a_remembered_slot_override():
)
+def test_remembered_slots_are_read_through_the_cached_repo_alias():
+ """An API auto-switch loads a cached repo by its concrete snapshot path, so
+ ``status.model_identifier`` (what ``resolveInferenceCheckpointId`` returns) is that
+ path while the settings are keyed by the repo id ``modelConfigIdentity`` writes. Read
+ only the raw identifier and the resident model looks unremembered: the slot control
+ blanks on the model change and the next Save writes the blank over the saved
+ ``n_parallel``, locally and through the server mirror."""
+ config = " ".join(_read("features/model-picker/model-config/per-model-config.ts").split())
+ # The raw identifier still wins, so a path-keyed record is never shadowed.
+ assert (
+ "const direct = resolveInitialConfig(modelId, ggufVariant); "
+ "if (direct.remembered) {" in config
+ )
+ assert "const alias = publicModelId(modelId);" in config
+ # Only a namespaced collapse, the rule residentModelIdMatches applies: every other
+ # path collapses onto a file stem two models can share.
+ assert 'if (alias === modelId || !alias.includes("/")) { return direct; }' in config
+
+ status = " ".join(_read("features/chat/lib/apply-inference-status-to-store.ts").split())
+ assert "resolveResidentInitialConfig(checkpointId, status.gguf_variant ?? null)" in status
+ assert "resolveInitialConfig(checkpointId" not in status
+
+ # The backend applies the same model's override by the same alias, which is why the
+ # echo the adoption gate compares against carries the saved count at all.
+ route = _read_backend("routes/inference.py")
+ overrides = route.split("Apply the saved launch config so an API swap loads as the picker", 1)[
+ 1
+ ].split("load_kwargs = {", 1)[0]
+ assert 'f"{override_id}:{variant}" if variant else None,' in overrides
+ assert "override_id," in overrides
+
+
def test_failed_switch_rollback_restores_the_slot_intent_not_the_resolved_count():
- """`loadedNParallel` holds a RESOLVED count even for a load that sent no
- slots (the echo falls back to the server-wide default), so it is the right
- value to re-send when recreating the previous server and the wrong one to put
- back in the control: it turns "follow the server default" into an explicit
- override that a later Save or preset capture pins. The outer catch only
- repairs that for a staged config, so a plain string pick keeps the phantom.
-
- The intent comes from the picker's own pre-switch snapshot when there is one:
- chat-page pre-applies the TARGET's config before calling selectModel, so the
- live control describes the outgoing model only for a bare pick."""
+ """`loadedNParallel` holds a RESOLVED count even for a load that sent no slots (the
+ echo falls back to the server-wide default), so it is the right value to re-send
+ when recreating the previous server and the wrong one to put back in the control: it
+ turns "follow the server default" into an explicit override that a later Save or
+ preset capture pins."""
runtime = " ".join(_read("features/chat/hooks/use-chat-model-runtime.ts").split())
assert (
'const previousNParallel = typeof selection !== "string" && '
@@ -1163,12 +1167,9 @@ def test_failed_switch_rollback_restores_the_slot_intent_not_the_resolved_count(
def test_vulkan_inference_devices_are_the_pickable_set():
- """GGUF loads run through llama-server, so on a Vulkan build the picker must
- offer the inference inventory (ggml ordinals, the space `--device Vulkan<i>`
- pins) rather than the torch view, which can miss cards llama-server drives.
- The XPU ban must not apply there: it is about torch-xpu ordinals no
- applicator speaks, and a Vulkan pick does not use them.
- """
+ """GGUF loads run through llama-server, so on a Vulkan build the picker must offer the
+ inference inventory (ggml ordinals, the space `--device Vulkan<i>` pins) rather than
+ the torch view, which can miss cards llama-server drives."""
src = " ".join(_read("hooks/use-gpu-info.ts").split())
# The Vulkan inventory is authoritative even while its probe is temporarily
# empty. Falling through would expose physical CUDA/ROCm IDs in an ordinal
@@ -1198,3 +1199,632 @@ def test_vulkan_inference_devices_are_the_pickable_set():
'data?.device_backend === "cuda" || data?.device_backend === "rocm";' in src
)
assert 'diffusionPinnable: diffusionBackend && d.index_kind === "physical",' in src
+
+
+def test_only_gguf_configs_are_mirrored_to_the_server():
+ """The server override map is read by the OpenAI-compatible auto-switch, and its
+ resolver indexes GGUFs only."""
+ src = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())
+ assert (
+ "if ( !saveFailed && (target.apiLoadable ?? target.isGguf) && !nativePathToken ) "
+ "{ syncModelOverride(" in src
+ )
+ # The local save is not behind the same gate.
+ assert "if (remember) { saveFailed = !savePerModelConfig(" in src
+
+
+def test_a_native_leased_gguf_is_not_mirrored_to_the_server():
+ """A dropped or file-picked GGUF loads through a signed native-path lease, and
+ /api/inference/status reports model_identifier as null for it, so the checkpoint the
+ browser keys settings by is the bare file name the backend echoes back."""
+ page = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())
+ assert "&& !nativePathToken ) { syncModelOverride(" in page
+ assert (
+ "const nativePathToken = target.meta.nativePathToken ?? "
+ "(isActiveModel ? activeNativePathToken : null);" in page
+ ), "the token this gate reads"
+ # The one-time backfill has no token to read, so it goes by the identity shape.
+ backfill = " ".join(_read("features/model-picker/api/migrate-model-overrides.ts").split())
+ assert "!isNativeFileLabel(entry.modelId) &&" in backfill
+ identity = " ".join(_read("features/hub/lib/model-identity.ts").split())
+ assert "export function isNativeFileLabel(" in identity
+ # A bare file name: no separator, and the .gguf the resolver's keys never carry.
+ assert "const NATIVE_FILE_LABEL_RE = /^[^/\\\\]+\\.gguf$/i;" in identity
+
+ inference = _read_backend("routes/inference.py")
+ assert (
+ "model_identifier = None if _native_grant_backed else _model_id" in inference
+ ), "why the checkpoint is only a display name"
+ models = _read_backend("routes/models.py")
+ assert "display_name = gguf_file.stem," in models, "why the name is never an index key"
+
+
+def test_evicted_local_configs_drop_their_server_overrides():
+ """savePerModelConfig evicts older models when the map exceeds its budget."""
+ src = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())
+ assert "const evicted: { modelId: string; ggufVariant: string | null }[] = [];" in src
+ assert (
+ "for (const dropped of evicted) { syncModelOverride(dropped.modelId, "
+ "dropped.ggufVariant, null, { keepLaunchFlags: true, }); }" in src
+ )
+ api = " ".join(_read("features/model-picker/api/model-overrides.ts").split())
+ assert "keepLaunchFlags?: boolean;" in api
+ # remove=false with no fields: the route re-supplies stored flags and drops an empty row.
+ assert "remove: config === null && !options?.keepLaunchFlags," in api
+ assert (
+ "...(config === null && !options?.keepLaunchFlags ? { llama_extra_args: [] } : {}),"
+ in api.replace("// biome-ignore lint/style/useNamingConvention: API schema ", "")
+ )
+ route = _read_backend("routes/settings.py")
+ assert 'requested_extra_args = stored.get("llama_extra_args")' in route, "the rule this mirrors"
+
+ # Eviction reports what it dropped as model id + variant, not the normalized storage key.
+ store = " ".join(_read("features/model-picker/model-config/per-model-config.ts").split())
+ assert "evicted?: { modelId: string; ggufVariant: string | null }[]" in store
+ assert "modelIdFromStorageKey(" in store and "ggufVariantFromStorageKey(" in store
+
+
+def test_backfill_compares_server_keys_by_normalized_identity():
+ """app_settings has no schema version, so an install predating identity normalization
+ holds rows keyed by whatever id was typed, e.g."""
+ src = " ".join(_read("features/model-picker/api/migrate-model-overrides.ts").split())
+ assert "function normalizedOverrideKey(" in src
+ # Folded on both sides: the older `id::variant` local keys are not.
+ assert "known.set(normalizedOverrideKey(storedKey), storedEntry);" in src
+ assert "const stored = known.get(key);" in src
+ # A quant-aware split, so a Windows drive letter is not read as a separator.
+ assert "const split = splitQuantSuffix(key);" in src
+ # Repo ids fold and POSIX paths do not, which is what these do.
+ assert "normalizeModelIdentity(" in src and "normalizeGgufVariantIdentity(" in src
+
+
+def test_monitor_stats_exclude_model_lifecycle_rows():
+ """A load, unload or download is recorded as a monitor entry but is not an HTTP call."""
+ src = " ".join(_read("features/api-monitor/use-api-monitor.ts").split())
+ assert 'if (entry.kind === "lifecycle") { continue; }' in src
+ # "Requests" is a request count too, so it cannot stay entries.length.
+ assert "total: requests," in src
+ assert "total: entries.length" not in src
+
+ backend = _read_backend("core/inference/api_monitor.py")
+ assert 'entry.kind != "lifecycle"' in backend, "the rule this mirrors"
+
+
+def test_api_reach_copy_is_limited_to_gguf_models():
+ """The Hub opens this page for every downloaded model, but ModelConfigPage mirrors
+ settings to the server only when target.isGguf, because API auto-switch indexes
+ GGUFs only."""
+ src = " ".join(_read("features/hub/catalog/hub-model-settings-view.tsx").split())
+ assert "{(target.apiLoadable ?? target.isGguf)" in src
+ assert "Saved settings apply everywhere Studio loads this model." in src
+
+
+def test_backfill_includes_a_standalone_gguf_with_no_variant():
+ """A standalone .gguf picked directly has no quant to choose between, so it is stored
+ with a null variant."""
+ src = " ".join(_read("features/model-picker/api/migrate-model-overrides.ts").split())
+ assert 'entry.modelId.toLowerCase().endsWith(".gguf")' in src
+ # Still excluded for safetensors, which auto-switch does not resolve.
+ assert "entry.ggufVariant != null ||" in src
+
+
+def test_monitor_overlay_does_not_pull_in_the_lazy_page():
+ """The overlay is mounted from __root.tsx, so a static import of the page for two label
+ helpers drags the whole 900-line page and its dependency graph into the eagerly
+ loaded bundle and undoes the route's lazyRouteComponent."""
+ overlay = _read("features/api-monitor/api-monitor-overlay.tsx")
+ assert 'from "./lifecycle"' in overlay
+ assert "api-monitor-page" not in overlay, "the overlay must not reach the page"
+ # The helpers live in their own module, not re-exported through the page.
+ shared = _read("features/api-monitor/lifecycle.ts")
+ assert "export function isLifecycleEntry(" in shared
+ assert "export function lifecycleLabel(" in shared
+
+
+def test_override_writes_are_ordered_per_model():
+ """Two saves for one model, or a save racing the one-time backfill, started independent
+ requests with no sequencing, so the older response could commit last and resurrect
+ the entry the newer one meant to replace."""
+ src = " ".join(_read("features/model-picker/api/model-overrides.ts").split())
+ assert "const writesByKey = new Map<string, Promise<void>>();" in src
+ # Keyed by the same override key the server stores under.
+ assert (
+ "const key = modelOverrideKey( normalizeModelIdentity(modelId), normalizeGgufVariantIdentity(ggufVariant), );"
+ in src
+ )
+ # Chained on the settled tail, so one failed write cannot cancel the next.
+ assert "previous .catch(() => {}) .then(() => sendModelOverride(" in src
+ # Only the last writer clears the slot, or a queue still building loses order.
+ assert "if (writesByKey.get(key) === write) { writesByKey.delete(key); }" in src
+
+
+def test_backfill_skips_future_schema_local_records():
+ """loadPerModelConfig refuses to apply a record written by a newer Studio and eviction
+ refuses to drop one, because this client cannot interpret that schema."""
+ src = " ".join(_read("features/model-picker/model-config/per-model-config.ts").split())
+ listing = src[src.index("export function listPerModelConfigs()") :]
+ assert "storedConfigVersion(raw) > STORAGE_SCHEMA_VERSION" in listing[:900]
+
+
+def test_detail_settings_need_a_resolved_quant():
+ """The on-device card passes a null variant while its own lookup is pending or after it
+ failed."""
+ src = " ".join(_read("features/hub/hub-page.tsx").split())
+ # `variant`, not the argument: a resident quant may have replaced it, so judge what is saved.
+ guard = "if (!variant && selectedModel.isGguf && selectedModel.requiresVariant) {"
+ assert guard in src
+ assert src.count("Couldn't determine which quant to configure.") == 2
+
+
+def test_a_failed_detail_fetch_is_retried():
+ """A terminal row's updated_at never advances and selectedIsMissing stays true, so a
+ fetch that failed had nothing left to re-run the effect and the payload stayed
+ unavailable until another row was selected."""
+ src = " ".join(_read("features/api-monitor/api-monitor-page.tsx").split())
+ assert "const DETAIL_FETCH_ATTEMPTS = 3;" in src
+ assert "const detailInFlight = selectedId_ != null && loadingDetails.has(selectedId_);" in src
+ assert "if (attemptsRef.current.count >= DETAIL_FETCH_ATTEMPTS) { return; }" in src
+
+
+def test_ollama_models_are_not_advertised_as_api_loadable():
+ """local_model_resolver skips Ollama's scanner, so an Ollama GGUF is never in the
+ auto-switch index and no OpenAI request can resolve it."""
+ types_src = " ".join(_read("features/model-picker/components/model-selector/types.ts").split())
+ assert "apiLoadable?: boolean;" in types_src
+ hub = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert "row.source !== LOCAL_MODEL_SOURCE.OLLAMA" in hub
+ assert "apiLoadable:" in hub
+ backend = _read_backend("core/inference/local_model_resolver.py")
+ assert (
+ "Ollama's\n scanner is skipped" in backend or "scanner is skipped" in backend
+ ), "the rule this mirrors"
+
+
+def test_cached_repo_settings_are_keyed_by_the_repo_id():
+ """A repo cached outside the active HF cache reports load_id = the snapshot path
+ (hub/services/cache_inventory.py), while the chat picker and the auto-switch index
+ key it by repo_id."""
+ config_page = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())
+ assert "const configId = target.configId ?? target.id;" in config_page
+ for call in (
+ "resolveInitialConfig(configId, target.ggufVariant)",
+ "savePerModelConfig( configId, target.ggufVariant,",
+ "deletePerModelConfig(configId, target.ggufVariant)",
+ "syncModelOverride( configId, target.ggufVariant,",
+ ):
+ assert call in config_page, call
+ # The probes have to open the model, so they keep the load id.
+ assert "useDefaultChatTemplate( target.id," in config_page
+ assert "model_path: target.id," in config_page
+
+ hub = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert 'if (kind !== "cache" && resource.source !== "hub_cache") {' in hub
+ assert "return resource.repoId ?? resource.runId;" in hub
+ # Both openers and the Hub's own load resolve through it.
+ assert hub.count("modelConfigIdentity(") == 3
+ assert 'const configId = row.kind === "cache" ? row.repoId : id;' in hub
+ assert hub.count("configId,") >= 2
+
+ backend = _read_backend("hub/tests/test_model_services.py")
+ assert 'fields["load_id"] == str(snapshot)' in backend, "the rule this mirrors"
+
+
+def test_backfill_splits_a_quant_suffix_the_way_the_backend_does():
+ """The backfill compared server keys under an identity taken by splitting on the last
+ colon, so a Windows drive letter and an ordinary colon inside a POSIX filename were
+ read as quant separators: `/models/foo:Bar.gguf` and `/models/foo:bar.gguf` folded
+ to one key, and whichever was already on the server made the other look migrated."""
+ identity = " ".join(_read("features/model-picker/model-config/model-identity.ts").split())
+ assert "export function splitQuantSuffix(" in identity
+ # Two rules keep a path out: no separator in the tail, and a non-.gguf head carries no label.
+ assert 'if (tail.includes("/") || tail.includes("\\\\"))' in identity
+ assert 'if (!head.toLowerCase().endsWith(".gguf")) { return null; }' in identity
+ # A .gguf head is not enough: the suffix must be the label the scanner derives, or a name
+ # containing ".gguf:" folds two real POSIX files onto one key.
+ assert "tail.toLowerCase() === ggufQuantLabel(filename).toLowerCase()" in identity
+
+ migrate = " ".join(_read("features/model-picker/api/migrate-model-overrides.ts").split())
+ assert "const split = splitQuantSuffix(key);" in migrate
+ assert 'key.lastIndexOf(":")' not in migrate, "the unconditional split is gone"
+
+ backend = _read_backend("utils/openai_auto_switch_settings.py")
+ assert "def split_quant_suffix(" in backend, "the rule this mirrors"
+ assert "_BPW_SUFFIX" in backend and "bpw" in identity
+ assert "extract_quant_label(filename).casefold()" in backend, "the label rule"
+ # Both sides accept the same quant vocabulary; the regex lives with the loader.
+ quants = _read_backend("core/inference/llama_cpp.py")
+ for token in ("MXFP", "IQ", "TQ", "BF16", "F16", "F32"):
+ assert token in quants and token in identity, token
+ # The .gguf label helpers are ported too, or the two sides label a filename apart.
+ gguf = _read_backend("hub/utils/gguf.py")
+ assert "def extract_quant_label(" in gguf and "def _gguf_stem(" in gguf
+ assert "function ggufQuantLabel(" in identity and "function ggufStem(" in identity
+ assert "_GGUF_SPLIT_SUFFIX_RE" in gguf and "GGUF_SPLIT_SUFFIX" in identity
+ assert "_FLOAT_PRECISION_QUANTS" in gguf and "FLOAT_PRECISION_QUANTS" in identity
+ # The executable half of this contract, case by case against split_quant_suffix.
+ assert (WORKDIR / "studio" / "frontend" / "tests" / "model-identity.test.ts").is_file()
+
+
+def test_the_detail_card_also_gates_ollama_out_of_the_api_promise():
+ """Settings opens from two places in the Hub."""
+ hub = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert hub.count("LOCAL_MODEL_SOURCE.OLLAMA") == 2
+ assert "selectedModel.localSource !== LOCAL_MODEL_SOURCE.OLLAMA" in hub
+ assert "row.source !== LOCAL_MODEL_SOURCE.OLLAMA" in hub
+
+
+def test_the_settings_page_judges_the_config_storage_actually_keeps():
+ """savePerModelConfig normalizes before deciding, and the runtime hands this page
+ Speculative Decoding "auto", which canonicalizes to null."""
+ src = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())
+ assert (
+ "const normalizedRuntimeConfig = normalizePerModelConfig( effectiveRuntimeConfig, );" in src
+ )
+ assert "const defaultConfig = isDefaultConfig(normalizedRuntimeConfig);" in src
+ # The same object goes to storage and to the server, or they disagree again.
+ assert "target.ggufVariant, normalizedRuntimeConfig, evicted," in src
+ assert "remember ? normalizedRuntimeConfig : null," in src
+ assert "isDefaultConfig(effectiveRuntimeConfig)" not in src
+
+ store = " ".join(_read("features/model-picker/model-config/per-model-config.ts").split())
+ assert "export function normalizePerModelConfig(" in store
+ assert "const normalized = normalize(config);" in store
+ assert "if (isDefaultConfig(normalized)) {" in store, "the rule this mirrors"
+
+
+def test_the_chat_picker_marks_ollama_targets_unloadable_by_the_api():
+ """A settings target opened from the Chat model picker carried no apiLoadable, so the
+ `??"""
+ picker = " ".join(_read("features/model-picker/components/model-selector.tsx").split())
+ assert "apiLoadable: isGguf && !isOllamaLinkPath(id)," in picker
+ sidebar = " ".join(_read("features/model-picker/components/sidebar-model-config.tsx").split())
+ assert "apiLoadable: isGguf && !isOllamaLinkPath(modelId)," in sidebar
+ # The same classification gates the backfill, or an older config still reaches the server.
+ backfill = " ".join(_read("features/model-picker/api/migrate-model-overrides.ts").split())
+ assert "!isOllamaLinkPath(entry.modelId) &&" in backfill
+
+ identity = _read("features/hub/lib/model-identity.ts")
+ assert 'new Set([".studio_links", "ollama_links"])' in identity
+ resolver = _read_backend("core/inference/local_model_resolver.py")
+ assert 'seg in (".studio_links", "ollama_links")' in resolver, "the rule this mirrors"
+
+
+def test_the_backfill_fills_in_fields_rather_than_skipping_known_keys():
+ """The backfill reads the override map once and then writes each model in turn, so a
+ save by another tab during that pass was overwritten by this browser's older
+ localStorage copy."""
+ backfill = " ".join(_read("features/model-picker/api/migrate-model-overrides.ts").split())
+ assert "{ fillAbsentFields: true }," in backfill
+ # Key presence alone is not "done": what the server lacks decides.
+ assert "const stored = known.get(key);" in backfill
+ assert (
+ "if (stored && absentFields(stored, current.config).length === 0) { continue; }" in backfill
+ )
+ assert "const fields = Object.keys(toApiOverride(config));" in backfill
+ assert "return fields.filter((field) => !(field in stored));" in backfill
+
+ api = " ".join(_read("features/model-picker/api/model-overrides.ts").split())
+ assert "fillAbsentFields?: boolean;" in api
+ assert "options?.fillAbsentFields ? { fill_absent_fields: true } : {}" in api.replace(
+ "// biome-ignore lint/style/useNamingConvention: API schema ", ""
+ )
+ # Ordinary saves must stay unconditional, or a settings edit would never land.
+ assert "syncModelOverride" in api and "fill_absent_fields: true" in api
+
+ route = _read_backend("routes/settings.py")
+ assert "fill_absent_fields: bool = False" in route, "the rule this mirrors"
+ assert "fill_absent_fields = payload.fill_absent_fields," in route
+ # A write mode must not leak into saved fields, or model_id-only removal stops working.
+ assert '"remove", "fill_absent_fields"' in route
+
+ # The merge is the server's, in the write's transaction: a client-side one reopens the race.
+ db = _read_backend("storage/studio_db.py")
+ assert "merged = {**entry_value, **stored}" in db
+ assert "BEGIN IMMEDIATE" in db
+
+
+def test_the_hub_settings_page_matches_a_resident_path_loaded_model():
+ """A GGUF loaded from an inactive HF cache or straight off disk loads by path, but
+ /status reports the clean public id, so comparing it to settingsTarget.id said "not
+ loaded" and the page showed saved or default values instead of the live launch
+ config."""
+ hub = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert (
+ "residentModelIdMatches( activeCheckpoint, settingsTarget.id, settingsTarget.configId, )"
+ in hub
+ )
+ assert "loadedConfig={settingsTargetIsResident ? activeModelConfig : null}" in hub
+ assert "settingsTargetIsResident ? activeGgufContextLength : null" in hub
+ # The loadable identifier, as every other status reader records it.
+ assert "checkpointId: resolveInferenceCheckpointId(status)," in hub
+ assert "setCheckpoint(status.active_model" not in hub
+ chat = " ".join(_read("features/chat/lib/apply-inference-status-to-store.ts").split())
+ assert "return status.model_identifier ?? status.active_model;" in chat, "the rule this mirrors"
+ # The alias is the backend's own public id rule, not a private heuristic.
+ identity = _read("features/hub/lib/model-identity.ts")
+ assert "export function publicModelId(" in identity
+ assert "models--" in identity and "snapshots" in identity
+ # Only a namespaced repo id names one model, so a bare stem must never stand in for it.
+ assert 'return publicId.includes("/") && modelIdsMatch(active, publicId);' in identity
+ backend = _read_backend("core/inference/model_ids.py")
+ assert "def public_model_id(" in backend, "the rule this mirrors"
+
+
+def test_the_hub_hydrates_the_live_settings_before_it_offers_them():
+ """The Hub builds activeModelConfig out of the chat runtime store, and landing straight
+ on /hub is the one entry point where nothing has applied /api/inference/status yet:
+ useChatModelRuntime has no mount sync and the chat page is a different route."""
+ hub = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert "adoptResidentModelStatus(" in hub
+ assert "applyActiveModelStatusToStore(status, {" in hub
+ assert "previousCheckpoint: previous.checkpoint ?? undefined," in hub
+ assert "previousGgufVariant: previous.ggufVariant," in hub
+ assert "modelLoading: store.modelLoading," in hub
+
+ adopt = " ".join(_read("features/hub/lib/adopt-inference-status.ts").split())
+ # Unconditional: a persisted checkpoint rehydrates without the fields saying how it launched.
+ assert "actions.applyStatus(previous); return true;" in adopt
+ # Never fight the owning load, nor describe an external model with the resident's settings.
+ assert "if (state.checkpointIsExternal) { return false; }" in adopt
+ assert "if (state.modelLoading) { return false; }" in adopt
+
+ # Same call the chat runtime's own refresh makes, which is the rule this mirrors.
+ runtime = " ".join(_read("features/chat/hooks/use-chat-model-runtime.ts").split())
+ assert "applyActiveModelStatusToStore(statusRes, {" in runtime
+
+
+def test_the_hub_settings_editor_reseeds_when_the_live_config_lands():
+ """ModelConfigPage reads loadedConfig in a useState initializer, so it seeds once per
+ mounted instance."""
+ view = " ".join(_read("features/hub/catalog/hub-model-settings-view.tsx").split())
+ assert "key={modelConfigInstanceKey( target.id, target.ggufVariant, loadedConfig, )}" in view
+ # Same key the sidebar entry uses; that parity is the point.
+ sidebar = " ".join(_read("features/model-picker/components/sidebar-model-config.tsx").split())
+ assert "key={modelConfigInstanceKey(modelId, settingsGgufVariant, loadedConfig)}" in sidebar
+
+ signature = " ".join(_read("features/model-picker/model-config/config-signature.ts").split())
+ # "No live config yet" needs its own value: that transition is the one that must remount.
+ assert 'if (!config) { return "none"; }' in signature
+ for field in (
+ "config.customContextLength",
+ "config.maxSeqLength",
+ "config.kvCacheDtype",
+ "config.speculativeType",
+ "config.specDraftNMax",
+ "config.tensorParallel",
+ "config.chatTemplateOverride",
+ ):
+ assert field in signature, field
+
+ page = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())
+ assert "const [initial] = useState(resolveInitial);" in page, "the rule this mirrors"
+
+
+def test_a_standalone_gguf_has_one_settings_key():
+ """The inventory labels a single scanned .gguf from its filename, so the Hub row menu
+ keyed its settings to `<path>:Q4_K_M` while the Chat picker, the detail card and the
+ backfill all use the bare path: two surfaces, two configs."""
+ hub = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert "let ggufVariant = settingsGgufVariantForRow(row);" in hub
+ assert "row.formatVariant" not in hub, "the row's raw label is not a settings key"
+
+ helper = " ".join(_read("features/hub/inventory/settings-identity.ts").split())
+ assert 'row.kind === "local" && row.path.toLowerCase().endsWith(".gguf")' in helper
+
+ common = _read_backend("hub/services/models/common.py")
+ # The rule this mirrors: a variant is derived only for a single scanned file.
+ assert "extract_quant_label(gguf_files[0].name)" in common
+ assert "if scan_path.is_file() and len(gguf_files) == 1" in common
+
+
+def test_a_standalone_gguf_is_resident_despite_its_derived_quant():
+ """A loose .gguf keys its settings by the bare path with no variant, but the loader
+ derives one from the filename (llama_cpp sets _hf_variant from _extract_quant_label)
+ and /status reports it, so an equality between the two could never hold and the
+ settings page withheld the live launch config from the very file that was loaded."""
+ hub = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert "const settingsTargetIsStandaloneFile =" in hub
+ assert 'settingsTarget.id.toLowerCase().endsWith(".gguf")' in hub
+ assert (
+ "(settingsTargetIsStandaloneFile || ggufVariantsMatch(activeGgufVariant, settingsTarget.ggufVariant))"
+ in hub
+ )
+ backend = _read_backend("core/inference/llama_cpp.py")
+ assert (
+ "self._hf_variant = _extract_quant_label(gguf_path)" in backend
+ ), "the derived label this accounts for"
+
+
+def test_a_standalone_gguf_has_one_settings_identity_everywhere():
+ """A loose .gguf has no quant to choose between, but llama_cpp falls back to
+ _extract_quant_label(gguf_path) when a load names no variant, and /status echoes
+ that as gguf_variant."""
+ sidebar = " ".join(_read("features/model-picker/components/sidebar-model-config.tsx").split())
+ # Nulled for the settings identity, and used for every field that keys it.
+ assert (
+ "const settingsGgufVariant = isStandaloneGgufPath(modelId) ? null : ggufVariant;" in sidebar
+ )
+ assert "ggufVariant: settingsGgufVariant," in sidebar
+ assert "ggufVariant: settingsGgufVariant ?? undefined," in sidebar
+ # The label still shows the quant; only the identity drops it.
+ assert "displayName: ggufVariant ? `${leaf} · ${ggufVariant}` : leaf," in sidebar
+
+ # One rule, one definition: the Hub row applies the same test.
+ identity = _read("features/hub/lib/model-identity.ts")
+ assert "export function isStandaloneGgufPath(" in identity
+ # The suffix, and something that names a file on this machine: see
+ # test_a_repo_id_ending_in_gguf_keeps_its_quant for why the suffix is not enough.
+ assert "GGUF_SUFFIX_RE.test(modelId)" in identity
+ row_identity = _read("features/hub/inventory/settings-identity.ts")
+ assert 'row.path.toLowerCase().endsWith(".gguf")' in row_identity
+
+ # The precedence that makes the bare path the one that wins.
+ route = _read_backend("routes/inference.py")
+ assert 'f"{target_id}:{file_variant}" if file_variant else None,' in route
+ bare = route.index("\n target_id,\n")
+ labelled = route.index('f"{target_id}:{file_variant}"')
+ assert bare < labelled, "the bare path must be read before the filename label"
+
+
+def test_monitor_unload_clears_only_the_model_it_freed():
+ """Unload targets the resident local model from /status, but the store may hold either
+ spelling: status reports the concrete load path while the store can hold the
+ advertised repo id.
+
+ The read/unload/recheck sequence itself is pinned behaviourally by
+ studio/frontend/tests/api-monitor-unload-resident.test.ts; this only holds the page to
+ delegating it, since a single-pass unload reports success over a model an API
+ auto-switch loaded under the click."""
+ page = " ".join(_read("features/api-monitor/api-monitor-page.tsx").split())
+ assert (
+ "aliases: [checkpoint, status.active_model].filter( (alias): alias is string "
+ "=> alias != null, )," in page
+ )
+ assert "!isExternalModelId(selected)" in page
+ assert "unloadedAliases.some((alias) => modelIdsMatch(selected, alias))" in page
+ assert "store.clearCheckpoint();" in page
+
+
+def test_settings_open_reads_status_before_resolving_the_quant():
+ """A cache row carries no quant, so opening its settings resolves one from the store's
+ active variant."""
+ page = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert "const refreshResidentModelStatus = useCallback((): Promise<void> => {" in page
+ assert (
+ "await refreshResidentModelStatus(); if (settingsOpenSeq.current !== openSeq) return;"
+ in page
+ )
+ # Three: both handlers read on entry, and openModelSettings reads again after the
+ # variant lookup, whose network round trip is its own window for a switch to land.
+ assert page.count("await refreshResidentModelStatus();") == 3
+
+
+def test_a_local_quant_folder_resolves_its_variants_by_path():
+ """A local row carries a repo id only inside the HF cache, so a plain folder of
+ quants has none while still being marked as needing one, and the row menu's
+ Settings could then only reach the error toast."""
+ hub = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert (
+ 'const repoId = row.kind === "cache" ? row.repoId : (row.repoId ?? row.path ?? null);'
+ in hub
+ )
+ # The on-device card already lists by path, so both surfaces choose from one set of quants.
+ card = " ".join(_read("features/hub/catalog/local-on-device-card.tsx").split())
+ assert "repoId: modelId, hfToken, preferLocalCache: true, localPath: localGgufPath," in card
+ # The backend scans a path in the repo_id position before the validation that would 400.
+ variants = _read_backend("hub/services/models/gguf_variants.py")
+ scan = variants.split("if is_local_path(repo_id):", 1)
+ assert len(scan) == 2, "the local-path branch this leans on"
+ assert "_is_valid_repo_id(repo_id)" in scan[1], "the branch has to come first"
+
+
+def test_no_settings_target_is_built_on_an_unread_store():
+ """Every path out of both handlers seeds the editor from the store, and Apply
+ reloads with what it seeded, so a target built before the status read lands can
+ persist and launch the settings of the model an API switch displaced."""
+ page = " ".join(_read("features/hub/hub-page.tsx").split())
+ # Both handlers read first and drop the open if a newer one started meanwhile, and
+ # the variant lookup's await gets the same treatment. Every read carries the guard.
+ assert page.count("await refreshResidentModelStatus();") == 3
+ assert (
+ page.count(
+ "await refreshResidentModelStatus(); if (settingsOpenSeq.current !== openSeq) return;"
+ )
+ == 3
+ )
+ # Nothing may build a target off a concurrent read instead of an awaited one.
+ assert "Promise.all([ listGgufVariants(" not in page
+
+
+def test_an_empty_status_is_read_against_the_idle_unload_setting():
+ """/status cannot say whether an empty answer is an idle eviction that reloads
+ or a real unload, so the Hub reads the only endpoint that knows and keeps the
+ checkpoint only while the loop is armed."""
+ hub = " ".join(_read("features/hub/hub-page.tsx").split())
+ adopt = " ".join(_read("features/hub/lib/adopt-inference-status.ts").split())
+ # Awaited, not raced: the first status read is the one most likely to land on an evicted
+ # model, and an unresolved default of false would clear a checkpoint that is coming back.
+ assert (
+ "Promise.all([getInferenceStatus(), readIdleUnloadArmed()]) "
+ ".then(([status, idleUnloadArmed]) => {" in hub
+ )
+ assert "idleUnloadArmed," in hub
+ # Read with every status read, not cached for the life of the page: the idle timeout
+ # is editable from Settings while this page stays mounted.
+ assert "idleUnloadRead.current ??=" not in hub
+ assert "idleUnloadArmed.current = settings.idleUnloadActive;" in hub
+ # A failed read keeps the last answer. The default is disarmed, which is the side
+ # that clears the checkpoint, so falling back to it would drop a live selection.
+ assert ".catch(() => idleUnloadArmed.current)" in hub
+ assert "if (state.idleUnloadArmed) { return false; }" in adopt
+ assert "actions.clearCheckpoint?.();" in adopt
+
+
+def test_a_repo_id_ending_in_gguf_keeps_its_quant():
+ """Repo ids ending in .gguf are real on the Hub, an iMat repo among them, and
+ those hold every quant. A suffix-only test reads one as a single file, drops
+ the variant, and saves Q4 and Q8 under one key."""
+ identity = " ".join(_read("features/hub/lib/model-identity.ts").split())
+ assert "if (modelId == null || !GGUF_SUFFIX_RE.test(modelId)) { return false; }" in identity
+ assert "PUBLIC_ID_PATH_PREFIX_RE.test(modelId) ||" in identity
+ assert 'modelId.split("/").length - 1 >= 2 ||' in identity
+ assert "isNativeFileLabel(modelId)" in identity
+
+
+def test_cached_repo_settings_key_follows_the_row_not_the_view():
+ """A repo in an inactive HF cache loads by snapshot path while its settings are keyed
+ by repo id."""
+ page = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert 'if (kind !== "cache" && resource.source !== "hub_cache") {' in page
+
+
+def test_detail_settings_defers_a_derived_quant_to_a_fresh_status_read():
+ """The on-device card resolves the quant it shows from the store's active variant, and
+ nothing re-reads status while the window keeps focus, so an API-driven switch leaves
+ that quant naming the model it displaced."""
+ page = " ".join(_read("features/hub/hub-page.tsx").split())
+ card = " ".join(_read("features/hub/catalog/local-on-device-card.tsx").split())
+ assert "if (!quantIsUserPicked) { const settled = useChatRuntimeStore.getState();" in page
+ assert "variant = settled.activeGgufVariant;" in page
+ assert "onOpenSettings(selectedQuant ?? null, quantIsUserPicked)" in card
+
+
+def test_only_a_physical_gpu_pin_is_mirrored_to_the_server():
+ """The same integers are Vulkan ordinals under Vulkan and device indices elsewhere,
+ and the server override carries no namespace, so a backend change would pin the model
+ to a different device with ids that validate."""
+ mirror = " ".join(_read("features/model-picker/api/model-overrides.ts").split())
+ assert 'const gpuIndexKind = config.selectedGpuIndexKind ?? "physical";' in mirror
+ assert 'gpuIndexKind === "physical"' in mirror
+
+
+def test_a_cached_repo_keeps_the_settings_saved_under_its_old_key():
+ """A cached repo was keyed by the snapshot path it loads from and is now keyed by its
+ repo id; the server backfill only mirrors what is stored, so nothing else moves it."""
+ config = " ".join(_read("features/model-picker/model-config/per-model-config.ts").split())
+ assert "export function adoptLegacyConfigKey(" in config
+ # The key is renamed in one write. Saving the second copy first puts a full map one entry
+ # over budget, and savePerModelConfig then evicts the oldest unrelated model silently, with
+ # no eviction list handed back here, so that model's server override outlives its settings.
+ assert "savePerModelConfig(modelId, ggufVariant, legacy)" not in config
+ assert (
+ "const alreadySaved = findConfigKeyForModelVariant(map, modelId, ggufVariant) "
+ "!== null;" in config
+ )
+ # A newer save under the current key wins, and the stale record still goes.
+ assert "if (!(alreadySaved || isDefaultConfig(legacy)))" in config
+ assert "map[key] = toStoredConfig(legacy);" in config
+ assert (
+ "delete map[legacyKey]; deleteConfigEntriesForModelVariant(map, legacyModelId, "
+ "ggufVariant);" in config
+ )
+ # Both entry points move it before anything reads the new key.
+ page = " ".join(_read("features/hub/hub-page.tsx").split())
+ assert page.count("adoptLegacyConfigKey(") == 2
+
+
+def test_clearing_the_log_keeps_a_request_that_is_still_running():
+ """Dropping an own row mid-flight loses the request outright: active_count falls to
+ zero and the finish or fail that follows has no entry left to land on."""
+ monitor = " ".join(_read_backend("core/inference/api_monitor.py").split())
+ assert 'if entry.shared or entry.subject != subject or entry.status == "running"' in monitor
diff --git a/tests/studio/test_settings_compact_overflow_contract.py b/tests/studio/test_settings_compact_overflow_contract.py
index b8547975d29..46af046aec4 100644
--- a/tests/studio/test_settings_compact_overflow_contract.py
+++ b/tests/studio/test_settings_compact_overflow_contract.py
@@ -5,7 +5,9 @@ from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
SETTINGS_DIALOG = REPO / "studio/frontend/src/features/settings/settings-dialog.tsx"
-API_MONITOR = REPO / "studio/frontend/src/features/settings/components/api-monitor-console.tsx"
+# The monitor has its own page and Settings links to it; the shrink contract covers both.
+API_MONITOR_PAGE = REPO / "studio/frontend/src/features/api-monitor/api-monitor-page.tsx"
+MONITOR_LINK = REPO / "studio/frontend/src/features/settings/components/monitor-link.tsx"
GENERAL_TAB = REPO / "studio/frontend/src/features/settings/tabs/general-tab.tsx"
@@ -16,15 +18,21 @@ def test_dialog_content_can_shrink_inside_the_dialog_grid():
def test_api_monitor_entries_and_expanded_text_can_shrink():
- source = API_MONITOR.read_text(encoding = "utf-8")
- assert (
- '<article className="min-w-0 rounded-lg border border-border/70 bg-background">' in source
- )
- assert (
- '<section className="flex min-w-0 flex-col rounded-lg border border-border/70 bg-background">'
- in source
- )
- assert source.count('className="max-h-44 overflow-auto whitespace-pre-wrap break-words') == 2
+ source = API_MONITOR_PAGE.read_text(encoding = "utf-8")
+ # Flex parents need min-w-0, or a long model id widens the layout past the viewport.
+ assert '"flex w-full min-w-0 flex-col gap-1 border-b border-border/50' in source
+ assert '<section className="flex min-w-0 flex-col gap-1.5">' in source
+ # Prompt and reply are unbounded user text: height-capped, scrollable, wrapped.
+ assert "max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-muted/50" in source
+ # A model id or path has no spaces to wrap on, so it needs break-all.
+ assert 'className="min-w-0 break-all font-mono' in source
+
+
+def test_settings_monitor_link_can_shrink():
+ source = MONITOR_LINK.read_text(encoding = "utf-8")
+ assert "flex w-full min-w-0 items-center gap-3" in source
+ # The summary line carries a model id, so it truncates instead of widening.
+ assert '<span className="truncate text-xs text-muted-foreground">' in source
def test_embedding_model_controls_stack_on_the_narrowest_viewports():
diff --git a/tests/studio/test_usage_examples_model_source_contract.py b/tests/studio/test_usage_examples_model_source_contract.py
index a0c0d04020f..0fb2d57f002 100644
--- a/tests/studio/test_usage_examples_model_source_contract.py
+++ b/tests/studio/test_usage_examples_model_source_contract.py
@@ -132,33 +132,42 @@ def test_usage_examples_has_no_duplicate_auto_switch_control():
assert "<ModelAutoSwitchSection />" in tab
-API_MONITOR_TSX = SETTINGS / "components/api-monitor-console.tsx"
+# The monitor moved onto its own page; Settings keeps configuration and links across.
+API_MONITOR_TSX = REPO / "studio/frontend/src/features/api-monitor/api-monitor-page.tsx"
+# Their own module: the overlay mounts from __root.tsx, so importing from the page
+# pulled it into the eager bundle.
+API_MONITOR_LIFECYCLE_TS = REPO / "studio/frontend/src/features/api-monitor/lifecycle.ts"
+MONITOR_LINK_TSX = SETTINGS / "components/monitor-link.tsx"
-def test_api_monitor_pages_five_at_a_time():
- # The backend retains 50 terminal entries; the console used to dump them all at once.
+def test_api_monitor_history_does_not_reorder_under_the_reader():
+ # The backend moves an entry to the front as it finishes, so the page pauses the poll
+ # to hold the whole list still while a payload is read.
src = API_MONITOR_TSX.read_text(encoding = "utf-8")
- assert "const PAGE_SIZE = 5;" in src
- assert "ordered.slice(" in src
- # Paging back must freeze the id order, or live traffic reorders history under it.
- assert "frozenIds" in src
- assert "setFrozenIds((prev) => prev ?? entries.map((entry) => entry.id))" in src
+ assert "paused" in src
+ assert "setPaused" in src
+ # Filters and search are what keep 50 rows usable without paging.
+ assert "filterEntries(" in src
+ assert "STATUS_FILTERS" in src
def test_api_monitor_renders_lifecycle_rows():
src = API_MONITOR_TSX.read_text(encoding = "utf-8")
- assert "function LifecycleEntry(" in src
- assert 'entry.kind === "lifecycle"' in src
+ labels = API_MONITOR_LIFECYCLE_TS.read_text(encoding = "utf-8")
+ assert "export function isLifecycleEntry(" in labels
+ assert 'entry.kind === "lifecycle"' in labels
for label in ("Loading model", "Model loaded", "Model unloaded"):
- assert label in src
- # Lifecycle rows have no prompt/reply to fetch.
- assert "isLifecycle(entry) || !expandedIds.has(entry.id)" in src
+ assert label in labels
+ # A lifecycle row has no prompt or reply, so it is not selectable for detail.
+ assert "if (isLifecycleEntry(entry)) {" in src
+ assert 'from "./lifecycle"' in src
-def test_auto_switch_section_sits_above_the_monitor():
+def test_auto_switch_section_sits_above_the_usage_examples():
tab = API_KEYS_TAB_TSX.read_text(encoding = "utf-8")
- assert tab.index("<ModelAutoSwitchSection />") < tab.index("<ApiMonitorConsole />")
- assert tab.index("<ApiMonitorConsole />") < tab.index("<UsageExamples")
+ # Configuration still comes ahead of the examples that depend on it.
+ assert tab.index("<MonitorLink />") < tab.index("<ModelAutoSwitchSection />")
+ assert tab.index("<ModelAutoSwitchSection />") < tab.index("<UsageExamples")
AUTO_SWITCH_TSX = SETTINGS / "components/model-auto-switch-section.tsx"
@@ -166,7 +175,7 @@ EN_TS = REPO / "studio/frontend/src/i18n/locales/en.ts"
def test_api_monitor_renders_download_rows():
- src = API_MONITOR_TSX.read_text(encoding = "utf-8")
+ src = API_MONITOR_LIFECYCLE_TS.read_text(encoding = "utf-8")
assert 'entry.event === "download"' in src
for label in ("Downloading model", "Model downloaded", "Model download failed"):
assert label in src
@@ -183,6 +192,12 @@ def test_monitor_can_unload_the_loaded_model():
assert "unloadModel({ model_path: checkpoint })" in src
+def test_settings_still_reaches_the_monitor():
+ # The console is gone, so Settings must still have a way through to it.
+ link = MONITOR_LINK_TSX.read_text(encoding = "utf-8")
+ assert 'to: "/api-monitor"' in link
+
+
def test_auto_download_toggle_is_gated_on_auto_switch():
# Downloading what auto-switch cannot load fetches gigabytes nothing can serve.
src = AUTO_SWITCH_TSX.read_text(encoding = "utf-8")