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.

Unsloth Studio: redesigned API page, multi-model support and a Run settings fix (#14455)

Michael Han97d38c788b10
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 794fdb6f7dd..c014fe470ba 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -23105,6 +23105,45 @@ async def get_api_monitor(current_subject: str = Depends(get_current_subject)):
}
+@studio_router.get("/sampling-defaults")
+async def get_sampling_defaults(model: str, current_subject: str = Depends(get_current_subject)):
+ """The sampling a /v1 request naming ``model`` gets for every field it leaves out.
+
+ The same resolution the request path applies (operator ``UNSLOTH_SAMPLING_*`` pins, then the
+ model's recommendation, then the schema default), so the API page's example request shows the
+ values a client would actually get. Off-loop: the first read of a model loads its YAML.
+ """
+ # A kept model answers its own requests: route as the request path does, so the backend getters
+ # below read that slot rather than the primary.
+ await _route_to_extra_slot(model)
+ return await asyncio.to_thread(_sampling_defaults_for, model)
+
+
+def _sampling_defaults_for(model: str) -> dict:
+ """``resolve_effective_sampling`` as the request path calls it. For the loaded llama model that
+ keys on its identifier and passes its default thinking mode: Qwen3-family recommendations
+ differ between thinking and non-thinking, and leaving it out shows values a request never gets.
+ """
+ from utils.inference.inference_config import resolve_effective_sampling
+
+ model_id, thinking = model, None
+ llama_backend = get_llama_cpp_backend()
+ # Another account's resident stays hidden, as on the monitor: resolving against it would tell
+ # the caller which model that account has loaded.
+ if getattr(llama_backend, "is_loaded", False) and not account_access.resident_hidden(
+ "chat", _monitor_active_model()
+ ):
+ identifier = getattr(llama_backend, "model_identifier", None)
+ names = {n for n in (identifier, _llama_public_model_id(llama_backend)) if n}
+ if model in names or model.rsplit(":", 1)[0] in names:
+ model_id = identifier or model
+ thinking = _sampling_thinking_mode(
+ llama_backend,
+ ChatCompletionRequest(messages = [{"role": "user", "content": "Hello!"}]),
+ )
+ return resolve_effective_sampling(model_id, {}, thinking = thinking)
+
+
@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.
diff --git a/studio/backend/tests/test_sampling_defaults_route.py b/studio/backend/tests/test_sampling_defaults_route.py
new file mode 100644
index 00000000000..a5aa989b5e0
--- /dev/null
+++ b/studio/backend/tests/test_sampling_defaults_route.py
@@ -0,0 +1,113 @@
+# 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 API page's example request reads its sampling values from /sampling-defaults, so they have to
+be the ones a /v1 request that omits them would get."""
+
+import asyncio
+import os
+import sys
+
+_backend = os.path.join(os.path.dirname(__file__), "..")
+sys.path.insert(0, _backend)
+
+from routes import inference as inference_routes
+from utils.inference import inference_config
+
+
+def test_route_answers_with_the_request_path_resolution():
+ model = "unsloth/gemma-3-270m-it-GGUF"
+ expected = inference_config.resolve_effective_sampling(model, {})
+ got = asyncio.run(inference_routes.get_sampling_defaults(model = model, current_subject = "owner"))
+ assert got == expected
+ assert set(got) == set(inference_config.SAMPLING_FIELD_NAMES)
+
+
+def test_an_operator_pin_wins_over_the_recommendation(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TEMPERATURE", "0.25")
+ got = asyncio.run(
+ inference_routes.get_sampling_defaults(
+ model = "unsloth/Qwen3-4B-GGUF", current_subject = "owner"
+ )
+ )
+ assert got["temperature"] == 0.25
+
+
+class _LoadedQwen:
+ is_loaded = True
+ model_identifier = "unsloth/Qwen3-4B-GGUF"
+ hf_variant = "Q4_K_M"
+ supports_reasoning = True
+
+
+def test_the_loaded_model_resolves_with_its_thinking_mode(monkeypatch):
+ monkeypatch.setattr(inference_routes, "get_llama_cpp_backend", lambda: _LoadedQwen())
+ seen = []
+ monkeypatch.setattr(
+ inference_routes,
+ "_sampling_thinking_mode",
+ lambda backend, payload: seen.append(payload) or False,
+ )
+ expected = inference_config.resolve_effective_sampling(
+ "unsloth/Qwen3-4B-GGUF", {}, thinking = False
+ )
+ assert expected != inference_config.resolve_effective_sampling("unsloth/Qwen3-4B-GGUF", {})
+ for name in ("unsloth/Qwen3-4B-GGUF", "unsloth/Qwen3-4B-GGUF:Q4_K_M"):
+ got = asyncio.run(
+ inference_routes.get_sampling_defaults(model = name, current_subject = "owner")
+ )
+ assert got == expected
+ assert all(p.enable_thinking is None and p.reasoning_effort is None for p in seen)
+
+ other = asyncio.run(
+ inference_routes.get_sampling_defaults(
+ model = "unsloth/gemma-3-270m-it-GGUF", current_subject = "owner"
+ )
+ )
+ assert other == inference_config.resolve_effective_sampling("unsloth/gemma-3-270m-it-GGUF", {})
+
+
+def test_a_resident_hidden_from_the_caller_is_not_resolved_against(monkeypatch):
+ # A managed account must not learn another account's resident from the values returned.
+ monkeypatch.setattr(inference_routes, "get_llama_cpp_backend", lambda: _LoadedQwen())
+ monkeypatch.setattr(inference_routes, "_sampling_thinking_mode", lambda backend, payload: False)
+ monkeypatch.setattr(
+ inference_routes, "_monitor_active_model", lambda: "unsloth/Qwen3-4B-GGUF:Q4_K_M"
+ )
+ monkeypatch.setattr(
+ inference_routes.account_access, "resident_hidden", lambda modality, reference = None: True
+ )
+ got = asyncio.run(
+ inference_routes.get_sampling_defaults(
+ model = "unsloth/Qwen3-4B-GGUF", current_subject = "managed"
+ )
+ )
+ assert got == inference_config.resolve_effective_sampling("unsloth/Qwen3-4B-GGUF", {})
+
+
+class _Unloaded:
+ is_loaded = False
+
+
+def test_a_kept_model_resolves_against_its_own_slot(monkeypatch):
+ # The primary holds something else; the request path routes a kept Qwen3 to its slot, and so must this.
+ from types import SimpleNamespace
+
+ monkeypatch.setattr(inference_routes, "_llama_cpp_backend", _Unloaded())
+
+ async def route(requested):
+ inference_routes.routed_slot.set(SimpleNamespace(llama = _LoadedQwen()))
+
+ monkeypatch.setattr(inference_routes, "_route_to_extra_slot", route)
+ monkeypatch.setattr(inference_routes, "_sampling_thinking_mode", lambda backend, payload: False)
+ monkeypatch.setattr(
+ inference_routes, "_monitor_active_model", lambda: "unsloth/Qwen3-4B-GGUF:Q4_K_M"
+ )
+ got = asyncio.run(
+ inference_routes.get_sampling_defaults(
+ model = "unsloth/Qwen3-4B-GGUF:Q4_K_M", current_subject = "owner"
+ )
+ )
+ assert got == inference_config.resolve_effective_sampling(
+ "unsloth/Qwen3-4B-GGUF", {}, thinking = False
+ )
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
index 6f9c248a789..7bb638bd9b2 100644
--- a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
+++ b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
@@ -5,7 +5,11 @@
// 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 { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import type {
+ ApiMonitorEntry,
+ ApiMonitorResponse,
+} from "@/features/chat/types/api";
import { FIND_PORTAL_ATTRIBUTE } from "@/features/find-in-page/lib/find-attributes";
import { useMonitorFrameStore, useShortcut } from "@/features/settings";
import { useFloatingPanelLayout } from "@/hooks/use-floating-panel-layout";
@@ -23,8 +27,9 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { XIcon } from "lucide-react";
import { AnimatePresence, motion, useIsPresent } from "motion/react";
-import { type ReactElement, useEffect, useRef, useState } from "react";
+import { type ReactElement, useEffect, useMemo, useRef, useState } from "react";
import { isLifecycleEntry, lifecycleLabel } from "./lifecycle";
+import { mergeMonitorResponse } from "./monitor-snapshot";
import {
type ApiMonitorWatch,
createWatch,
@@ -65,7 +70,7 @@ function compactEndpoint(endpoint: string): string {
function formatDuration(value?: number | null): string {
if (value == null) {
- return "live";
+ return "–";
}
if (value < 1000) {
return `${Math.round(value)}ms`;
@@ -73,6 +78,22 @@ function formatDuration(value?: number | null): string {
return `${(value / 1000).toFixed(value < 10000 ? 1 : 0)}s`;
}
+function entryDuration(entry: ApiMonitorEntry): string {
+ if (entry.duration_ms == null && entry.status === "running") {
+ return "live";
+ }
+ return formatDuration(entry.duration_ms);
+}
+
+const SERVER_STATUS: Record<
+ ApiMonitorResponse["status"],
+ { label: string; dot: string }
+> = {
+ generating: { label: "Serving", dot: "animate-pulse bg-blue-500" },
+ ready: { label: "Ready", dot: "bg-emerald-500" },
+ idle: { label: "No model", dot: "bg-muted-foreground" },
+};
+
function statusDotClass(status: ApiMonitorEntry["status"]): string {
switch (status) {
case "running":
@@ -121,9 +142,9 @@ export function ApiMonitorOverlay(): ReactElement | null {
const pathname = useRouterState({ select: (s) => s.location.pathname });
const onFullPage = pathname === "/api-monitor";
- const [data, setData] = useState<Awaited<
- ReturnType<typeof getApiMonitor>
- > | null>(null);
+ const [data, setData] = useState<ApiMonitorResponse | null>(null);
+ // Kept apart from `data`: a failed poll keeps the last rows instead of blanking them.
+ const [unreachable, setUnreachable] = useState(false);
// The chord lives with the panel: reaching this store from the shell would
// pull the whole feature index into the root chunk. The full page has
@@ -156,6 +177,9 @@ export function ApiMonitorOverlay(): ReactElement | null {
}
let cancelled = false;
let timer: number | undefined;
+ let inFlight = false;
+ // A stand up's first snapshot is a fresh object so the watch refolds it; later polls share unchanged entries.
+ let first = true;
const intervalMs = isOpen ? OPEN_POLL_MS : IDLE_POLL_MS;
// Anchor the watch here, not at mount: the first snapshot can arrive much later
@@ -163,31 +187,47 @@ export function ApiMonitorOverlay(): ReactElement | null {
startWatching(watchRef.current, performance.now());
function schedule(): void {
- timer = window.setTimeout(poll, intervalMs);
+ timer = window.setTimeout(() => {
+ timer = undefined;
+ if (!document.hidden) poll();
+ }, intervalMs);
}
function poll(): void {
- // A hidden tab has nobody to show the panel to.
- if (document.hidden) {
- schedule();
- return;
- }
+ inFlight = true;
getApiMonitor()
.then((next) => {
- if (!cancelled) setData(next);
+ if (cancelled) return;
+ const fresh = first;
+ first = false;
+ setData((previous) =>
+ fresh ? next : mergeMonitorResponse(previous, next),
+ );
+ setUnreachable(false);
})
.catch(() => {
- // An unreachable server is the full page's story to tell.
- if (!cancelled) setData(null);
+ if (!cancelled) setUnreachable(true);
})
.finally(() => {
+ inFlight = false;
if (!cancelled) schedule();
});
}
- poll();
+ function onVisibilityChange(): void {
+ if (document.hidden || inFlight || cancelled) return;
+ if (timer !== undefined) {
+ window.clearTimeout(timer);
+ timer = undefined;
+ }
+ poll();
+ }
+
+ if (!document.hidden) poll();
+ document.addEventListener("visibilitychange", onVisibilityChange);
return () => {
cancelled = true;
+ document.removeEventListener("visibilitychange", onVisibilityChange);
if (timer !== undefined) window.clearTimeout(timer);
};
}, [isOpen, onFullPage, autoOpen]);
@@ -241,6 +281,7 @@ export function ApiMonitorOverlay(): ReactElement | null {
<ApiMonitorPanel
key={panelKey}
data={data}
+ unreachable={unreachable}
close={close}
setAutoOpen={setAutoOpen}
/>
@@ -251,17 +292,42 @@ export function ApiMonitorOverlay(): ReactElement | null {
function ApiMonitorPanel({
data,
+ unreachable,
close,
setAutoOpen,
}: {
- data: Awaited<ReturnType<typeof getApiMonitor>> | null;
+ data: ApiMonitorResponse | null;
+ unreachable: boolean;
close: () => void;
setAutoOpen: (value: boolean) => void;
}): ReactElement {
const navigate = useNavigate();
- const entries = data?.entries ?? [];
- const stats = computeStats(entries);
- const serverStatus = data?.status ?? "idle";
+ const focusRequest = useApiMonitorOverlayStore((s) => s.focusRequest);
+ const entries = useMemo(() => data?.entries ?? [], [data]);
+ const stats = useMemo(() => computeStats(entries), [entries]);
+ const loadedModels = useChatRuntimeStore((s) => s.loadedModels);
+ const servedNames = useMemo(() => {
+ const names = loadedModels.map((model) =>
+ model.quant && !model.id.includes(":")
+ ? `${model.id}:${model.quant}`
+ : model.id,
+ );
+ const active = data?.active_model;
+ if (!active) return names;
+ const key = active.toLowerCase();
+ return [active, ...names.filter((name) => name.toLowerCase() !== key)];
+ }, [loadedModels, data?.active_model]);
+ const serverStatus =
+ SERVER_STATUS[
+ data?.status === "idle" && servedNames.length > 0
+ ? "ready"
+ : (data?.status ?? "idle")
+ ];
+ const openApiPage = (requestId?: string): void => {
+ if (requestId) focusRequest(requestId);
+ close();
+ void navigate({ to: "/api-monitor" });
+ };
const isPresent = useIsPresent();
const [constraintsElement, setConstraintsElement] =
useState<HTMLDivElement | null>(null);
@@ -365,17 +431,16 @@ function ApiMonitorPanel({
<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}
- />
+ <span className="flex shrink-0 items-center gap-1.5 text-ui-11 tracking-nav text-muted-foreground">
+ <span
+ className={cn(
+ "size-1.5 shrink-0 rounded-full",
+ unreachable ? "bg-red-500" : serverStatus.dot,
+ )}
+ aria-hidden={true}
+ />
+ {unreachable ? "Offline" : serverStatus.label}
+ </span>
</div>
<div className="flex shrink-0 items-center gap-0.5">
<div
@@ -407,14 +472,31 @@ function ApiMonitorPanel({
<div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto">
<div ref={contentRef}>
- <p className="truncate px-1.5 pb-2.5 text-ui-11p5 tracking-nav text-muted-foreground">
- {data?.active_model ?? "No model loaded"}
+ <p
+ className={cn(
+ "flex min-w-0 items-center gap-1.5 px-1.5 pb-2.5 text-ui-11p5 tracking-nav text-muted-foreground",
+ unreachable && "text-red-600 dark:text-red-400",
+ )}
+ title={
+ servedNames.length > 1 ? servedNames.join("\n") : undefined
+ }
+ >
+ <span className="min-w-0 truncate">
+ {unreachable
+ ? "Can't reach Unsloth. Retrying…"
+ : (servedNames[0] ?? "No model loaded")}
+ </span>
+ {!unreachable && servedNames.length > 1 ? (
+ <span className="shrink-0 rounded-full bg-muted/60 px-1.5 text-ui-10 tabular-nums dark:bg-background/50">
+ +{servedNames.length - 1}
+ </span>
+ ) : null}
</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">
+ <div className="grid grid-cols-4 rounded-[14px] bg-muted/45 pt-[calc(11.5px*var(--ui-space-scale,1))] pb-[calc(8.5px*var(--ui-space-scale,1))] dark:bg-background/45">
<StatCell
- label="Live"
+ label="In flight"
value={stats.active.toLocaleString()}
tone={stats.active > 0 ? "active" : undefined}
/>
@@ -425,7 +507,7 @@ function ApiMonitorPanel({
tone={stats.errors > 0 ? "error" : undefined}
/>
<StatCell
- label="Avg"
+ label="Avg time"
value={
stats.avgDurationMs == null
? "--"
@@ -438,41 +520,66 @@ function ApiMonitorPanel({
<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.
+ No API requests yet. They show here as they arrive.
</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",
- )}
+ entries.slice(0, VISIBLE_ENTRIES).map((entry) => {
+ const lifecycle = isLifecycleEntry(entry);
+ const cells = (
+ <>
+ <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">
+ {lifecycle
+ ? 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={cn(
+ "shrink-0 text-ui-11 tabular-nums text-muted-foreground",
+ entry.status === "running" &&
+ "text-blue-600 dark:text-blue-400",
+ )}
+ >
+ {entryDuration(entry)}
+ </span>
+ </>
+ );
+ return lifecycle ? (
+ <div
+ key={entry.id}
+ className="flex h-9 min-w-0 items-center gap-2.5 px-3"
+ >
+ {cells}
+ </div>
+ ) : (
+ <button
+ key={entry.id}
+ type="button"
+ data-entry-id={entry.id}
+ onClick={() => openApiPage(entry.id)}
+ title="Inspect this request on the API page"
+ className="flex h-9 w-full min-w-0 items-center gap-2.5 rounded-[12px] px-3 text-left transition-colors hover:bg-nav-surface-hover focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
- {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>
- ))
+ {cells}
+ </button>
+ );
+ })
)}
</div>
</div>
@@ -480,10 +587,7 @@ function ApiMonitorPanel({
{/* Through to payloads, filters and per request tokens. */}
<button
type="button"
- onClick={() => {
- close();
- void navigate({ to: "/api-monitor" });
- }}
+ onClick={() => openApiPage()}
className="mt-1 flex shrink-0 h-[calc(33px*var(--ui-space-scale,1))] w-full items-center justify-center gap-[calc(8.5px*var(--ui-space-scale,1))] 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
@@ -491,7 +595,7 @@ function ApiMonitorPanel({
strokeWidth={1.75}
className="size-icon shrink-0"
/>
- Expand to full monitor
+ Open API page
</button>
{/* Closing silences this burst; this is the permanent off. */}
@@ -501,6 +605,7 @@ function ApiMonitorPanel({
setAutoOpen(false);
close();
}}
+ title="Turn it back on in Settings, under API"
className="mt-1.5 shrink-0 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
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
index 5f742954637..686a1690f32 100644
--- a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
+++ b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
@@ -22,7 +22,8 @@ import { fetchDeviceType, 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";
+import { type ApiMonitorEntry, useChatModelRuntime } from "@/features/chat";
+import type { ApiMonitorResponse } from "@/features/chat/types/api";
import { isExternalModelId } from "@/features/chat/external-providers";
import { modelIdsMatch } from "@/features/hub/lib/model-identity";
import {
@@ -30,8 +31,8 @@ import {
createModelConfigHandoffRequestId,
} from "@/features/model-picker";
import {
- lanApiUrls,
loadLanAccess,
+ publishLanUrls,
useSettingsDialogStore,
} from "@/features/settings";
import { remoteApiOrigin } from "@/features/settings/api/remote-access-state";
@@ -40,32 +41,60 @@ import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { Tick02Icon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
import {
+ ApiIcon,
+ Cancel01Icon,
+ CodeIcon,
+ ComputerTerminal01Icon,
Copy01Icon,
+ CursorPointer02Icon,
Delete02Icon,
+ FlashIcon,
+ Key01Icon,
PauseIcon,
PlayIcon,
Refresh01Icon,
RemoveCircleIcon,
+ Search01Icon,
Settings02Icon,
- ApiIcon,
+ Timer01Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { type ReactElement, useEffect, useMemo, useRef, useState } from "react";
+import {
+ type CSSProperties,
+ type KeyboardEvent,
+ type ReactElement,
+ type ReactNode,
+ memo,
+ useDeferredValue,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { ApiExampleDialog } from "./components/api-example-dialog";
import { ApiModelLoadControls } from "./components/api-model-load-controls";
import { SavedModelSettingsPanel } from "./components/saved-model-settings";
import { isLifecycleEntry, lifecycleLabel } from "./lifecycle";
+import { useApiMonitorOverlayStore } from "./overlay-store";
+import { useSingleLine } from "./use-single-line";
import { PAYLOAD_SHOW_ALL_MAX_CHARS, payloadPreview } from "./payload-preview";
import { ToolbarTooltip } from "./components/toolbar-tooltip";
import { unloadResident } from "./unload-resident";
import {
residentHasRunSettings,
residentHasSlotsSetting,
+ keptRunSettingsRequest,
runSettingsRequest,
slotsSettingsRequest,
} from "./slots-settings-request";
-import { useResidentRunTarget } from "./use-resident-run-target";
+import {
+ monitorSelection,
+ useResidentRunTarget,
+} from "./use-resident-run-target";
import {
type MonitorStatusFilter,
+ computeStats,
+ countByStatus,
filterEntries,
useApiMonitor,
} from "./use-api-monitor";
@@ -75,25 +104,82 @@ 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 ALL_MODELS = "__all__";
+
const STATUS_FILTERS: { value: MonitorStatusFilter; label: string }[] = [
- { value: "all", label: "All requests" },
+ { value: "all", label: "All" },
{ value: "running", label: "In flight" },
{ value: "completed", label: "Completed" },
{ value: "error", label: "Errors" },
{ value: "cancelled", label: "Cancelled" },
];
+const SERVER_STATUS: Record<
+ ApiMonitorResponse["status"],
+ { label: string; dot: string }
+> = {
+ generating: { label: "Serving", dot: "bg-blue-500 animate-pulse" },
+ ready: { label: "Ready", dot: "bg-emerald-500" },
+ idle: { label: "No model loaded", dot: "bg-muted-foreground/60" },
+};
+
+const PANE_HEIGHT =
+ "max-h-[calc(560px*var(--ui-space-scale,1))] min-h-[calc(260px*var(--ui-space-scale,1))] max-lg:max-h-[45dvh] 3xl:max-h-[calc(100dvh-22rem*var(--ui-space-scale,1))] overflow-y-auto";
+
+const SURFACE = "elevated-card bg-card";
+const DIVIDER = "border-border/60 dark:border-background";
+const INSET =
+ "border border-border/50 bg-muted/40 dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.05*var(--contrast-wash-gain,1)))]";
+const INSET_OPAQUE =
+ "bg-[color-mix(in_oklab,var(--muted)_40%,var(--card))] dark:bg-[rgb(255_255_255_/_calc(0.05*var(--contrast-wash-gain,1)))]";
+
function formatTime(value: number): string {
return new Date(value * 1000).toLocaleTimeString([], {
- hour: "2-digit",
+ hour: "numeric",
minute: "2-digit",
- second: "2-digit",
});
}
+function formatFullTime(value: number): string {
+ return new Date(value * 1000).toLocaleString();
+}
+
+function formatAgo(value: number, now: number): string {
+ const seconds = Math.max(0, Math.round(now - value));
+ if (seconds < 10) return "now";
+ if (seconds < 60) return `${seconds}s ago`;
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return new Date(value * 1000).toLocaleDateString([], {
+ month: "short",
+ day: "numeric",
+ });
+}
+
+const AGO_TICK_MS = 10_000;
+
+// Server-clock seconds (host clock may differ over a tunnel); ticks itself since a paused feed stops polls.
+function useServerNow(
+ serverTime: number | undefined,
+ ticking: boolean,
+): number {
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ if (!ticking) return;
+ const timer = window.setInterval(() => setTick((n) => n + 1), AGO_TICK_MS);
+ return () => window.clearInterval(timer);
+ }, [ticking]);
+ const skew = useMemo(
+ () => (serverTime == null ? 0 : Math.round(serverTime - Date.now() / 1000)),
+ [serverTime],
+ );
+ // biome-ignore lint/correctness/useExhaustiveDependencies: tick is what advances the clock
+ return useMemo(() => Date.now() / 1000 + skew, [skew, tick]);
+}
+
function formatDuration(value?: number | null): string {
if (value == null) {
- return "running";
+ return "–";
}
if (value < 1000) {
return `${Math.round(value)} ms`;
@@ -101,6 +187,13 @@ function formatDuration(value?: number | null): string {
return `${(value / 1000).toFixed(value < 10000 ? 1 : 0)} s`;
}
+function entryDuration(entry: ApiMonitorEntry): string {
+ if (entry.duration_ms == null && entry.status === "running") {
+ return "running";
+ }
+ return formatDuration(entry.duration_ms);
+}
+
function formatCount(value: number): string {
return value.toLocaleString();
}
@@ -118,6 +211,17 @@ function compactEndpoint(endpoint: string): string {
.replace(V1_PREFIX_RE, "/");
}
+function quickStartSnippet(baseUrl: string, model: string): string {
+ const body = JSON.stringify({
+ model,
+ messages: [{ role: "user", content: "Hello!" }],
+ }).replace(/'/g, "'\\''");
+ return `curl ${baseUrl}/chat/completions \\
+ -H "Authorization: Bearer $UNSLOTH_API_KEY" \\
+ -H "Content-Type: application/json" \\
+ -d '${body}'`;
+}
+
function statusDotClass(status: ApiMonitorEntry["status"]): string {
switch (status) {
case "running":
@@ -144,7 +248,55 @@ function statusTextClass(status: ApiMonitorEntry["status"]): string {
}
}
-function StatCard({
+type ServedModel = {
+ name: string;
+ checkpoint: string;
+ active: boolean;
+ quant: string | null;
+};
+
+function servedModels(
+ loaded: { id: string; quant?: string | null; checkpoint?: string }[],
+ activeModel: string | null,
+ residentCheckpoint: string | null | undefined,
+): ServedModel[] {
+ const activeId = monitorSelection(activeModel).id;
+ // At most one primary row: two local files can share a public name, and marking both ejected the primary.
+ const named = (model: { id: string }): boolean =>
+ Boolean(activeId) && modelIdsMatch(model.id, activeId);
+ const byCheckpoint = residentCheckpoint
+ ? loaded.findIndex(
+ (model) =>
+ named(model) && (model.checkpoint ?? model.id) === residentCheckpoint,
+ )
+ : -1;
+ const activeIndex =
+ byCheckpoint >= 0 ? byCheckpoint : loaded.findIndex(named);
+ const rows = loaded.map((model, index) => ({
+ name:
+ model.quant && !model.id.includes(":")
+ ? `${model.id}:${model.quant}`
+ : model.id,
+ checkpoint: model.checkpoint ?? model.id,
+ active: index === activeIndex,
+ quant: model.quant ?? null,
+ }));
+ if (activeModel && !rows.some((row) => row.active)) {
+ rows.unshift({
+ name: activeModel,
+ checkpoint: activeModel,
+ active: true,
+ quant: monitorSelection(activeModel).ggufVariant,
+ });
+ }
+ return rows.sort((a, b) => Number(b.active) - Number(a.active));
+}
+
+function openApiSettings(): void {
+ useSettingsDialogStore.getState().openDialog("api-keys");
+}
+
+function Stat({
label,
value,
hint,
@@ -156,24 +308,21 @@ function StatCard({
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>
+ <div className="flex min-w-0 flex-col gap-0.5 bg-card px-5 py-4">
+ <span className="truncate text-ui-12 text-muted-foreground">{label}</span>
<span
className={cn(
- "truncate text-ui-22 font-semibold leading-tight tracking-[-0.02em]",
+ "truncate text-ui-21 font-semibold leading-tight tracking-[-0.02em] tabular-nums text-foreground",
+ value === "–" && "text-muted-foreground/70",
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}
+ <span className="min-h-[1lh] truncate text-ui-11 text-muted-foreground">
+ {hint}
+ </span>
</div>
);
}
@@ -181,9 +330,11 @@ function StatCard({
function CopyButton({
value,
label,
+ revealOnHover = false,
}: {
value: string;
label: string;
+ revealOnHover?: boolean;
}): ReactElement {
const [copied, setCopied] = useState(false);
// Cancel on cleanup, or navigating away mid-flash sets state after unmount.
@@ -210,7 +361,12 @@ function CopyButton({
timerRef.current = window.setTimeout(() => setCopied(false), 1800);
}
}}
- className="size-7 shrink-0 p-0"
+ className={cn(
+ "size-7 shrink-0 rounded-full p-0",
+ revealOnHover &&
+ !copied &&
+ "opacity-0 group-hover/copy:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100",
+ )}
>
<HugeiconsIcon
icon={copied ? Tick02Icon : Copy01Icon}
@@ -225,15 +381,69 @@ function CopyButton({
);
}
-function ContextUsageBar({
- value,
-}: { value?: number | null }): ReactElement | null {
+function Fact({
+ label,
+ children,
+ className,
+}: {
+ label: string;
+ children: ReactNode;
+ className?: string;
+}): ReactElement {
+ return (
+ <div className={cn("flex min-w-0 items-center gap-2", className)}>
+ <dt className="shrink-0 text-ui-12 text-muted-foreground">{label}</dt>
+ <dd className="flex min-w-0 items-center gap-1 text-ui-12 text-foreground">
+ {children}
+ </dd>
+ </div>
+ );
+}
+
+function Banner({
+ children,
+ onDismiss,
+}: {
+ children: ReactNode;
+ onDismiss?: () => void;
+}): ReactElement {
+ const [ref, singleLine] = useSingleLine<HTMLDivElement>();
+ return (
+ <div
+ ref={ref}
+ role="alert"
+ className={cn(
+ "flex items-start gap-3 border border-red-500/40 bg-red-500/5 px-4 py-3 text-sm text-red-600 dark:text-red-400",
+ singleLine ? "rounded-full" : "rounded-xl",
+ )}
+ >
+ <span className="min-w-0 flex-1 break-words">{children}</span>
+ {onDismiss ? (
+ <button
+ type="button"
+ onClick={onDismiss}
+ aria-label="Dismiss"
+ className="-my-0.5 shrink-0 rounded-full p-0.5 opacity-70 transition-opacity hover:opacity-100"
+ >
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ ) : null}
+ </div>
+ );
+}
+
+function ContextUsageBar({ value }: { value?: number | null }): ReactElement {
if (value == null) {
- return null;
+ return <>–</>;
}
const pct = Math.max(0, Math.min(100, Math.round(value * 100)));
return (
- <div className="flex items-center gap-2">
+ <div className="flex h-[1lh] items-center gap-2">
+ <span className="shrink-0">{pct}%</span>
<div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
<div
className={cn(
@@ -248,22 +458,26 @@ function ContextUsageBar({
style={{ width: `${pct}%` }}
/>
</div>
- <span className="shrink-0 text-ui-11 tabular-nums text-muted-foreground">
- {pct}%
- </span>
</div>
);
}
-function RequestRow({
+const RequestRow = memo(function RequestRow({
entry,
selected,
onSelect,
+ now,
}: {
entry: ApiMonitorEntry;
selected: boolean;
- onSelect: () => void;
+ onSelect: (id: string) => void;
+ now: number;
}): ReactElement {
+ const age = (
+ <span title={formatFullTime(entry.started_at)}>
+ {formatAgo(entry.started_at, now)}
+ </span>
+ );
const preview =
entry.error ||
entry.reply_preview ||
@@ -272,30 +486,30 @@ function RequestRow({
// 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 w-full min-w-0 flex-col gap-0.5 rounded-lg px-3 py-2">
<div className="flex min-w-0 items-center gap-2">
<span
className={cn(
- "size-2 shrink-0 rounded-full",
+ "size-1.5 shrink-0 rounded-full",
statusDotClass(entry.status),
)}
aria-hidden={true}
/>
- <span className="truncate text-ui-13 font-medium text-foreground">
+ <span className="truncate text-ui-12 text-muted-foreground">
{lifecycleLabel(entry)}
</span>
<span className="ml-auto shrink-0 text-ui-11 tabular-nums text-muted-foreground">
- {formatTime(entry.started_at)}
+ {age}
</span>
</div>
- <div className="min-w-0 truncate pl-4 text-ui-11 text-muted-foreground">
+ <div className="min-w-0 truncate pl-3.5 text-ui-11 text-muted-foreground/80">
{entry.model}
</div>
{entry.error ? (
// Backend error text can quote the request, so keep it out too.
<div
data-reload-snapshot-sensitive
- className="min-w-0 break-words pl-4 text-ui-11 text-red-600 dark:text-red-400"
+ className="min-w-0 break-words pl-3.5 text-ui-11 text-red-600 dark:text-red-400"
>
{entry.error}
</div>
@@ -303,14 +517,16 @@ function RequestRow({
</div>
);
}
+ const speed = formatTokPerSec(entry.tok_per_sec);
return (
<button
type="button"
- onClick={onSelect}
+ data-entry-id={entry.id}
+ onClick={() => onSelect(entry.id)}
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",
+ "flex w-full min-w-0 flex-col gap-1 rounded-lg px-3 py-2.5 text-left outline-none transition-colors focus-visible:ring-1 focus-visible:ring-ring/70",
+ selected ? "bg-muted" : "hover:bg-muted/50",
)}
>
<div className="flex min-w-0 items-center gap-2">
@@ -321,22 +537,43 @@ function RequestRow({
)}
aria-hidden={true}
/>
- <span className="truncate text-ui-13 font-medium text-foreground">
+ <span className="truncate font-mono text-ui-12 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)}
+ {age}
</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 flex shrink-0 items-center gap-2 text-ui-11 tabular-nums text-muted-foreground">
- {formatTokPerSec(entry.tok_per_sec) ? (
- <span>{formatTokPerSec(entry.tok_per_sec)}</span>
+ <span className="ml-auto flex shrink-0 items-center gap-2.5 text-ui-11 tabular-nums text-muted-foreground">
+ <span
+ className="flex items-center gap-1"
+ title={
+ entry.prompt_tokens != null || entry.completion_tokens != null
+ ? `Total time: queue wait, prompt processing and generation\nTokens: ${optionalCount(entry.prompt_tokens)} in, ${optionalCount(entry.completion_tokens)} out`
+ : "Total time: queue wait, prompt processing and generation"
+ }
+ >
+ <HugeiconsIcon
+ icon={Timer01Icon}
+ strokeWidth={1.75}
+ className="size-3"
+ />
+ {entryDuration(entry)}
+ </span>
+ {speed ? (
+ <span className="flex items-center gap-1" title="Generation speed">
+ <HugeiconsIcon
+ icon={FlashIcon}
+ strokeWidth={1.75}
+ className="size-3"
+ />
+ {speed}
+ </span>
) : null}
- <span>{formatTime(entry.started_at)}</span>
</span>
</div>
{/* A prompt or reply excerpt, same as the expanded payload below it. */}
@@ -353,7 +590,7 @@ function RequestRow({
</p>
</button>
);
-}
+});
function PayloadBlock({
title,
@@ -371,14 +608,14 @@ function PayloadBlock({
const [showAll, setShowAll] = useState(false);
const preview = payloadPreview(body);
const canShowAll =
- !truncated &&
- preview !== body &&
- body.length <= PAYLOAD_SHOW_ALL_MAX_CHARS;
+ !truncated && preview !== body && body.length <= PAYLOAD_SHOW_ALL_MAX_CHARS;
const shown = showAll && canShowAll ? body : preview;
+ const [boxRef, singleLine] = useSingleLine<HTMLPreElement>();
+ const copyable = Boolean(body) && !truncated;
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">
+ <h3 className="text-ui-12 font-medium text-muted-foreground">
{title}
</h3>
<div className="flex items-center gap-1">
@@ -398,21 +635,35 @@ function PayloadBlock({
preview only
</span>
) : null}
- {body && !truncated ? (
- <CopyButton value={body} label={`Copy ${title.toLowerCase()}`} />
- ) : null}
</div>
</div>
- {/* Prompt and reply bodies, so keep them out of the reload snapshot. */}
- <pre
- data-reload-snapshot-sensitive
- className={cn(
- "max-h-72 overflow-auto whitespace-pre-wrap break-words scroll-rounded 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…" : shown || "–"}
- </pre>
+ <div className="relative min-w-0">
+ {/* Prompt and reply bodies, so keep them out of the reload snapshot. */}
+ <pre
+ ref={boxRef}
+ data-reload-snapshot-sensitive
+ className={cn(
+ "max-h-72 overflow-auto whitespace-pre-wrap break-words scroll-rounded p-3 text-ui-11 leading-[1.55]",
+ singleLine ? "rounded-full" : "rounded-lg",
+ copyable && "pr-11",
+ tone === "error"
+ ? "bg-red-500/5 text-red-700 dark:text-red-400"
+ : INSET,
+ )}
+ >
+ {loading && !body ? "Loading…" : shown || "–"}
+ </pre>
+ {copyable ? (
+ <div
+ className={cn(
+ "absolute right-1.5",
+ singleLine ? "top-1/2 -translate-y-1/2" : "top-1.5",
+ )}
+ >
+ <CopyButton value={body} label={`Copy ${title.toLowerCase()}`} />
+ </div>
+ ) : null}
+ </div>
</section>
);
}
@@ -431,6 +682,42 @@ function requestStatusLabel(entry: ApiMonitorEntry): string {
return "Prompt processing";
}
+function MetricGroup({
+ title,
+ items,
+}: {
+ title: string;
+ items: { label: string; value: ReactNode }[];
+}): ReactElement {
+ return (
+ <section className="flex min-w-0 flex-col gap-2">
+ <h3 className="text-ui-12 font-medium text-muted-foreground">{title}</h3>
+ <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-xl border border-border/50 bg-border/50 sm:grid-cols-3 dark:border-transparent dark:bg-card">
+ {items.map((item) => (
+ <div
+ key={item.label}
+ className={cn(
+ "flex min-w-0 flex-col gap-0.5 px-3 py-2",
+ INSET_OPAQUE,
+ )}
+ >
+ <dt className="truncate text-ui-11 text-muted-foreground">
+ {item.label}
+ </dt>
+ <dd className="truncate text-ui-13 tabular-nums text-foreground">
+ {item.value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+ );
+}
+
+function optionalCount(value?: number | null): string {
+ return value != null ? formatCount(value) : "–";
+}
+
function RequestDetail({
entry,
detail,
@@ -451,79 +738,47 @@ function RequestDetail({
? (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">
+ <header className="flex min-w-0 flex-col gap-1.5">
<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",
+ "inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-ui-11 font-medium capitalize",
+ INSET,
statusTextClass(entry.status),
)}
>
+ <span
+ className={cn(
+ "size-1.5 shrink-0 rounded-full",
+ statusDotClass(entry.status),
+ )}
+ aria-hidden={true}
+ />
{requestStatusLabel(entry)}
</span>
- <span className="ml-auto shrink-0 font-mono text-ui-10 text-muted-foreground">
+ <span className="ml-auto truncate 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 className="min-w-0 break-all font-mono text-ui-14 font-medium text-foreground">
+ <span className="text-muted-foreground">{entry.method}</span>{" "}
+ {entry.endpoint}
</h2>
- <p className="min-w-0 break-all text-ui-11 text-muted-foreground">
+ <p className="min-w-0 break-all text-ui-12 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">
- {[
+ <MetricGroup
+ title="Timing"
+ items={[
{ 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)
- : "–",
- },
- {
- label: "First token",
- value: entry.ttft_ms != null ? formatDuration(entry.ttft_ms) : "–",
- },
+ { label: "Total time", value: entryDuration(entry) },
+ { label: "First token", value: formatDuration(entry.ttft_ms) },
// Duration minus this is the queue wait, not slow decoding.
- {
- label: "Generating",
- value: entry.decode_ms != null ? formatDuration(entry.decode_ms) : "–",
- },
+ { label: "Generating", value: formatDuration(entry.decode_ms) },
{
label: "Prompt speed",
value: formatTokPerSec(entry.prompt_tok_per_sec) ?? "–",
@@ -532,30 +787,29 @@ function RequestDetail({
label: "Generation speed",
value: formatTokPerSec(entry.tok_per_sec) ?? "–",
},
+ ]}
+ />
+
+ <MetricGroup
+ title="Tokens"
+ items={[
{
- label: "Stop reason",
- value: entry.stop_reason ?? "–",
+ label: "Input (prompt)",
+ value: optionalCount(entry.prompt_tokens),
},
- ].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}
+ {
+ label: "Output (completion)",
+ value: optionalCount(entry.completion_tokens),
+ },
+ { label: "Total", value: optionalCount(entry.total_tokens) },
+ { label: "Context", value: optionalCount(entry.context_length) },
+ {
+ label: "Context used",
+ value: <ContextUsageBar value={entry.context_usage} />,
+ },
+ { label: "Stop reason", value: entry.stop_reason ?? "–" },
+ ]}
+ />
{entry.error ? (
<PayloadBlock title="Error" body={entry.error} tone="error" />
@@ -579,6 +833,65 @@ function RequestDetail({
);
}
+function QuickStart({
+ baseUrl,
+ model,
+}: {
+ baseUrl: string;
+ model: string | null;
+}): ReactElement {
+ const snippet = quickStartSnippet(baseUrl, model ?? "MODEL_ID");
+ return (
+ <div className="flex flex-col items-center gap-4 px-6 py-12 text-center">
+ <span
+ className={cn(
+ "flex size-10 items-center justify-center rounded-xl text-muted-foreground",
+ INSET,
+ )}
+ >
+ <HugeiconsIcon
+ icon={ComputerTerminal01Icon}
+ strokeWidth={1.75}
+ className="size-5"
+ />
+ </span>
+ <div className="flex max-w-md flex-col gap-1">
+ <h3 className="text-ui-15 font-semibold text-foreground">
+ No API traffic yet
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ {model
+ ? "Send a request to the base URL and it appears here as it streams."
+ : "Load a model, then send a request to the base URL. It appears here as it streams."}
+ </p>
+ </div>
+ <div className="relative w-full max-w-2xl text-left">
+ <pre
+ className={cn(
+ "overflow-x-auto scroll-rounded rounded-lg py-3 pr-11 pl-3.5 font-mono text-ui-11 leading-[1.6] text-foreground",
+ INSET,
+ )}
+ >
+ {snippet}
+ </pre>
+ <div className="absolute top-1.5 right-1.5">
+ <CopyButton value={snippet} label="Copy example request" />
+ </div>
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={openApiSettings}
+ className="h-8 gap-1.5 rounded-full"
+ >
+ <HugeiconsIcon icon={Key01Icon} strokeWidth={1.75} className="size-4" />
+ Create an API key and see more examples
+ </Button>
+ </div>
+ );
+}
+
export function ApiMonitorPage(): ReactElement {
const signalReady = useAppShellReadySignal();
const tour = useGuidedTourController({
@@ -611,9 +924,22 @@ export function ApiMonitorPage(): ReactElement {
const serverUrl = usePlatformStore((s) => s.serverUrl);
const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
const lanUrls = usePlatformStore((s) => s.lanUrls);
+ const runtime = useChatModelRuntime();
+ const loadedModels = useChatRuntimeStore((s) => s.loadedModels);
+ const residentCheckpoint = useChatRuntimeStore((s) => s.residentCheckpoint);
const [unloading, setUnloading] = useState(false);
+ const [ejectingKept, setEjectingKept] = useState(false);
+ const [exampleModel, setExampleModel] = useState<ServedModel | null>(null);
// block raw unloads while a picker load could finish afterward without a lifecycle guard.
const modelLoading = useChatRuntimeStore((s) => s.modelLoading);
+ const residencyKey = useMemo(
+ () =>
+ entries
+ .filter(isLifecycleEntry)
+ .map((entry) => `${entry.id}:${entry.status}`)
+ .join(","),
+ [entries],
+ );
const [unloadError, setUnloadError] = useState<string | null>(null);
const resident = useResidentRunTarget(data?.active_model);
const [configRequest, setConfigRequest] =
@@ -627,9 +953,7 @@ export function ApiMonitorPage(): ReactElement {
const refreshRemoteBase = () => {
void fetchDeviceType({ force: true });
loadLanAccess()
- .then((status) =>
- usePlatformStore.setState({ lanUrls: lanApiUrls(status) }),
- )
+ .then(publishLanUrls)
.catch(() => undefined);
};
refreshRemoteBase();
@@ -686,17 +1010,59 @@ export function ApiMonitorPage(): ReactElement {
}
};
const [statusFilter, setStatusFilter] = useState<MonitorStatusFilter>("all");
+ const [modelFilter, setModelFilter] = useState<string>(ALL_MODELS);
const [query, setQuery] = useState("");
+ const deferredQuery = useDeferredValue(query);
const [selectedId, setSelectedId] = useState<string | null>(null);
+ const listRef = useRef<HTMLDivElement>(null);
+ const focusRequestId = useApiMonitorOverlayStore((s) => s.focusRequestId);
+ const scrollToSelected = useRef(false);
+ useEffect(() => {
+ if (focusRequestId == null) return;
+ setSelectedId(focusRequestId);
+ setQuery("");
+ setStatusFilter("all");
+ setModelFilter(ALL_MODELS);
+ scrollToSelected.current = true;
+ useApiMonitorOverlayStore.getState().focusRequest(null);
+ }, [focusRequestId]);
+
+ const loggedModels = useMemo(() => {
+ const names = new Set<string>();
+ for (const entry of entries) {
+ if (!isLifecycleEntry(entry) && entry.model) names.add(entry.model);
+ }
+ return [...names].sort();
+ }, [entries]);
+ const effectiveModelFilter =
+ modelFilter !== ALL_MODELS && loggedModels.includes(modelFilter)
+ ? modelFilter
+ : ALL_MODELS;
+ const modelEntries = useMemo(
+ () =>
+ effectiveModelFilter === ALL_MODELS
+ ? entries
+ : entries.filter((entry) => entry.model === effectiveModelFilter),
+ [entries, effectiveModelFilter],
+ );
+ const modelStats = useMemo(
+ () =>
+ effectiveModelFilter === ALL_MODELS ? stats : computeStats(modelEntries),
+ [effectiveModelFilter, stats, modelEntries],
+ );
const visible = useMemo(
- () => filterEntries(entries, statusFilter, query),
- [entries, statusFilter, query],
+ () => filterEntries(modelEntries, statusFilter, deferredQuery),
+ [modelEntries, statusFilter, deferredQuery],
);
const selected = useMemo(
() => visible.find((entry) => entry.id === selectedId) ?? null,
[visible, selectedId],
);
+ const statusCounts = useMemo(
+ () => countByStatus(modelEntries),
+ [modelEntries],
+ );
// 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.
@@ -749,385 +1115,711 @@ export function ApiMonitorPage(): ReactElement {
detailInFlight,
]);
+ useEffect(() => {
+ if (!scrollToSelected.current || selectedId == null) return;
+ const row = listRef.current?.querySelector<HTMLElement>(
+ `[data-entry-id="${CSS.escape(selectedId)}"]`,
+ );
+ if (!row) return;
+ scrollToSelected.current = false;
+ row.scrollIntoView({ block: "nearest" });
+ }, [selectedId, visible]);
+
+ const onListKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") {
+ return;
+ }
+ const selectable = visible.filter((entry) => !isLifecycleEntry(entry));
+ if (selectable.length === 0) {
+ return;
+ }
+ event.preventDefault();
+ const index = selectable.findIndex((entry) => entry.id === selectedId);
+ const step = event.key === "ArrowDown" ? 1 : -1;
+ const next =
+ selectable[
+ index === -1
+ ? 0
+ : Math.max(0, Math.min(selectable.length - 1, index + step))
+ ];
+ setSelectedId(next.id);
+ listRef.current
+ ?.querySelector<HTMLElement>(`[data-entry-id="${CSS.escape(next.id)}"]`)
+ ?.focus();
+ };
+
// Tauri uses the runtime API base because its tauri:// origin omits the dynamic port.
const origin = typeof window === "undefined" ? "" : window.location.origin;
const localOrigin = isTauri ? (serverUrl ?? getApiBase()) : origin;
const baseUrl = `${remoteApiOrigin(cloudflareUrl, localOrigin, lanUrls)}/v1`;
- const serverStatus = data?.status ?? "idle";
+ const activeModel = data?.active_model ?? null;
+ const now = useServerNow(data?.server_time, entries.length > 0);
+ const served = useMemo(
+ () => servedModels(loadedModels, activeModel, residentCheckpoint),
+ [loadedModels, activeModel, residentCheckpoint],
+ );
+ const serverStatus =
+ SERVER_STATUS[
+ data?.status === "idle" && served.length > 0
+ ? "ready"
+ : (data?.status ?? "idle")
+ ];
// older backends omit the field, so only explicit `false` disables recording.
const loggingDisabled = data?.logging_enabled === false;
- const statusCopy =
- serverStatus === "generating"
- ? "Serving requests"
- : serverStatus === "ready"
- ? "Ready"
- : "No model loaded";
+ const queued = data?.queue?.queued ?? 0;
const slotsLabel = data?.queue
? `${data.queue.active}/${data.queue.capacity} busy${
- data.queue.queued > 0 ? ` · ${data.queue.queued} queued` : ""
+ queued > 0 ? ` · ${queued} queued` : ""
}`
: "";
const slotsClassName = cn(
- "text-ui-12 tabular-nums text-foreground",
- (data?.queue?.queued ?? 0) > 0 && "text-amber-700 dark:text-amber-500",
+ "tabular-nums",
+ queued > 0 && "text-amber-700 dark:text-amber-500",
+ );
+
+ const ejecting = unloading || ejectingKept;
+ const ejectServed = async (model: ServedModel): Promise<void> => {
+ if (model.active) {
+ await unloadActiveModel();
+ return;
+ }
+ setEjectingKept(true);
+ try {
+ await runtime.ejectModel(model.checkpoint);
+ refresh();
+ } finally {
+ setEjectingKept(false);
+ }
+ };
+ const ejectAll = async (): Promise<void> => {
+ setEjectingKept(true);
+ try {
+ await runtime.ejectAllModels();
+ refresh();
+ } finally {
+ setEjectingKept(false);
+ }
+ };
+ const openRunSettings = (model: ServedModel): void => {
+ const requestId = createModelConfigHandoffRequestId();
+ setConfigRequest(
+ model.active
+ ? runSettingsRequest(resident, requestId)
+ : keptRunSettingsRequest(model, requestId),
+ );
+ };
+ const settingsButton = (model: ServedModel): ReactElement => (
+ <ToolbarTooltip label={`Run settings for ${model.name}`}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={`Run settings for ${model.name}`}
+ aria-haspopup="dialog"
+ onClick={() => openRunSettings(model)}
+ // Primary opens only on live settings: the kept-model fallback would send Run its bare label.
+ disabled={
+ ejecting || modelLoading || (model.active && !canEditSettings)
+ }
+ className="size-7 shrink-0 rounded-full p-0 text-muted-foreground hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={Settings02Icon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </Button>
+ </ToolbarTooltip>
+ );
+ const exampleButton = (model: ServedModel): ReactElement => (
+ <ToolbarTooltip label={`API example for ${model.name}`}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={`API example for ${model.name}`}
+ aria-haspopup="dialog"
+ onClick={() => setExampleModel(model)}
+ className="size-7 shrink-0 rounded-full p-0 text-muted-foreground hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={CodeIcon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </Button>
+ </ToolbarTooltip>
+ );
+ const ejectLabel =
+ served.length > 1
+ ? `Eject all ${served.length} models and free their memory`
+ : served.length === 1
+ ? `Eject ${served[0].name} and free its memory`
+ : "No model is loaded";
+ const contextFact = (
+ <>
+ {data?.context_length ? (
+ <Fact label="Context">
+ <span className="tabular-nums">
+ {formatCount(data.context_length)} tokens
+ </span>
+ </Fact>
+ ) : null}
+ </>
+ );
+ const slotsFact = (
+ <>
+ {data?.queue ? (
+ <Fact label="Slots">
+ {canEditSlots ? (
+ <ToolbarTooltip label="Change parallel slots">
+ <button
+ type="button"
+ onClick={() =>
+ setConfigRequest(
+ slotsSettingsRequest(
+ resident,
+ createModelConfigHandoffRequestId(),
+ ),
+ )
+ }
+ className={cn(
+ slotsClassName,
+ "w-fit cursor-pointer text-left underline decoration-dotted decoration-muted-foreground/60 underline-offset-4 hover:decoration-foreground",
+ )}
+ >
+ {slotsLabel}
+ </button>
+ </ToolbarTooltip>
+ ) : (
+ <span className={slotsClassName}>{slotsLabel}</span>
+ )}
+ </Fact>
+ ) : null}
+ </>
+ );
+ const activeFacts = (
+ <>
+ {contextFact}
+ {slotsFact}
+ </>
);
return (
- <main className="mx-auto flex w-full max-w-6xl 3xl:max-w-[calc(1440px*var(--ui-space-scale,1))] 4xl:max-w-[calc(1760px*var(--ui-space-scale,1))] flex-col gap-6 px-6 pb-10 pt-12 max-sm:px-4 max-sm:pt-8 font-heading sm:px-10">
+ <main className="api-rounding mx-auto flex w-full max-w-6xl 3xl:max-w-[calc(1440px*var(--ui-space-scale,1))] 4xl:max-w-[calc(1760px*var(--ui-space-scale,1))] flex-col gap-5 px-6 pb-10 pt-12 max-sm:px-4 max-sm:pt-8 font-heading sm:px-10">
<GuidedTour {...tour.tourProps} />
- <header className="flex flex-wrap items-start justify-between gap-4">
+ <header className="flex flex-wrap items-end 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>
+ <div className="flex flex-wrap items-center gap-3">
+ <h1 className="text-ui-30 font-semibold leading-[1.04] tracking-[-0.028em] text-foreground sm:text-ui-34">
+ API
+ </h1>
+ <span
+ className={cn(
+ "inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-ui-12 font-medium text-foreground",
+ INSET,
+ )}
+ >
+ <span
+ className={cn("size-2 rounded-full", serverStatus.dot)}
+ aria-hidden={true}
+ />
+ {serverStatus.label}
+ {served.length > 1 ? (
+ <span className="text-muted-foreground">
+ · {served.length} models
+ </span>
+ ) : null}
+ </span>
+ </div>
<p className="text-sm text-muted-foreground">
- Live traffic through Unsloth&apos;s OpenAI-compatible server.
+ Serve your local models to any OpenAI-compatible client and watch
+ each request live.
</p>
</div>
- <div data-tour="api-toolbar" className="flex flex-wrap items-center gap-2">
- <ApiModelLoadControls
- activeModel={data?.active_model}
- onSettled={refresh}
- onUnloadActive={unloadActiveModel}
- unloading={unloading}
- configRequest={configRequest}
- onConfigRequestAdopted={() => setConfigRequest(null)}
- onOpenSettings={
- canEditSettings
- ? () =>
- setConfigRequest(
- runSettingsRequest(
- resident,
- createModelConfigHandoffRequestId(),
- ),
- )
- : undefined
- }
- />
- <ToolbarTooltip
- label={paused ? "Resume the live feed" : "Pause the live feed"}
+ <ToolbarTooltip label="API settings">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={openApiSettings}
+ aria-label="API settings"
+ className="size-10 rounded-full text-muted-foreground hover:bg-[color-mix(in_oklab,var(--foreground)_calc(10%*var(--contrast-wash-gain,1)),transparent)] hover:text-foreground dark:hover:bg-[color-mix(in_oklab,var(--foreground)_calc(14%*var(--contrast-wash-gain,1)),transparent)]"
>
- <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>
- </ToolbarTooltip>
- <ToolbarTooltip
- label={
- data?.active_model
- ? `Eject ${data.active_model} and free its VRAM`
- : "No model is loaded"
- }
- >
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => void unloadActiveModel()}
- disabled={unloading || modelLoading || !data?.active_model}
- className="h-9 gap-1.5 rounded-full"
- >
- <HugeiconsIcon
- icon={RemoveCircleIcon}
- strokeWidth={1.75}
- className="size-4"
- />
- {unloading ? "Ejecting" : "Eject"}
- </Button>
- </ToolbarTooltip>
- <ToolbarTooltip label="Refresh">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={refresh}
- disabled={refreshing}
- aria-label="Refresh"
- className="size-9 rounded-full p-0"
- >
- <HugeiconsIcon
- icon={Refresh01Icon}
- strokeWidth={1.75}
- className={cn("size-4", refreshing && "animate-spin")}
- />
- </Button>
- </ToolbarTooltip>
- <ToolbarTooltip label="Clear log">
- <Button
- type="button"
- variant="outline"
- size="sm"
- disabled={entries.length === 0}
- onClick={() => {
- setSelectedId(null);
- void clear();
- }}
- aria-label="Clear log"
- className="size-9 rounded-full p-0"
- >
- <HugeiconsIcon
- icon={Delete02Icon}
- strokeWidth={1.75}
- className="size-4"
- />
- </Button>
- </ToolbarTooltip>
- <ToolbarTooltip label="API settings">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() =>
- useSettingsDialogStore.getState().openDialog("api-keys")
- }
- aria-label="API settings"
- className="size-9 rounded-full p-0"
- >
- <HugeiconsIcon
- icon={Settings02Icon}
- strokeWidth={1.75}
- className="size-4"
- />
- </Button>
- </ToolbarTooltip>
- </div>
+ <HugeiconsIcon
+ icon={Settings02Icon}
+ strokeWidth={1.75}
+ className="size-5"
+ />
+ </Button>
+ </ToolbarTooltip>
</header>
{/* Checked first when a client can't reach the API: base URL and what is loaded. */}
<section
data-tour="api-endpoint"
- className="flex flex-wrap items-center gap-x-6 gap-y-3 rounded-xl border border-border/60 bg-card px-4 py-3"
+ className={cn("flex flex-col", SURFACE)}
>
- <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={ApiIcon}
- 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">
+ <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-3 px-5 py-4">
+ <div className="flex min-w-0 items-center gap-3">
<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>
- {data?.queue ? (
- <div className="flex min-w-0 flex-col">
- <span className="text-ui-10 font-medium uppercase tracking-wider text-muted-foreground">
- Slots
+ className="train-section-chip inline-flex size-9 shrink-0 items-center justify-center rounded-full"
+ style={
+ { "--chip-tint": "var(--control-accent)" } as CSSProperties
+ }
+ >
+ <HugeiconsIcon
+ icon={ApiIcon}
+ strokeWidth={1.5}
+ className="size-[calc(18px*var(--ui-space-scale,1))]"
+ />
</span>
- {canEditSlots ? (
- <ToolbarTooltip label="Change parallel slots">
- <button
+ <div className="flex min-w-0 flex-col">
+ <span className="text-ui-11 text-muted-foreground">Base URL</span>
+ <div className="group/copy flex min-w-0 items-center gap-1">
+ <span className="truncate font-mono text-ui-13 text-foreground">
+ {baseUrl}
+ </span>
+ <CopyButton
+ value={baseUrl}
+ label="Copy API base URL"
+ revealOnHover={true}
+ />
+ </div>
+ </div>
+ </div>
+ <div data-tour="api-toolbar" className="flex min-w-0 max-w-full">
+ <ApiModelLoadControls
+ runtime={runtime}
+ activeModel={data?.active_model}
+ residencyKey={residencyKey}
+ onSettled={refresh}
+ onUnloadActive={unloadActiveModel}
+ unloading={ejecting}
+ configRequest={configRequest}
+ onConfigRequestAdopted={() => setConfigRequest(null)}
+ onEjectAll={() => void ejectAll()}
+ >
+ <ToolbarTooltip label={ejectLabel}>
+ <Button
type="button"
+ variant="outline"
+ size="sm"
onClick={() =>
- setConfigRequest(
- slotsSettingsRequest(
- resident,
- createModelConfigHandoffRequestId(),
- ),
- )
+ void (served.length > 1
+ ? ejectAll()
+ : ejectServed(served[0]))
}
- className={cn(
- slotsClassName,
- "w-fit cursor-pointer text-left underline decoration-dotted decoration-muted-foreground/60 underline-offset-4 hover:decoration-foreground",
- )}
+ disabled={ejecting || modelLoading || served.length === 0}
+ className="h-9 gap-1.5 rounded-full px-3.5"
>
- {slotsLabel}
- </button>
+ <HugeiconsIcon
+ icon={RemoveCircleIcon}
+ strokeWidth={1.75}
+ className={cn("size-4", ejecting && "animate-pulse")}
+ />
+ {ejecting
+ ? "Ejecting"
+ : served.length > 1
+ ? "Eject all"
+ : "Eject"}
+ </Button>
</ToolbarTooltip>
- ) : (
- <span className={slotsClassName}>{slotsLabel}</span>
- )}
+ </ApiModelLoadControls>
</div>
- ) : null}
- <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}
+ <div className={cn("border-t px-5 pt-3.5 pb-5", DIVIDER)}>
+ {served.length > 1 ? (
+ <div className="flex flex-col gap-2">
+ <p className="text-ui-12 text-muted-foreground">
+ {served.length} models answering requests
+ </p>
+ <div className="grid grid-cols-[minmax(0,max-content)_auto_auto_auto_1fr] items-center gap-x-6 gap-y-1.5">
+ {served.map((model) => (
+ <div key={model.checkpoint} className="contents">
+ <span className="group/copy flex min-w-0 items-center gap-1 text-ui-12">
+ <span
+ className="size-1.5 shrink-0 rounded-full bg-emerald-500"
+ aria-hidden={true}
+ />
+ <span className="ml-1 truncate font-mono text-foreground">
+ {model.name}
+ </span>
+ <CopyButton
+ value={model.name}
+ label="Copy model name"
+ revealOnHover={true}
+ />
+ </span>
+ <span className="flex items-center gap-0.5">
+ {settingsButton(model)}
+ {exampleButton(model)}
+ </span>
+ <dl className="min-w-0">
+ {model.active ? contextFact : null}
+ </dl>
+ <dl className="min-w-0">
+ {model.active ? slotsFact : null}
+ </dl>
+ <span className="justify-self-end">
+ <ToolbarTooltip label={`Eject ${model.name}`}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={`Eject ${model.name}`}
+ onClick={() => void ejectServed(model)}
+ disabled={ejecting || modelLoading}
+ className="size-7 rounded-full p-0 text-muted-foreground hover:text-foreground"
+ >
+ <HugeiconsIcon
+ icon={RemoveCircleIcon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </Button>
+ </ToolbarTooltip>
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : (
+ <dl className="flex flex-wrap items-center gap-x-6 gap-y-2">
+ <Fact label="Model" className="group/copy max-w-full">
+ {served.length === 1 ? (
+ <>
+ <span className="truncate font-mono">{served[0].name}</span>
+ <CopyButton
+ value={served[0].name}
+ label="Copy model name"
+ revealOnHover={true}
+ />
+ {settingsButton(served[0])}
+ {exampleButton(served[0])}
+ </>
+ ) : (
+ <span className="text-muted-foreground">None loaded</span>
+ )}
+ </Fact>
+ {served[0]?.active ? activeFacts : null}
+ </dl>
+ )}
+ </div>
</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>
+ {error ? <Banner>{error}</Banner> : null}
+ {unloadError ? (
+ <Banner onDismiss={() => setUnloadError(null)}>{unloadError}</Banner>
) : null}
- <section className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
- <StatCard
+ <section
+ aria-label="Traffic summary"
+ className="elevated-card grid grid-cols-2 gap-px overflow-hidden bg-border/60 sm:grid-cols-3 lg:grid-cols-6 dark:bg-background"
+ >
+ <Stat
label="In flight"
- value={formatCount(stats.active)}
- tone={stats.active > 0 ? "active" : "default"}
+ value={formatCount(modelStats.active)}
+ tone={modelStats.active > 0 ? "active" : "default"}
+ hint={queued > 0 ? `${formatCount(queued)} queued` : undefined}
/>
- <StatCard
+ <Stat
label="Requests"
- value={formatCount(stats.total)}
- hint={loggingDisabled ? "recording off" : "recent window"}
+ value={formatCount(modelStats.total)}
+ hint={loggingDisabled ? "recording off" : "in the recent log"}
/>
- <StatCard label="Completed" value={formatCount(stats.completed)} />
- <StatCard
+ <Stat
label="Errors"
- value={formatCount(stats.errors)}
- tone={stats.errors > 0 ? "error" : "default"}
+ value={formatCount(modelStats.errors)}
+ tone={modelStats.errors > 0 ? "error" : "default"}
hint={
- stats.errorRate != null
- ? `${Math.round(stats.errorRate * 100)}% of finished`
+ modelStats.errorRate != null
+ ? `${Math.round(modelStats.errorRate * 100)}% of finished`
: undefined
}
/>
- <StatCard
+ <Stat
label="Avg latency"
- value={
- stats.avgDurationMs == null
- ? "–"
- : formatDuration(stats.avgDurationMs)
- }
+ value={formatDuration(modelStats.avgDurationMs)}
hint={
- stats.maxDurationMs != null
- ? `max ${formatDuration(stats.maxDurationMs)}`
+ modelStats.maxDurationMs != null
+ ? `max ${formatDuration(modelStats.maxDurationMs)}`
: undefined
}
/>
- <StatCard
- label="Throughput"
+ <Stat
+ label="Generation speed"
value={
- stats.tokensPerSecond == null
+ modelStats.tokensPerSecond == null
? "–"
- : `${stats.tokensPerSecond.toFixed(1)} tok/s`
+ : `${modelStats.tokensPerSecond.toFixed(1)} tok/s`
}
- hint={`${formatCount(stats.totalTokens)} tokens · generation only`}
+ hint="while decoding"
+ />
+ <Stat
+ label="Tokens"
+ value={formatCount(modelStats.totalTokens)}
+ hint={`${formatCount(modelStats.inputTokens)} in · ${formatCount(modelStats.outputTokens)} out`}
/>
</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 max-sm:basis-full 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)
- }
+ <section className={cn("flex min-h-0 flex-col overflow-hidden", SURFACE)}>
+ <div
+ className={cn(
+ "flex flex-wrap items-center gap-2 border-b px-4 py-3",
+ DIVIDER,
+ )}
+ >
+ <div className="relative w-full min-w-0 sm:w-56">
+ <HugeiconsIcon
+ icon={Search01Icon}
+ strokeWidth={1.75}
+ className="pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2 text-muted-foreground"
+ aria-hidden={true}
+ />
+ <Input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder="Search requests"
+ aria-label="Search API requests"
+ title="Matches the model, endpoint, prompt, reply or error"
+ className="pl-8"
+ />
+ </div>
+ <nav
+ aria-label="Filter by status"
+ className="-my-2 flex max-w-full gap-1 overflow-x-auto px-1 py-2 [scrollbar-width:none]!"
>
- <SelectTrigger
- aria-label="Filter by status"
- className="h-9 w-[calc(150px*var(--ui-space-scale,1))] 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}>
+ {STATUS_FILTERS.map((option) => {
+ const active = statusFilter === option.value;
+ const count = statusCounts[option.value];
+ return (
+ <button
+ key={option.value}
+ type="button"
+ aria-current={active ? "page" : undefined}
+ onClick={() => setStatusFilter(option.value)}
+ className={cn(
+ "flex h-9 shrink-0 items-center gap-1.5 rounded-full px-3.5 text-ui-14 text-foreground/80 transition-colors hover:text-foreground",
+ active &&
+ "bg-white font-medium text-foreground shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] dark:shadow-none",
+ )}
+ >
{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>
+ {option.value !== "all" && count > 0 ? (
+ <span
+ className={cn(
+ "tabular-nums text-muted-foreground",
+ option.value === "error" &&
+ "text-red-600 dark:text-red-400",
+ )}
+ >
+ {formatCount(count)}
+ </span>
+ ) : null}
+ </button>
+ );
+ })}
+ </nav>
+ {loggedModels.length > 1 ? (
+ <Select value={effectiveModelFilter} onValueChange={setModelFilter}>
+ <SelectTrigger
+ aria-label="Filter by model"
+ className="h-9 max-w-64 rounded-full"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={ALL_MODELS}>All models</SelectItem>
+ {loggedModels.map((model) => (
+ <SelectItem key={model} value={model}>
+ {model}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : null}
+ <div className="ml-auto flex shrink-0 items-center gap-1">
+ {visible.length !== entries.length ? (
+ <span className="mr-1 text-ui-11 tabular-nums text-muted-foreground">
+ {formatCount(visible.length)} of {formatCount(entries.length)}
+ </span>
+ ) : null}
+ <ToolbarTooltip
+ label={paused ? "Resume the live feed" : "Pause the live feed"}
+ >
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={
+ paused ? "Resume the live feed" : "Pause the live feed"
+ }
+ aria-pressed={paused}
+ onClick={() => setPaused(!paused)}
+ className={cn(
+ "rounded-full",
+ paused &&
+ "bg-amber-500/10 text-amber-700 hover:bg-amber-500/15 dark:text-amber-500",
+ )}
+ >
+ <HugeiconsIcon
+ icon={paused ? PlayIcon : PauseIcon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </Button>
+ </ToolbarTooltip>
+ <ToolbarTooltip label="Refresh">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={refresh}
+ disabled={refreshing}
+ aria-label="Refresh"
+ className="rounded-full"
+ >
+ <HugeiconsIcon
+ icon={Refresh01Icon}
+ strokeWidth={1.75}
+ className={cn("size-4", refreshing && "animate-spin")}
+ />
+ </Button>
+ </ToolbarTooltip>
+ <ToolbarTooltip label="Clear log">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ disabled={entries.length === 0}
+ onClick={() => {
+ setSelectedId(null);
+ void clear();
+ }}
+ aria-label="Clear log"
+ className="rounded-full"
+ >
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </Button>
+ </ToolbarTooltip>
+ </div>
</div>
- <div
- data-tour="api-log"
- className="grid min-h-0 grid-cols-1 lg:grid-cols-[minmax(0,380px)_minmax(0,1fr)] 4xl:grid-cols-[minmax(0,480px)_minmax(0,1fr)]"
- >
- <div className="max-h-[calc(560px*var(--ui-space-scale,1))] min-h-[calc(220px*var(--ui-space-scale,1))] max-lg:max-h-[45dvh] 3xl:max-h-[calc(100dvh-22rem*var(--ui-space-scale,1))] 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 Unsloth to re-enable."
- : "No API traffic yet. Point a client at the base URL above to see requests here."}
+ {!loading && entries.length === 0 ? (
+ <div data-tour="api-log">
+ {loggingDisabled ? (
+ <p className="mx-auto max-w-lg px-6 py-14 text-center text-sm text-muted-foreground">
+ 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 Unsloth to
+ re-enable.
</p>
) : (
- visible.map((entry) => (
- <RequestRow
- key={entry.id}
- entry={entry}
- selected={entry.id === selectedId}
- onSelect={() => setSelectedId(entry.id)}
- />
- ))
+ <QuickStart
+ baseUrl={baseUrl}
+ model={
+ (served.find((m) => m.active) ?? served[0])?.name ?? null
+ }
+ />
)}
</div>
+ ) : (
+ <div
+ data-tour="api-log"
+ className="grid min-h-0 grid-cols-1 lg:grid-cols-[minmax(0,380px)_minmax(0,1fr)] 4xl:grid-cols-[minmax(0,480px)_minmax(0,1fr)]"
+ >
+ <div
+ ref={listRef}
+ onKeyDown={onListKeyDown}
+ className={cn(
+ PANE_HEIGHT,
+ DIVIDER,
+ "flex flex-col gap-0.5 border-b p-1.5 lg:border-b-0 lg:border-r",
+ )}
+ >
+ {loading ? (
+ <div className="flex flex-col gap-2 p-1.5">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-16 w-full rounded-lg" />
+ ))}
+ </div>
+ ) : visible.length === 0 ? (
+ <div className="flex flex-col items-center gap-3 px-4 py-10 text-center text-sm text-muted-foreground">
+ No requests match this filter.
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ setQuery("");
+ setStatusFilter("all");
+ setModelFilter(ALL_MODELS);
+ }}
+ className="h-8 rounded-full"
+ >
+ Clear filters
+ </Button>
+ </div>
+ ) : (
+ visible.map((entry) => (
+ <RequestRow
+ key={entry.id}
+ entry={entry}
+ selected={entry.id === selectedId}
+ onSelect={setSelectedId}
+ now={now}
+ />
+ ))
+ )}
+ </div>
- <div className="max-h-[calc(560px*var(--ui-space-scale,1))] min-h-[calc(220px*var(--ui-space-scale,1))] max-lg:max-h-[45dvh] 3xl:max-h-[calc(100dvh-22rem*var(--ui-space-scale,1))] 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 className={PANE_HEIGHT}>
+ {selected ? (
+ <RequestDetail
+ entry={selected}
+ detail={details[selected.id]}
+ loading={loadingDetails.has(selected.id)}
+ />
+ ) : (
+ <div className="flex h-full flex-col items-center justify-center gap-3 px-6 py-10 text-center">
+ <span
+ className={cn(
+ "flex size-10 items-center justify-center rounded-xl text-muted-foreground",
+ INSET,
+ )}
+ >
+ <HugeiconsIcon
+ icon={CursorPointer02Icon}
+ strokeWidth={1.75}
+ className="size-5"
+ />
+ </span>
+ <p className="max-w-xs text-sm text-muted-foreground">
+ Select a request to inspect its prompt, reply, tokens and
+ errors. Use the arrow keys to step through the list.
+ </p>
+ </div>
+ )}
+ </div>
</div>
- </div>
+ )}
</section>
<SavedModelSettingsPanel />
+ <ApiExampleDialog
+ open={exampleModel != null}
+ onOpenChange={(open) => {
+ if (!open) setExampleModel(null);
+ }}
+ baseUrl={baseUrl}
+ model={exampleModel?.name ?? ""}
+ samplingModelId={exampleModel?.checkpoint ?? ""}
+ />
</main>
);
}
diff --git a/studio/frontend/src/features/api-monitor/api-sampling-example.ts b/studio/frontend/src/features/api-monitor/api-sampling-example.ts
new file mode 100644
index 00000000000..2558aa1e82e
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/api-sampling-example.ts
@@ -0,0 +1,55 @@
+// 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 type ApiSamplingDefaults = Partial<{
+ temperature: number;
+ top_p: number;
+ top_k: number;
+ min_p: number;
+ repetition_penalty: number;
+ presence_penalty: number;
+}>;
+
+// The OpenAI client takes these as kwargs; the Unsloth extensions only go through extra_body.
+const CLIENT_FIELDS = ["temperature", "top_p", "presence_penalty"] as const;
+const EXTRA_FIELDS = ["top_k", "min_p", "repetition_penalty"] as const;
+
+export function apiExampleModelName(
+ id: string,
+ ggufVariant: string | null,
+): string {
+ return ggufVariant && !id.includes(":") ? `${id}:${ggufVariant}` : id;
+}
+
+export function buildApiSamplingExample({
+ baseUrl,
+ model,
+ sampling,
+}: {
+ baseUrl: string;
+ model: string;
+ sampling: ApiSamplingDefaults;
+}): string {
+ const args = CLIENT_FIELDS.filter((field) => sampling[field] != null).map(
+ (field) => ` ${field}=${sampling[field]},`,
+ );
+ const extras = EXTRA_FIELDS.filter((field) => sampling[field] != null).map(
+ (field) => ` "${field}": ${sampling[field]},`,
+ );
+ return [
+ "from openai import OpenAI",
+ "",
+ "client = OpenAI(",
+ ` base_url=${JSON.stringify(baseUrl)},`,
+ ' api_key="sk-unsloth-YOUR_KEY",',
+ ")",
+ "",
+ "response = client.chat.completions.create(",
+ ` model=${JSON.stringify(model)},`,
+ ' messages=[{"role": "user", "content": "Hello!"}],',
+ ...args,
+ ...(extras.length > 0 ? [" extra_body={", ...extras, " },"] : []),
+ ")",
+ "print(response.choices[0].message.content)",
+ ].join("\n");
+}
diff --git a/studio/frontend/src/features/api-monitor/components/api-example-dialog.tsx b/studio/frontend/src/features/api-monitor/components/api-example-dialog.tsx
new file mode 100644
index 00000000000..c6a7e41a280
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/components/api-example-dialog.tsx
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { createCodePlugin } from "@/components/assistant-ui/code-plugin";
+import {
+ unslothDarkTheme,
+ unslothLightTheme,
+} from "@/components/assistant-ui/code-themes";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { authFetch } from "@/features/auth";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { Tick02Icon } from "@/lib/tick-icon";
+import { Copy01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { type ReactElement, useEffect, useMemo, useRef, useState } from "react";
+import { Streamdown } from "streamdown";
+import {
+ type ApiSamplingDefaults,
+ buildApiSamplingExample,
+} from "../api-sampling-example";
+
+const SHIKI_THEMES = [unslothLightTheme, unslothDarkTheme] as [
+ typeof unslothLightTheme,
+ typeof unslothDarkTheme,
+];
+const codePlugin = createCodePlugin({ themes: SHIKI_THEMES });
+
+export function ApiExampleDialog({
+ open,
+ onOpenChange,
+ baseUrl,
+ model,
+ samplingModelId,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ baseUrl: string;
+ model: string;
+ samplingModelId: string;
+}): ReactElement {
+ const [sampling, setSampling] = useState<ApiSamplingDefaults | null>(null);
+ const [copied, setCopied] = useState(false);
+ const timer = useRef<number | undefined>(undefined);
+
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ setSampling(null);
+ authFetch(
+ `/api/inference/sampling-defaults?model=${encodeURIComponent(samplingModelId)}`,
+ )
+ .then((res) => (res.ok ? res.json() : {}))
+ .then((body: ApiSamplingDefaults) => {
+ if (!cancelled) setSampling(body);
+ })
+ // Older backends lack the route: the example still runs, without values.
+ .catch(() => {
+ if (!cancelled) setSampling({});
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, samplingModelId]);
+
+ useEffect(() => () => window.clearTimeout(timer.current), []);
+
+ const snippet = buildApiSamplingExample({
+ baseUrl,
+ model,
+ sampling: sampling ?? {},
+ });
+ const markdown = useMemo(() => `\`\`\`python\n${snippet}\n\`\`\``, [snippet]);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="api-rounding corner-squircle dialog-soft-surface gap-5 sm:max-w-3xl">
+ <DialogHeader>
+ <DialogTitle>API example</DialogTitle>
+ <DialogDescription>
+ A request to <span className="font-mono">{model}</span> with the
+ sampling it gets when a request leaves these out. Send your own
+ values to override them.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="relative min-w-0">
+ <div className="corner-squircle max-h-[60dvh] overflow-auto scroll-rounded rounded-xl bg-[color-mix(in_oklab,var(--foreground)_calc(5%*var(--contrast-wash-gain,1)),transparent)] py-3 pr-11 pl-3 text-ui-12 leading-[1.6] dark:bg-[rgb(255_255_255_/_calc(0.05*var(--contrast-wash-gain,1)))] [&_[data-streamdown=code-block-header]]:hidden [&_[data-streamdown=code-block]]:!my-0 [&_[data-streamdown=code-block]]:!border-0 [&_[data-streamdown=code-block]]:!bg-transparent [&_[data-streamdown=code-block]]:!p-0 [&_code]:!text-ui-12 [&_pre]:!m-0 [&_pre]:!border-0 [&_pre]:!bg-transparent [&_pre]:!p-0 [&_pre]:!text-ui-12 [&_pre]:!leading-[1.6]">
+ {sampling ? (
+ <Streamdown
+ mode="static"
+ plugins={{ code: codePlugin }}
+ controls={{ code: false }}
+ shikiTheme={SHIKI_THEMES}
+ >
+ {markdown}
+ </Streamdown>
+ ) : (
+ <span className="font-mono text-muted-foreground">Loading…</span>
+ )}
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label="Copy example request"
+ title={copied ? "Copied" : "Copy example request"}
+ disabled={!sampling}
+ onClick={async () => {
+ if (await copyToClipboard(snippet)) {
+ setCopied(true);
+ window.clearTimeout(timer.current);
+ timer.current = window.setTimeout(() => setCopied(false), 1800);
+ }
+ }}
+ className="absolute top-2 right-2 size-7 rounded-full p-0"
+ >
+ <HugeiconsIcon
+ icon={copied ? Tick02Icon : Copy01Icon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/studio/frontend/src/features/api-monitor/components/api-model-load-controls.tsx b/studio/frontend/src/features/api-monitor/components/api-model-load-controls.tsx
index dbf39c45354..2ce722374f8 100644
--- a/studio/frontend/src/features/api-monitor/components/api-model-load-controls.tsx
+++ b/studio/frontend/src/features/api-monitor/components/api-model-load-controls.tsx
@@ -9,7 +9,7 @@ import {
chatLocalModelOptions,
isExternalModelId,
readLastLocalModelLoad,
- useChatModelRuntime,
+ type useChatModelRuntime,
useChatRuntimeStore,
wantsDownloadManagerStaging,
} from "@/features/chat";
@@ -32,11 +32,12 @@ import {
} from "@/features/model-picker";
import { isNpuModelId } from "@/features/npu";
import { cn } from "@/lib/utils";
-import { ReloadIcon, Settings02Icon } from "@hugeicons/core-free-icons";
+import { ReloadIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
type Dispatch,
type ReactElement,
+ type ReactNode,
type SetStateAction,
useCallback,
useEffect,
@@ -207,25 +208,37 @@ function toModelOptions(
}
export function ApiModelLoadControls({
+ runtime,
activeModel,
+ residencyKey,
onSettled,
onUnloadActive,
unloading,
configRequest = null,
onConfigRequestAdopted,
- onOpenSettings,
+ onEjectAll,
+ children,
}: {
+ runtime: ReturnType<typeof useChatModelRuntime>;
activeModel: string | null | undefined;
+ // Not active_model: a kept-model unload or a side load leaves that unchanged.
+ residencyKey: string;
onSettled: () => void;
onUnloadActive: () => void;
// The page's unload rereads the resident on its second pass, so a load started meanwhile would be unloaded.
unloading: boolean;
configRequest?: ModelConfigHandoffRequest | null;
onConfigRequestAdopted?: (requestId: string) => void;
- onOpenSettings?: () => void;
+ onEjectAll?: () => void;
+ children?: ReactNode;
}): ReactElement {
- const { selectModel, loadNpuModel, refresh, ejectModel } =
- useChatModelRuntime();
+ const { selectModel, loadNpuModel, refresh, ejectModel } = runtime;
+ const loadedModels = useChatRuntimeStore((s) => s.loadedModels);
+ const loadedNames = useMemo(
+ () =>
+ loadedModels.map((model) => model.id.split(/[\\/]/).pop() || model.id),
+ [loadedModels],
+ );
const modelsFromStore = useChatRuntimeStore((s) => s.models);
const lorasFromStore = useChatRuntimeStore((s) => s.loras);
const modelLoading = useChatRuntimeStore((s) => s.modelLoading);
@@ -273,6 +286,7 @@ export function ApiModelLoadControls({
// An API auto-switch changes the resident model behind Chat's store; this page's own loads
// reconcile themselves.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: residencyKey is the trigger, not an input
useEffect(() => {
if (activeModel === undefined) {
return;
@@ -281,7 +295,7 @@ export function ApiModelLoadControls({
if (!useChatRuntimeStore.getState().modelLoading) {
refresh({ includeLoras: false });
}
- }, [activeModel, refresh, refreshLastLoadLabel]);
+ }, [activeModel, residencyKey, refresh, refreshLastLoadLabel]);
const models = useMemo(
() => toModelOptions(modelsFromStore),
@@ -443,6 +457,9 @@ export function ApiModelLoadControls({
}}
// The page unload skips the runtime's load guard, so a replacement mid-load would land after it.
onEject={busy ? undefined : handleEject}
+ onEjectAll={busy || !onEjectAll ? undefined : onEjectAll}
+ loadedCount={loadedModels.length}
+ loadedNames={loadedNames}
onFoldersChange={() => {
refreshLocalModels();
}}
@@ -456,59 +473,33 @@ export function ApiModelLoadControls({
placeholder="Load model"
open={selectorOpen && !unloading}
onOpenChange={setSelectorOpen}
- className="h-9 max-w-full rounded-full"
+ className="h-9 max-w-full rounded-full sm:max-w-[calc(28rem*var(--ui-space-scale,1))]"
contentClassName="max-sm:max-w-[calc(100vw-3rem)]"
/>
- <ToolbarTooltip
- label={
- activeModel
- ? "Model run settings"
- : "Load a model to change its run settings"
- }
- >
- <Button
- type="button"
- variant="outline"
- size="sm"
- aria-label="Model settings"
- aria-haspopup="dialog"
- aria-expanded={selectorOpen && !unloading}
- onClick={onOpenSettings}
- disabled={busy || reloading || !onOpenSettings}
- className="h-9 gap-1.5 rounded-full"
- >
- <HugeiconsIcon
- icon={Settings02Icon}
- strokeWidth={1.75}
- className="size-4"
- />
- Settings
- </Button>
- </ToolbarTooltip>
<ToolbarTooltip label={reloadTitle(lastLoadLabel, Boolean(activeModel))}>
<Button
type="button"
variant="outline"
- size="sm"
+ size="icon"
+ aria-label={reloading ? "Reloading" : "Reload"}
onClick={() => {
handleReload();
}}
disabled={reloadDisabled}
- className="h-9 gap-1.5 rounded-full"
+ className="rounded-full"
>
<HugeiconsIcon
icon={ReloadIcon}
strokeWidth={1.75}
className={cn("size-4", reloading && "animate-spin")}
/>
- {reloading ? "Reloading" : "Reload"}
</Button>
</ToolbarTooltip>
+ {children}
{actionError ? (
<span
role="alert"
- className="max-w-64 truncate text-ui-11 text-red-600 dark:text-red-400"
- title={actionError}
+ className="basis-full break-words text-ui-12 text-red-600 dark:text-red-400"
>
{actionError}
</span>
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
index dde6b5396ec..73cf1a8260b 100644
--- a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
+++ b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
@@ -6,6 +6,7 @@
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
+import { cn } from "@/lib/utils";
import {
type ApiModelOverride,
type ApiModelOverrides,
@@ -23,6 +24,7 @@ import {
} from "react";
import { toast } from "sonner";
import { forgetModelOverride } from "../forget-model-override";
+import { useSingleLine } from "../use-single-line";
function plural(count: number, noun: string): string {
return `${count} ${noun}${count === 1 ? "" : "s"}`;
@@ -129,6 +131,8 @@ function describeOverride(override: ApiModelOverride): string[] {
export function SavedModelSettingsPanel(): ReactElement {
const [overrides, setOverrides] = useState<ApiModelOverrides | null>(null);
const [error, setError] = useState<string | null>(null);
+ const [errorRef, errorSingle] = useSingleLine<HTMLDivElement>();
+ const [emptyRef, emptySingle] = useSingleLine<HTMLParagraphElement>();
const [forgetting, setForgetting] = useState<ReadonlySet<string>>(
() => new Set(),
);
@@ -191,22 +195,26 @@ export function SavedModelSettingsPanel(): ReactElement {
const entries = Object.entries(overrides ?? {});
return (
- <section className="flex flex-col gap-3">
+ <section className="flex flex-col gap-3 pt-2">
<div className="flex flex-col gap-1">
<h2 className="text-ui-16 font-semibold tracking-[-0.01em] text-foreground">
- Settings applied on API load
+ Saved load settings
</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 an entry from
- that model&apos;s settings, or forget it here, which clears it from
- the picker too.
+ A request that names one of these models loads it with the settings
+ saved in its Run settings. Other models load with app defaults.
+ Forgetting an entry also clears it from the picker.
</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">
+ <div
+ ref={errorRef}
+ className={cn(
+ "border border-red-500/40 bg-red-500/5 px-4 py-3 text-sm text-red-600 dark:text-red-400",
+ errorSingle ? "rounded-full" : "rounded-xl",
+ )}
+ >
{error}
</div>
) : overrides == null ? (
@@ -216,19 +224,24 @@ export function SavedModelSettingsPanel(): ReactElement {
))}
</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
+ ref={emptyRef}
+ className={cn(
+ "border border-dashed border-border/80 px-4 text-center text-sm text-muted-foreground",
+ emptySingle ? "rounded-full py-3" : "rounded-xl py-6",
+ )}
+ >
+ No saved settings yet. Turn on &quot;Remember for this model&quot; in
+ a model&apos;s Run settings and API loads will use them too.
</p>
) : (
- <ul className="flex flex-col gap-2">
+ <ul className="elevated-card flex flex-col divide-y divide-border/60 overflow-hidden bg-card dark:divide-background">
{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"
+ className="flex min-w-0 items-start gap-3 px-5 py-3.5"
>
<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">
diff --git a/studio/frontend/src/features/api-monitor/monitor-snapshot.ts b/studio/frontend/src/features/api-monitor/monitor-snapshot.ts
new file mode 100644
index 00000000000..086927a805e
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/monitor-snapshot.ts
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// React-free so the node --test suite can import it.
+
+import type {
+ ApiMonitorEntry,
+ ApiMonitorResponse,
+} from "@/features/chat/types/api";
+
+export type MonitorStatusFilter =
+ | "all"
+ | "running"
+ | "completed"
+ | "error"
+ | "cancelled";
+
+function sameValue(a: unknown, b: unknown): boolean {
+ if (a === b) return true;
+ if (
+ a == null ||
+ b == null ||
+ typeof a !== "object" ||
+ typeof b !== "object"
+ ) {
+ return false;
+ }
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+function sameFields(
+ a: Record<string, unknown>,
+ b: Record<string, unknown>,
+ skip?: string,
+): boolean {
+ const keys = Object.keys(a);
+ if (keys.length !== Object.keys(b).length) return false;
+ return keys.every((key) => key === skip || sameValue(a[key], b[key]));
+}
+
+function mergeEntries(
+ previous: ApiMonitorEntry[],
+ next: ApiMonitorEntry[],
+): ApiMonitorEntry[] {
+ const byId = new Map(previous.map((entry) => [entry.id, entry]));
+ let unchanged = previous.length === next.length;
+ const merged = next.map((entry, index) => {
+ const kept = byId.get(entry.id);
+ if (
+ kept &&
+ sameFields(
+ kept as unknown as Record<string, unknown>,
+ entry as unknown as Record<string, unknown>,
+ )
+ ) {
+ if (previous[index] !== kept) unchanged = false;
+ return kept;
+ }
+ unchanged = false;
+ return entry;
+ });
+ return unchanged ? previous : merged;
+}
+
+export function mergeMonitorResponse(
+ previous: ApiMonitorResponse | null,
+ next: ApiMonitorResponse,
+): ApiMonitorResponse {
+ if (previous == null) return next;
+ const entries = mergeEntries(previous.entries, next.entries);
+ const merged = { ...next, entries };
+ if (
+ entries === previous.entries &&
+ sameFields(
+ previous as unknown as Record<string, unknown>,
+ merged as unknown as Record<string, unknown>,
+ "server_time",
+ )
+ ) {
+ return previous;
+ }
+ return merged;
+}
+
+export function matchesStatus(
+ entry: ApiMonitorEntry,
+ status: MonitorStatusFilter,
+): boolean {
+ if (status === "all") return true;
+ if (entry.status !== status) return false;
+ return entry.kind !== "lifecycle" || status === "error";
+}
+
+export function filterEntries(
+ entries: ApiMonitorEntry[],
+ status: MonitorStatusFilter,
+ query: string,
+): ApiMonitorEntry[] {
+ const needle = query.trim().toLowerCase();
+ return entries.filter((entry) => {
+ if (!matchesStatus(entry, status)) {
+ return false;
+ }
+ if (!needle) {
+ return true;
+ }
+ // Coerced: one malformed network 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),
+ );
+ });
+}
+
+const COUNTED_STATUSES = [
+ "running",
+ "completed",
+ "error",
+ "cancelled",
+] as const;
+
+export function countByStatus(
+ entries: ApiMonitorEntry[],
+): Record<MonitorStatusFilter, number> {
+ const counts: Record<MonitorStatusFilter, number> = {
+ all: entries.length,
+ running: 0,
+ completed: 0,
+ error: 0,
+ cancelled: 0,
+ };
+ for (const entry of entries) {
+ for (const status of COUNTED_STATUSES) {
+ if (matchesStatus(entry, status)) counts[status] += 1;
+ }
+ }
+ return counts;
+}
diff --git a/studio/frontend/src/features/api-monitor/overlay-store.ts b/studio/frontend/src/features/api-monitor/overlay-store.ts
index 88810f42dac..d985a7c54d7 100644
--- a/studio/frontend/src/features/api-monitor/overlay-store.ts
+++ b/studio/frontend/src/features/api-monitor/overlay-store.ts
@@ -39,9 +39,11 @@ interface ApiMonitorOverlayState {
suppressed: boolean;
/** Persisted opt out: when false the panel never opens itself. */
autoOpen: boolean;
+ focusRequestId: string | null;
open: () => void;
close: () => void;
setAutoOpen: (autoOpen: boolean) => void;
+ focusRequest: (id: string | null) => void;
}
/** Only `autoOpen` persists; a dismissal lasts the sitting, not forever. */
@@ -51,9 +53,11 @@ export const useApiMonitorOverlayStore = create<ApiMonitorOverlayState>()(
isOpen: false,
suppressed: false,
autoOpen: true,
+ focusRequestId: null,
open: () => set({ isOpen: true, suppressed: false }),
close: () => set({ isOpen: false, suppressed: true }),
setAutoOpen: (autoOpen) => set({ autoOpen }),
+ focusRequest: (focusRequestId) => set({ focusRequestId }),
}),
{
name: "unsloth_api_monitor_overlay",
diff --git a/studio/frontend/src/features/api-monitor/slots-settings-request.ts b/studio/frontend/src/features/api-monitor/slots-settings-request.ts
index cf0ab0eea2c..5a2e2ff6a07 100644
--- a/studio/frontend/src/features/api-monitor/slots-settings-request.ts
+++ b/studio/frontend/src/features/api-monitor/slots-settings-request.ts
@@ -1,6 +1,8 @@
// 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 { isStandaloneGgufPath } from "@/features/hub/lib/model-identity";
+import { cachedRepoConfigId } from "@/features/model-picker/model-config/model-identity";
// eslint-disable-next-line no-restricted-imports -- The barrel pulls in React components, which node tests cannot load.
import {
type ModelConfigHandoffRequest,
@@ -61,6 +63,7 @@ export function runSettingsRequest(
requestId,
id: resident.checkpoint,
focus: "advanced",
+ standalone: true,
meta: {
source: "local",
isLora: resident.isLora,
@@ -75,6 +78,31 @@ export function runSettingsRequest(
};
}
+export function keptRunSettingsRequest(
+ model: { checkpoint: string; quant: string | null },
+ requestId: string,
+): ModelConfigHandoffRequest {
+ // A standalone .gguf's quant is a filename label; saved without it (residentModelConfigTarget), else a second record.
+ const standalone = isStandaloneGgufPath(model.checkpoint);
+ const ggufVariant = standalone ? undefined : (model.quant ?? undefined);
+ // An HF cache snapshot keeps its settings under the repo id: open that record, load the snapshot.
+ const repoId = cachedRepoConfigId(model.checkpoint, ggufVariant);
+ return {
+ requestId,
+ id: repoId ?? model.checkpoint,
+ focus: "advanced",
+ standalone: true,
+ meta: {
+ source: repoId ? "hub" : "local",
+ ...(repoId ? { loadId: model.checkpoint } : {}),
+ isLora: false,
+ ggufVariant,
+ isGguf: standalone || model.quant != null,
+ isDownloaded: true,
+ },
+ };
+}
+
/** Opens the resident's Run settings on Parallel Slots, so Run saves and reloads as it does there. */
export function slotsSettingsRequest(
resident: ResidentRunTarget | null,
diff --git a/studio/frontend/src/features/api-monitor/stats.ts b/studio/frontend/src/features/api-monitor/stats.ts
index 2f47a000d35..3e99510f5cf 100644
--- a/studio/frontend/src/features/api-monitor/stats.ts
+++ b/studio/frontend/src/features/api-monitor/stats.ts
@@ -17,6 +17,8 @@ export interface MonitorStats {
/** Slowest finished request, for spotting a pathological call. */
maxDurationMs: number | null;
totalTokens: number;
+ inputTokens: number;
+ outputTokens: 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. */
@@ -51,6 +53,8 @@ export function computeStats(entries: ApiMonitorEntry[]): MonitorStats {
let errors = 0;
let cancelled = 0;
let totalTokens = 0;
+ let inputTokens = 0;
+ let outputTokens = 0;
let durationSum = 0;
let durationCount = 0;
let maxDurationMs: number | null = null;
@@ -68,6 +72,8 @@ export function computeStats(entries: ApiMonitorEntry[]): MonitorStats {
}
requests += 1;
totalTokens += entryTokens(entry);
+ inputTokens += entry.prompt_tokens ?? 0;
+ outputTokens += completionTokens(entry) ?? 0;
if (entry.status === "running") {
active += 1;
} else if (entry.status === "error") {
@@ -104,6 +110,8 @@ export function computeStats(entries: ApiMonitorEntry[]): MonitorStats {
avgDurationMs: durationCount > 0 ? durationSum / durationCount : null,
maxDurationMs,
totalTokens,
+ inputTokens,
+ outputTokens,
errorRate: finished > 0 ? errors / finished : null,
tokensPerSecond:
generatedDurationMs > 0
diff --git a/studio/frontend/src/features/api-monitor/tour/steps.tsx b/studio/frontend/src/features/api-monitor/tour/steps.tsx
index dbfed0ada20..c5b9688b0cb 100644
--- a/studio/frontend/src/features/api-monitor/tour/steps.tsx
+++ b/studio/frontend/src/features/api-monitor/tour/steps.tsx
@@ -11,20 +11,21 @@ export const apiMonitorTourSteps: TourStep[] = [
body: (
<>
Unsloth serves an OpenAI-compatible API. Point any client at this base
- URL, keep the model name the same, and it works. Status and queue slots
- sit beside it.
+ URL and send the model name shown below it. Context and queue slots sit
+ beside the model.
</>
),
},
{
id: "toolbar",
target: "api-toolbar",
- title: "Controls",
+ title: "Model controls",
body: (
<>
- Pause the live feed to read a request without it scrolling away. Eject
- frees the model's VRAM. The gear opens API settings, where you create
- keys.
+ Load or switch the model the API serves, reload the last one, or eject
+ it to free memory. Each model's row below opens its run settings and an
+ API example. Keys and other API options are under API settings at the
+ top.
</>
),
},
@@ -34,9 +35,9 @@ export const apiMonitorTourSteps: TourStep[] = [
title: "Request log",
body: (
<>
- Pick a request on the left to see its prompt, reply, token counts and
- any error on the right. Search and the status filter above narrow it
- down.
+ Pick a request to see its prompt, reply, token counts and any error.
+ Search and the status filter narrow the list, and Live pauses the feed
+ so a request does not scroll away.
</>
),
},
diff --git a/studio/frontend/src/features/api-monitor/use-api-monitor.ts b/studio/frontend/src/features/api-monitor/use-api-monitor.ts
index 3394c614f40..fae8619c90e 100644
--- a/studio/frontend/src/features/api-monitor/use-api-monitor.ts
+++ b/studio/frontend/src/features/api-monitor/use-api-monitor.ts
@@ -12,21 +12,20 @@ import type {
} from "@/features/chat/types/api";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { clearMonitor } from "./clear-monitor";
+import {
+ type MonitorStatusFilter,
+ countByStatus,
+ filterEntries,
+ mergeMonitorResponse,
+} from "./monitor-snapshot";
import { type MonitorStats, computeStats } from "./stats";
/** Poll cadence while live. Matches the settings console it replaces. */
const POLL_INTERVAL_MS = 1500;
const MAX_CACHED_PROMPT_CHARS = 64 * 1024 * 1024;
-export { computeStats };
-export type { MonitorStats };
-
-export type MonitorStatusFilter =
- | "all"
- | "running"
- | "completed"
- | "error"
- | "cancelled";
+export { computeStats, countByStatus, filterEntries };
+export type { MonitorStats, MonitorStatusFilter };
function retainDetail(
previous: Record<string, ApiMonitorEntry>,
@@ -64,35 +63,6 @@ function dropDetail(
return next;
}
-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[];
@@ -139,7 +109,7 @@ export function useApiMonitor({
const updateData = useCallback((next: ApiMonitorResponse): void => {
const ids = new Set(next.entries.map((entry) => entry.id));
retainedEntryIds.current = ids;
- setData(next);
+ setData((previous) => mergeMonitorResponse(previous, next));
setDetails((previous) => {
const expired = Object.keys(previous).filter((id) => !ids.has(id));
if (expired.length === 0) return previous;
@@ -181,8 +151,17 @@ export function useApiMonitor({
}
let cancelled = false;
let timer: number | undefined;
+ let inFlight = false;
+
+ function schedule(): void {
+ timer = window.setTimeout(() => {
+ timer = undefined;
+ if (!document.hidden) poll();
+ }, intervalMs);
+ }
function poll(): void {
+ inFlight = true;
const requestGeneration = ++listRequestGeneration.current;
getApiMonitor()
.then((next) => {
@@ -205,19 +184,33 @@ export function useApiMonitor({
setError(err instanceof Error ? err.message : "Monitor unavailable");
})
.finally(() => {
+ inFlight = false;
if (cancelled) {
return;
}
if (listRequestGeneration.current === requestGeneration) {
setLoading(false);
}
- timer = window.setTimeout(poll, intervalMs);
+ schedule();
});
}
+ function onVisibilityChange(): void {
+ if (document.hidden || inFlight) {
+ return;
+ }
+ if (timer !== undefined) {
+ window.clearTimeout(timer);
+ timer = undefined;
+ }
+ poll();
+ }
+
poll();
+ document.addEventListener("visibilitychange", onVisibilityChange);
return () => {
cancelled = true;
+ document.removeEventListener("visibilitychange", onVisibilityChange);
if (timer !== undefined) {
window.clearTimeout(timer);
}
diff --git a/studio/frontend/src/features/api-monitor/use-single-line.ts b/studio/frontend/src/features/api-monitor/use-single-line.ts
new file mode 100644
index 00000000000..4e0bd90c62a
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/use-single-line.ts
@@ -0,0 +1,29 @@
+// 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 { useLayoutEffect, useState } from "react";
+
+/** Callback ref, so a box that mounts later is measured too; ResizeObserver catches wrapping. */
+export function useSingleLine<T extends HTMLElement>(): [
+ (element: T | null) => void,
+ boolean,
+] {
+ const [element, setElement] = useState<T | null>(null);
+ const [single, setSingle] = useState(true);
+ useLayoutEffect(() => {
+ if (!element) return;
+ const measure = () => {
+ const style = getComputedStyle(element);
+ const line = Number.parseFloat(style.lineHeight);
+ const padding =
+ Number.parseFloat(style.paddingTop) +
+ Number.parseFloat(style.paddingBottom);
+ setSingle(element.scrollHeight - padding <= line * 1.5);
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [element]);
+ return [setElement, single];
+}
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 624029c2069..2b06dd20187 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -2788,7 +2788,13 @@ export function ChatPage({
const residentCheckpoint = useChatRuntimeStore(
(state) => state.residentCheckpoint,
);
- const loadedCount = useChatRuntimeStore((state) => state.loadedModels.length);
+ const loadedModels = useChatRuntimeStore((state) => state.loadedModels);
+ const loadedCount = loadedModels.length;
+ const loadedNames = useMemo(
+ () =>
+ loadedModels.map((model) => model.id.split(/[\\/]/).pop() || model.id),
+ [loadedModels],
+ );
const loadedContextLength = useChatRuntimeStore(
(state) => state.loadedContextLength,
);
@@ -4797,6 +4803,7 @@ export function ChatPage({
onEject={handleEject}
onEjectAll={handleEjectAll}
loadedCount={loadedCount}
+ loadedNames={loadedNames}
onFoldersChange={refreshLocalModels}
onModelsChange={refreshModelLists}
deleteDisabled={modelOperationInProgress}
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 fd3ed959043..c94f32f37e4 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
@@ -3904,7 +3904,7 @@ export function ModelConfigPage({
{/* Stacked in both variants: a row that wraps on demand reflows when the same click that
commits a draft mounts Save settings, moving Load out from under the cursor. */}
- <div className="mt-5 flex flex-col gap-2 border-t border-border pt-5">
+ <div className="mt-5 flex flex-col gap-3.5 border-t border-border pt-5">
<div className="flex min-w-0 items-center gap-2">
<Checkbox
id={rememberId}
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 7e903ceaac9..08f61cd1ceb 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx
@@ -124,6 +124,7 @@ interface ModelSelectorProps {
onEject?: (modelId?: string) => void;
onEjectAll?: () => void;
loadedCount?: number;
+ loadedNames?: string[];
onFoldersChange?: () => void;
onModelsChange?: (deletedModel?: DeletedModelRef) => void;
deleteDisabled?: boolean;
@@ -177,10 +178,12 @@ function ModelSelectorTrigger({
dataTour,
onEject,
loadedCount = 0,
+ loadedNames,
// Task pages name what they pick ("Select image model"), so the choice reads as separate from the chat model.
placeholder = "Select model",
}: {
loadedCount?: number;
+ loadedNames?: string[];
currentModel?: ModelOption;
isLoaded: boolean;
showCloudIndicator?: boolean;
@@ -193,10 +196,17 @@ function ModelSelectorTrigger({
placeholder?: string;
}) {
const severalLoaded = loadedCount > 1;
- const triggerTitle = severalLoaded
- ? `${loadedCount} models loaded`
- : (currentModel?.name ?? placeholder);
- const subtitle = severalLoaded ? currentModel?.name : currentModel?.description;
+ const listsNames = severalLoaded && (loadedNames?.length ?? 0) > 1;
+ const triggerTitle = listsNames
+ ? loadedNames?.join(" • ")
+ : severalLoaded
+ ? `${loadedCount} models loaded`
+ : (currentModel?.name ?? placeholder);
+ const subtitle = listsNames
+ ? undefined
+ : severalLoaded
+ ? currentModel?.name
+ : currentModel?.description;
return (
<PopoverTrigger asChild={true}>
<button
@@ -288,7 +298,7 @@ function ModelSelectorTrigger({
</span>
)}
</span>
- {currentModel?.descriptionSuffix && (
+ {!listsNames && currentModel?.descriptionSuffix && (
<span
className={cn(
"min-w-0 shrink-[1000000] truncate whitespace-nowrap text-xs leading-tight text-muted-foreground",
@@ -482,6 +492,18 @@ function ModelSelectorContent({
string | null
>(null);
const [configFocus, setConfigFocus] = useState<ModelConfigFocus | null>(null);
+ const [configStandalone, setConfigStandalone] = useState(false);
+
+ // Cleared during render, not in an effect: a reopen inside the exit animation dropped the adopted target.
+ const [renderedOpen, setRenderedOpen] = useState(open);
+ if (renderedOpen !== open) {
+ setRenderedOpen(open);
+ if (!open) {
+ setConfigTarget(null);
+ setConfigFocus(null);
+ setConfigStandalone(false);
+ }
+ }
// The picker remounts on each open but this section state does not, so re-derive the default
// section on the open edge.
@@ -494,10 +516,6 @@ function ModelSelectorContent({
: defaultHubSection(hasAdditionalOnDeviceModels),
);
}
- if (!open && wasOpen.current) {
- setConfigTarget(null);
- setConfigFocus(null);
- }
wasOpen.current = open;
}, [open, wantsConnectedDefault, hasAdditionalOnDeviceModels]);
@@ -549,6 +567,7 @@ function ModelSelectorContent({
: undefined;
setConfigTarget(modelConfigTarget(id, meta, displayName));
setConfigFocus(null);
+ setConfigStandalone(false);
};
const requestedConfigTarget = useMemo(
() =>
@@ -586,6 +605,7 @@ function ModelSelectorContent({
setAdoptedConfigRequestId(configRequest.requestId);
setConfigTarget(requestedConfigTarget);
setConfigFocus(configRequest.focus ?? null);
+ setConfigStandalone(configRequest.standalone === true);
}
useEffect(() => {
if (!configRequest || adoptedConfigRequestId !== configRequest.requestId) {
@@ -657,10 +677,14 @@ function ModelSelectorContent({
visibleLoadedConfig,
)}
target={visibleConfigTarget}
- onBack={() => {
- setConfigTarget(null);
- setConfigFocus(null);
- }}
+ onBack={
+ configStandalone
+ ? undefined
+ : () => {
+ setConfigTarget(null);
+ setConfigFocus(null);
+ }
+ }
focusField={configFocus ?? undefined}
onRun={(config, isDiffusion) =>
onSelect(
@@ -789,6 +813,7 @@ export function ModelSelector({
placeholder,
loaded,
loadedCount,
+ loadedNames,
}: ModelSelectorProps) {
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
const open = controlledOpen ?? uncontrolledOpen;
@@ -969,6 +994,7 @@ export function ModelSelector({
dataTour={triggerDataTour}
onEject={onEject ? () => handleEject() : undefined}
loadedCount={loadedCount}
+ loadedNames={loadedNames}
placeholder={placeholder}
/>
<ModelSelectorContent
diff --git a/studio/frontend/src/features/model-picker/model-config/model-config-handoff.ts b/studio/frontend/src/features/model-picker/model-config/model-config-handoff.ts
index 6164b69701b..b1b000ecb9f 100644
--- a/studio/frontend/src/features/model-picker/model-config/model-config-handoff.ts
+++ b/studio/frontend/src/features/model-picker/model-config/model-config-handoff.ts
@@ -26,6 +26,7 @@ export interface ModelConfigHandoffRequest {
meta: ModelSelectorChangeMeta;
/** Section or field the Run settings page opens on. */
focus?: ModelConfigFocus;
+ standalone?: boolean;
}
export type ModelConfigFocus = "advanced" | "parallelSlots";
diff --git a/studio/frontend/src/features/settings/api/lan-access.ts b/studio/frontend/src/features/settings/api/lan-access.ts
index 28c809df883..e9e6882f7ae 100644
--- a/studio/frontend/src/features/settings/api/lan-access.ts
+++ b/studio/frontend/src/features/settings/api/lan-access.ts
@@ -1,10 +1,12 @@
// 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 { usePlatformStore } from "@/config/env";
import { authFetch } from "@/features/auth";
import { readFastApiError } from "@/lib/format-fastapi-error";
import {
type LanAccessStatus,
+ lanApiUrls,
normalizeLanAccessStatus,
} from "./lan-access-state";
@@ -24,6 +26,19 @@ async function requestLanAccess(
}
export const loadLanAccess = () => requestLanAccess();
+
+/** Publishes only on change: each poll's fresh array re-rendered every reader every 5 s. */
+export function publishLanUrls(status: LanAccessStatus): void {
+ const next = lanApiUrls(status);
+ const current = usePlatformStore.getState().lanUrls;
+ if (
+ next.length === current.length &&
+ next.every((url, i) => url === current[i])
+ ) {
+ return;
+ }
+ usePlatformStore.setState({ lanUrls: next });
+}
export const startLanAccess = () =>
requestLanAccess("/start", { method: "POST" });
export const stopLanAccess = () =>
diff --git a/studio/frontend/src/features/settings/components/lan-access-section.tsx b/studio/frontend/src/features/settings/components/lan-access-section.tsx
index df8d48bd0b2..e58a1749647 100644
--- a/studio/frontend/src/features/settings/components/lan-access-section.tsx
+++ b/studio/frontend/src/features/settings/components/lan-access-section.tsx
@@ -21,9 +21,9 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
-import { usePlatformStore } from "@/config/env";
import {
loadLanAccess,
+ publishLanUrls,
startLanAccess,
stopLanAccess,
updateLanAccessAddresses,
@@ -42,7 +42,6 @@ import {
lanAccessErrorMessage,
lanAccessPortReadOnly,
lanAccessStopDisconnectsOrigin,
- lanApiUrls,
sameLanAccessAddresses,
validLanAccessPort,
} from "@/features/settings/api/lan-access-state";
@@ -259,7 +258,7 @@ export function LanAccessSection() {
const applyStatus = useCallback((next: LanAccessStatus) => {
setStatus(next);
- usePlatformStore.setState({ lanUrls: lanApiUrls(next) });
+ publishLanUrls(next);
}, []);
useEffect(() => {
@@ -295,6 +294,10 @@ export function LanAccessSection() {
if (pollSuppressed.current) {
return;
}
+ if (document.hidden) {
+ schedule();
+ return;
+ }
const epoch = mutationEpoch.current;
loadLanAccess()
.then((next) => {
diff --git a/studio/frontend/src/features/settings/components/remote-access-section.tsx b/studio/frontend/src/features/settings/components/remote-access-section.tsx
index 2edece5f8de..f711ba8b227 100644
--- a/studio/frontend/src/features/settings/components/remote-access-section.tsx
+++ b/studio/frontend/src/features/settings/components/remote-access-section.tsx
@@ -259,6 +259,10 @@ export function RemoteAccessSection() {
if (pollSuppressed.current) {
return;
}
+ if (document.hidden) {
+ schedule(null);
+ return;
+ }
const epoch = mutationEpoch.current;
loadRemoteAccess()
.then((next) => {
diff --git a/studio/frontend/src/features/settings/components/remote-lan-summary.tsx b/studio/frontend/src/features/settings/components/remote-lan-summary.tsx
new file mode 100644
index 00000000000..b9dbb74b7d9
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/remote-lan-summary.tsx
@@ -0,0 +1,157 @@
+// 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 { usePlatformStore } from "@/config/env";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { ArrowRight01Icon, HomeWifiIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useEffect, useState } from "react";
+import {
+ type LanAccessStatus,
+ loadLanAccess,
+ publishLanUrls,
+} from "../api/lan-access";
+import {
+ type RemoteAccessStatus,
+ loadRemoteAccess,
+} from "../api/remote-access";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+
+type AccessState = "off" | "starting" | "online" | "stopping" | "error";
+
+const STATE_LABEL: Record<AccessState, string> = {
+ off: "Off",
+ starting: "Starting",
+ online: "Online",
+ stopping: "Stopping",
+ error: "Error",
+};
+
+function stateDotClass(state?: AccessState): string {
+ if (state === "online") return "bg-emerald-500";
+ if (state === "starting" || state === "stopping") {
+ return "animate-pulse bg-blue-500";
+ }
+ return state === "error" ? "bg-red-500" : "bg-muted-foreground";
+}
+
+function AccessLine({
+ label,
+ state,
+ url,
+}: {
+ label: string;
+ state: AccessState | "unavailable" | null;
+ url: string | null;
+}) {
+ const known = state !== null && state !== "unavailable" ? state : undefined;
+ return (
+ <div className="flex min-w-0 items-center gap-3 px-4 py-2.5">
+ <span className="w-28 shrink-0 text-sm text-foreground">{label}</span>
+ <span className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">
+ <span
+ className={cn("size-2 rounded-full", stateDotClass(known))}
+ aria-hidden={true}
+ />
+ {known
+ ? STATE_LABEL[known]
+ : state === "unavailable"
+ ? "Unavailable"
+ : "Checking…"}
+ </span>
+ {url ? (
+ <span className="min-w-0 truncate font-mono text-xs text-muted-foreground">
+ {url}
+ </span>
+ ) : null}
+ </div>
+ );
+}
+
+/**
+ * Reads each once instead of mounting both panels and their five-second polls here.
+ */
+export function RemoteLanSummary() {
+ const t = useT();
+ const [remote, setRemote] = useState<RemoteAccessStatus | null>(null);
+ const [lan, setLan] = useState<LanAccessStatus | null>(null);
+ const [remoteFailed, setRemoteFailed] = useState(false);
+ const [lanFailed, setLanFailed] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ loadRemoteAccess()
+ .then((next) => {
+ if (cancelled) return;
+ setRemote(next);
+ usePlatformStore.setState({ cloudflareUrl: next.url });
+ })
+ .catch(() => {
+ if (!cancelled) setRemoteFailed(true);
+ });
+ loadLanAccess()
+ .then((next) => {
+ if (cancelled) return;
+ setLan(next);
+ publishLanUrls(next);
+ })
+ .catch(() => {
+ if (!cancelled) setLanFailed(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ return (
+ <section
+ data-settings-label={t("settings.remoteLan.title")}
+ className="overflow-hidden rounded-lg border border-border/70"
+ >
+ <div className="flex items-center justify-between gap-4 bg-muted/30 p-4">
+ <div className="flex min-w-0 items-start gap-3">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-md border border-border/70 bg-muted/40">
+ <HugeiconsIcon
+ icon={HomeWifiIcon}
+ className="size-4 text-foreground"
+ />
+ </div>
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <h2 className="settings-heading text-base font-semibold font-heading">
+ {t("settings.remoteLan.title")}
+ </h2>
+ <p className="text-xs text-muted-foreground leading-relaxed">
+ {t("settings.remoteLan.description")}
+ </p>
+ </div>
+ </div>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="shrink-0 gap-1.5"
+ onClick={() =>
+ useSettingsDialogStore.getState().setActiveTab("remote-lan")
+ }
+ >
+ Manage
+ <HugeiconsIcon icon={ArrowRight01Icon} className="size-3.5" />
+ </Button>
+ </div>
+ <div className="flex flex-col py-1">
+ <AccessLine
+ label="Remote access"
+ state={remote?.state ?? (remoteFailed ? "unavailable" : null)}
+ url={remote?.state === "online" ? remote.url : null}
+ />
+ <AccessLine
+ label="LAN access"
+ state={lan?.state ?? (lanFailed ? "unavailable" : null)}
+ url={lan?.state === "online" ? (lan.urls[0] ?? null) : null}
+ />
+ </div>
+ </section>
+ );
+}
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index d3d1efe17c2..695526b0360 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -16,7 +16,7 @@ export {
} from "./api/download-transport";
export { loadEmbeddingModelSettings } from "./api/embedding-model";
export { updateHubSource } from "./api/hub-settings";
-export { loadLanAccess } from "./api/lan-access";
+export { loadLanAccess, publishLanUrls } from "./api/lan-access";
export { lanApiUrls } from "./api/lan-access-state";
export { loadMultiModelEnabled } from "./api/multi-model";
export { loadOpenAIAutoSwitchSettings } from "./api/openai-auto-switch";
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 566e5ce77c3..8be21a337dc 100644
--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
@@ -25,12 +25,11 @@ import { CreateKeyForm } from "../components/create-key-form";
import { DecisionApiSection } from "../components/decision-api-section";
import { KeyRevealCard } from "../components/key-reveal-card";
import { KeylessApiAccessSection } from "../components/keyless-api-access-section";
-import { LanAccessSection } from "../components/lan-access-section";
import { McpAccessSection } from "../components/mcp-access-section";
import { ModelAliasesSection } from "../components/model-aliases-section";
import { ModelAutoSwitchSection } from "../components/model-auto-switch-section";
import { MonitorLink } from "../components/monitor-link";
-import { RemoteAccessSection } from "../components/remote-access-section";
+import { RemoteLanSummary } from "../components/remote-lan-summary";
import {
UsageExamples,
useApiTunnelPref,
@@ -189,6 +188,15 @@ export function ApiKeysTab() {
)}
</section>
+ <UsageExamples
+ apiKey={revealed}
+ useTunnel={useTunnel}
+ onUseTunnelChange={setUseTunnel}
+ keylessScope={keyless.scope}
+ keylessTools={keyless.tools}
+ keylessExposure={keyless.exposure}
+ />
+
<MonitorLink />
{/* Installation-wide controls: owner-only routes. */}
@@ -196,10 +204,7 @@ export function ApiKeysTab() {
<>
<KeylessApiAccessSection onSettingsChange={setKeyless} />
- {/* Also on the Remote & LAN tab. One panel mounts at a time, so only one polls. */}
- <RemoteAccessSection />
-
- <LanAccessSection />
+ <RemoteLanSummary />
<ModelAutoSwitchSection />
@@ -207,15 +212,6 @@ export function ApiKeysTab() {
</>
) : null}
- <UsageExamples
- apiKey={revealed}
- useTunnel={useTunnel}
- onUseTunnelChange={setUseTunnel}
- keylessScope={keyless.scope}
- keylessTools={keyless.tools}
- keylessExposure={keyless.exposure}
- />
-
<AudioApiExamples
apiKey={revealed}
useTunnel={useTunnel}
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 9d83de3adee..55f13ccdcb9 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -6050,6 +6050,30 @@ html.force-reduced-motion .sidebar-section-drop-line {
box-shadow: none;
}
+ /* rounded-* compile to var(--radius) (@theme inline), so the step goes on --radius. */
+ .api-rounding {
+ --radius: calc(1.1rem - 2px);
+ }
+
+ .api-rounding .elevated-card,
+ .api-rounding.elevated-card {
+ border-radius: 18px;
+ }
+
+ @media (min-width: 640px) {
+ .api-rounding .elevated-card,
+ .api-rounding.elevated-card {
+ border-radius: 25px;
+ }
+ }
+
+ @media (min-width: 1024px) {
+ .api-rounding .elevated-card,
+ .api-rounding.elevated-card {
+ border-radius: 29px;
+ }
+ }
+
.dark .elevated-card.elevated-card-dark-border {
border-color: color-mix(in srgb, var(--border) 70%, transparent);
}
diff --git a/studio/frontend/tests/api-monitor-slots-settings-request.test.ts b/studio/frontend/tests/api-monitor-slots-settings-request.test.ts
index deb52bf0c76..77a70ba4170 100644
--- a/studio/frontend/tests/api-monitor-slots-settings-request.test.ts
+++ b/studio/frontend/tests/api-monitor-slots-settings-request.test.ts
@@ -10,12 +10,16 @@ import { registerBundlerResolver } from "./helpers/kit.ts";
registerBundlerResolver();
const {
+ keptRunSettingsRequest,
residentHasRunSettings,
residentHasSlotsSetting,
residentMatchesMonitor,
runSettingsRequest,
slotsSettingsRequest,
} = await import("../src/features/api-monitor/slots-settings-request.ts");
+const { modelConfigTarget } = await import(
+ "../src/features/model-picker/model-config/model-config-handoff.ts"
+);
const GGUF: ResidentRunTarget = {
checkpoint: "unsloth/Qwen3-4B-GGUF",
@@ -71,6 +75,7 @@ test("a GGUF resident opens its Run settings on Parallel Slots, as Chat's reload
requestId: "req-1",
id: "unsloth/Qwen3-4B-GGUF",
focus: "parallelSlots",
+ standalone: true,
meta: {
source: "local",
isLora: false,
@@ -135,3 +140,47 @@ test("the readout is offered only when the picker takes the target for the monit
);
assert.equal(residentMatchesMonitor(null, monitor), false);
});
+
+test("a kept model's settings open on its own checkpoint and quant", () => {
+ const gguf = keptRunSettingsRequest(
+ { checkpoint: "unsloth/gemma-3-270m-it-GGUF", quant: "Q4_K_M" },
+ "kept",
+ );
+ assert.equal(gguf.id, "unsloth/gemma-3-270m-it-GGUF");
+ assert.equal(gguf.focus, "advanced");
+ assert.equal(gguf.meta.ggufVariant, "Q4_K_M");
+ assert.equal(gguf.meta.isGguf, true);
+ assert.equal(gguf.standalone, true);
+ assert.equal(runSettingsRequest(GGUF, "live")?.standalone, true);
+ const safetensors = keptRunSettingsRequest(
+ { checkpoint: "unsloth/Qwen3-0.6B", quant: null },
+ "kept",
+ );
+ assert.equal(safetensors.meta.ggufVariant, undefined);
+ assert.equal(safetensors.meta.isGguf, false);
+});
+
+test("a kept standalone GGUF opens its saved settings, keyed without the filename quant", () => {
+ const request = keptRunSettingsRequest(
+ { checkpoint: "/models/gemma-3-270m-it-Q4_K_M.gguf", quant: "Q4_K_M" },
+ "kept",
+ );
+ assert.equal(request.meta.ggufVariant, undefined);
+ assert.equal(request.meta.isGguf, true);
+ assert.equal(
+ keptRunSettingsRequest(
+ { checkpoint: "unsloth/gemma-3-270m-it-GGUF", quant: "Q4_K_M" },
+ "kept",
+ ).meta.ggufVariant,
+ "Q4_K_M",
+ );
+});
+
+test("a kept HF cache snapshot opens the repo's saved settings and still loads the snapshot", () => {
+ const snapshot =
+ "/Users/me/.cache/huggingface/hub/models--unsloth--Qwen3-0.6B/snapshots/abc123";
+ const request = keptRunSettingsRequest({ checkpoint: snapshot, quant: null }, "kept");
+ const target = modelConfigTarget(request.id, request.meta);
+ assert.equal(target.configId, "unsloth/Qwen3-0.6B");
+ assert.equal(target.id, snapshot);
+});
diff --git a/studio/frontend/tests/api-monitor-snapshot.test.ts b/studio/frontend/tests/api-monitor-snapshot.test.ts
new file mode 100644
index 00000000000..679fb014013
--- /dev/null
+++ b/studio/frontend/tests/api-monitor-snapshot.test.ts
@@ -0,0 +1,161 @@
+// 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 {
+ countByStatus,
+ filterEntries,
+ mergeMonitorResponse,
+} from "../src/features/api-monitor/monitor-snapshot.ts";
+import type {
+ ApiMonitorEntry,
+ ApiMonitorResponse,
+} from "../src/features/chat/types/api.ts";
+
+const PROGRESS = {
+ total: 100,
+ processed: null,
+ cached: null,
+ time_ms: null,
+ percent: null,
+};
+
+function entry(overrides: Partial<ApiMonitorEntry>): ApiMonitorEntry {
+ return {
+ id: "a",
+ status: "completed",
+ model: "m",
+ endpoint: "/v1/chat/completions",
+ method: "POST",
+ started_at: 1,
+ updated_at: 1,
+ prompt_preview: "hi",
+ reply_preview: "hello",
+ ...overrides,
+ } as ApiMonitorEntry;
+}
+
+function snapshot(
+ entries: ApiMonitorEntry[],
+ serverTime = 100,
+): ApiMonitorResponse {
+ return {
+ status: "ready",
+ server_time: serverTime,
+ active_model: "m",
+ active_requests: 0,
+ queue: { active: 0, capacity: 4, queued: 0, free: 4 },
+ entries,
+ } as ApiMonitorResponse;
+}
+
+test("a poll that only moved server_time keeps the previous snapshot", () => {
+ const first = snapshot([entry({ id: "a" }), entry({ id: "b" })]);
+ const second = snapshot([entry({ id: "a" }), entry({ id: "b" })], 101.5);
+ assert.equal(mergeMonitorResponse(first, second), first);
+});
+
+test("a changed entry is replaced while unchanged ones keep their identity", () => {
+ const first = snapshot([
+ entry({ id: "a", status: "running", updated_at: 1 }),
+ entry({ id: "b" }),
+ ]);
+ const second = snapshot([
+ entry({ id: "a", status: "running", updated_at: 2, reply_preview: "hel" }),
+ entry({ id: "b" }),
+ ]);
+ const merged = mergeMonitorResponse(first, second);
+ assert.notEqual(merged, first);
+ assert.notEqual(merged.entries[0], first.entries[0]);
+ assert.equal(merged.entries[0].reply_preview, "hel");
+ assert.equal(merged.entries[1], first.entries[1]);
+});
+
+test("a new entry, a reorder or a queue change produces a new snapshot", () => {
+ const first = snapshot([entry({ id: "a" })]);
+ const added = mergeMonitorResponse(
+ first,
+ snapshot([entry({ id: "b" }), entry({ id: "a" })]),
+ );
+ assert.equal(added.entries.length, 2);
+ assert.equal(added.entries[1], first.entries[0]);
+
+ const queue = snapshot([entry({ id: "a" })]);
+ queue.queue = { active: 1, capacity: 4, queued: 0, free: 3 };
+ const merged = mergeMonitorResponse(first, queue);
+ assert.notEqual(merged, first);
+ assert.equal(merged.entries, first.entries);
+ assert.equal(merged.queue?.active, 1);
+});
+
+test("nested fields such as prompt progress count as changes", () => {
+ const first = snapshot([
+ entry({
+ id: "a",
+ status: "running",
+ prompt_progress: { ...PROGRESS, percent: 10 },
+ }),
+ ]);
+ const second = snapshot([
+ entry({
+ id: "a",
+ status: "running",
+ prompt_progress: { ...PROGRESS, percent: 40 },
+ }),
+ ]);
+ const merged = mergeMonitorResponse(first, second);
+ assert.equal(merged.entries[0].prompt_progress?.percent, 40);
+});
+
+test("status tabs count requests only, and a failed load lists under Errors", () => {
+ const entries = [
+ entry({ id: "r1", status: "completed" }),
+ entry({ id: "r2", status: "error", error: "boom" }),
+ entry({ id: "r3", status: "running" }),
+ entry({ id: "l1", kind: "lifecycle", status: "completed" }),
+ entry({ id: "l2", kind: "lifecycle", status: "running" }),
+ entry({
+ id: "l3",
+ kind: "lifecycle",
+ status: "error",
+ error: "out of memory",
+ }),
+ ];
+ const counts = countByStatus(entries);
+ assert.deepEqual(counts, {
+ all: 6,
+ running: 1,
+ completed: 1,
+ error: 2,
+ cancelled: 0,
+ });
+ for (const status of [
+ "running",
+ "completed",
+ "error",
+ "cancelled",
+ ] as const) {
+ assert.equal(filterEntries(entries, status, "").length, counts[status]);
+ }
+ assert.equal(filterEntries(entries, "all", "").length, 6);
+ assert.deepEqual(
+ filterEntries(entries, "error", "memory").map((e) => e.id),
+ ["l3"],
+ );
+});
+
+test("the floating monitor folds a fresh first snapshot and pauses while hidden", async () => {
+ const { readSrc } = await import("./helpers/kit.ts");
+ const overlay = readSrc("features/api-monitor/api-monitor-overlay.tsx");
+ assert.match(
+ overlay,
+ /fresh \? next : mergeMonitorResponse\(previous, next\)/,
+ );
+ assert.match(overlay, /if \(!document\.hidden\) poll\(\);/);
+ assert.match(
+ overlay,
+ /addEventListener\("visibilitychange", onVisibilityChange\)/,
+ );
+});
diff --git a/studio/frontend/tests/api-monitor-throughput.test.ts b/studio/frontend/tests/api-monitor-throughput.test.ts
index c59ce9d254d..20bd7a174b0 100644
--- a/studio/frontend/tests/api-monitor-throughput.test.ts
+++ b/studio/frontend/tests/api-monitor-throughput.test.ts
@@ -55,3 +55,19 @@ test("rating is total tokens over total decode time, not a mean of rates", () =>
]);
assert.equal(stats.tokensPerSecond, 50);
});
+
+test("tokens split into what requests sent in and what the model sent back", () => {
+ const stats = computeStats([
+ queuedEntry({ id: "a", prompt_tokens: 30, completion_tokens: 10 }),
+ queuedEntry({
+ id: "b",
+ prompt_tokens: 20,
+ completion_tokens: null,
+ total_tokens: 25,
+ }),
+ queuedEntry({ id: "l", kind: "lifecycle", prompt_tokens: 999 }),
+ ]);
+ assert.equal(stats.inputTokens, 50);
+ assert.equal(stats.outputTokens, 15);
+ assert.equal(stats.totalTokens, 65);
+});
diff --git a/studio/frontend/tests/api-sampling-example.test.ts b/studio/frontend/tests/api-sampling-example.test.ts
new file mode 100644
index 00000000000..6e4be75ad38
--- /dev/null
+++ b/studio/frontend/tests/api-sampling-example.test.ts
@@ -0,0 +1,46 @@
+// 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 {
+ apiExampleModelName,
+ buildApiSamplingExample,
+} from "../src/features/api-monitor/api-sampling-example.ts";
+
+test("client fields are keyword arguments, Unsloth fields ride extra_body", () => {
+ const snippet = buildApiSamplingExample({
+ baseUrl: "http://127.0.0.1:8888/v1",
+ model: "unsloth/gemma-3-270m-it-GGUF:Q4_K_M",
+ sampling: {
+ temperature: 1,
+ top_p: 0.95,
+ presence_penalty: 0,
+ top_k: 64,
+ min_p: 0,
+ repetition_penalty: 1,
+ },
+ });
+ assert.match(snippet, /base_url="http:\/\/127\.0\.0\.1:8888\/v1"/);
+ assert.match(snippet, /model="unsloth\/gemma-3-270m-it-GGUF:Q4_K_M"/);
+ assert.match(snippet, /\n {4}temperature=1,\n {4}top_p=0\.95,\n {4}presence_penalty=0,/);
+ assert.match(snippet, /extra_body=\{\n {8}"top_k": 64,\n {8}"min_p": 0,\n {8}"repetition_penalty": 1,\n {4}\},/);
+});
+
+test("no values from the server leaves a request that still runs", () => {
+ const snippet = buildApiSamplingExample({
+ baseUrl: "http://h/v1",
+ model: "m",
+ sampling: {},
+ });
+ assert.doesNotMatch(snippet, /extra_body|temperature/);
+ assert.match(snippet, /messages=\[/);
+});
+
+test("the quant is pinned once", () => {
+ assert.equal(apiExampleModelName("unsloth/x-GGUF", "Q4_K_M"), "unsloth/x-GGUF:Q4_K_M");
+ assert.equal(apiExampleModelName("unsloth/x-GGUF:Q8_0", "Q4_K_M"), "unsloth/x-GGUF:Q8_0");
+ assert.equal(apiExampleModelName("unsloth/x", null), "unsloth/x");
+});
diff --git a/studio/frontend/tests/api-settings-tab.test.ts b/studio/frontend/tests/api-settings-tab.test.ts
new file mode 100644
index 00000000000..c3e70e6ac36
--- /dev/null
+++ b/studio/frontend/tests/api-settings-tab.test.ts
@@ -0,0 +1,60 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+const TAB = readSrc("features/settings/tabs/api-keys-tab.tsx");
+const SUMMARY = readSrc("features/settings/components/remote-lan-summary.tsx");
+const LAN_API = readSrc("features/settings/api/lan-access.ts");
+
+test("the API tab shows Remote & LAN as a status line, not a second set of polling panels", () => {
+ assert.doesNotMatch(TAB, /<RemoteAccessSection|<LanAccessSection/);
+ assert.match(TAB, /<RemoteLanSummary \/>/);
+ assert.doesNotMatch(SUMMARY, /setInterval|setTimeout/);
+ assert.match(SUMMARY, /setActiveTab\("remote-lan"\)/);
+});
+
+test("usage examples sit right under the keys, where a new key lands", () => {
+ const examples = TAB.indexOf("<UsageExamples");
+ assert.ok(examples > TAB.indexOf("<CreateKeyForm"));
+ assert.ok(examples < TAB.indexOf("<MonitorLink />"));
+ assert.ok(examples < TAB.indexOf("<KeylessApiAccessSection"));
+});
+
+test("the remote and LAN polls skip their request while the tab is hidden", () => {
+ for (const path of [
+ "features/settings/components/lan-access-section.tsx",
+ "features/settings/components/remote-access-section.tsx",
+ ]) {
+ assert.match(
+ readSrc(path),
+ /if \(document\.hidden\) \{\s*schedule\([^)]*\);\s*return;\s*\}/,
+ path,
+ );
+ }
+});
+
+test("LAN URLs publish only when they change", () => {
+ assert.match(
+ LAN_API,
+ /next\.every\(\(url, i\) => url === current\[i\]\)[\s\S]{0,40}return;/,
+ );
+ assert.doesNotMatch(
+ readSrc("features/settings/components/lan-access-section.tsx"),
+ /setState\(\{ lanUrls/,
+ );
+ assert.doesNotMatch(
+ readSrc("features/api-monitor/api-monitor-page.tsx"),
+ /setState\(\{ lanUrls/,
+ );
+});
+
+test("the API page marks one served row as the primary, found by checkpoint first", () => {
+ const page = readSrc("features/api-monitor/api-monitor-page.tsx");
+ assert.match(page, /active: index === activeIndex,/);
+ assert.match(page, /\(model\.checkpoint \?\? model\.id\) === residentCheckpoint/);
+ assert.match(page, /\(model\.active && !canEditSettings\)/);
+});