Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: lighter system polling and clearer unified-memory monitor (#14592)
Michael Han870f37741f4d
diff --git a/studio/backend/core/inference/gpu_residency.py b/studio/backend/core/inference/gpu_residency.pyindex b77a0f84123..1a4ec9e5e73 100644--- a/studio/backend/core/inference/gpu_residency.py+++ b/studio/backend/core/inference/gpu_residency.py@@ -87,6 +87,16 @@ def media_held_mib() -> dict[int, int]:return {}+def media_owner_held_mib(owner: str) -> Optional[int]:+ """MiB admitted for one resident media owner across its GPUs, or None when unpriced. Never raises."""+ try:+ need = _media_records().get(owner)+ total = sum(int(mib) for mib in need.values()) if need else 0+ return total or None+ except Exception: # noqa: BLE001+ return None++def media_unallocated_mib() -> dict[int, int]:"""{physical GPU id: MiB} of the media price live free VRAM still shows as free: an idle resident's generationheadroom, or all of a resident still loading. Never raises."""diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 4b27191125a..0f07aceb310 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -8870,6 +8870,22 @@ class LlamaCppBackend:"""True if a llama-server process exists (loading or loaded)."""return self._process is not None+ def resident_memory_mib(self) -> Optional[int]:+ """Best-effort MiB the loaded model holds: its GPU model buffers when known, else the+ child's RSS (CPU, and Apple unified memory where RSS covers the Metal buffers). Never raises."""+ process = self._process+ if process is None or process.poll() is not None:+ return None+ try:+ gpu = self.reclaimable_gpu_memory_gb()+ if gpu:+ return int(round(sum(gpu.values()) * 1024))+ import psutil++ return int(psutil.Process(process.pid).memory_info().rss // (1024 * 1024)) or None+ except Exception: # noqa: BLE001 - a size is decoration, never a failed status read+ return None+def reclaimable_gpu_memory_gb(self) -> Optional[dict[int, float]]:"""Stable GPU model buffers the disposable llama-server will release.@@ -8884,18 +8900,28 @@ class LlamaCppBackend:physical_ids = list(getattr(self, "_child_gpu_physical_ids", None) or ())if not physical_ids:return None- reported: dict[int, float] = {}+ # The buffer lines are startup output, so once healthy the answer is fixed per process; the status poll+ # would otherwise rescan up to _STDOUT_TRIM_AT lines on the event loop every few seconds.+ ids = tuple(physical_ids)+ cached = getattr(self, "_reclaimable_gpu_cache", None)+ if cached is not None and cached[0] is process and cached[1] == ids:+ return dict(cached[2]) if cached[2] else None+ healthy = bool(getattr(self, "_healthy", False))+ reported: Optional[dict[int, float]] = {}for line in list(self._stdout_lines):match = _GPU_MODEL_BUFFER_RE.search(line)if match is None:continueordinal = int(match.group(1))if ordinal >= len(physical_ids):- return None+ reported = None+ breakphysical = int(physical_ids[ordinal])reported[physical] = reported.get(physical, 0.0) + float(match.group(2)) / 1024.0if self._process is not process or process.poll() is not None:return None+ if healthy:+ self._reclaimable_gpu_cache = (process, ids, dict(reported) if reported else None)return reported or None@propertydiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 6a0be53280c..077da213c52 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2154,6 +2154,10 @@ class LlamaFlagCatalogResponse(BaseModel):class InferenceStatusResponse(_InferenceRuntimeFields):"""Current inference backend status"""+ resident_mib: Optional[int] = Field(+ None,+ description = "Best-effort memory the resident model holds, in MiB; null when unknown.",+ )active_model: Optional[str] = Field(None, description = "Currently active model display identifier")@@ -5660,6 +5664,10 @@ class DiffusionDownloadPlanResponse(BaseModel):class DiffusionStatusResponse(BaseModel):"""Current diffusion backend state."""+ resident_mib: Optional[int] = Field(+ None,+ description = "Best-effort memory the resident model holds, in MiB; null when unknown.",+ )multi_gpu: Optional[Dict[str, Any]] = Field(None,description = "Multi-GPU placement (component -> card, primary, secondary) and CFG-parallel state (armed, "@@ -7312,6 +7320,10 @@ class VideoGenerationDefaults(BaseModel):class VideoStatusResponse(BaseModel):"""Current video backend state."""+ resident_mib: Optional[int] = Field(+ None,+ description = "Best-effort memory the resident model holds, in MiB; null when unknown.",+ )multi_gpu: Optional[Dict[str, Any]] = Field(None,description = "Multi-GPU placement (component -> card, primary, secondary) and CFG-parallel state (armed, "diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 57a34e24485..4e38a6d0522 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -23730,6 +23730,8 @@ async def get_status(current_subject: str, model: Optional[str] = None):"""Status of the slot serving ``model`` (the primary one by default), listing every loaded model."""slot = await _route_to_extra_slot(model)response = await _slot_status(current_subject)+ if isinstance(response, InferenceStatusResponse) and response.is_gguf:+ response.resident_mib = _llama_resident_mib()if isinstance(response, InferenceStatusResponse):from utils.multi_model_settings import get_multi_model_mode@@ -23752,6 +23754,15 @@ async def get_status(current_subject: str, model: Optional[str] = None):return response+def _llama_resident_mib() -> Optional[int]:+ """The routed slot's llama-server footprint; None when not loaded or unreadable."""+ try:+ llama = get_llama_cpp_backend()+ return llama.resident_memory_mib() if getattr(llama, "is_loaded", False) else None+ except Exception: # noqa: BLE001 - optional decoration on a status read+ return None++def _slot_entries_and_checkpoints() -> "tuple[list[dict], dict[str, str]]":"""This slot's /v1/models entries, and the checkpoint each local one is loaded from."""checkpoints: dict[str, str] = {}@@ -53518,6 +53529,9 @@ async def diffusion_status(owner, stats = view() if callable(view) else (None, status_dict["transformer_cache_stats"])visible = owner is None or owner == current_account_id()status_dict = {**status_dict, "transformer_cache_stats": stats if visible else None}+ if status_dict.get("loaded") and status_dict.get("resident_mib") is None:+ from core.inference.gpu_residency import media_owner_held_mib+ status_dict = {**status_dict, "resident_mib": media_owner_held_mib("diffusion")}# Answered long after the resolving request ended, so no handle is in context.return redact_host_paths(DiffusionStatusResponse(**status_dict), via_api_key = via_api_key)diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex a956860f70e..f64478fbca9 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -917,6 +917,9 @@ async def video_status(owner, stats = view() if callable(view) else (None, status_dict["transformer_cache_stats"])visible = owner is None or owner == current_account_id()status_dict = {**status_dict, "transformer_cache_stats": stats if visible else None}+ if status_dict.get("loaded") and status_dict.get("resident_mib") is None:+ from core.inference.gpu_residency import media_owner_held_mib+ status_dict = {**status_dict, "resident_mib": media_owner_held_mib("video")}# This route answers long after the request that resolved the reference ended, so there is# no handle in context to put back.return redact_host_paths(VideoStatusResponse(**status_dict), via_api_key = via_api_key)diff --git a/studio/backend/tests/test_loaded_model_resident_mib.py b/studio/backend/tests/test_loaded_model_resident_mib.pynew file mode 100644index 00000000000..8f464f5b910--- /dev/null+++ b/studio/backend/tests/test_loaded_model_resident_mib.py@@ -0,0 +1,169 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""``resident_mib``: the best-effort per-model size the Loaded models card shows.++Decoration only, so every path that cannot measure answers None instead of raising.+"""++import asyncio+from types import SimpleNamespace+from unittest.mock import patch++import pytest++import routes.inference as inference_route+from core.inference import gpu_arbiter as arb+from core.inference import gpu_residency as gr+from core.inference.llama_cpp import LlamaCppBackend+from models.inference import (+ DiffusionStatusResponse,+ InferenceStatusResponse,+ VideoStatusResponse,+)+++class _Alive:+ pid = 4242++ def poll(self):+ return None+++def _backend(process = None):+ backend = LlamaCppBackend(manages_processes = False)+ backend._process = process+ return backend+++def test_no_process_has_no_size():+ assert _backend().resident_memory_mib() is None+++def test_gpu_model_buffers_win_over_rss():+ backend = _backend(_Alive())+ with patch.object(backend, "reclaimable_gpu_memory_gb", return_value = {0: 4.0, 1: 1.5}):+ assert backend.resident_memory_mib() == 5632+++def test_cpu_load_reports_child_rss():+ pytest.importorskip("psutil")+ backend = _backend(_Alive())+ fake = SimpleNamespace(memory_info = lambda: SimpleNamespace(rss = 3 * 1024 * 1024 * 1024))+ with (+ patch.object(backend, "reclaimable_gpu_memory_gb", return_value = None),+ patch("psutil.Process", return_value = fake) as process,+ ):+ assert backend.resident_memory_mib() == 3072+ process.assert_called_once_with(4242)+++class _CountingLines(list):+ copies = 0++ def __iter__(self):+ type(self).copies += 1+ return super().__iter__()+++def test_buffer_scan_runs_once_per_healthy_process():+ backend = _backend(_Alive())+ backend._child_gpu_physical_ids = (1, 3)+ backend._healthy = True+ _CountingLines.copies = 0+ backend._stdout_lines = _CountingLines(+ ["noise"] * 20000+ + [+ "load_tensors: CUDA0 model buffer size = 2048.0 MiB",+ "load_tensors: CUDA1 model buffer size = 1024.0 MiB",+ ]+ )+ for _ in range(5):+ assert backend.reclaimable_gpu_memory_gb() == {1: 2.0, 3: 1.0}+ assert _CountingLines.copies == 1+ # A new process (reload) is scanned afresh.+ backend._process = _Alive()+ backend._stdout_lines = _CountingLines(["load_tensors: CUDA0 model buffer size = 512.0 MiB"])+ assert backend.reclaimable_gpu_memory_gb() == {1: 0.5}+++def test_buffer_scan_is_not_memoised_while_loading():+ backend = _backend(_Alive())+ backend._child_gpu_physical_ids = (0,)+ backend._healthy = False+ backend._stdout_lines = ["load_tensors: CUDA0 model buffer size = 1024.0 MiB"]+ assert backend.reclaimable_gpu_memory_gb() == {0: 1.0}+ backend._stdout_lines.append("load_tensors: CUDA0 model buffer size = 1024.0 MiB")+ assert backend.reclaimable_gpu_memory_gb() == {0: 2.0}+++def test_unreadable_child_is_none_not_an_error():+ psutil = pytest.importorskip("psutil")+ backend = _backend(_Alive())+ with (+ patch.object(backend, "reclaimable_gpu_memory_gb", return_value = None),+ patch("psutil.Process", side_effect = psutil.NoSuchProcess(4242)),+ ):+ assert backend.resident_memory_mib() is None+++def media_needs():+ saved = arb._owner, arb._residents, arb._media_needs+ arb._owner, arb._residents, arb._media_needs = None, {}, {}+ with patch.object(gr, "_loaded_or_loading", return_value = True):+ yield arb+ arb._owner, arb._residents, arb._media_needs = saved+++def test_media_owner_sums_its_own_gpus_only(media_needs):+ media_needs._residents = {arb.DIFFUSION: frozenset({0, 1}), arb.VIDEO: frozenset({0})}+ media_needs._owner = arb.DIFFUSION+ media_needs._media_needs = {arb.DIFFUSION: {0: 7000, 1: 500}, arb.VIDEO: {0: 9000}}+ assert gr.media_owner_held_mib(arb.DIFFUSION) == 7500+ assert gr.media_owner_held_mib(arb.VIDEO) == 9000+++def test_unpriced_media_owner_is_none(media_needs):+ assert gr.media_owner_held_mib(arb.VIDEO) is None+ media_needs._media_needs = {arb.VIDEO: {0: "lots"}}+ media_needs._residents = {arb.VIDEO: frozenset({0})}+ assert gr.media_owner_held_mib(arb.VIDEO) is None+++def test_status_models_default_to_unknown():+ assert InferenceStatusResponse().resident_mib is None+ assert DiffusionStatusResponse().resident_mib is None+ assert VideoStatusResponse().resident_mib is None+++def _run_status(+ monkeypatch,+ backend,+ *,+ is_gguf = True,+):+ async def _slot_status(_subject):+ return InferenceStatusResponse(active_model = "org/A-GGUF", is_gguf = is_gguf)++ monkeypatch.setattr(inference_route, "_slot_status", _slot_status)+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)+ return asyncio.run(inference_route.get_status("tester"))+++def test_gguf_status_carries_the_llama_size(monkeypatch):+ backend = SimpleNamespace(is_loaded = True, resident_memory_mib = lambda: 2048)+ assert _run_status(monkeypatch, backend).resident_mib == 2048+++def test_a_failing_probe_leaves_the_size_unknown(monkeypatch):+ def _boom():+ raise RuntimeError("gone")++ backend = SimpleNamespace(is_loaded = True, resident_memory_mib = _boom)+ assert _run_status(monkeypatch, backend).resident_mib is None+++def test_a_non_gguf_status_is_not_sized_from_llama(monkeypatch):+ backend = SimpleNamespace(is_loaded = True, resident_memory_mib = lambda: 2048)+ assert _run_status(monkeypatch, backend, is_gguf = False).resident_mib is Nonediff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex 270da542663..524c70486cc 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -377,8 +377,10 @@ export const BUDGET = {// Opt-in reply times (#14500: the Settings > Chat row, its eager English strings and the reply footer gate):// +1,514 B raw / +418 B transfer over main (6,891,262 -> 6,892,776 B raw, 2,076,131 -> 2,076,549 B transfer// merged at c2f75c4, Node 24, 98 chunks). Raised by that, on top of the above.- transferBytes: 2_077_313,- rawBytes: 6_894_730,+ // #14592 + #14601 (system polling, floating panels) merged with main at 0c001fceb: 6,907,598 B raw /+ // 2,080,708 B transfer (Node 26, 98 chunks). Raised to that plus about 200 B.+ transferBytes: 2_080_908,+ rawBytes: 6_907_798,};// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering thediff --git a/studio/frontend/src/components/floating-monitor.tsx b/studio/frontend/src/components/floating-monitor.tsxindex bef44c9a30b..7b31210838b 100644--- a/studio/frontend/src/components/floating-monitor.tsx+++ b/studio/frontend/src/components/floating-monitor.tsx@@ -9,6 +9,7 @@ import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";import { FIND_PORTAL_ATTRIBUTE } from "@/features/find-in-page/lib/find-attributes";import { useMonitorOverlayStore } from "@/features/settings";+import { useCornerCardFrameStore } from "@/features/settings/stores/monitor-frame-store";import { gpuMemoryDisplay } from "@/hooks/gpu-memory-display";import { gpuMemoryTotalsGb, resolveGpuVramUsedGb } from "@/hooks/gpu-vram";import { useChatSettingsWidth } from "@/hooks/use-chat-settings-width";@@ -136,6 +137,7 @@ function FloatingMonitorPanel({const t = useT();const [constraintsElement, setConstraintsElement] =useState<HTMLDivElement | null>(null);+ const cornerCard = useCornerCardFrameStore((state) => state.frame);const {monitorRef,scrollRef,@@ -144,16 +146,18 @@ function FloatingMonitorPanel({startDrag,updateDrag,finishDrag,+ resetPosition,+ nudge,} = useFloatingPanelLayout(constraintsElement,dockedBesideRunSettings || suppressed,suppressed,undefined,FLOATING_PANEL_POSITION_KEYS.liveMonitor,+ cornerCard,);- // offsetWidth, not the bounding rect: the panel animates in from scale 0.94, and- // a rect read through that transform is short of the width it settles at.+ // offsetWidth, not the bounding rect: a drag's transform skews the rect.useEffect(() => {const monitor = monitorRef.current;if (!monitor) {@@ -179,6 +183,9 @@ function FloatingMonitorPanel({const ramAvailable = systemInfo.memory?.available_gb ?? 0;const ramUsed = Math.max(0, ramTotal - ramAvailable);const ramPercent = clampPercent(systemInfo.memory?.percent_used ?? 0);+ // The placeholder's zeros are not a reading: loading or a failed first request shows "--".+ const ramKnown = systemInfo.status === "ready";+ const stale = systemInfo.stale === true;const displayedGpu = systemInfo.gpu?.available? systemInfo.gpu@@ -198,6 +205,8 @@ function FloatingMonitorPanel({const memoryTotals = gpuMemoryTotalsGb(devices);const vramTotal = memoryTotals.total;const hasSharedPool = memoryTotals.shared > 0;+ // No dedicated pool (Apple unified memory): the shared total alone is the capacity.+ const unifiedPool = hasSharedPool && memoryTotals.dedicated === 0;// null usage = unknown (e.g. Windows ROCm perf counter); 0 would fabricate a// readout. The host figure can still be known when no device's is (#7452).const resolvedVramUsed = resolveGpuVramUsedGb(memoryDisplay.usageGpu);@@ -227,11 +236,11 @@ function FloatingMonitorPanel({(displayedGpu?.devices.length ?? 0) > 0;// The container sits on the floating panel layer, above the bottom-right overlay stack. The stack- // is anchored to that same corner and does not move for this monitor, so the two can overlap. The- // stack is passive status; this is a window being dragged, resized and closed, so it wins. Still- // below the startup screen and tooltips. See lib/z-layers. The API monitor panel shares this- // layer rather than sitting under it, and whichever of the two the user touched last is the one- // in front.+ // is anchored to that same corner and does not move for this monitor; at its default corner the+ // monitor rests above the Loaded models card instead (useCornerCardFrameStore), and anywhere it+ // overlaps it wins, since this is a window being dragged, resized and closed. Still below the+ // startup screen and tooltips. See lib/z-layers. The API monitor panel shares this layer rather+ // than sitting under it, and whichever of the two the user touched last is the one in front.return (<divref={setConstraintsElement}@@ -266,6 +275,14 @@ function FloatingMonitorPanel({data-testid="floating-monitor"// Takes its own clicks over a macOS browser page (native-view.ts).data-native-clickable=""+ // biome-ignore lint/a11y/useSemanticElements: a floating panel landmark on the shared layout hook's div.+ role="region"+ aria-label={t("settings.resources.liveMonitor.title")}+ onKeyDown={(event) => {+ if (event.key !== "Escape" || event.defaultPrevented) return;+ event.preventDefault();+ onClose();+ }}style={layout? {@@ -285,16 +302,32 @@ function FloatingMonitorPanel({<span className="truncate">{t("settings.resources.liveMonitor.title")}</span>+ {stale && (+ <span+ className="truncate font-normal text-muted-foreground"+ aria-live="polite"+ data-testid="floating-monitor-stale"+ >+ {t("floatingPanels.monitor.reconnecting")}+ </span>+ )}</div><div className="flex items-center gap-1 shrink-0"><divdata-testid="floating-monitor-drag-handle"+ // biome-ignore lint/a11y/useSemanticElements: a pointer-captured drag grip, not a pressable control.+ role="button"+ tabIndex={0}+ aria-label={t("floatingPanels.monitor.dragHandleLabel")}+ title={t("floatingPanels.monitor.dragHandleLabel")}onPointerDown={startDrag}onPointerMove={updateDrag}onPointerUp={finishDrag}onPointerCancel={finishDrag}onLostPointerCapture={finishDrag}- className="touch-none cursor-grab rounded-md px-1 text-muted-foreground/60 transition-colors hover:bg-muted/60 hover:text-muted-foreground active:cursor-grabbing"+ onDoubleClick={resetPosition}+ onKeyDown={(event) => void nudge(event)}+ className="touch-none cursor-grab rounded-md px-1 text-muted-foreground/60 transition-colors hover:bg-muted/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"><GripVerticalIcon className="size-3.5" /></div>@@ -316,22 +349,29 @@ function FloatingMonitorPanel({<divref={contentRef}data-testid="floating-monitor-content"- className="space-y-3"+ className={cn("space-y-3 transition-opacity", stale && "opacity-50")}><div className="space-y-1"><div className="flex justify-between text-ui-11 font-medium font-mono"><span>{t("settings.resources.liveMonitor.ram")}</span><span- className={cn("tabular-nums", usageTextClass(ramPercent))}+ className={cn(+ "tabular-nums",+ ramKnown+ ? usageTextClass(ramPercent)+ : "text-muted-foreground",+ )}>- {Math.round(ramPercent)}%+ {ramKnown ? `${Math.round(ramPercent)}%` : "--"}</span></div><div className="text-xs text-muted-foreground font-mono tabular-nums">- {formatGiB(ramUsed)} / {formatGiB(ramTotal)}+ {ramKnown+ ? `${formatGiB(ramUsed)} / ${formatGiB(ramTotal)}`+ : "-- / --"}</div><Progress- value={ramPercent}+ value={ramKnown ? ramPercent : 0}className="mt-1 h-1.5 rounded-full bg-muted"indicatorClassName={usageIndicatorClass(ramPercent)}/>@@ -359,13 +399,25 @@ function FloatingMonitorPanel({</div><div className="text-xs text-muted-foreground font-mono tabular-nums">{vramUsageKnown ? formatGiB(vramUsed) : unknownLabel} /{" "}- {hasSharedPool+ {hasSharedPool && !unifiedPool? t("settings.resources.environment.vramWithShared", {vram: formatGiB(memoryTotals.dedicated),shared: formatGiB(memoryTotals.shared),}): formatGiB(vramTotal)}</div>+ {unifiedPool && memoryDisplay.sharedDevices.length === 0 && (+ <div className="text-xs font-mono text-muted-foreground">+ {t("settings.resources.gpu.sharedWithSystemRam")}+ {memoryDisplay.unifiedAvailableGb !== null && (+ <span className="block">+ {t("settings.resources.gpu.estimatedAvailable", {+ value: formatGiB(memoryDisplay.unifiedAvailableGb),+ })}+ </span>+ )}+ </div>+ )}<Progressvalue={vramUsageKnown ? vramPercent : 0}className="mt-1 h-1.5 rounded-full bg-muted"diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 973ba4ddfad..5cfdc3914cd 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -419,6 +419,7 @@ export interface InferenceStatusResponse {serving?: string[];/** Per `serving` entry, the id to select, load and unload it by: a local model's path. */serving_checkpoints?: string[];+ resident_mib?: number | null;/** Keep multiple models loaded, as saved on the server. Absent from older servers. */multi_model_mode?: "off" | "fit" | "always";inference?: {diff --git a/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts b/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.tsindex 786eb13a2e0..eab5c95ca8d 100644--- a/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts+++ b/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts@@ -11,6 +11,8 @@ import {import { useExportRuntimeStore } from "../stores/export-runtime-store";const STATUS_POLL_INTERVAL_MS = 5000;+// Idle: only catches a run started in another tab, so slow and skipped while hidden.+const IDLE_STATUS_POLL_INTERVAL_MS = 30_000;const STREAM_RECONNECT_DELAY_MS = 600;// Short-response fallback cadence, for a proxy that drops or stalls the log stream.const LOG_POLL_INTERVAL_MS = 750;@@ -37,6 +39,7 @@ export function useExportRuntimeLifecycle(): void {let logPolling = false;let logPollTimer: ReturnType<typeof setTimeout> | null = null;let statusPolling = false;+ let statusTimer: ReturnType<typeof setTimeout> | null = null;const store = useExportRuntimeStore;@@ -151,8 +154,27 @@ export function useExportRuntimeLifecycle(): void {}};+ const scheduleStatusPoll = () => {+ if (disposed) return;+ if (statusTimer) clearTimeout(statusTimer);+ const { isExporting, backendActive } = store.getState();+ const active = isExporting || backendActive;+ statusTimer = setTimeout(+ () => {+ statusTimer = null;+ if (!active && document.hidden) return;+ void pollStatus();+ },+ active ? STATUS_POLL_INTERVAL_MS : IDLE_STATUS_POLL_INTERVAL_MS,+ );+ };+const pollStatus = async () => {- if (!hasAuthToken() || statusPolling) return;+ if (statusPolling) return;+ if (!hasAuthToken()) {+ scheduleStatusPoll();+ return;+ }statusPolling = true;try {const status = await getExportStatus();@@ -166,15 +188,24 @@ export function useExportRuntimeLifecycle(): void {// ignore transient status failures} finally {statusPolling = false;+ scheduleStatusPoll();}};+ const onVisibilityChange = () => {+ if (document.hidden || statusPolling || disposed) return;+ if (statusTimer) clearTimeout(statusTimer);+ statusTimer = null;+ void pollStatus();+ };+// React to isExporting flipping (run start / terminal) without needing the// subscribeWithSelector middleware: the base subscribe fires on every change.let prevExporting = store.getState().isExporting;const unsubscribe = store.subscribe((state) => {if (state.isExporting === prevExporting) return;prevExporting = state.isExporting;+ if (!statusPolling) scheduleStatusPoll();if (state.isExporting) {void ensureStream();startLogPolling();@@ -189,13 +220,12 @@ export function useExportRuntimeLifecycle(): void {startLogPolling();}- const statusTimer = setInterval(() => {- void pollStatus();- }, STATUS_POLL_INTERVAL_MS);+ document.addEventListener("visibilitychange", onVisibilityChange);return () => {disposed = true;- clearInterval(statusTimer);+ if (statusTimer) clearTimeout(statusTimer);+ document.removeEventListener("visibilitychange", onVisibilityChange);unsubscribe();stopStream();};diff --git a/studio/frontend/src/features/export/stores/export-runtime-store.ts b/studio/frontend/src/features/export/stores/export-runtime-store.tsindex 997efd530bd..b217d03da26 100644--- a/studio/frontend/src/features/export/stores/export-runtime-store.ts+++ b/studio/frontend/src/features/export/stores/export-runtime-store.ts@@ -380,6 +380,10 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>// Load-only op, or no clear success record: nothing was exported.return { ...base, isExporting: false, phase: "idle" as const };}+ // The same object makes zustand skip notifying, so an idle poll re-renders nothing.+ if (state.hasHydrated && state.backendActive === base.backendActive) {+ return state;+ }return base;}),diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 94ffc85f406..5c32246a596 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -37,6 +37,7 @@ export interface DiffusionStatus {repo_id: string | null;/** Logical Hub identity when repo_id is an exact local snapshot. */display_repo_id?: string | null;+ resident_mib?: number | null;family: string | null;supported_families?: string[];// Of those, the families shipped as Modular Diffusers pipelines (the family override classes an opaque folder).diff --git a/studio/frontend/src/features/loaded-models/loaded-models-api.ts b/studio/frontend/src/features/loaded-models/loaded-models-api.tsindex 3e97270b9f7..17c4b442c79 100644--- a/studio/frontend/src/features/loaded-models/loaded-models-api.ts+++ b/studio/frontend/src/features/loaded-models/loaded-models-api.ts@@ -6,7 +6,7 @@// images/video/api-monitor are reached directly, as api-monitor-page.tsx does:// their indexes re-export pages __root.tsx keeps out of the eager bundle.-import { authFetch } from "@/features/auth";+import { authFetch, isAccountOwner } from "@/features/auth";import {confirmStopRunningChatsIfNeeded,getInferenceStatus,@@ -23,16 +23,22 @@ import {unloadDiffusionModel,} from "@/features/images/api";import { getVideoStatus, unloadVideoModel } from "@/features/video/api";+import { unloadEmbeddingModel } from "@/features/settings/api/embedding-model";+import { useEmbeddingModelStore } from "@/features/settings/stores/embedding-model-store";import { notifyModelEjected } from "@/lib/model-lifecycle-events";import { ejectChatModel } from "./eject-chat-model";import {+ embeddingRowName,+ type EmbeddingStatusResponse,type LoadedModelEntry,type LoadedModelSource,type SttStatusResponse,describeDiffusionStatus,+ describeEmbeddingStatus,describeInferenceStatus,describeSttStatus,describeVideoStatus,+ heldByAnotherAccount,mergeLoadedModels,sttEngineStatus,verifyResident,@@ -63,6 +69,17 @@ async function readSttStatus(return (await response.json()) as SttStatusResponse;}+// Owner-only route: a managed account would only collect 403s, so it is not asked.+async function readEmbeddingStatus(+ signal?: AbortSignal,+): Promise<EmbeddingStatusResponse | null> {+ const response = await authFetch("/api/settings/embedding-model", {+ signal,+ });+ if (!response.ok) return null;+ return (await response.json()) as EmbeddingStatusResponse;+}+// A runtime that accepts the connection and never answers would leave the whole batch pending// forever, and with it the in-flight guard gating every later refresh. Well past a cold status// probe, so a slow-but-healthy read still lands and only a real hang trips it.@@ -120,16 +137,19 @@ export type LoadedModelsRead = {/** Sources whose status did not come back, so nothing in this read is* evidence about them. */unreadable: LoadedModelSource[];+ heldByOther: boolean;};export async function readLoadedModels(previous: readonly LoadedModelEntry[] = [],): Promise<LoadedModelsRead> {- const [inference, diffusion, video, stt] = await Promise.all([+ const owner = isAccountOwner();+ const [inference, diffusion, video, stt, embedding] = await Promise.all([settled(readInferenceStatus),settled(getDiffusionStatus),settled(getVideoStatus),settled(readSttStatus),+ owner ? settled(readEmbeddingStatus) : Promise.resolve(null),]);const kept = (source: LoadedModelSource) =>previous.filter((row) => row.source === source);@@ -148,12 +168,19 @@ export async function readLoadedModels(group("image", diffusion, describeDiffusionStatus),group("video", video, describeVideoStatus),group("stt", stt, describeSttStatus),+ owner ? group("embedding", embedding, describeEmbeddingStatus) : [],]);- return { entries, unreadable };+ const heldByOther = heldByAnotherAccount([+ inference as { yours?: boolean } | null,+ diffusion as { yours?: boolean } | null,+ video as { yours?: boolean } | null,+ ]);+ return { entries, unreadable, heldByOther };}/** Release the model this row names, and only that one. See eject-chat-model.ts. */async function ejectChatRow(entry: LoadedModelEntry): Promise<EjectOutcome> {+ if (entry.servingCheckpoint) return ejectServingRow(entry);const decision = await confirmStopRunningChatsIfNeeded("Unloading this model","unloadOne",@@ -198,6 +225,36 @@ async function ejectChatRow(entry: LoadedModelEntry): Promise<EjectOutcome> {return { status: "ejected" };}+async function ejectServingRow(entry: LoadedModelEntry): Promise<EjectOutcome> {+ const checkpoint = entry.servingCheckpoint ?? entry.name;+ const decision = await confirmStopRunningChatsIfNeeded(+ "Unloading this model",+ "unloadOne",+ checkpoint,+ );+ if (!decision.proceed) return { status: "declined" };+ const servedCheckpoints = async () =>+ (await bounded(getInferenceStatus)).serving_checkpoints ?? [];+ const { unloadedAliases, stillResident } = await ejectChatModel(checkpoint, {+ // Never the active model: that row has no servingCheckpoint.+ readResident: async () => null,+ unload: (modelPath) => {+ requestScopedLocalPromptQueueStop(decision.promptQueueThreadIds);+ return unloadModel({+ model_path: modelPath,+ force_cancel_active: decision.forceCancelActive,+ });+ },+ matches: (left, right) => left === right,+ cachedRow: true,+ readCached: servedCheckpoints,+ });+ if (stillResident) return { status: "stillResident", model: stillResident };+ if (unloadedAliases.length === 0) return { status: "alreadyFree" };+ clearChatSelectionFor([checkpoint, entry.name]);+ return { status: "ejected" };+}+/** Clear the picker only when it names something this eject released: chat can* hold an external selection while a local model is resident. */function clearChatSelectionFor(aliases: string[]): void {@@ -289,6 +346,27 @@ export async function ejectLoadedModel(},);}+ case "embedding": {+ const before = await bounded(readEmbeddingStatus);+ if (!before) {+ throw new Error(+ "Could not read the embedding model status, so nothing was ejected.",+ );+ }+ if (!(before.backend_loaded ?? before.loaded))+ return { status: "alreadyFree" };+ // The unload route releases whatever is resident: a model swapped in since the poll stays.+ const resident = embeddingRowName(before);+ if (resident !== entry.name) return { status: "replaced", resident };+ await useEmbeddingModelStore+ .getState()+ .applyResidency(unloadEmbeddingModel);+ const after = await bounded(readEmbeddingStatus);+ if (!after) return { status: "unverified" };+ return (after.backend_loaded ?? after.loaded)+ ? { status: "stillResident", model: entry.name }+ : { status: "ejected" };+ }case "stt": {const engine = entry.sttEngine;if (!engine) throw new Error("This row names no dictation engine.");diff --git a/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsx b/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsxindex 152ec7f5cac..6a7189f34c1 100644--- a/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsx+++ b/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsx@@ -16,6 +16,7 @@ import { useAudioWorkspaceStore } from "@/features/audio/stores/audio-workspace-import { hasAuthToken, mustChangePassword } from "@/features/auth";import { useSettingsDialogStore } from "@/features/settings";import { usePersistedToggle } from "@/hooks/use-persisted-toggle";+import { useT } from "@/i18n";import { isTauri } from "@/lib/api-base";import { ChevronDownStandardIcon } from "@/lib/chevron-icons";import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";@@ -23,8 +24,10 @@ import { SparkleIcon } from "@/lib/sparkle-icon";import { cn } from "@/lib/utils";import {Cancel01Icon,+ DatabaseIcon,DragDropVerticalIcon,Image01Icon,+ LockIcon,Message01Icon,Mic01Icon,RemoveCircleIcon,@@ -33,13 +36,15 @@ import {import { Volume02Icon } from "@/lib/volume-icons";import { HugeiconsIcon } from "@hugeicons/react";import { useNavigate, useRouterState } from "@tanstack/react-router";-import { useCallback, useEffect, useRef } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import {type LoadedModelEntry,type LoadedModelKind,+ formatResidentMib,loadedModelKindLabel,+ loadedModelLabel,loadedModelTarget,- shortModelLabel,+ loadedModelsCardState,} from "./loaded-models-sources";import {LOADED_MODELS_PREFERENCE_KEYS,@@ -48,6 +53,7 @@ import {useShowLoadedModels,} from "./show-loaded-models-pref";import { useDragPosition } from "./use-drag-position";+import { usePublishedCornerFrame } from "./use-published-corner-frame";import { useLoadedModels } from "./use-loaded-models";// Collapsing to the pill is deliberate, so it survives reloads. Expanded by@@ -60,8 +66,14 @@ const KIND_ICONS: Record<LoadedModelKind, typeof SparkleIcon> = {image: Image01Icon,video: Video01Icon,stt: Mic01Icon,+ embedding: DatabaseIcon,};+const EMPTY_HINT_MS = 5000;++const ROW_ICON_CLASS =+ "flex size-7 shrink-0 items-center justify-center rounded-full bg-[color-mix(in_oklab,var(--foreground)_calc(5%*var(--contrast-wash-gain,1)),transparent)] text-muted-foreground";+// Nothing to report on auth screens. Desktop auto-authenticates, so only the// browser needs the token check: polling before one exists is all 401s.const HIDDEN_ROUTES = new Set(["/login", "/signup", "/change-password"]);@@ -72,9 +84,50 @@ function canShowIndicator(pathname: string): boolean {return hasAuthToken() && !mustChangePassword();}-function rowSubtitle(entry: LoadedModelEntry): string {+type Translate = ReturnType<typeof useT>;++function rowSubtitle(entry: LoadedModelEntry, t: Translate): string {const kind = loadedModelKindLabel(entry);- return entry.detail ? `${kind} · ${entry.detail}` : kind;+ const detail = entry.loading+ ? t("floatingPanels.loadedModels.loading")+ : entry.inactive+ ? t("floatingPanels.loadedModels.stillInMemory")+ : entry.servingCheckpoint+ ? t("floatingPanels.loadedModels.alsoServing")+ : entry.detail;+ return [kind, detail, formatResidentMib(entry.residentMib)]+ .filter(Boolean)+ .join(" · ");+}++function NoteRow({+ icon,+ title,+ detail,+}: {+ icon: typeof SparkleIcon;+ title: string;+ detail: string;+}) {+ return (+ <div className="flex items-center gap-2 rounded-[14px] px-1.5 py-1">+ <span className={ROW_ICON_CLASS}>+ <HugeiconsIcon+ icon={icon}+ strokeWidth={1.75}+ className="size-[calc(15px*var(--ui-space-scale,1))]"+ />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-ui-12p5 font-medium text-foreground">+ {title}+ </span>+ <span className="block truncate text-ui-11 text-muted-foreground">+ {detail}+ </span>+ </span>+ </div>+ );}function LoadedModelRow({@@ -88,7 +141,8 @@ function LoadedModelRow({onEject: () => void;onOpen: () => void;}) {- const label = shortModelLabel(entry.name);+ const t = useT();+ const label = loadedModelLabel(entry);const target = loadedModelTarget(entry.source, entry.workflows);return (<div className="flex items-center gap-2 rounded-[14px] px-1.5 py-1 transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_calc(4%*var(--contrast-wash-gain,1)),transparent)]">@@ -97,11 +151,14 @@ function LoadedModelRow({<TooltipTrigger asChild={true}><buttontype="button"- aria-label={`${label}. Open ${target.label}`}+ aria-label={t("floatingPanels.loadedModels.rowLabel", {+ model: label,+ target: target.label,+ })}onClick={onOpen}className="flex min-w-0 flex-1 items-center gap-2 text-left">- <span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-[color-mix(in_oklab,var(--foreground)_calc(5%*var(--contrast-wash-gain,1)),transparent)] text-muted-foreground">+ <span className={ROW_ICON_CLASS}><HugeiconsIconicon={KIND_ICONS[entry.kind]}strokeWidth={1.75}@@ -113,15 +170,17 @@ function LoadedModelRow({{label}</span><span className="block truncate text-ui-11 text-muted-foreground">- {rowSubtitle(entry)}+ {rowSubtitle(entry, t)}</span></span></button></TooltipTrigger><TooltipContent side="left" sideOffset={6}>- <span className="block">{entry.name}</span>+ <span className="block">{entry.label || entry.name}</span><span className="block text-muted-foreground">- Open {target.label}+ {t("floatingPanels.loadedModels.openTarget", {+ target: target.label,+ })}</span></TooltipContent></Tooltip>@@ -129,20 +188,28 @@ function LoadedModelRow({// Nothing resident to release yet, so the eject slot holds the spinner// the toast is showing at the same moment.<span className="flex size-6 shrink-0 items-center justify-center">- <Spinner className="size-3.5" label="Loading" />+ <Spinner+ className="size-3.5"+ label={t("floatingPanels.loadedModels.loading")}+ /></span>) : (<Tooltip><TooltipTrigger asChild={true}><buttontype="button"- aria-label={`Eject ${label}`}+ aria-label={t("floatingPanels.loadedModels.ejectLabel", {+ model: label,+ })}disabled={ejecting}onClick={onEject}className="flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_calc(7%*var(--contrast-wash-gain,1)),transparent)] hover:text-foreground disabled:pointer-events-none disabled:opacity-60">{ejecting ? (- <Spinner className="size-3.5" label="Ejecting" />+ <Spinner+ className="size-3.5"+ label={t("floatingPanels.loadedModels.ejecting")}+ />) : (// Eject, not dismiss: this releases the weights, which the// header's X does not. Same glyph the model picker's own eject@@ -156,7 +223,7 @@ function LoadedModelRow({</button></TooltipTrigger><TooltipContent side="left" sideOffset={6}>- Eject to free memory+ {t("floatingPanels.loadedModels.ejectToFree")}</TooltipContent></Tooltip>)}@@ -167,8 +234,20 @@ function LoadedModelRow({export function LoadedModelsIndicator({positioned = true,}: { positioned?: boolean } = {}) {+ const t = useT();const pathname = useRouterState({ select: (s) => s.location.pathname });const showIndicator = useShowLoadedModels();+ const [wasShown, setWasShown] = useState(showIndicator);+ const [justEnabled, setJustEnabled] = useState(false);+ if (wasShown !== showIndicator) {+ setWasShown(showIndicator);+ setJustEnabled(showIndicator);+ }+ useEffect(() => {+ if (!justEnabled) return;+ const timer = window.setTimeout(() => setJustEnabled(false), EMPTY_HINT_MS);+ return () => window.clearTimeout(timer);+ }, [justEnabled]);const dismissed = useLoadedModelsDismissed();const reachable = canShowIndicator(pathname);const enabled = showIndicator && !dismissed && reachable;@@ -177,10 +256,8 @@ export function LoadedModelsIndicator({// -- tracking on /login polls four protected endpoints every 5s, and each 401// runs authFetch's refresh-then-redirect ladder against a session that does// not exist yet.- const { entries, polledEntries, ejecting, eject } = useLoadedModels(- enabled,- showIndicator && reachable,- );+ const { entries, polledEntries, ejecting, heldByOther, eject } =+ useLoadedModels(enabled, showIndicator && reachable);const [collapsed, setCollapsed] = usePersistedToggle(COLLAPSED_KEY);const navigate = useNavigate();const openEntry = useCallback(@@ -203,8 +280,16 @@ export function LoadedModelsIndicator({},[navigate],);- const { position, panelRef, startDrag, dragging, justDragged } =- useDragPosition(LOADED_MODELS_PREFERENCE_KEYS.position);+ const {+ position,+ panelRef,+ element,+ startDrag,+ dragging,+ justDragged,+ nudge,+ } = useDragPosition(LOADED_MODELS_PREFERENCE_KEYS.position);+ usePublishedCornerFrame(position ? null : element);// A new load brings a closed card back: closing it means "not now", not "stop telling me", which// is what the Settings toggle is for. Subscribed above the early return, so a dismissed card is@@ -244,9 +329,23 @@ export function LoadedModelsIndicator({}}, [dismissed, polledEntries]);- if (!enabled || entries.length === 0) return null;+ const cardState = enabled+ ? loadedModelsCardState(entries.length, heldByOther, justEnabled)+ : null;+ if (cardState === null) return null;- const countLabel = `${entries.length} ${entries.length === 1 ? "model" : "models"} loaded`;+ const countLabel = t(+ entries.length === 1+ ? "floatingPanels.loadedModels.countOne"+ : "floatingPanels.loadedModels.countMany",+ { count: entries.length },+ );+ const showPill = collapsed && cardState !== "empty";+ const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== "Escape" || event.defaultPrevented) return;+ event.preventDefault();+ setLoadedModelsDismissed(true);+ };return (<div@@ -264,14 +363,24 @@ export function LoadedModelsIndicator({dragging && "select-none",)}style={position ? { left: position.left, top: position.top } : undefined}+ // biome-ignore lint/a11y/useSemanticElements: a floating panel landmark; the drag hook measures this div.+ role="region"+ aria-label={t("floatingPanels.loadedModels.title")}+ onKeyDown={onKeyDown}>- {collapsed ? (+ {showPill ? (<Tooltip><TooltipTrigger asChild={true}><buttontype="button"- aria-label={`${countLabel}. Show details, or drag to move`}+ aria-label={t("floatingPanels.loadedModels.pillLabel", {+ count:+ cardState === "otherAccount"+ ? t("floatingPanels.loadedModels.otherAccount")+ : countLabel,+ })}onPointerDown={startDrag}+ onKeyDown={(event) => void nudge(event)}// The pill is its own drag handle, so a press that moved is a// drag and must not also expand the card.onClick={() => {@@ -280,17 +389,21 @@ export function LoadedModelsIndicator({className="menu-soft-surface menu-soft-edgeless pointer-events-auto flex h-9 cursor-grab touch-none items-center gap-1.5 rounded-full pl-2.5 pr-3 font-heading text-muted-foreground transition-colors hover:text-foreground active:cursor-grabbing"><HugeiconsIcon- icon={SparkleIcon}+ icon={cardState === "otherAccount" ? LockIcon : SparkleIcon}strokeWidth={1.75}className="size-[calc(15px*var(--ui-space-scale,1))]"/>- <span className="text-ui-12p5 font-medium tabular-nums">- {entries.length}- </span>+ {cardState === "rows" && (+ <span className="text-ui-12p5 font-medium tabular-nums">+ {entries.length}+ </span>+ )}</button></TooltipTrigger><TooltipContent side="left" sideOffset={6}>- {countLabel}+ {cardState === "otherAccount"+ ? t("floatingPanels.loadedModels.otherAccount")+ : countLabel}</TooltipContent></Tooltip>) : (@@ -302,16 +415,19 @@ export function LoadedModelsIndicator({className="size-[calc(15px*var(--ui-space-scale,1))] shrink-0 text-muted-foreground"/><span className="min-w-0 flex-1 truncate text-ui-12p5 font-semibold text-foreground">- Loaded models+ {t("floatingPanels.loadedModels.title")}</span><Tooltip><TooltipTrigger asChild={true}><div- aria-label="Drag to move"- // Not a button, so no click follows to consume the drag sentinel: say so, or the- // collapsed pill's next click reads this drag as its own and refuses to expand.+ // biome-ignore lint/a11y/useSemanticElements: a <button> click would consume the drag sentinel meant for the pill.+ role="button"+ tabIndex={0}+ aria-label={t("floatingPanels.loadedModels.dragHandleLabel")}+ // Not a button element, so useDragPosition clears the drag sentinel itself.onPointerDown={startDrag}- className="flex size-6 shrink-0 cursor-grab touch-none items-center justify-center rounded-full text-muted-foreground/60 transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_calc(7%*var(--contrast-wash-gain,1)),transparent)] hover:text-foreground active:cursor-grabbing"+ onKeyDown={(event) => void nudge(event)}+ className="flex size-6 shrink-0 cursor-grab touch-none items-center justify-center rounded-full text-muted-foreground/60 transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_calc(7%*var(--contrast-wash-gain,1)),transparent)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"><HugeiconsIconicon={DragDropVerticalIcon}@@ -321,14 +437,14 @@ export function LoadedModelsIndicator({</div></TooltipTrigger><TooltipContent side="left" sideOffset={6}>- Drag to move+ {t("floatingPanels.loadedModels.dragToMove")}</TooltipContent></Tooltip><Tooltip><TooltipTrigger asChild={true}><buttontype="button"- aria-label="Collapse loaded models"+ aria-label={t("floatingPanels.loadedModels.collapseLabel")}onClick={() => setCollapsed(true)}className="flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_calc(7%*var(--contrast-wash-gain,1)),transparent)] hover:text-foreground">@@ -340,14 +456,14 @@ export function LoadedModelsIndicator({</button></TooltipTrigger><TooltipContent side="left" sideOffset={6}>- Collapse+ {t("floatingPanels.loadedModels.collapse")}</TooltipContent></Tooltip><Tooltip><TooltipTrigger asChild={true}><buttontype="button"- aria-label="Close loaded models"+ aria-label={t("floatingPanels.loadedModels.closeLabel")}onClick={() => setLoadedModelsDismissed(true)}className="flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_calc(7%*var(--contrast-wash-gain,1)),transparent)] hover:text-foreground">@@ -359,15 +475,31 @@ export function LoadedModelsIndicator({</button></TooltipTrigger><TooltipContent side="left" sideOffset={6}>- <span className="block">Close</span>+ <span className="block">+ {t("floatingPanels.loadedModels.close")}+ </span><span className="block text-muted-foreground">- Back on the next model load+ {t("floatingPanels.loadedModels.backOnNextLoad")}</span></TooltipContent></Tooltip></div>{/* Capped so four resident runtimes still leave the banners on screen. */}<div className="flex max-h-[min(272px,42dvh)] min-h-0 flex-col gap-0.5 overflow-y-auto">+ {cardState === "otherAccount" && (+ <NoteRow+ icon={LockIcon}+ title={t("floatingPanels.loadedModels.otherAccount")}+ detail={t("floatingPanels.loadedModels.otherAccountDetail")}+ />+ )}+ {cardState === "empty" && (+ <NoteRow+ icon={SparkleIcon}+ title={t("floatingPanels.loadedModels.noneLoaded")}+ detail={t("floatingPanels.loadedModels.noneLoadedDetail")}+ />+ )}{entries.map((entry) => (<LoadedModelRowkey={entry.id}diff --git a/studio/frontend/src/features/loaded-models/loaded-models-sources.ts b/studio/frontend/src/features/loaded-models/loaded-models-sources.tsindex ae491e04336..974eb28deb7 100644--- a/studio/frontend/src/features/loaded-models/loaded-models-sources.ts+++ b/studio/frontend/src/features/loaded-models/loaded-models-sources.ts@@ -22,10 +22,21 @@ import type { DiffusionStatus } from "@/features/images/api";import type { VideoStatus } from "@/features/video/api";/** What the row is, for the icon and label. */-export type LoadedModelKind = "text" | "tts" | "image" | "video" | "stt";+export type LoadedModelKind =+ | "text"+ | "tts"+ | "image"+ | "video"+ | "stt"+ | "embedding";/** Which runtime holds the weights, so which endpoint releases them. */-export type LoadedModelSource = "chat" | "image" | "video" | "stt";+export type LoadedModelSource =+ | "chat"+ | "image"+ | "video"+ | "stt"+ | "embedding";/** The dictation sidecars, as /audio/stt/status names them. */export type SttEngine = "transformers" | "mtmd" | "gguf" | "audiocpp";@@ -37,6 +48,9 @@ export type LoadedModelEntry = {source: LoadedModelSource;/** The id the backend reports; also what the eject call names. */name: string;+ label?: string;+ servingCheckpoint?: string;+ residentMib?: number;/** One short line: quantisation, family, device. */detail: string;/** Only on a `tts` row: the Audio page workflows that run the model, first one first. */@@ -89,7 +103,7 @@ export type LoadedModelTarget =search?: { workflow: AudioWorkflowId };label: string;}- | { open: "settings"; tab: "voice"; label: string };+ | { open: "settings"; tab: "voice" | "data"; label: string };export function loadedModelTarget(source: LoadedModelSource,@@ -116,6 +130,8 @@ export function loadedModelTarget(return { open: "route", to: "/video", label: "Video" };case "stt":return { open: "settings", tab: "voice", label: "Voice settings" };+ case "embedding":+ return { open: "settings", tab: "data", label: "Data settings" };default:return { open: "route", to: "/chat", label: "Chat" };}@@ -127,6 +143,7 @@ export const LOADED_MODEL_KIND_LABELS: Record<LoadedModelKind, string> = {image: "Image",video: "Video",stt: "Dictation",+ embedding: "Embeddings",};const AUDIO_WORKFLOW_KIND_LABELS: Partial<Record<AudioWorkflowId, string>> = {@@ -175,6 +192,24 @@ export function shortModelLabel(name: string): string {return segments.slice(-2).join("/");}+export function loadedModelLabel(+ entry: Pick<LoadedModelEntry, "name" | "label">,+): string {+ return shortModelLabel(entry.label || entry.name);+}++export function formatResidentMib(mib: number | null | undefined): string | null {+ if (typeof mib !== "number" || !Number.isFinite(mib) || mib <= 0) return null;+ const gib = mib / 1024;+ return `${gib >= 10 ? gib.toFixed(0) : gib.toFixed(1)} GiB`;+}++function residentMib(value: unknown): { residentMib?: number } {+ return typeof value === "number" && Number.isFinite(value) && value > 0+ ? { residentMib: value }+ : {};+}+/** Rows for whatever the chat runtime holds. `audio_type` splits TTS and whisper* out of the chat row: same picker, but neither answers prompts. */export function describeInferenceStatus(@@ -223,6 +258,7 @@ export function describeInferenceStatus(status.gguf_variant,status.is_vision ? "Vision" : null,),+ ...residentMib(status.resident_mib),});}// Reported by /status for the whole load, so a load started in another tab or@@ -238,6 +274,29 @@ export function describeInferenceStatus(loading: true,});}+ // Matched by checkpoint, which /unload routes on: two local files can share a label.+ const serving = status.serving ?? [];+ const checkpoints = status.serving_checkpoints ?? [];+ const activeCheckpoint = status.model_identifier || active;+ for (let i = 0; i < serving.length; i++) {+ const name = serving[i];+ const checkpoint = checkpoints[i] || name;+ // By checkpoint when both are known: a kept model may share the active one's label.+ const isActive =+ checkpoints[i] && status.model_identifier+ ? checkpoint === status.model_identifier+ : checkpoint === activeCheckpoint || name === active;+ if (!name || (active && isActive)) continue;+ if (entries.some((entry) => entry.id === `chat:${checkpoint}`)) continue;+ entries.push({+ id: `chat:${checkpoint}`,+ kind: "text",+ source: "chat",+ name,+ detail: "Also serving",+ servingCheckpoint: checkpoint,+ });+ }// Only the Transformers backend caches past the active model, but it is memory// nothing else surfaces or releases.for (const name of status.loaded ?? []) {@@ -297,6 +356,8 @@ export function describeDiffusionStatus(kind: "image",source: "image",name: status.repo_id,+ ...(status.display_repo_id ? { label: status.display_repo_id } : {}),+ ...residentMib(status.resident_mib),detail: joinDetail(status.family,// Only while the GGUF is what ran. A GGUF pick the dense fast path replaced is a@@ -327,6 +388,8 @@ export function describeVideoStatus(kind: "video",source: "video",name: status.repo_id,+ ...(status.display_repo_id ? { label: status.display_repo_id } : {}),+ ...residentMib(status.resident_mib),detail: joinDetail(status.family,status.model_kind === "gguf" || status.gguf_variant ? "GGUF" : null,@@ -475,4 +538,78 @@ const PENDING_KINDS: Record<LoadedModelSource, LoadedModelKind> = {image: "image",video: "video",stt: "stt",+ embedding: "embedding",};++export type EmbeddingStatusResponse = {+ // biome-ignore lint/style/useNamingConvention: API schema+ embedding_model?: string;+ loaded?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ backend_loaded?: boolean;+};++export function describeEmbeddingStatus(+ status: EmbeddingStatusResponse | null,+): LoadedModelEntry[] {+ const resident = status?.backend_loaded ?? status?.loaded ?? false;+ if (!resident) return [];+ return [+ {+ id: "embedding:rag",+ kind: "embedding",+ source: "embedding",+ name: embeddingRowName(status),+ detail: "Documents",+ },+ ];+}++export function embeddingRowName(+ status: EmbeddingStatusResponse | null,+): string {+ return (status?.loaded ? status.embedding_model : undefined) || "Embedding model";+}++export function heldByAnotherAccount(+ statuses: readonly ({ yours?: boolean } | null | undefined)[],+): boolean {+ return statuses.some((status) => status?.yours === false);+}++export function sameLoadedModels(+ left: readonly LoadedModelEntry[],+ right: readonly LoadedModelEntry[],+): boolean {+ if (left === right) return true;+ if (left.length !== right.length) return false;+ return left.every((entry, i) => {+ const other = right[i];+ return (+ entry.id === other.id &&+ entry.kind === other.kind &&+ entry.source === other.source &&+ entry.name === other.name &&+ entry.label === other.label &&+ entry.detail === other.detail &&+ entry.inactive === other.inactive &&+ entry.loading === other.loading &&+ entry.sttEngine === other.sttEngine &&+ entry.servingCheckpoint === other.servingCheckpoint &&+ entry.residentMib === other.residentMib &&+ (entry.workflows ?? []).join() === (other.workflows ?? []).join()+ );+ });+}++export type LoadedModelsCardState = "rows" | "otherAccount" | "empty" | null;++export function loadedModelsCardState(+ rowCount: number,+ heldByOther: boolean,+ justEnabled: boolean,+): LoadedModelsCardState {+ if (rowCount > 0) return "rows";+ if (heldByOther) return "otherAccount";+ return justEnabled ? "empty" : null;+}diff --git a/studio/frontend/src/features/loaded-models/show-loaded-models-pref.ts b/studio/frontend/src/features/loaded-models/show-loaded-models-pref.tsindex aa64ee07bf9..bd3bf977493 100644--- a/studio/frontend/src/features/loaded-models/show-loaded-models-pref.ts+++ b/studio/frontend/src/features/loaded-models/show-loaded-models-pref.ts@@ -41,6 +41,8 @@ export function setShowLoadedModels(show: boolean): void {// a pre-update tab does not flip the card back on through the storage event. Absent still means// off here, so the default is unaffected.localStorage.setItem(STORAGE_KEY, show ? "true" : "false");+ // Switching it on asks to see the card, so an earlier X must not keep it hidden.+ if (show) localStorage.removeItem(DISMISSED_KEY);} catch {// storage unavailable}diff --git a/studio/frontend/src/features/loaded-models/use-drag-position.ts b/studio/frontend/src/features/loaded-models/use-drag-position.tsindex c3ed97ac7f4..bbfb6f449c0 100644--- a/studio/frontend/src/features/loaded-models/use-drag-position.ts+++ b/studio/frontend/src/features/loaded-models/use-drag-position.ts@@ -5,7 +5,10 @@// user moves it, then kept where they left it. Absolute viewport coordinates rather than a// transform, so the position survives a reload and can be clamped when the window changes size.-import { isDegenerateBox } from "../../hooks/floating-panel-position.ts";+import {+ isDegenerateBox,+ nudgeDelta,+} from "../../hooks/floating-panel-position.ts";import { useCallback, useEffect, useMemo, useRef, useState } from "react";export type DragPosition = { left: number; top: number };@@ -49,6 +52,11 @@ export function passedDragThreshold(dx: number, dy: number): boolean {return Math.hypot(dx, dy) >= DRAG_THRESHOLD_PX;}+/** Non-button handles get no click, so they must clear the sentinel here or the pill's next click is swallowed. */+export function sentinelAfterSettle(moved: boolean, clickFollows: boolean): boolean {+ return moved && clickFollows;+}+function viewport(): Viewport {return { width: window.innerWidth, height: window.innerHeight };}@@ -90,6 +98,8 @@ export type UseDragPosition = {* button. Reading it clears the flag, so a later keyboard activation on the* same button is not swallowed too. */justDragged: () => boolean;+ element: HTMLDivElement | null;+ nudge: (event: React.KeyboardEvent<HTMLElement>) => boolean;};@@ -136,6 +146,7 @@ export function useDragPosition(storageKey: string): UseDragPosition {/** Where the last painted frame put it, committed to state on release. */lastLeft: number;lastTop: number;+ clickFollows: boolean;} | null>(null);// The drag paints through the DOM rather than through state, so a frame costs no render at all.// Held here so pointermove only ever records the latest offset and the frame reads it.@@ -204,6 +215,7 @@ export function useDragPosition(storageKey: string): UseDragPosition {height: box.height,lastLeft: box.left,lastTop: box.top,+ clickFollows: event.currentTarget instanceof HTMLButtonElement,};movedRef.current = false;setPressing(true);@@ -270,6 +282,10 @@ export function useDragPosition(storageKey: string): UseDragPosition {// window permanently overwrite a position saved on a large one; the read path clamps anyway.store(storageKey, landed);}+ movedRef.current = sentinelAfterSettle(+ movedRef.current,+ session?.clickFollows ?? false,+ );sessionRef.current = null;setPressing(false);setDragging(false);@@ -341,5 +357,33 @@ export function useDragPosition(storageKey: string): UseDragPosition {return moved;}, []);- return { position, panelRef: attachPanel, startDrag, dragging, justDragged };+ const nudge = useCallback(+ (event: React.KeyboardEvent<HTMLElement>) => {+ const delta = nudgeDelta(event.key, event.shiftKey);+ const panel = panelRef.current;+ if (!(delta && panel)) return false;+ event.preventDefault();+ const box = panel.getBoundingClientRect();+ const next = clampToViewport(+ { left: box.left + delta.dx, top: box.top + delta.dy },+ box.width,+ box.height,+ viewport(),+ );+ setPosition(next);+ store(storageKey, next);+ return true;+ },+ [storageKey],+ );++ return {+ position,+ panelRef: attachPanel,+ element: panelEl,+ startDrag,+ dragging,+ justDragged,+ nudge,+ };}diff --git a/studio/frontend/src/features/loaded-models/use-loaded-models.ts b/studio/frontend/src/features/loaded-models/use-loaded-models.tsindex 6475d6cda1a..659f4435568 100644--- a/studio/frontend/src/features/loaded-models/use-loaded-models.ts+++ b/studio/frontend/src/features/loaded-models/use-loaded-models.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { useT } from "@/i18n";import { toast } from "@/lib/toast";import { useCallback, useEffect, useRef, useState } from "react";import {@@ -11,6 +12,8 @@ import { ejectLoadedModel, readLoadedModels } from "./loaded-models-api";import {type LoadedModelEntry,type LoadedModelSource,+ loadedModelLabel,+ sameLoadedModels,shortModelLabel,withPendingLoads,} from "./loaded-models-sources";@@ -20,7 +23,13 @@ const POLL_INTERVAL_MS = 5000;const NO_ENTRIES: LoadedModelEntry[] = [];-const ALL_SOURCES: LoadedModelSource[] = ["chat", "image", "video", "stt"];+const ALL_SOURCES: LoadedModelSource[] = [+ "chat",+ "image",+ "video",+ "stt",+ "embedding",+];// A TTS load takes the chat slot and the chat unload releases it, so it folds into that// row rather than adding one.@@ -36,6 +45,7 @@ export type UseLoadedModels = {polledEntries: LoadedModelEntry[];/** Row ids with an eject in flight. */ejecting: ReadonlySet<string>;+ heldByOther: boolean;eject: (entry: LoadedModelEntry) => Promise<void>;refresh: () => void;};@@ -53,7 +63,9 @@ export function useLoadedModels(enabled: boolean,track: boolean = enabled,): UseLoadedModels {+ const t = useT();const [polled, setEntries] = useState<LoadedModelEntry[]>([]);+ const [heldByOther, setHeldByOther] = useState(false);// Mirrored for the read below, which needs the last rows without taking a// dependency that would rebuild `refresh` on every poll.const polledRef = useRef<LoadedModelEntry[]>(NO_ENTRIES);@@ -131,7 +143,10 @@ export function useLoadedModels(.then((next) => {unreadable = next.unreadable;if (mountedRef.current && generation === generationRef.current) {- setEntries(next.entries);+ setEntries((prev) =>+ sameLoadedModels(prev, next.entries) ? prev : next.entries,+ );+ setHeldByOther(next.heldByOther);}}).catch(() => {@@ -213,24 +228,28 @@ export function useLoadedModels(const eject = useCallback(async (entry: LoadedModelEntry) => {setEjecting((prev) => new Set(prev).add(entry.id));- const label = shortModelLabel(entry.name);+ const label = loadedModelLabel(entry);try {const outcome = await ejectLoadedModel(entry);if (outcome.status === "declined") return;if (outcome.status === "stillResident") {toast.warning(- `"${shortModelLabel(outcome.model)}" was loaded while ejecting, so it is still using memory. Eject again to release it.`,+ t("floatingPanels.loadedModels.toastStillResident", {+ model: shortModelLabel(outcome.model),+ }),);} else if (outcome.status === "unverified") {// Neither success nor failure: say so, and leave the row for the poll// to settle rather than claiming work that was not confirmed.toast.warning(- `${label} was asked to unload, but its runtime did not confirm. Check the card in a moment.`,+ t("floatingPanels.loadedModels.toastUnverified", { model: label }),);} else if (outcome.status === "alreadyFree") {// The row was stale and nothing was unloaded, so say that rather than// report an eject. The row still goes: its memory is free either way.- toast.info(`${label} was no longer loaded.`);+ toast.info(+ t("floatingPanels.loadedModels.toastAlreadyFree", { model: label }),+ );generationRef.current += 1;if (mountedRef.current) {setEntries((prev) => prev.filter((row) => row.id !== entry.id));@@ -239,10 +258,15 @@ export function useLoadedModels(// Nothing was unloaded: this runtime holds something else now, and// releasing that is not what the click asked for.toast.info(- `${label} is no longer loaded. "${shortModelLabel(outcome.resident)}" took its place and was left alone.`,+ t("floatingPanels.loadedModels.toastReplaced", {+ model: label,+ resident: shortModelLabel(outcome.resident),+ }),);} else {- toast.success(`Ejected ${label}`);+ toast.success(+ t("floatingPanels.loadedModels.toastEjected", { model: label }),+ );// Drop the row now, rather than offering to eject it again until the next poll. Any read// already in flight predates this and would put the row back, so retire it.generationRef.current += 1;@@ -252,7 +276,9 @@ export function useLoadedModels(}} catch (error: unknown) {toast.error(- error instanceof Error ? error.message : `Failed to eject ${label}`,+ error instanceof Error+ ? error.message+ : t("floatingPanels.loadedModels.toastFailed", { model: label }),);} finally {if (mountedRef.current) {@@ -265,8 +291,15 @@ export function useLoadedModels(refresh();}},- [refresh],+ [refresh, t],);- return { entries, polledEntries: polled, ejecting, eject, refresh };+ return {+ entries,+ polledEntries: polled,+ ejecting,+ heldByOther: enabled && heldByOther,+ eject,+ refresh,+ };}diff --git a/studio/frontend/src/features/loaded-models/use-published-corner-frame.ts b/studio/frontend/src/features/loaded-models/use-published-corner-frame.tsnew file mode 100644index 00000000000..7d9d2dc8628--- /dev/null+++ b/studio/frontend/src/features/loaded-models/use-published-corner-frame.ts@@ -0,0 +1,44 @@+// 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 { useCornerCardFrameStore } from "@/features/settings/stores/monitor-frame-store";+import { subscribeCornerInsets } from "@/lib/toast-offset";+import { useEffect } from "react";++export function usePublishedCornerFrame(element: HTMLElement | null): void {+ useEffect(() => {+ const { setFrame } = useCornerCardFrameStore.getState();+ if (!element) {+ setFrame(null);+ return;+ }+ const measure = () => {+ const box = element.getBoundingClientRect();+ setFrame(+ box.width > 0 && box.height > 0+ ? {+ left: box.left,+ top: box.top,+ right: box.right,+ bottom: box.bottom,+ }+ : null,+ );+ };+ measure();+ window.addEventListener("resize", measure);+ // Run settings and the composer lift move the rail by its padding, which resizes nothing.+ const unsubscribe = subscribeCornerInsets(measure);+ const observer =+ typeof ResizeObserver === "undefined"+ ? null+ : new ResizeObserver(measure);+ observer?.observe(element);+ return () => {+ window.removeEventListener("resize", measure);+ unsubscribe();+ observer?.disconnect();+ setFrame(null);+ };+ }, [element]);+}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex 57669fb4ece..e69185201c0 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -121,6 +121,7 @@ import {ggufVariantFitSizeBytes,requiredGgufMemoryGb,} from "@/lib/gguf-fit";+import { formatGiB } from "@/lib/memory/format";import { extractParamLabel } from "@/lib/model-size";import { toast } from "@/lib/toast";import { cn, formatCompact } from "@/lib/utils";@@ -1241,10 +1242,10 @@ function ModelRow({// is weights plus activations plus KV, so "Needs ~47GB VRAM" contradicted the verdict.? vramBudget? curatedBudgetText(vramEst, gpuGb, vramBudget)- : `Needs ~${vramEst}GB memory (GPU: ${gpuGb}GB)`+ : `Needs ~${formatGiB(vramEst)} memory (GPU: ${formatGiB(gpuGb)})`: vramStatus === "tight" || vramStatus === "marginal"- ? `~${vramEst}GB VRAM (tight fit on ${gpuGb}GB)`- : `~${vramEst}GB VRAM`+ ? `~${formatGiB(vramEst)} VRAM (tight fit on ${formatGiB(gpuGb)})`+ : `~${formatGiB(vramEst)} VRAM`: null;const { owner, name } = splitRepoLabel(label);diff --git a/studio/frontend/src/features/settings/stores/monitor-frame-store.ts b/studio/frontend/src/features/settings/stores/monitor-frame-store.tsindex 65b33f0f6d7..4f3719df6dd 100644--- a/studio/frontend/src/features/settings/stores/monitor-frame-store.ts+++ b/studio/frontend/src/features/settings/stores/monitor-frame-store.ts@@ -63,3 +63,14 @@ export const useMonitorFrameStore = create<MonitorFrameState>((set) => ({return { frames };}),}));++interface CornerCardFrameState {+ frame: MonitorFrame | null;+ setFrame: (frame: MonitorFrame | null) => void;+}++export const useCornerCardFrameStore = create<CornerCardFrameState>((set) => ({+ frame: null,+ setFrame: (frame) =>+ set((state) => (sameFrame(state.frame, frame) ? state : { frame })),+}));diff --git a/studio/frontend/src/features/settings/tabs/resources-tab.tsx b/studio/frontend/src/features/settings/tabs/resources-tab.tsxindex 8af18607592..f5602a2c12a 100644--- a/studio/frontend/src/features/settings/tabs/resources-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/resources-tab.tsx@@ -524,13 +524,14 @@ export function ResourcesTab() {.join(" · "): null;const unknownLabel = t("settings.resources.environment.unknown");+ const unifiedPool = metrics.vramShared > 0 && metrics.vramDedicated === 0;const vramCapacityLabel =- metrics.vramShared > 0+ metrics.vramShared > 0 && !unifiedPool? t("settings.resources.environment.vramWithShared", {vram: formatGiB(metrics.vramDedicated),shared: formatGiB(metrics.vramShared),})- : formatGiB(metrics.vramTotal);+ : formatGiB(unifiedPool ? metrics.vramShared : metrics.vramTotal);// The placeholder's cpu backend and empty package list are not facts about the host either.const hostReading = (value: string) => (hostUnread ? unknownLabel : value);// systemInfo.gpu rather than displayedGpu: this describes the TRAINING view of the host,@@ -686,11 +687,15 @@ export function ResourcesTab() {: hasGpu? memoryDisplay.sharedOnly? t("settings.resources.gpu.sharedWithSystemRam")- : metrics.vramUsageKnown- ? t("settings.resources.liveMonitor.free", {- value: formatGiB(metrics.vramFree),+ : unifiedPool && memoryDisplay.unifiedAvailableGb !== null+ ? t("settings.resources.gpu.estimatedAvailable", {+ value: formatGiB(memoryDisplay.unifiedAvailableGb),})- : unknownLabel+ : metrics.vramUsageKnown+ ? t("settings.resources.liveMonitor.free", {+ value: formatGiB(metrics.vramFree),+ })+ : unknownLabel: gpuMismatch? t("settings.resources.liveMonitor.gpuUnusableDetail"): backendLabel@@ -700,7 +705,9 @@ export function ResourcesTab() {!memoryDisplay.sharedOnly &&memoryDisplay.sharedDevices.length > 0? `${t("settings.resources.gpu.sharedWithSystemRam")}\n${t("settings.resources.gpu.estimatedAvailable", { value: memoryDisplay.sharedAvailableGb === null ? unknownLabel : formatGiB(memoryDisplay.sharedAvailableGb) })}`- : undefined+ : unifiedPool && !memoryDisplay.sharedOnly+ ? t("settings.resources.gpu.sharedWithSystemRam")+ : undefined}percent={metrics.vramUsageKnown ? metrics.vramPercent : null}/>diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.tsindex 50e636d2837..50ca84976af 100644--- a/studio/frontend/src/features/video/api.ts+++ b/studio/frontend/src/features/video/api.ts@@ -61,6 +61,7 @@ export interface VideoStatus {repo_id: string | null;/** Logical Hub identity when repo_id is an exact local snapshot. */display_repo_id?: string | null;+ resident_mib?: number | null;family: string | null;supported_families?: string[];/** Pipeline-capable families whose loader accepts a Modular Diffusers manifest on this host. */diff --git a/studio/frontend/src/hooks/floating-panel-position.ts b/studio/frontend/src/hooks/floating-panel-position.tsindex ddb55da99ab..dfc1df7f937 100644--- a/studio/frontend/src/hooks/floating-panel-position.ts+++ b/studio/frontend/src/hooks/floating-panel-position.ts@@ -45,3 +45,60 @@ export function placeAxis(intent: number | null, max: number): number {export function isDegenerateBox(box: { width: number; height: number }): boolean {return !(box.width > 0 && box.height > 0);}++export function clearPanelIntent(key: string | undefined): void {+ if (!key) return;+ try {+ localStorage.removeItem(key);+ } catch {+ // storage unavailable+ }+}++export function nudgeDelta(+ key: string,+ shift: boolean,+): { dx: number; dy: number } | null {+ const step = shift ? 32 : 8;+ switch (key) {+ case "ArrowLeft":+ return { dx: -step, dy: 0 };+ case "ArrowRight":+ return { dx: step, dy: 0 };+ case "ArrowUp":+ return { dx: 0, dy: -step };+ case "ArrowDown":+ return { dx: 0, dy: step };+ default:+ return null;+ }+}++export type FrameBox = { left: number; top: number; right: number; bottom: number };++export function liftAboveObstacle(+ panel: { left: number; top: number; width: number; height: number },+ obstacle: FrameBox | null | undefined,+ gap: number,+): number | null {+ if (!obstacle) return null;+ const overlapsX =+ panel.left < obstacle.right && panel.left + panel.width > obstacle.left;+ // Not only on collision: a card the composer lifted would leave the panel below it, over the composer.+ const reaches = panel.top + panel.height > obstacle.top - gap;+ return overlapsX && reaches ? obstacle.top - gap - panel.height : null;+}++export const ANCHOR_SNAP_PX = 16;++export function snapsToAnchor(+ drop: { left: number; top: number },+ rest: { left: number; top: number },+ max: { left: number; top: number },+ threshold: number = ANCHOR_SNAP_PX,+): boolean {+ const near = (a: { left: number; top: number }) =>+ Math.abs(drop.left - a.left) <= threshold &&+ Math.abs(drop.top - a.top) <= threshold;+ return near(rest) || near(max);+}diff --git a/studio/frontend/src/hooks/gpu-memory-display.ts b/studio/frontend/src/hooks/gpu-memory-display.tsindex 5d7d6323ba4..c5808efab68 100644--- a/studio/frontend/src/hooks/gpu-memory-display.ts+++ b/studio/frontend/src/hooks/gpu-memory-display.ts@@ -8,6 +8,21 @@ export function hasSharedMemoryHeadroom(device: GpuDevice): boolean {return device.index_kind === "vulkan" && device.shared_memory === true;}+/** A usage device whose whole budget is host RAM (Apple unified memory, CUDA integrated): its free reading is headroom. */+export function hasUnifiedPoolHeadroom(device: GpuDevice): boolean {+ const total = device.memory_total_gb ?? 0;+ const hostBacked = device.shared_memory_host_backed_gb;+ return (+ !hasSharedMemoryHeadroom(device) &&+ device.shared_memory === true &&+ total > 0 &&+ Number.isFinite(hostBacked) &&+ (hostBacked as number) >= total &&+ Number.isFinite(device.vram_free_gb) &&+ (device.vram_free_gb as number) >= 0+ );+}+export function sharedMemoryAvailableGb(devices: GpuDevice[]): number | null {if (!devices.length ||@@ -34,6 +49,9 @@ export function gpuMemoryDisplay(gpu: SystemGpuInfo | null | undefined) {usageDevices,sharedOnly: sharedDevices.length > 0 && usageDevices.length === 0,sharedAvailableGb: sharedMemoryAvailableGb(sharedDevices),+ unifiedAvailableGb: sharedMemoryAvailableGb(+ usageDevices.filter(hasUnifiedPoolHeadroom),+ ),usageGpu: gpu? {...gpu,diff --git a/studio/frontend/src/hooks/system-discovery.ts b/studio/frontend/src/hooks/system-discovery.tsindex ef27a538732..07005dea11e 100644--- a/studio/frontend/src/hooks/system-discovery.ts+++ b/studio/frontend/src/hooks/system-discovery.ts@@ -31,3 +31,29 @@ export function shouldRetrySystemDiscovery(}return inferenceGpu?.backend === "vulkan" && !inferenceGpu.available;}++const VULKAN_RETRY_BASE_MS = 3000;+const VULKAN_RETRY_MAX_MS = 60_000;++export function vulkanRetryDelayMs(attempt: number): number {+ return Math.min(+ VULKAN_RETRY_BASE_MS * 2 ** Math.max(0, attempt),+ VULKAN_RETRY_MAX_MS,+ );+}++export const STALE_AFTER_FAILED_POLLS = 2;++export function nextFailedPolls(previous: number, ok: boolean): number {+ return ok ? 0 : previous + 1;+}++export function isReadingStale(+ status: SystemInfoStatus,+ failedPolls: number,+ polling: boolean,+): boolean {+ return (+ polling && status === "ready" && failedPolls >= STALE_AFTER_FAILED_POLLS+ );+}diff --git a/studio/frontend/src/hooks/use-floating-panel-layout.ts b/studio/frontend/src/hooks/use-floating-panel-layout.tsindex 366b4987067..df94b169977 100644--- a/studio/frontend/src/hooks/use-floating-panel-layout.ts+++ b/studio/frontend/src/hooks/use-floating-panel-layout.ts@@ -3,13 +3,19 @@import { useMonitorFrameStore } from "@/features/settings";import {+ type FrameBox,type PanelIntent,+ clearPanelIntent,isDegenerateBox,+ liftAboveObstacle,+ nudgeDelta,placeAxis,readPanelIntent,+ snapsToAnchor,storePanelIntent,} from "@/hooks/floating-panel-position";import {+ type KeyboardEvent,type PointerEvent,useLayoutEffect,useMemo,@@ -41,6 +47,8 @@ interface DragSession {baseTop: number;}+const OBSTACLE_GAP_PX = 8;+function clamp(value: number, min: number, max: number): number {return Math.max(min, Math.min(max, value));}@@ -87,6 +95,7 @@ export function useFloatingPanelLayout(bounds: DOMRect,) => { left: number; top: number },storageKey?: string,+ restingObstacle?: FrameBox | null,) {// Per-instance frame owner: a panel unmounting mid-exit clears only its own frame.const publisher = useMemo(() => ({}), []);@@ -109,6 +118,8 @@ export function useFloatingPanelLayout(const reconcileRef = useRef<(() => void) | null>(null);const initialPlacementRef = useRef(initialPlacement);const initializedRef = useRef(false);+ const obstacleRef = useRef(restingObstacle ?? null);+ const restRef = useRef({ left: 0, top: 0, maxLeft: 0, maxTop: 0 });useLayoutEffect(() => {const monitor = monitorRef.current;@@ -186,6 +197,31 @@ export function useFloatingPanelLayout(}initializedRef.current = true;+ const bottomTop = (atLeft: number) => {+ const lifted = liftAboveObstacle(+ {+ left: constraintsBox.left + atLeft,+ top: constraintsBox.top + maxTop,+ width,+ height,+ },+ obstacleRef.current,+ OBSTACLE_GAP_PX,+ );+ return lifted === null+ ? maxTop+ : clamp(lifted - constraintsBox.top, 0, maxTop);+ };+ restRef.current = {+ left: maxLeft,+ top: bottomTop(maxLeft),+ maxLeft,+ maxTop,+ };+ if (!session && intentRef.current.top === null) {+ top = bottomTop(left);+ }+if (session) {session.left = left;session.top = top;@@ -252,6 +288,13 @@ export function useFloatingPanelLayout(}}, [hidden, publisher]);+ useLayoutEffect(() => {+ obstacleRef.current = restingObstacle ?? null;+ if (!dragSessionRef.current) {+ reconcileRef.current?.();+ }+ }, [restingObstacle]);+useLayoutEffect(() => {if (narrowedRef.current === narrowed) {return;@@ -378,6 +421,20 @@ export function useFloatingPanelLayout(constraintsHeight,} = session;dragSessionRef.current = null;+ const rest = restRef.current;+ if (+ (left !== baseLeft || top !== baseTop) &&+ snapsToAnchor(+ { left, top },+ rest,+ { left: rest.maxLeft, top: rest.maxTop },+ )+ ) {+ const monitor = monitorRef.current;+ if (monitor) monitor.style.transform = "";+ resetPosition();+ return;+ }if (left !== baseLeft || top !== baseTop) {const intent = intentRef.current;intentRef.current = {@@ -406,6 +463,61 @@ export function useFloatingPanelLayout();}+ function commitPosition(left: number, top: number, constraints: DOMRect) {+ const monitor = monitorRef.current;+ if (monitor) {+ monitor.style.left = `${left}px`;+ monitor.style.top = `${top}px`;+ }+ setLayout((current) =>+ !current || (current.left === left && current.top === top)+ ? current+ : {+ ...current,+ left,+ top,+ maxWidth: constraints.width - left,+ maxHeight: constraints.height - top,+ },+ );+ }++ function resetPosition() {+ intentRef.current = { left: null, top: null };+ clearPanelIntent(storageKey);+ reconcileRef.current?.();+ }++ function nudge(event: KeyboardEvent<HTMLElement>): boolean {+ const delta = nudgeDelta(event.key, event.shiftKey);+ const monitor = monitorRef.current;+ if (!(delta && monitor && constraintsElement) || dragSessionRef.current) {+ return false;+ }+ event.preventDefault();+ const constraintsBox = constraintsElement.getBoundingClientRect();+ const monitorBox = monitor.getBoundingClientRect();+ const left = clamp(+ monitorBox.left - constraintsBox.left + delta.dx,+ 0,+ Math.max(0, constraintsBox.width - monitorBox.width),+ );+ const top = clamp(+ monitorBox.top - constraintsBox.top + delta.dy,+ 0,+ Math.max(0, constraintsBox.height - monitorBox.height),+ );+ // Only the moved axis becomes absolute: a null axis stays anchored to the far edge, as after a drag.+ const previous = intentRef.current;+ intentRef.current = {+ left: delta.dx !== 0 ? left : previous.left,+ top: delta.dy !== 0 ? top : previous.top,+ };+ storePanelIntent(storageKey, intentRef.current);+ commitPosition(left, top, constraintsBox);+ return true;+ }+return {publisher,monitorRef,@@ -415,5 +527,7 @@ export function useFloatingPanelLayout(startDrag,updateDrag,finishDrag,+ resetPosition,+ nudge,};}diff --git a/studio/frontend/src/hooks/use-gpu-info.ts b/studio/frontend/src/hooks/use-gpu-info.tsindex 154d341f6d8..5e3e2d0fa4a 100644--- a/studio/frontend/src/hooks/use-gpu-info.ts+++ b/studio/frontend/src/hooks/use-gpu-info.ts@@ -288,6 +288,29 @@ export function withStableSchemes(current: GpuInfo, next: GpuInfo): GpuInfo {return next;}+const RAM_DRIFT_TOLERANCE_GB = 0.25;++/** Keeps `current` when only free RAM drifted, so subscribed pages do not re-render on every poll. */+export function nextGpuInfo(current: GpuInfo, next: GpuInfo): GpuInfo {+ const ramDrift = Math.max(+ Math.abs(current.systemRamAvailableGb - next.systemRamAvailableGb),+ Math.abs(current.systemRamAvailableHostGb - next.systemRamAvailableHostGb),+ );+ const withoutLiveRam = (info: GpuInfo) =>+ JSON.stringify({+ ...info,+ systemRamAvailableGb: 0,+ systemRamAvailableHostGb: 0,+ });+ if (+ ramDrift < RAM_DRIFT_TOLERANCE_GB &&+ withoutLiveRam(current) === withoutLiveRam(next)+ ) {+ return current;+ }+ return withStableSchemes(current, next);+}+/** Aggregate GPU info from /api/system; shares one module-level fetch across all GPU hooks. */function useGpuInfoSource(source: "gpu" | "inference_gpu"): GpuInfo {const cachedSystem = getCachedSystemInfo();@@ -301,11 +324,7 @@ function useGpuInfoSource(source: "gpu" | "inference_gpu"): GpuInfo {const sync = (data: SystemInfoResponse) => {if (cancelled) return;const next = toGpuInfo(data, source);- setGpu((current) =>- JSON.stringify(current) === JSON.stringify(next)- ? current- : withStableSchemes(current, next),- );+ setGpu((current) => nextGpuInfo(current, next));};const update = () => {fetchSystemInfo().then((d) => {diff --git a/studio/frontend/src/hooks/use-system.ts b/studio/frontend/src/hooks/use-system.tsindex ce06fc4945a..f42de00879d 100644--- a/studio/frontend/src/hooks/use-system.ts+++ b/studio/frontend/src/hooks/use-system.ts@@ -2,11 +2,15 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { authFetch } from "@/features/auth";-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";+import { disposableTimeoutSignal } from "../features/hub/lib/abort-signals";import {+ isReadingStale,+ nextFailedPolls,settledFailureStatus,shouldRetrySystemDiscovery,type SystemInfoStatus,+ vulkanRetryDelayMs,} from "./system-discovery";export interface GpuDevice {@@ -56,6 +60,7 @@ export interface SystemInfoResponse {/** Client-side, not sent by the backend. Readers rendering a host verdict -- "no GPU",* "CPU only" -- must check it, or they state the placeholder below as fact. */status: SystemInfoStatus;+ stale?: boolean;platform: string;python_version: string;device_backend: "cuda" | "rocm" | "cpu" | "mlx" | "xpu";@@ -117,6 +122,10 @@ let systemFetchPromise: Promise<SystemInfoResponse | null> | null = null;const systemSubscribers = new Set<(data: SystemInfoResponse) => void>();let vulkanRetrySubscribers = 0;let vulkanRetryId: number | null = null;+let vulkanRetryAttempt = 0;+let vulkanRetryDeferred = false;+// A hung request must not hold systemFetchPromise, which every refreshMemory caller awaits.+const SYSTEM_FETCH_TIMEOUT_MS = 15_000;const DEFAULT_SYSTEM: SystemInfoResponse = {status: "pending",@@ -148,14 +157,26 @@ export function subscribeSystemInfo(systemSubscribers.delete(subscriber);if (options.retryUnavailableVulkan) {vulkanRetrySubscribers = Math.max(0, vulkanRetrySubscribers - 1);- if (vulkanRetrySubscribers === 0 && vulkanRetryId !== null) {- window.clearTimeout(vulkanRetryId);+ if (vulkanRetrySubscribers === 0) {+ if (vulkanRetryId !== null) window.clearTimeout(vulkanRetryId);vulkanRetryId = null;+ if (vulkanRetryDeferred) cancelDeferredVulkanRetry();}}};}+function cancelDeferredVulkanRetry(): void {+ vulkanRetryDeferred = false;+ document.removeEventListener("visibilitychange", retryVulkanWhenVisible);+}++function retryVulkanWhenVisible(): void {+ if (document.hidden) return;+ cancelDeferredVulkanRetry();+ void fetchSystemInfo({ force: true });+}+function scheduleVulkanRetry(): void {if (!shouldRetrySystemDiscovery(@@ -170,15 +191,25 @@ function scheduleVulkanRetry(): void {window.clearTimeout(vulkanRetryId);vulkanRetryId = null;}+ vulkanRetryAttempt = 0;+ if (vulkanRetryDeferred) cancelDeferredVulkanRetry();return;}- if (vulkanRetryId !== null) {+ if (vulkanRetryId !== null || vulkanRetryDeferred) {return;}- vulkanRetryId = window.setTimeout(() => {- vulkanRetryId = null;- void fetchSystemInfo({ force: true });- }, 3000);+ vulkanRetryId = window.setTimeout(+ () => {+ vulkanRetryId = null;+ if (document.hidden) {+ vulkanRetryDeferred = true;+ document.addEventListener("visibilitychange", retryVulkanWhenVisible);+ return;+ }+ void fetchSystemInfo({ force: true });+ },+ vulkanRetryDelayMs(vulkanRetryAttempt++),+ );}export async function fetchSystemInfo({@@ -194,9 +225,11 @@ export async function fetchSystemInfo({if (!force && !refreshMemory && cachedSystem) return cachedSystem;systemFetchPromise = (async () => {+ const timeout = disposableTimeoutSignal(SYSTEM_FETCH_TIMEOUT_MS);try {const res = await authFetch(refreshMemory ? "/api/system?refresh_memory=true" : "/api/system",+ { signal: timeout.signal },);if (!res.ok) throw new Error(`HTTP ${res.status}`);const data = await res.json();@@ -207,6 +240,7 @@ export async function fetchSystemInfo({} catch {return null;} finally {+ timeout.dispose();systemFetchPromise = null;scheduleVulkanRetry();}@@ -225,11 +259,13 @@ export function useSystemInfo({enabled = true,}: UseSystemInfoOptions = {}): SystemInfoResponse {const [systemInfo, setSystemInfo] = useState<SystemInfoResponse>(cachedSystem ?? DEFAULT_SYSTEM);+ const [failedPolls, setFailedPolls] = useState(0);useEffect(() => {if (!enabled) return;let cancelled = false;+ let inFlight = false;let timeoutId: number | null = null;// A placeholder has nothing to retry it once its own request settled, so it takes any@@ -240,9 +276,11 @@ export function useSystemInfo({});const update = (force: boolean) => {+ inFlight = true;void fetchSystemInfo({ force }).then((info) => {if (cancelled) return;+ setFailedPolls((previous) => nextFailedPolls(previous, info !== null));if (info) {setSystemInfo(info);return;@@ -255,18 +293,35 @@ export function useSystemInfo({});}).finally(() => {+ inFlight = false;if (cancelled || !pollMs) return;- timeoutId = window.setTimeout(() => update(true), pollMs);+ timeoutId = window.setTimeout(() => {+ timeoutId = null;+ if (!document.hidden) update(true);+ }, pollMs);});};+ const onVisibilityChange = () => {+ if (document.hidden || inFlight || cancelled) return;+ if (timeoutId !== null) window.clearTimeout(timeoutId);+ timeoutId = null;+ update(true);+ };+update(Boolean(pollMs));+ if (pollMs) document.addEventListener("visibilitychange", onVisibilityChange);return () => {cancelled = true;unsubscribe();if (timeoutId !== null) window.clearTimeout(timeoutId);+ document.removeEventListener("visibilitychange", onVisibilityChange);};}, [enabled, pollMs]);- return systemInfo;+ const stale = enabled && isReadingStale(systemInfo.status, failedPolls, Boolean(pollMs));+ return useMemo(+ () => (stale ? { ...systemInfo, stale: true } : systemInfo),+ [stale, systemInfo],+ );}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex b4ad73c1aac..2932e1a82df 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -4685,4 +4685,41 @@ export const ar = {failed: "خطأ {status}",invalidJson: "نص الطلب ليس JSON صالحًا.",},+ floatingPanels: {+ loadedModels: {+ title: "النماذج المحمّلة",+ countOne: "تم تحميل {count} نموذج",+ countMany: "تم تحميل {count} نماذج",+ pillLabel: "{count}. اعرض التفاصيل أو اسحب للنقل",+ dragToMove: "اسحب للنقل",+ dragHandleLabel: "انقل النماذج المحمّلة. مفاتيح الأسهم تحركها قليلًا.",+ collapse: "طي",+ collapseLabel: "طي النماذج المحمّلة",+ close: "إغلاق",+ closeLabel: "إغلاق النماذج المحمّلة",+ backOnNextLoad: "تعود عند تحميل النموذج التالي",+ ejectToFree: "أخرج لتحرير الذاكرة",+ ejectLabel: "إخراج {model}",+ openTarget: "فتح {target}",+ rowLabel: "{model}. فتح {target}",+ loading: "جارٍ التحميل",+ ejecting: "جارٍ الإخراج",+ stillInMemory: "لا يزال في الذاكرة",+ alsoServing: "يخدم أيضًا",+ noneLoaded: "لا توجد نماذج محمّلة",+ noneLoadedDetail: "ستظهر هنا النماذج التي تحمّلها.",+ otherAccount: "قيد الاستخدام من حساب آخر",+ otherAccountDetail: "الذاكرة محجوزة بواسطة نموذج لا يمكنك رؤيته",+ toastStillResident: "تم تحميل «{model}» أثناء الإخراج، لذا لا يزال يستخدم الذاكرة. أخرجه مرة أخرى لتحريرها.",+ toastUnverified: "طُلب إلغاء تحميل {model} لكن بيئة التشغيل لم تؤكد ذلك. تحقق من البطاقة بعد قليل.",+ toastAlreadyFree: "{model} لم يعد محمّلًا.",+ toastReplaced: "{model} لم يعد محمّلًا. حلّ «{resident}» محله وتُرك كما هو.",+ toastEjected: "تم إخراج {model}",+ toastFailed: "تعذّر إخراج {model}",+ },+ monitor: {+ dragHandleLabel: "انقل شاشة المراقبة المباشرة. مفاتيح الأسهم تحركها قليلًا، والنقر المزدوج يعيدها إلى مكانها.",+ reconnecting: "جارٍ إعادة الاتصال...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 5701b2cba62..681dab2c6b7 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -4760,4 +4760,41 @@ export const de = {failed: "Fehler {status}",invalidJson: "Der Anfrage-Body ist kein gültiges JSON.",},+ floatingPanels: {+ loadedModels: {+ title: "Geladene Modelle",+ countOne: "{count} Modell geladen",+ countMany: "{count} Modelle geladen",+ pillLabel: "{count}. Details anzeigen oder zum Verschieben ziehen",+ dragToMove: "Zum Verschieben ziehen",+ dragHandleLabel: "Geladene Modelle verschieben. Mit den Pfeiltasten feinjustieren.",+ collapse: "Einklappen",+ collapseLabel: "Geladene Modelle einklappen",+ close: "Schließen",+ closeLabel: "Geladene Modelle schließen",+ backOnNextLoad: "Erscheint beim nächsten Laden eines Modells wieder",+ ejectToFree: "Auswerfen, um Speicher freizugeben",+ ejectLabel: "{model} auswerfen",+ openTarget: "{target} öffnen",+ rowLabel: "{model}. {target} öffnen",+ loading: "Wird geladen",+ ejecting: "Wird ausgeworfen",+ stillInMemory: "Noch im Speicher",+ alsoServing: "Stellt außerdem bereit",+ noneLoaded: "Keine Modelle geladen",+ noneLoadedDetail: "Modelle, die du lädst, werden hier angezeigt.",+ otherAccount: "Von einem anderen Konto verwendet",+ otherAccountDetail: "Der Speicher wird von einem Modell belegt, das du nicht sehen kannst",+ toastStillResident: "„{model}“ wurde während des Auswerfens geladen und belegt daher weiterhin Speicher. Wirf es erneut aus, um ihn freizugeben.",+ toastUnverified: "{model} sollte entladen werden, aber die Laufzeit hat dies nicht bestätigt. Prüfe die Karte gleich noch einmal.",+ toastAlreadyFree: "{model} war nicht mehr geladen.",+ toastReplaced: "{model} ist nicht mehr geladen. „{resident}“ hat seinen Platz eingenommen und wurde nicht angetastet.",+ toastEjected: "{model} ausgeworfen",+ toastFailed: "{model} konnte nicht ausgeworfen werden",+ },+ monitor: {+ dragHandleLabel: "Live-Monitor verschieben. Mit den Pfeiltasten feinjustieren, per Doppelklick zurücksetzen.",+ reconnecting: "Verbindung wird wiederhergestellt...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 404a50c0fb0..e3149dabb28 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -4755,4 +4755,45 @@ export const en = {failed: "Error {status}",invalidJson: "The request body is not valid JSON.",},+ floatingPanels: {+ loadedModels: {+ title: "Loaded models",+ countOne: "{count} model loaded",+ countMany: "{count} models loaded",+ pillLabel: "{count}. Show details, or drag to move",+ dragToMove: "Drag to move",+ dragHandleLabel: "Drag to move",+ collapse: "Collapse",+ collapseLabel: "Collapse loaded models",+ close: "Close",+ closeLabel: "Close loaded models",+ backOnNextLoad: "Back on the next model load",+ ejectToFree: "Eject to free memory",+ ejectLabel: "Eject {model}",+ openTarget: "Open {target}",+ rowLabel: "{model}. Open {target}",+ loading: "Loading",+ ejecting: "Ejecting",+ stillInMemory: "Still in memory",+ alsoServing: "Also serving",+ noneLoaded: "No models loaded",+ noneLoadedDetail: "Models you load will show here.",+ otherAccount: "In use by another account",+ otherAccountDetail: "Memory is held by a model you cannot see",+ toastStillResident:+ "\"{model}\" was loaded while ejecting, so it is still using memory. Eject again to release it.",+ toastUnverified:+ "{model} was asked to unload, but its runtime did not confirm. Check the card in a moment.",+ toastAlreadyFree: "{model} was no longer loaded.",+ toastReplaced:+ "{model} is no longer loaded. \"{resident}\" took its place and was left alone.",+ toastEjected: "Ejected {model}",+ toastFailed: "Failed to eject {model}",+ },+ monitor: {+ dragHandleLabel:+ "Move the live monitor. Arrow keys nudge it, double-click resets it.",+ reconnecting: "Reconnecting...",+ },+ },} as const;diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex ad1f3de0ea9..257de694ea4 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -4759,4 +4759,41 @@ export const es = {failed: "Error {status}",invalidJson: "El cuerpo de la solicitud no es JSON válido.",},+ floatingPanels: {+ loadedModels: {+ title: "Modelos cargados",+ countOne: "{count} modelo cargado",+ countMany: "{count} modelos cargados",+ pillLabel: "{count}. Mostrar detalles o arrastrar para mover",+ dragToMove: "Arrastra para mover",+ dragHandleLabel: "Mover los modelos cargados. Las teclas de flecha lo desplazan un poco.",+ collapse: "Contraer",+ collapseLabel: "Contraer los modelos cargados",+ close: "Cerrar",+ closeLabel: "Cerrar los modelos cargados",+ backOnNextLoad: "Vuelve al cargar el siguiente modelo",+ ejectToFree: "Expulsar para liberar memoria",+ ejectLabel: "Expulsar {model}",+ openTarget: "Abrir {target}",+ rowLabel: "{model}. Abrir {target}",+ loading: "Cargando",+ ejecting: "Expulsando",+ stillInMemory: "Sigue en memoria",+ alsoServing: "También en servicio",+ noneLoaded: "No hay modelos cargados",+ noneLoadedDetail: "Los modelos que cargues aparecerán aquí.",+ otherAccount: "En uso por otra cuenta",+ otherAccountDetail: "La memoria la ocupa un modelo que no puedes ver",+ toastStillResident: "«{model}» se cargó mientras se expulsaba, así que sigue usando memoria. Expúlsalo de nuevo para liberarla.",+ toastUnverified: "Se pidió descargar {model}, pero el entorno de ejecución no lo confirmó. Revisa la tarjeta en un momento.",+ toastAlreadyFree: "{model} ya no estaba cargado.",+ toastReplaced: "{model} ya no está cargado. «{resident}» ocupó su lugar y no se tocó.",+ toastEjected: "{model} expulsado",+ toastFailed: "No se pudo expulsar {model}",+ },+ monitor: {+ dragHandleLabel: "Mover el monitor en vivo. Las teclas de flecha lo desplazan un poco; con doble clic se restablece.",+ reconnecting: "Reconectando...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 48fc2ef2dce..28a0daad574 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -4771,4 +4771,41 @@ export const fr = {failed: "Erreur {status}",invalidJson: "Le corps de la requête n'est pas un JSON valide.",},+ floatingPanels: {+ loadedModels: {+ title: "Modèles chargés",+ countOne: "{count} modèle chargé",+ countMany: "{count} modèles chargés",+ pillLabel: "{count}. Afficher les détails ou faire glisser pour déplacer",+ dragToMove: "Faire glisser pour déplacer",+ dragHandleLabel: "Déplacer les modèles chargés. Les touches fléchées le déplacent légèrement.",+ collapse: "Réduire",+ collapseLabel: "Réduire les modèles chargés",+ close: "Fermer",+ closeLabel: "Fermer les modèles chargés",+ backOnNextLoad: "Réapparaît au prochain chargement de modèle",+ ejectToFree: "Éjecter pour libérer la mémoire",+ ejectLabel: "Éjecter {model}",+ openTarget: "Ouvrir {target}",+ rowLabel: "{model}. Ouvrir {target}",+ loading: "Chargement",+ ejecting: "Éjection",+ stillInMemory: "Toujours en mémoire",+ alsoServing: "Sert aussi",+ noneLoaded: "Aucun modèle chargé",+ noneLoadedDetail: "Les modèles que vous chargez s’afficheront ici.",+ otherAccount: "Utilisé par un autre compte",+ otherAccountDetail: "La mémoire est occupée par un modèle que vous ne pouvez pas voir",+ toastStillResident: "« {model} » a été chargé pendant l’éjection et utilise donc toujours de la mémoire. Éjectez-le à nouveau pour la libérer.",+ toastUnverified: "Le déchargement de {model} a été demandé, mais l’environnement d’exécution ne l’a pas confirmé. Vérifiez la carte dans un instant.",+ toastAlreadyFree: "{model} n’était plus chargé.",+ toastReplaced: "{model} n’est plus chargé. « {resident} » a pris sa place et n’a pas été modifié.",+ toastEjected: "{model} éjecté",+ toastFailed: "Impossible d’éjecter {model}",+ },+ monitor: {+ dragHandleLabel: "Déplacer le moniteur en direct. Les touches fléchées le déplacent légèrement, un double-clic le réinitialise.",+ reconnecting: "Reconnexion...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex e639b7a55ca..b74df8ed1f1 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -4820,4 +4820,41 @@ export const he = {failed: "שגיאה {status}",invalidJson: "גוף הבקשה אינו JSON תקין.",},+ floatingPanels: {+ loadedModels: {+ title: "מודלים טעונים",+ countOne: "{count} מודל טעון",+ countMany: "{count} מודלים טעונים",+ pillLabel: "{count}. הצג פרטים, או גרור כדי להזיז",+ dragToMove: "גרור כדי להזיז",+ dragHandleLabel: "הזז את המודלים הטעונים. מקשי החיצים מזיזים אותו מעט.",+ collapse: "כווץ",+ collapseLabel: "כווץ את המודלים הטעונים",+ close: "סגירה",+ closeLabel: "סגור את המודלים הטעונים",+ backOnNextLoad: "יחזור בטעינת המודל הבאה",+ ejectToFree: "הוצא כדי לפנות זיכרון",+ ejectLabel: "הוצא את {model}",+ openTarget: "פתח את {target}",+ rowLabel: "{model}. פתח את {target}",+ loading: "טוען",+ ejecting: "מוציא",+ stillInMemory: "עדיין בזיכרון",+ alsoServing: "מספק שירות גם ל־",+ noneLoaded: "אין מודלים טעונים",+ noneLoadedDetail: "מודלים שתטען יוצגו כאן.",+ otherAccount: "בשימוש בחשבון אחר",+ otherAccountDetail: "הזיכרון תפוס על ידי מודל שאינך יכול לראות",+ toastStillResident: "„{model}” נטען בזמן ההוצאה, ולכן עדיין משתמש בזיכרון. הוצא אותו שוב כדי לפנות אותו.",+ toastUnverified: "התבקשה הוצאה של {model}, אך סביבת ההרצה לא אישרה זאת. בדוק את הכרטיס בעוד רגע.",+ toastAlreadyFree: "{model} כבר לא היה טעון.",+ toastReplaced: "{model} אינו טעון עוד. „{resident}” תפס את מקומו ולא נגעו בו.",+ toastEjected: "{model} הוצא",+ toastFailed: "הוצאת {model} נכשלה",+ },+ monitor: {+ dragHandleLabel: "הזז את מסך הניטור החי. מקשי החיצים מזיזים אותו מעט, ולחיצה כפולה מאפסת אותו.",+ reconnecting: "מתחבר מחדש...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex b0c76aa33fd..f0dd35ea66d 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -4696,4 +4696,41 @@ export const hi = {failed: "त्रुटि {status}",invalidJson: "अनुरोध की बॉडी मान्य JSON नहीं है।",},+ floatingPanels: {+ loadedModels: {+ title: "लोड किए गए मॉडल",+ countOne: "{count} मॉडल लोड है",+ countMany: "{count} मॉडल लोड हैं",+ pillLabel: "{count}. विवरण दिखाएँ, या हिलाने के लिए खींचें",+ dragToMove: "हिलाने के लिए खींचें",+ dragHandleLabel: "लोड किए गए मॉडल हिलाएँ। एरो कुंजियाँ इसे थोड़ा खिसकाती हैं।",+ collapse: "समेटें",+ collapseLabel: "लोड किए गए मॉडल समेटें",+ close: "बंद करें",+ closeLabel: "लोड किए गए मॉडल बंद करें",+ backOnNextLoad: "अगला मॉडल लोड होने पर फिर दिखेगा",+ ejectToFree: "मेमोरी खाली करने के लिए इजेक्ट करें",+ ejectLabel: "{model} इजेक्ट करें",+ openTarget: "{target} खोलें",+ rowLabel: "{model}। {target} खोलें",+ loading: "लोड हो रहा है",+ ejecting: "इजेक्ट हो रहा है",+ stillInMemory: "अब भी मेमोरी में",+ alsoServing: "इसे भी सर्व कर रहा है",+ noneLoaded: "कोई मॉडल लोड नहीं है",+ noneLoadedDetail: "आपके लोड किए मॉडल यहाँ दिखेंगे।",+ otherAccount: "किसी दूसरे खाते द्वारा उपयोग में",+ otherAccountDetail: "मेमोरी ऐसे मॉडल के पास है जिसे आप नहीं देख सकते",+ toastStillResident: "इजेक्ट करते समय “{model}” लोड हो गया, इसलिए वह अब भी मेमोरी इस्तेमाल कर रहा है। उसे खाली करने के लिए दोबारा इजेक्ट करें।",+ toastUnverified: "{model} को अनलोड करने का अनुरोध किया गया था, लेकिन रनटाइम ने पुष्टि नहीं की। कुछ देर बाद कार्ड देखें।",+ toastAlreadyFree: "{model} अब लोड नहीं था।",+ toastReplaced: "{model} अब लोड नहीं है। “{resident}” ने उसकी जगह ले ली और उसे छुआ नहीं गया।",+ toastEjected: "{model} इजेक्ट हो गया",+ toastFailed: "{model} इजेक्ट नहीं हो सका",+ },+ monitor: {+ dragHandleLabel: "लाइव मॉनिटर हिलाएँ। एरो कुंजियाँ इसे थोड़ा खिसकाती हैं, डबल-क्लिक करने पर यह रीसेट हो जाता है।",+ reconnecting: "फिर से कनेक्ट हो रहा है...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 547f64e030e..58eaf276d0f 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -4761,4 +4761,41 @@ export const it = {failed: "Errore {status}",invalidJson: "Il corpo della richiesta non è un JSON valido.",},+ floatingPanels: {+ loadedModels: {+ title: "Modelli caricati",+ countOne: "{count} modello caricato",+ countMany: "{count} modelli caricati",+ pillLabel: "{count}. Mostra i dettagli o trascina per spostare",+ dragToMove: "Trascina per spostare",+ dragHandleLabel: "Sposta i modelli caricati. I tasti freccia lo spostano leggermente.",+ collapse: "Comprimi",+ collapseLabel: "Comprimi i modelli caricati",+ close: "Chiudi",+ closeLabel: "Chiudi i modelli caricati",+ backOnNextLoad: "Tornerà al prossimo caricamento di un modello",+ ejectToFree: "Espelli per liberare memoria",+ ejectLabel: "Espelli {model}",+ openTarget: "Apri {target}",+ rowLabel: "{model}. Apri {target}",+ loading: "Caricamento",+ ejecting: "Espulsione",+ stillInMemory: "Ancora in memoria",+ alsoServing: "Serve anche",+ noneLoaded: "Nessun modello caricato",+ noneLoadedDetail: "I modelli che carichi verranno mostrati qui.",+ otherAccount: "In uso da un altro account",+ otherAccountDetail: "La memoria è occupata da un modello che non puoi vedere",+ toastStillResident: "“{model}” è stato caricato durante l'espulsione, quindi usa ancora memoria. Espellilo di nuovo per liberarla.",+ toastUnverified: "È stato richiesto lo scaricamento di {model}, ma il runtime non lo ha confermato. Controlla la scheda tra un attimo.",+ toastAlreadyFree: "{model} non era più caricato.",+ toastReplaced: "{model} non è più caricato. “{resident}” ha preso il suo posto e non è stato toccato.",+ toastEjected: "{model} espulso",+ toastFailed: "Impossibile espellere {model}",+ },+ monitor: {+ dragHandleLabel: "Sposta il monitor in tempo reale. I tasti freccia lo spostano leggermente, il doppio clic lo reimposta.",+ reconnecting: "Riconnessione...",+ },+ },} as const;diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex fdb92d5ae64..626851fecd0 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -4635,4 +4635,41 @@ export const ja = {failed: "エラー {status}",invalidJson: "リクエストのボディが有効な JSON ではありません。",},+ floatingPanels: {+ loadedModels: {+ title: "読み込み済みモデル",+ countOne: "{count} 件のモデルを読み込み済み",+ countMany: "{count} 件のモデルを読み込み済み",+ pillLabel: "{count}。詳細を表示、またはドラッグして移動",+ dragToMove: "ドラッグして移動",+ dragHandleLabel: "読み込み済みモデルを移動します。矢印キーで少しずつ動かせます。",+ collapse: "折りたたむ",+ collapseLabel: "読み込み済みモデルを折りたたむ",+ close: "閉じる",+ closeLabel: "読み込み済みモデルを閉じる",+ backOnNextLoad: "次にモデルを読み込むと再表示されます",+ ejectToFree: "取り出してメモリを解放",+ ejectLabel: "{model} を取り出す",+ openTarget: "{target} を開く",+ rowLabel: "{model}。{target} を開く",+ loading: "読み込み中",+ ejecting: "取り出し中",+ stillInMemory: "まだメモリ上にあります",+ alsoServing: "他にも提供中",+ noneLoaded: "読み込み済みのモデルはありません",+ noneLoadedDetail: "読み込んだモデルはここに表示されます。",+ otherAccount: "別のアカウントが使用中",+ otherAccountDetail: "表示できないモデルがメモリを保持しています",+ toastStillResident: "取り出し中に「{model}」が読み込まれたため、まだメモリを使用しています。もう一度取り出すと解放されます。",+ toastUnverified: "{model} のアンロードを要求しましたが、ランタイムから確認が取れませんでした。しばらくしてからカードを確認してください。",+ toastAlreadyFree: "{model} はすでに読み込まれていませんでした。",+ toastReplaced: "{model} は読み込まれていません。代わりに「{resident}」が読み込まれており、そのままにしています。",+ toastEjected: "{model} を取り出しました",+ toastFailed: "{model} を取り出せませんでした",+ },+ monitor: {+ dragHandleLabel: "ライブモニターを移動します。矢印キーで少しずつ動かせ、ダブルクリックで位置をリセットします。",+ reconnecting: "再接続中...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex c6cadaf59f3..d8baa62d5e5 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -4674,4 +4674,41 @@ export const ko = {failed: "오류 {status}",invalidJson: "요청 본문이 올바른 JSON이 아닙니다.",},+ floatingPanels: {+ loadedModels: {+ title: "로드된 모델",+ countOne: "모델 {count}개 로드됨",+ countMany: "모델 {count}개 로드됨",+ pillLabel: "{count}. 세부 정보를 보거나 드래그하여 이동",+ dragToMove: "드래그하여 이동",+ dragHandleLabel: "로드된 모델 패널을 이동합니다. 방향키로 조금씩 움직일 수 있습니다.",+ collapse: "접기",+ collapseLabel: "로드된 모델 접기",+ close: "닫기",+ closeLabel: "로드된 모델 닫기",+ backOnNextLoad: "다음 모델을 로드할 때 다시 표시됩니다",+ ejectToFree: "꺼내서 메모리 확보",+ ejectLabel: "{model} 꺼내기",+ openTarget: "{target} 열기",+ rowLabel: "{model}. {target} 열기",+ loading: "로딩 중",+ ejecting: "꺼내는 중",+ stillInMemory: "아직 메모리에 있음",+ alsoServing: "함께 서비스 중",+ noneLoaded: "로드된 모델 없음",+ noneLoadedDetail: "로드한 모델이 여기에 표시됩니다.",+ otherAccount: "다른 계정에서 사용 중",+ otherAccountDetail: "볼 수 없는 모델이 메모리를 점유하고 있습니다",+ toastStillResident: "꺼내는 중에 \"{model}\"이(가) 로드되어 아직 메모리를 사용하고 있습니다. 다시 꺼내면 메모리가 해제됩니다.",+ toastUnverified: "{model}의 언로드를 요청했지만 런타임이 확인하지 않았습니다. 잠시 후 카드를 확인하세요.",+ toastAlreadyFree: "{model}은(는) 더 이상 로드되어 있지 않았습니다.",+ toastReplaced: "{model}은(는) 더 이상 로드되어 있지 않습니다. \"{resident}\"이(가) 그 자리를 차지했으며 그대로 두었습니다.",+ toastEjected: "{model} 꺼냄",+ toastFailed: "{model}을(를) 꺼내지 못했습니다",+ },+ monitor: {+ dragHandleLabel: "실시간 모니터를 이동합니다. 방향키로 조금씩 움직이고, 더블클릭하면 위치가 초기화됩니다.",+ reconnecting: "다시 연결하는 중...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 7358f038a92..6b1989ca1b8 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -4719,4 +4719,41 @@ export const ptBR = {failed: "Erro {status}",invalidJson: "O corpo da solicitação não é um JSON válido.",},+ floatingPanels: {+ loadedModels: {+ title: "Modelos carregados",+ countOne: "{count} modelo carregado",+ countMany: "{count} modelos carregados",+ pillLabel: "{count}. Mostrar detalhes ou arrastar para mover",+ dragToMove: "Arraste para mover",+ dragHandleLabel: "Mover os modelos carregados. As setas do teclado o deslocam um pouco.",+ collapse: "Recolher",+ collapseLabel: "Recolher os modelos carregados",+ close: "Fechar",+ closeLabel: "Fechar os modelos carregados",+ backOnNextLoad: "Volta no próximo carregamento de modelo",+ ejectToFree: "Ejetar para liberar memória",+ ejectLabel: "Ejetar {model}",+ openTarget: "Abrir {target}",+ rowLabel: "{model}. Abrir {target}",+ loading: "Carregando",+ ejecting: "Ejetando",+ stillInMemory: "Ainda na memória",+ alsoServing: "Também em serviço",+ noneLoaded: "Nenhum modelo carregado",+ noneLoadedDetail: "Os modelos que você carregar aparecerão aqui.",+ otherAccount: "Em uso por outra conta",+ otherAccountDetail: "A memória está ocupada por um modelo que você não pode ver",+ toastStillResident: "\"{model}\" foi carregado durante a ejeção, então ainda está usando memória. Ejete novamente para liberá-la.",+ toastUnverified: "Foi solicitado descarregar {model}, mas o runtime não confirmou. Verifique o card em instantes.",+ toastAlreadyFree: "{model} não estava mais carregado.",+ toastReplaced: "{model} não está mais carregado. \"{resident}\" ocupou o lugar e foi deixado como está.",+ toastEjected: "{model} ejetado",+ toastFailed: "Falha ao ejetar {model}",+ },+ monitor: {+ dragHandleLabel: "Mover o monitor ao vivo. As setas do teclado o deslocam um pouco; clique duplo o redefine.",+ reconnecting: "Reconectando...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 3121c4f6566..9ad9d80576b 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -4717,4 +4717,41 @@ export const ru = {failed: "Ошибка {status}",invalidJson: "Тело запроса не является корректным JSON.",},+ floatingPanels: {+ loadedModels: {+ title: "Загруженные модели",+ countOne: "Загружена {count} модель",+ countMany: "Загружено моделей: {count}",+ pillLabel: "{count}. Показать подробности или перетащить",+ dragToMove: "Перетащите, чтобы переместить",+ dragHandleLabel: "Переместить панель загруженных моделей. Стрелки сдвигают её понемногу.",+ collapse: "Свернуть",+ collapseLabel: "Свернуть загруженные модели",+ close: "Закрыть",+ closeLabel: "Закрыть загруженные модели",+ backOnNextLoad: "Появится снова при следующей загрузке модели",+ ejectToFree: "Извлечь, чтобы освободить память",+ ejectLabel: "Извлечь {model}",+ openTarget: "Открыть {target}",+ rowLabel: "{model}. Открыть {target}",+ loading: "Загрузка",+ ejecting: "Извлечение",+ stillInMemory: "Всё ещё в памяти",+ alsoServing: "Также обслуживает",+ noneLoaded: "Нет загруженных моделей",+ noneLoadedDetail: "Загруженные вами модели появятся здесь.",+ otherAccount: "Используется другой учётной записью",+ otherAccountDetail: "Память занята моделью, которую вы не видите",+ toastStillResident: "Пока шло извлечение, «{model}» была загружена, поэтому она всё ещё занимает память. Извлеките её ещё раз, чтобы освободить.",+ toastUnverified: "Запрошена выгрузка {model}, но среда выполнения не подтвердила её. Проверьте карточку через минуту.",+ toastAlreadyFree: "{model} уже не была загружена.",+ toastReplaced: "{model} больше не загружена. Её место заняла «{resident}», её не трогали.",+ toastEjected: "{model} извлечена",+ toastFailed: "Не удалось извлечь {model}",+ },+ monitor: {+ dragHandleLabel: "Переместить живой монитор. Стрелки сдвигают его понемногу, двойной щелчок сбрасывает положение.",+ reconnecting: "Повторное подключение…",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex a2005da456f..079e425e3aa 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -4967,4 +4967,41 @@ export const sv = {failed: "Fel {status}",invalidJson: "Begärans body är inte giltig JSON.",},+ floatingPanels: {+ loadedModels: {+ title: "Inlästa modeller",+ countOne: "{count} modell inläst",+ countMany: "{count} modeller inlästa",+ pillLabel: "{count}. Visa detaljer eller dra för att flytta",+ dragToMove: "Dra för att flytta",+ dragHandleLabel: "Flytta inlästa modeller. Piltangenterna flyttar den lite i taget.",+ collapse: "Fäll ihop",+ collapseLabel: "Fäll ihop inlästa modeller",+ close: "Stäng",+ closeLabel: "Stäng inlästa modeller",+ backOnNextLoad: "Visas igen vid nästa modellinläsning",+ ejectToFree: "Mata ut för att frigöra minne",+ ejectLabel: "Mata ut {model}",+ openTarget: "Öppna {target}",+ rowLabel: "{model}. Öppna {target}",+ loading: "Läser in",+ ejecting: "Matar ut",+ stillInMemory: "Finns kvar i minnet",+ alsoServing: "Betjänar även",+ noneLoaded: "Inga modeller inlästa",+ noneLoadedDetail: "Modeller du läser in visas här.",+ otherAccount: "Används av ett annat konto",+ otherAccountDetail: "Minnet hålls av en modell som du inte kan se",+ toastStillResident: "”{model}” lästes in under utmatningen och använder därför fortfarande minne. Mata ut den igen för att frigöra det.",+ toastUnverified: "{model} ombads att laddas ur, men körmiljön bekräftade inte. Kontrollera kortet om en stund.",+ toastAlreadyFree: "{model} var inte längre inläst.",+ toastReplaced: "{model} är inte längre inläst. ”{resident}” tog dess plats och lämnades orörd.",+ toastEjected: "{model} utmatad",+ toastFailed: "Det gick inte att mata ut {model}",+ },+ monitor: {+ dragHandleLabel: "Flytta liveövervakaren. Piltangenterna flyttar den lite i taget, dubbelklick återställer den.",+ reconnecting: "Återansluter …",+ },+ },} as const;diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 3b6fce3892a..9de352c7461 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -4587,4 +4587,41 @@ export const zhCN = {failed: "错误 {status}",invalidJson: "请求体不是有效的 JSON。",},+ floatingPanels: {+ loadedModels: {+ title: "已加载的模型",+ countOne: "已加载 {count} 个模型",+ countMany: "已加载 {count} 个模型",+ pillLabel: "{count}。显示详情,或拖动以移动",+ dragToMove: "拖动以移动",+ dragHandleLabel: "移动已加载的模型面板。方向键可微调位置。",+ collapse: "折叠",+ collapseLabel: "折叠已加载的模型",+ close: "关闭",+ closeLabel: "关闭已加载的模型",+ backOnNextLoad: "下次加载模型时会重新显示",+ ejectToFree: "弹出以释放内存",+ ejectLabel: "弹出 {model}",+ openTarget: "打开 {target}",+ rowLabel: "{model}。打开 {target}",+ loading: "加载中",+ ejecting: "弹出中",+ stillInMemory: "仍在内存中",+ alsoServing: "同时也在服务",+ noneLoaded: "没有已加载的模型",+ noneLoadedDetail: "你加载的模型会显示在这里。",+ otherAccount: "正被其他账户使用",+ otherAccountDetail: "内存被一个你看不到的模型占用",+ toastStillResident: "弹出期间“{model}”被加载,因此仍在占用内存。请再次弹出以释放。",+ toastUnverified: "已请求卸载 {model},但运行时未确认。请稍后查看卡片。",+ toastAlreadyFree: "{model} 已不再处于加载状态。",+ toastReplaced: "{model} 已不再加载。“{resident}”取代了它,未做处理。",+ toastEjected: "已弹出 {model}",+ toastFailed: "弹出 {model} 失败",+ },+ monitor: {+ dragHandleLabel: "移动实时监控。方向键可微调位置,双击可重置。",+ reconnecting: "正在重新连接...",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/lib/toast-offset.ts b/studio/frontend/src/lib/toast-offset.tsindex 81887144761..a2194db5cff 100644--- a/studio/frontend/src/lib/toast-offset.ts+++ b/studio/frontend/src/lib/toast-offset.ts@@ -79,11 +79,17 @@ type InsetStyle = Pick<const insetScopes = new Set<HTMLElement>();const insetValues = new Map<string, string>();+const insetListeners = new Set<() => void>();++function notifyInsetChange(): void {+ for (const listener of insetListeners) listener();+}function removeCornerInset(name: string): string {const previous = insetValues.get(name) ?? "";insetValues.delete(name);for (const scope of insetScopes) scope.style.removeProperty(name);+ if (previous) notifyInsetChange();return previous;}@@ -92,8 +98,18 @@ function setCornerInset(name: string, value: string | null): void {removeCornerInset(name);return;}+ const changed = insetValues.get(name) !== value;insetValues.set(name, value);for (const scope of insetScopes) scope.style.setProperty(name, value);+ if (changed) notifyInsetChange();+}++/** Fires after a corner inset changes: rail cards move with it without resizing, so no ResizeObserver sees it. */+export function subscribeCornerInsets(listener: () => void): () => void {+ insetListeners.add(listener);+ return () => {+ insetListeners.delete(listener);+ };}export const cornerInsets: { style: InsetStyle } = {diff --git a/studio/frontend/tests/dense-quant-schemes-identity.test.ts b/studio/frontend/tests/dense-quant-schemes-identity.test.tsindex 753403ab975..a46f7f22709 100644--- a/studio/frontend/tests/dense-quant-schemes-identity.test.ts+++ b/studio/frontend/tests/dense-quant-schemes-identity.test.ts@@ -126,3 +126,19 @@ test("the first snapshot to arrive is published as-is", () => {assert.equal(held.denseQuantSchemes, warm.denseQuantSchemes);assert.deepEqual(held.denseQuantSchemes, ["fp8"]);});++test("free RAM drifting under 0.25 GiB keeps the published snapshot, so pages do not re-render", () => {+ const current = snapshot(normalizeDenseQuantSchemes(["fp8"]), 31.2);+ const drift = snapshot(normalizeDenseQuantSchemes(["fp8"]), 31.05);+ assert.equal(hooks.nextGpuInfo(current, drift), current);++ const moved = snapshot(normalizeDenseQuantSchemes(["fp8"]), 30.9);+ const published = hooks.nextGpuInfo(current, moved);+ assert.equal(published.systemRamAvailableGb, 30.9, "a real move is published");+ assert.equal(published.denseQuantSchemes, current.denseQuantSchemes);++ const otherChange = { ...drift, name: "NVIDIA RTX 6000" };+ assert.equal(hooks.nextGpuInfo(current, otherChange).name, "NVIDIA RTX 6000");+ const knownFlip = { ...drift, systemRamAvailableKnown: false };+ assert.equal(hooks.nextGpuInfo(current, knownFlip).systemRamAvailableKnown, false);+});diff --git a/studio/frontend/tests/export-backend-status-identity.test.ts b/studio/frontend/tests/export-backend-status-identity.test.tsnew file mode 100644index 00000000000..c6dc7756f7c--- /dev/null+++ b/studio/frontend/tests/export-backend-status-identity.test.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++register("./helpers/export-store-resolver.mjs", import.meta.url);++const { useExportRuntimeStore } = await import(+ "../src/features/export/stores/export-runtime-store.ts"+);++type Status = Parameters<+ ReturnType<typeof useExportRuntimeStore.getState>["applyBackendStatus"]+>[0];++const idle = { is_export_active: false } as Status;++test("an unchanged idle status poll does not notify store listeners", () => {+ useExportRuntimeStore.getState().reset();+ useExportRuntimeStore.getState().applyBackendStatus(idle);+ const hydrated = useExportRuntimeStore.getState();+ assert.equal(hydrated.hasHydrated, true);++ let notified = 0;+ const unsubscribe = useExportRuntimeStore.subscribe(() => {+ notified += 1;+ });+ try {+ useExportRuntimeStore.getState().applyBackendStatus(idle);+ useExportRuntimeStore.getState().applyBackendStatus({ ...idle });+ assert.equal(notified, 0);+ assert.equal(useExportRuntimeStore.getState(), hydrated);++ useExportRuntimeStore+ .getState()+ .applyBackendStatus({ is_export_active: true } as Status);+ assert.equal(notified, 1, "a real change still publishes");+ assert.equal(useExportRuntimeStore.getState().backendActive, true);+ } finally {+ unsubscribe();+ useExportRuntimeStore.getState().reset();+ }+});diff --git a/studio/frontend/tests/export-status-poll-stall-guard.test.ts b/studio/frontend/tests/export-status-poll-stall-guard.test.tsindex f50ab4e195f..9b22370b95c 100644--- a/studio/frontend/tests/export-status-poll-stall-guard.test.ts+++ b/studio/frontend/tests/export-status-poll-stall-guard.test.ts@@ -11,25 +11,26 @@ type ExportLifecycle = {};const STATUS_POLL_INTERVAL_MS = 5_000;+const IDLE_STATUS_POLL_INTERVAL_MS = 30_000;-test("status polling does not stack while the previous request is stalled", async (t) => {- t.mock.timers.enable({ apis: ["setInterval"] });-- let cleanup: (() => void) | undefined;- let finishStatusRequest: (() => void) | undefined;- let statusRequests = 0;- const stalledStatusRequest = new Promise<void>((resolve) => {- finishStatusRequest = resolve;- });- const state = {- isExporting: false,- lastSeq: 0,- applyBackendStatus: () => {},- setConnected: () => {},- appendLogs: () => {},- appendLog: () => {},+/** A document stub whose `hidden` the test flips; dispatch() fires visibilitychange. */+function stubDocument() {+ const target = new EventTarget();+ const doc = {+ hidden: false,+ addEventListener: target.addEventListener.bind(target),+ removeEventListener: target.removeEventListener.bind(target),+ dispatch: () => target.dispatchEvent(new Event("visibilitychange")),};+ (globalThis as { document?: unknown }).document = doc;+ return doc;+}+function loadLifecycle(+ state: Record<string, unknown>,+ getExportStatus: () => Promise<unknown>,+): ExportLifecycle & { cleanup: () => void } {+ let cleanup: (() => void) | undefined;const lifecycle = loadWithStubs<ExportLifecycle>(new URL("../src/features/export/hooks/use-export-runtime-lifecycle.ts",@@ -44,11 +45,7 @@ test("status polling does not stack while the previous request is stalled", asyn"@/features/auth": { hasAuthToken: () => true },"../api/export-api": {fetchExportLogs: async () => ({ entries: [] }),- getExportStatus: async () => {- statusRequests += 1;- await stalledStatusRequest;- return {};- },+ getExportStatus,streamExportLogs: async () => {},},"../stores/export-runtime-store": {@@ -59,12 +56,40 @@ test("status polling does not stack while the previous request is stalled", asyn},},);+ return { ...lifecycle, cleanup: () => cleanup?.() };+}++const settle = () => new Promise<void>((resolve) => setImmediate(resolve));++test("status polling does not stack while the previous request is stalled", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "setInterval"] });+ const doc = stubDocument();+ let finishStatusRequest: (() => void) | undefined;+ let statusRequests = 0;+ const stalledStatusRequest = new Promise<void>((resolve) => {+ finishStatusRequest = resolve;+ });+ const state = {+ isExporting: false,+ backendActive: true,+ lastSeq: 0,+ applyBackendStatus: () => {},+ setConnected: () => {},+ appendLogs: () => {},+ appendLog: () => {},+ };+ const lifecycle = loadLifecycle(state, async () => {+ statusRequests += 1;+ await stalledStatusRequest;+ return {};+ });try {lifecycle.useExportRuntimeLifecycle();assert.equal(statusRequests, 1, "mount must start one status request");t.mock.timers.tick(STATUS_POLL_INTERVAL_MS * 3);+ doc.dispatch();assert.equal(statusRequests,1,@@ -72,7 +97,7 @@ test("status polling does not stack while the previous request is stalled", asyn);finishStatusRequest?.();- await new Promise<void>((resolve) => setImmediate(resolve));+ await settle();t.mock.timers.tick(STATUS_POLL_INTERVAL_MS);assert.equal(statusRequests,@@ -80,7 +105,51 @@ test("status polling does not stack while the previous request is stalled", asyn"polling must resume after the request settles",);} finally {- cleanup?.();+ lifecycle.cleanup();finishStatusRequest?.();}});++test("an idle app polls export status slowly and not at all while hidden", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout", "setInterval"] });+ const doc = stubDocument();+ let statusRequests = 0;+ const state = {+ isExporting: false,+ backendActive: false,+ lastSeq: 0,+ applyBackendStatus: () => {},+ setConnected: () => {},+ appendLogs: () => {},+ appendLog: () => {},+ };+ const lifecycle = loadLifecycle(state, async () => {+ statusRequests += 1;+ return {};+ });++ try {+ lifecycle.useExportRuntimeLifecycle();+ await settle();+ assert.equal(statusRequests, 1);++ t.mock.timers.tick(STATUS_POLL_INTERVAL_MS);+ await settle();+ assert.equal(statusRequests, 1, "idle must not poll at the active cadence");+ t.mock.timers.tick(IDLE_STATUS_POLL_INTERVAL_MS - STATUS_POLL_INTERVAL_MS);+ await settle();+ assert.equal(statusRequests, 2);++ doc.hidden = true;+ t.mock.timers.tick(IDLE_STATUS_POLL_INTERVAL_MS * 3);+ await settle();+ assert.equal(statusRequests, 2, "a hidden idle tab skips its polls");++ doc.hidden = false;+ doc.dispatch();+ await settle();+ assert.equal(statusRequests, 3, "returning to the tab polls at once");+ } finally {+ lifecycle.cleanup();+ }+});diff --git a/studio/frontend/tests/floating-monitor-polish.test.ts b/studio/frontend/tests/floating-monitor-polish.test.tsnew file mode 100644index 00000000000..795f8f368f5--- /dev/null+++ b/studio/frontend/tests/floating-monitor-polish.test.ts@@ -0,0 +1,84 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++import assert from "node:assert/strict";+import test from "node:test";++import {+ liftAboveObstacle,+ nudgeDelta,+ snapsToAnchor,+} from "../src/hooks/floating-panel-position.ts";+import {+ STALE_AFTER_FAILED_POLLS,+ isReadingStale,+ nextFailedPolls,+} from "../src/hooks/system-discovery.ts";++test("one failed poll is a blip, two in a row make the reading stale", () => {+ let failed = 0;+ failed = nextFailedPolls(failed, false);+ assert.equal(isReadingStale("ready", failed, true), false);+ failed = nextFailedPolls(failed, false);+ assert.equal(failed, STALE_AFTER_FAILED_POLLS);+ assert.equal(isReadingStale("ready", failed, true), true);+ failed = nextFailedPolls(failed, true);+ assert.equal(isReadingStale("ready", failed, true), false);+});++test("only a polled, real reading can go stale", () => {+ assert.equal(+ isReadingStale("ready", 5, false),+ false,+ "nothing would clear it",+ );+ assert.equal(isReadingStale("pending", 5, true), false);+ assert.equal(isReadingStale("unavailable", 5, true), false);+});++const PANEL = { left: 1168, top: 684, width: 256, height: 200 };+const CARD = { left: 1156, top: 764, right: 1424, bottom: 884 };++test("at the default corner the monitor rests just above the card", () => {+ assert.equal(liftAboveObstacle(PANEL, CARD, 8), 764 - 8 - 200);+});++test("a card the composer lifted still has the monitor resting above it, not below over the composer", () => {+ const lifted = { left: 1156, top: 460, right: 1424, bottom: 549 };+ assert.equal(liftAboveObstacle(PANEL, lifted, 8), 460 - 8 - 200);+});++test("no card, or a card elsewhere, leaves the corner alone", () => {+ assert.equal(liftAboveObstacle(PANEL, null, 8), null);+ const dragged = { left: 40, top: 40, right: 308, bottom: 160 };+ assert.equal(liftAboveObstacle(PANEL, dragged, 8), null);+ const leftOfPanel = { left: 800, top: 764, right: 1100, bottom: 884 };+ assert.equal(liftAboveObstacle(PANEL, leftOfPanel, 8), null);+});++test("a drop near the resting or far corner snaps back to the anchor", () => {+ const rest = { left: 1152, top: 540 };+ const max = { left: 1152, top: 668 };+ assert.equal(snapsToAnchor({ left: 1140, top: 530 }, rest, max), true);+ assert.equal(snapsToAnchor({ left: 1150, top: 660 }, rest, max), true);+ assert.equal(snapsToAnchor({ left: 1100, top: 540 }, rest, max), false);+ assert.equal(snapsToAnchor({ left: 200, top: 200 }, rest, max), false);+});++test("arrow keys nudge by 8 px, 32 with Shift, and nothing else moves it", () => {+ assert.deepEqual(nudgeDelta("ArrowLeft", false), { dx: -8, dy: 0 });+ assert.deepEqual(nudgeDelta("ArrowDown", true), { dx: 0, dy: 32 });+ assert.equal(nudgeDelta("Enter", false), null);+ assert.equal(nudgeDelta("Escape", false), null);+});++test("a nudge makes only the moved axis absolute, so the other stays anchored", async () => {+ const { readFileSync } = await import("node:fs");+ const layout = readFileSync(+ new URL("../src/hooks/use-floating-panel-layout.ts", import.meta.url),+ "utf8",+ );+ assert.match(layout, /left: delta\.dx !== 0 \? left : previous\.left/);+ assert.match(layout, /top: delta\.dy !== 0 \? top : previous\.top/);+});diff --git a/studio/frontend/tests/floating-panel-position.test.ts b/studio/frontend/tests/floating-panel-position.test.tsindex 50002c1f632..38132d2cf9a 100644--- a/studio/frontend/tests/floating-panel-position.test.ts+++ b/studio/frontend/tests/floating-panel-position.test.ts@@ -89,7 +89,7 @@ test("a corrupt stored spot falls back to the default placement", () => {test("both monitors persist under their own key and a reset clears them", () => {assert.match(readSrc("components/floating-monitor.tsx"),- /FLOATING_PANEL_POSITION_KEYS\.liveMonitor,\s*\);/,+ /FLOATING_PANEL_POSITION_KEYS\.liveMonitor,\s*cornerCard,\s*\);/,);assert.match(readSrc("features/api-monitor/api-monitor-overlay.tsx"),@@ -101,10 +101,12 @@ test("both monitors persist under their own key and a reset clears them", () =>);});-test("layout skips a 0x0 frame and only a drag writes the stored spot", () => {+test("layout skips a 0x0 frame and only a drag or a nudge writes the stored spot", () => {const hook = readSrc("hooks/use-floating-panel-layout.ts");assert.match(hook, /if \(isDegenerateBox\(constraintsBox\)\) \{\s*return;/);- assert.equal(hook.split("storePanelIntent(").length - 1, 1);+ assert.equal(hook.split("storePanelIntent(").length - 1, 2);+ const nudge = hook.slice(hook.indexOf("function nudge("));+ assert.match(nudge, /storePanelIntent\(storageKey, intentRef\.current\)/);const finish = hook.slice(hook.indexOf("function finishDrag"));assert.match(finish, /storePanelIntent\(storageKey, intentRef\.current\)/);const card = readSrc("features/loaded-models/use-drag-position.ts");diff --git a/studio/frontend/tests/gpu-memory-display.test.ts b/studio/frontend/tests/gpu-memory-display.test.tsindex 0e960b60885..9c61b9c49af 100644--- a/studio/frontend/tests/gpu-memory-display.test.ts+++ b/studio/frontend/tests/gpu-memory-display.test.ts@@ -104,3 +104,47 @@ test("other backends retain their shared-pool usage reporting", () => {}assert.deepEqual(gpuMemoryDisplay(undefined).usageDevices, []);});++test("Apple unified memory reports headroom without moving its usage bar", () => {+ // M3 Max live reading: 64 GiB pool, 7.03 GiB GPU-allocated, min(free RAM, Metal working set) free.+ const mlx: GpuDevice = {+ index_kind: "relative",+ shared_memory: true,+ shared_memory_host_backed_gb: 64,+ memory_total_gb: 64,+ vram_used_gb: 7.03,+ vram_free_gb: 21.93,+ };+ const display = gpuMemoryDisplay(gpu([mlx]));+ assert.equal(display.unifiedAvailableGb, 21.93);+ assert.equal(display.sharedDevices.length, 0);+ assert.equal(resolveGpuVramUsedGb(display.usageGpu), 7.03);+ assert.deepEqual(gpuMemoryTotalsGb(display.usageDevices), {+ dedicated: 0,+ shared: 64,+ total: 64,+ });+ const noFree = { ...mlx, vram_free_gb: undefined };+ assert.equal(gpuMemoryDisplay(gpu([noFree])).unifiedAvailableGb, null);+});++test("unified headroom leaves Vulkan iGPUs, ROCm APUs and carve-outs alone", () => {+ assert.equal(gpuMemoryDisplay(gpu([integrated])).unifiedAvailableGb, null);+ const linuxApu: GpuDevice = {+ index_kind: "physical",+ unified_memory: true,+ memory_total_gb: 96,+ vram_used_gb: 4,+ vram_free_gb: 92,+ };+ assert.equal(gpuMemoryDisplay(gpu([linuxApu])).unifiedAvailableGb, null);+ const carveOut: GpuDevice = {+ index_kind: "physical",+ shared_memory: true,+ shared_memory_host_backed_gb: 12,+ memory_total_gb: 16,+ vram_used_gb: 1,+ vram_free_gb: 15,+ };+ assert.equal(gpuMemoryDisplay(gpu([carveOut])).unifiedAvailableGb, null);+});diff --git a/studio/frontend/tests/helpers/loaded-models-eject-resolver.mjs b/studio/frontend/tests/helpers/loaded-models-eject-resolver.mjsindex d339487b1ce..15b72fbcfb5 100644--- a/studio/frontend/tests/helpers/loaded-models-eject-resolver.mjs+++ b/studio/frontend/tests/helpers/loaded-models-eject-resolver.mjs@@ -2,7 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0// bundler-resolver's two rules, plus the barrels loaded-models-api.ts reaches that pull in-// TSX: chat, images and video go to loaded-models-eject-stub.ts, auth to its store stub.+// TSX: chat, images, video and the embedder go to loaded-models-eject-stub.ts, auth to its store stub.import { resolve as resolveBundler } from "../bundler-resolver.mjs";const EJECT_STUB = new URL("./loaded-models-eject-stub.ts", import.meta.url)@@ -11,6 +11,8 @@ const STUBS = new Map([["@/features/chat", EJECT_STUB],["@/features/images/api", EJECT_STUB],["@/features/video/api", EJECT_STUB],+ ["@/features/settings/api/embedding-model", EJECT_STUB],+ ["@/features/settings/stores/embedding-model-store", EJECT_STUB],["@/features/auth", new URL("./store-stubs/auth.ts", import.meta.url).href],]);diff --git a/studio/frontend/tests/helpers/loaded-models-eject-stub.ts b/studio/frontend/tests/helpers/loaded-models-eject-stub.tsindex f79707fbb36..1397a1fea17 100644--- a/studio/frontend/tests/helpers/loaded-models-eject-stub.ts+++ b/studio/frontend/tests/helpers/loaded-models-eject-stub.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Stubs the chat, images and video barrels; /unload 409s like the backend while a chat+// Stubs the chat, images and video barrels and the embedder; /unload 409s like the backend while a chat// is generating unless forced.type UnloadPayload = { model_path: string; force_cancel_active?: boolean };@@ -9,6 +9,8 @@ type UnloadPayload = { model_path: string; force_cancel_active?: boolean };export const state = {active: null as string | null,loaded: [] as string[],+ servingCheckpoints: [] as string[],+ embeddingLoaded: false,generating: false,confirmAnswer: { proceed: true, forceCancelActive: false },confirmCalls: [] as { action: string; effect: string; model?: string }[],@@ -19,10 +21,14 @@ export const state = {export function resetStub({active = null as string | null,loaded = [] as string[],+ servingCheckpoints = [] as string[],+ embeddingLoaded = false,generating = false,} = {}): void {state.active = active;state.loaded = [...loaded];+ state.servingCheckpoints = [...servingCheckpoints];+ state.embeddingLoaded = embeddingLoaded;state.generating = generating;state.confirmAnswer = { proceed: true, forceCancelActive: false };state.confirmCalls = [];@@ -31,7 +37,11 @@ export function resetStub({}export async function getInferenceStatus() {- return { active_model: state.active, loaded: [...state.loaded] };+ return {+ active_model: state.active,+ loaded: [...state.loaded],+ serving_checkpoints: [...state.servingCheckpoints],+ };}export function resolveInferenceCheckpointId(status: {@@ -53,6 +63,9 @@ export async function unloadModel(payload: UnloadPayload): Promise<void> {}state.generating = false;state.loaded = state.loaded.filter((name) => name !== payload.model_path);+ state.servingCheckpoints = state.servingCheckpoints.filter(+ (checkpoint) => checkpoint !== payload.model_path,+ );if (state.active === payload.model_path) state.active = null;}@@ -89,3 +102,15 @@ export async function getVideoStatus() {export async function unloadVideoModel() {return { loaded: false };}++export async function unloadEmbeddingModel() {+ state.embeddingLoaded = false;+ return { backendLoaded: false };+}+export const useEmbeddingModelStore = {+ getState: () => ({+ applyResidency: async (request: () => Promise<unknown>) => {+ await request();+ },+ }),+};diff --git a/studio/frontend/tests/loaded-models-dismiss.test.ts b/studio/frontend/tests/loaded-models-dismiss.test.tsindex 9e02d771f7f..99fe48176af 100644--- a/studio/frontend/tests/loaded-models-dismiss.test.ts+++ b/studio/frontend/tests/loaded-models-dismiss.test.ts@@ -104,7 +104,10 @@ test("the dismissal key is cleared by Reset all local preferences", () => {});test("the card carries a close button, and a load brings it back", () => {- assert.match(LOADED_MODELS_INDICATOR, /aria-label="Close loaded models"/);+ assert.match(+ LOADED_MODELS_INDICATOR,+ /aria-label=\{t\("floatingPanels\.loadedModels\.closeLabel"\)\}/,+ );assert.match(LOADED_MODELS_INDICATOR,/onClick=\{\(\) => setLoadedModelsDismissed\(true\)\}/,@@ -134,7 +137,7 @@ test("a row ejects with the eject glyph, the header closes with an X", () => {assert.match(row, /icon=\{RemoveCircleIcon\}/);assert.doesNotMatch(row, /icon=\{Cancel01Icon\}/);const header = LOADED_MODELS_INDICATOR.slice(- LOADED_MODELS_INDICATOR.indexOf('aria-label="Close loaded models"'),+ LOADED_MODELS_INDICATOR.indexOf("floatingPanels.loadedModels.closeLabel"),);assert.match(header, /icon=\{Cancel01Icon\}/);});@@ -163,3 +166,17 @@ test("recording follows the route and auth gate, but not the dismissal", () => {// Dismissal stays out, or a closed card could never reopen.assert.doesNotMatch(call, /dismissed/);});++test("switching the setting on clears an earlier dismissal", () => {+ reset();+ setLoadedModelsDismissed(true);+ setShowLoadedModels(true);+ assert.equal(getLoadedModelsDismissed(), false);+ setLoadedModelsDismissed(true);+ setShowLoadedModels(false);+ assert.equal(+ getLoadedModelsDismissed(),+ true,+ "switching off leaves it alone",+ );+});diff --git a/studio/frontend/tests/loaded-models-drag-restore.test.ts b/studio/frontend/tests/loaded-models-drag-restore.test.tsindex a7d593c7fa9..77e22a28eb6 100644--- a/studio/frontend/tests/loaded-models-drag-restore.test.ts+++ b/studio/frontend/tests/loaded-models-drag-restore.test.ts@@ -150,15 +150,15 @@ test("every drag handle goes through startDrag, which resets the sentinel", () =test("only the pill consumes the sentinel, since only it has a click", () => {const pill = INDICATOR.slice(- INDICATOR.indexOf("Show details, or drag to move"),- INDICATOR.indexOf("Show details, or drag to move") + 400,+ INDICATOR.indexOf("floatingPanels.loadedModels.pillLabel"),+ INDICATOR.indexOf("floatingPanels.loadedModels.pillLabel") + 600,);assert.match(pill, /onPointerDown=\{startDrag\}/);assert.match(pill, /if \(!justDragged\(\)\) setCollapsed\(false\)/);});-// Only a landed drag persists; reclamps are display-time and must not overwrite the save.-test("only a drag persists a position, never a reclamp", () => {+// Only a landed drag or a keyboard nudge persists; reclamps are display-time and must not overwrite the save.+test("only a drag or a nudge persists a position, never a reclamp", () => {const settleAt = USE_DRAG_POSITION.indexOf("const settle = useCallback(");const settle = USE_DRAG_POSITION.slice(settleAt,@@ -168,7 +168,9 @@ test("only a drag persists a position, never a reclamp", () => {assert.doesNotMatch(USE_DRAG_POSITION, /useEffect\(\(\) => \{\s*if \(pressing\) return;\s*store\(/);assert.equal(USE_DRAG_POSITION.split("store(storageKey").length - 1,- 1,- "one write, in settle",+ 2,+ "one write in settle, one in nudge",);+ const nudge = USE_DRAG_POSITION.slice(USE_DRAG_POSITION.indexOf("const nudge = useCallback("));+ assert.match(nudge, /store\(storageKey, next\)/);});diff --git a/studio/frontend/tests/loaded-models-eject-serving.test.ts b/studio/frontend/tests/loaded-models-eject-serving.test.tsnew file mode 100644index 00000000000..19066e2d28f--- /dev/null+++ b/studio/frontend/tests/loaded-models-eject-serving.test.ts@@ -0,0 +1,109 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++register("./helpers/loaded-models-eject-resolver.mjs", import.meta.url);++const stub = await import("./helpers/loaded-models-eject-stub.ts");+const auth = await import("./helpers/store-stubs/auth.ts");+const { ejectLoadedModel } = await import(+ "../src/features/loaded-models/loaded-models-api.ts"+);++const ACTIVE = "unsloth/Qwen3-4B-GGUF";+const KEPT = "/models/kept-b.gguf";++function servingRow() {+ return {+ id: `chat:${KEPT}`,+ kind: "text" as const,+ source: "chat" as const,+ name: "kept-b",+ detail: "Also serving",+ servingCheckpoint: KEPT,+ };+}++test("a kept model unloads by its checkpoint and leaves the active one", async () => {+ stub.resetStub({+ active: ACTIVE,+ loaded: [ACTIVE, "kept-b"],+ servingCheckpoints: [ACTIVE, KEPT],+ });+ assert.deepEqual(await ejectLoadedModel(servingRow()), { status: "ejected" });+ assert.deepEqual(+ stub.state.unloads.map((u) => u.model_path),+ [KEPT],+ );+ assert.equal(stub.state.active, ACTIVE);+ // The running-chat check and the unload must address the same slot.+ assert.deepEqual(+ stub.state.confirmCalls.map((c) => c.model),+ [KEPT],+ );+});++test("a kept model already gone unloads nothing", async () => {+ stub.resetStub({+ active: ACTIVE,+ loaded: [ACTIVE],+ servingCheckpoints: [ACTIVE],+ });+ assert.deepEqual(await ejectLoadedModel(servingRow()), {+ status: "alreadyFree",+ });+ assert.deepEqual(stub.state.unloads, []);+});++function embeddingRow() {+ return {+ id: "embedding:rag",+ kind: "embedding" as const,+ source: "embedding" as const,+ name: "org/E",+ detail: "Documents",+ };+}++function answerEmbeddingStatus() {+ auth.setAuthFetchHandler((url) => {+ assert.equal(url, "/api/settings/embedding-model");+ return Response.json({+ embedding_model: "org/E",+ loaded: stub.state.embeddingLoaded,+ backend_loaded: stub.state.embeddingLoaded,+ });+ });+}++test("the embedder ejects through its own unload and is confirmed gone", async (t) => {+ t.after(() => auth.setAuthFetchHandler(null));+ stub.resetStub({ embeddingLoaded: true });+ answerEmbeddingStatus();+ assert.deepEqual(await ejectLoadedModel(embeddingRow()), {+ status: "ejected",+ });+ assert.equal(stub.state.embeddingLoaded, false);+});++test("an embedder already released is reported as free", async (t) => {+ t.after(() => auth.setAuthFetchHandler(null));+ stub.resetStub({ embeddingLoaded: false });+ answerEmbeddingStatus();+ assert.deepEqual(await ejectLoadedModel(embeddingRow()), {+ status: "alreadyFree",+ });+});++test("an embedder swapped in since the poll is reported, not unloaded", async (t) => {+ t.after(() => auth.setAuthFetchHandler(null));+ stub.resetStub({ embeddingLoaded: true });+ answerEmbeddingStatus();+ const outcome = await ejectLoadedModel({ ...embeddingRow(), name: "org/Old" });+ assert.deepEqual(outcome, { status: "replaced", resident: "org/E" });+ assert.equal(stub.state.embeddingLoaded, true);+});diff --git a/studio/frontend/tests/loaded-models-floating-polish.test.ts b/studio/frontend/tests/loaded-models-floating-polish.test.tsnew file mode 100644index 00000000000..22eae079ec1--- /dev/null+++ b/studio/frontend/tests/loaded-models-floating-polish.test.ts@@ -0,0 +1,202 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++import assert from "node:assert/strict";+import test from "node:test";++import {+ type LoadedModelEntry,+ describeDiffusionStatus,+ describeEmbeddingStatus,+ describeInferenceStatus,+ describeVideoStatus,+ formatResidentMib,+ heldByAnotherAccount,+ loadedModelLabel,+ loadedModelTarget,+ loadedModelsCardState,+ sameLoadedModels,+} from "../src/features/loaded-models/loaded-models-sources.ts";+import { sentinelAfterSettle } from "../src/features/loaded-models/use-drag-position.ts";++type Inference = Parameters<typeof describeInferenceStatus>[0];++function inference(overrides: Record<string, unknown>): Inference {+ return {+ active_model: null,+ is_vision: false,+ loading: [],+ loaded: [],+ ...overrides,+ } as Inference;+}++const SNAPSHOT =+ "/home/u/.cache/huggingface/hub/models--org--Flux/snapshots/0a1b2c3d4e5f";++test("an image row shows the Hub id but ejects by the snapshot it loaded", () => {+ const [row] = describeDiffusionStatus({+ loaded: true,+ repo_id: SNAPSHOT,+ display_repo_id: "org/Flux",+ } as never);+ assert.equal(row.name, SNAPSHOT);+ assert.equal(loadedModelLabel(row), "org/Flux");+});++test("a video row does the same, and falls back to the repo id without one", () => {+ const [labelled] = describeVideoStatus({+ loaded: true,+ repo_id: SNAPSHOT,+ display_repo_id: "org/Wan",+ } as never);+ assert.equal(loadedModelLabel(labelled), "org/Wan");+ const [plain] = describeVideoStatus({+ loaded: true,+ repo_id: "org/Wan",+ } as never);+ assert.equal(plain.label, undefined);+ assert.equal(loadedModelLabel(plain), "org/Wan");+});++test("models kept alongside the active one are serving, not idle", () => {+ const rows = describeInferenceStatus(+ inference({+ active_model: "org/A-GGUF",+ model_identifier: "org/A-GGUF",+ is_gguf: true,+ loaded: ["org/A-GGUF", "kept-b", "org/Cached"],+ serving: ["org/A-GGUF", "kept-b"],+ serving_checkpoints: ["org/A-GGUF", "/models/kept-b.gguf"],+ }),+ );+ assert.deepEqual(+ rows.map((row) => [row.id, Boolean(row.inactive), row.servingCheckpoint]),+ [+ ["chat:org/A-GGUF", false, undefined],+ ["chat:/models/kept-b.gguf", false, "/models/kept-b.gguf"],+ ["chat:org/Cached", true, undefined],+ ],+ );+ assert.equal(rows[1].name, "kept-b");+});++test("two kept models sharing a label stay two rows", () => {+ const rows = describeInferenceStatus(+ inference({+ active_model: "org/A",+ loaded: ["org/A", "model"],+ serving: ["org/A", "model", "model"],+ serving_checkpoints: ["org/A", "/x/model.gguf", "/y/model.gguf"],+ }),+ );+ assert.equal(rows.filter((row) => row.servingCheckpoint).length, 2);+});++test("an older backend without serving keeps the cached rows as before", () => {+ const rows = describeInferenceStatus(+ inference({ active_model: "org/A", loaded: ["org/A", "org/B"] }),+ );+ assert.equal(rows[1].inactive, true);+});++test("resident sizes ride along and format in binary GiB", () => {+ const [chat] = describeInferenceStatus(+ inference({ active_model: "org/A", resident_mib: 5325 }),+ );+ assert.equal(chat.residentMib, 5325);+ assert.equal(formatResidentMib(5325), "5.2 GiB");+ assert.equal(formatResidentMib(20 * 1024), "20 GiB");+ for (const unknown of [null, undefined, 0, -1, Number.NaN]) {+ assert.equal(formatResidentMib(unknown), null);+ }+ const [image] = describeDiffusionStatus({+ loaded: true,+ repo_id: "org/Flux",+ resident_mib: null,+ } as never);+ assert.equal(image.residentMib, undefined);+});++test("the embedder is listed only while one is resident", () => {+ assert.deepEqual(describeEmbeddingStatus(null), []);+ assert.deepEqual(+ describeEmbeddingStatus({+ embedding_model: "org/E",+ loaded: false,+ backend_loaded: false,+ }),+ [],+ );+ const [row] = describeEmbeddingStatus({+ embedding_model: "org/E",+ loaded: true,+ backend_loaded: true,+ });+ assert.equal(row.name, "org/E");+ assert.equal(row.source, "embedding");+ assert.deepEqual(loadedModelTarget(row.source), {+ open: "settings",+ tab: "data",+ label: "Data settings",+ });+ const [stale] = describeEmbeddingStatus({+ embedding_model: "org/New",+ loaded: false,+ backend_loaded: true,+ });+ assert.equal(stale.name, "Embedding model");+});++test("another account's resident shows only when nothing of this account's is loaded", () => {+ assert.equal(heldByAnotherAccount([{ yours: false }, null, {}]), true);+ assert.equal(heldByAnotherAccount([{ yours: true }, null, {}]), false);+ assert.equal(loadedModelsCardState(0, true, false), "otherAccount");+ assert.equal(loadedModelsCardState(2, true, false), "rows");+ assert.equal(loadedModelsCardState(0, false, true), "empty");+ assert.equal(loadedModelsCardState(0, false, false), null);+});++test("a poll that changed nothing is the same rows", () => {+ const row: LoadedModelEntry = {+ id: "chat:a",+ kind: "text",+ source: "chat",+ name: "a",+ detail: "GGUF",+ residentMib: 100,+ };+ assert.equal(sameLoadedModels([row], [{ ...row }]), true);+ assert.equal(sameLoadedModels([row], [{ ...row, residentMib: 200 }]), false);+ assert.equal(sameLoadedModels([row], [{ ...row, detail: "MLX" }]), false);+ assert.equal(sameLoadedModels([row], []), false);+ assert.equal(+ sameLoadedModels(+ [{ ...row, workflows: ["speak"] }],+ [{ ...row, workflows: ["music"] }],+ ),+ false,+ );+});++test("a drag from a handle no click follows clears the sentinel", () => {+ assert.equal(sentinelAfterSettle(true, true), true);+ assert.equal(sentinelAfterSettle(true, false), false);+ assert.equal(sentinelAfterSettle(false, true), false);+});++test("a kept model sharing the active model's label still gets its own row", () => {+ const rows = describeInferenceStatus({+ active_model: "model",+ model_identifier: "/x/model.gguf",+ is_gguf: true,+ loaded: ["model"],+ serving: ["model", "model"],+ serving_checkpoints: ["/x/model.gguf", "/y/model.gguf"],+ } as never);+ assert.deepEqual(+ rows.filter((r) => r.servingCheckpoint).map((r) => r.servingCheckpoint),+ ["/y/model.gguf"],+ );+});diff --git a/studio/frontend/tests/loaded-models-pending-reset.test.ts b/studio/frontend/tests/loaded-models-pending-reset.test.tsindex 2e55bc94647..9349f8d5c0d 100644--- a/studio/frontend/tests/loaded-models-pending-reset.test.ts+++ b/studio/frontend/tests/loaded-models-pending-reset.test.ts@@ -160,7 +160,7 @@ test("recording is gated on the preference, not on whether the card shows", () =// Reachability carries the auth gate; dismissal must not stop recording.assert.match(INDICATOR,- /useLoadedModels\(\s*enabled,\s*showIndicator && reachable,\s*\)/,+ /useLoadedModels\(\s*enabled,\s*showIndicator && reachable,?\s*\)/,"recording survives a dismissal but not a route with no session",);});diff --git a/studio/frontend/tests/loaded-models-settled-retire.test.ts b/studio/frontend/tests/loaded-models-settled-retire.test.tsindex bfcfa87422d..5d4ae965ccd 100644--- a/studio/frontend/tests/loaded-models-settled-retire.test.ts+++ b/studio/frontend/tests/loaded-models-settled-retire.test.ts@@ -15,7 +15,7 @@ test("the read reports which sources it could not see", () => {assert.match(API, /export type LoadedModelsRead = \{/);assert.match(API, /unreadable: LoadedModelSource\[\];/);assert.match(API, /unreadable\.push\(source\);/);- assert.match(API, /return \{ entries, unreadable \};/);+ assert.match(API, /return \{ entries, unreadable, heldByOther \};/);});test("an unreadable source keeps its settled row", () => {@@ -29,7 +29,10 @@ test("an unreadable source keeps its settled row", () => {});test("a read that failed outright is evidence about nothing", () => {- assert.match(HOOK, /const ALL_SOURCES: LoadedModelSource\[\] = \["chat", "image", "video", "stt"\]/);+ assert.match(+ HOOK,+ /const ALL_SOURCES: LoadedModelSource\[\] = \[\s*"chat",\s*"image",\s*"video",\s*"stt",\s*"embedding",\s*\]/,+ );const refresh = HOOK.slice(HOOK.indexOf("void readLoadedModels(polledRef.current)"),HOOK.indexOf("}, [track, retireSettled]);"),diff --git a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts b/studio/frontend/tests/on-device-dot-and-header-alignment.test.tsindex b328436919d..819f66bb5ba 100644--- a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts+++ b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts@@ -400,12 +400,16 @@ test("each fit verdict is an info mark that explains itself", () => {),);assert.ok(PICKERS.includes("aria-label={verdict.label}"));- assert.ok(PICKERS.includes("`Needs ~${vramEst}GB memory (GPU: ${gpuGb}GB)`"));assert.ok(- !PICKERS.includes("GB VRAM (GPU:"),+ PICKERS.includes(+ "`Needs ~${formatGiB(vramEst)} memory (GPU: ${formatGiB(gpuGb)})`",+ ),+ );+ assert.ok(+ !PICKERS.includes("VRAM (GPU:"),"no VRAM wording on an overage",);- assert.ok(PICKERS.includes("GB VRAM (tight fit on"));+ assert.ok(PICKERS.includes("} VRAM (tight fit on ${formatGiB(gpuGb)})"));assert.ok(PICKERS.includes('return status === "partial" || status === "ram" || status === "oom" || status === "exceeds";',diff --git a/studio/frontend/tests/resources-shared-memory-display.test.ts b/studio/frontend/tests/resources-shared-memory-display.test.tsindex ca090774952..f71b7284544 100644--- a/studio/frontend/tests/resources-shared-memory-display.test.ts+++ b/studio/frontend/tests/resources-shared-memory-display.test.ts@@ -16,3 +16,38 @@ test("Resources separates dedicated VRAM from shared GPU memory", () => {assert.match(resourcesTab, /shared: formatGiB\(metrics\.vramShared\)/);assert.match(resourcesTab, /\$\{vramCapacityLabel\}/);});++const floatingMonitor = readSrc("components/floating-monitor.tsx");++test("a pool with no dedicated VRAM shows the shared total alone, with its headroom", () => {+ // "7.03 GiB / 0.00 GiB VRAM + 64.0 GiB shared" on an M3 Max read as a broken probe.+ assert.match(+ resourcesTab,+ /metrics\.vramShared > 0 && metrics\.vramDedicated === 0/,+ );+ assert.match(+ resourcesTab,+ /formatGiB\(unifiedPool \? metrics\.vramShared : metrics\.vramTotal\)/,+ );+ assert.match(resourcesTab, /memoryDisplay\.unifiedAvailableGb !== null/);+ assert.match(+ floatingMonitor,+ /hasSharedPool && memoryTotals\.dedicated === 0/,+ );+ assert.match(floatingMonitor, /hasSharedPool && !unifiedPool/);+ assert.match(+ floatingMonitor,+ /formatGiB\(memoryDisplay\.unifiedAvailableGb\)/,+ );+});++test("the Live Monitor shows -- for RAM until the host has been read", () => {+ assert.match(+ floatingMonitor,+ /const ramKnown = systemInfo\.status === "ready"/,+ );+ assert.match(+ floatingMonitor,+ /ramKnown \? `\$\{Math\.round\(ramPercent\)\}%` : "--"/,+ );+});diff --git a/studio/frontend/tests/system-poll-visibility.test.ts b/studio/frontend/tests/system-poll-visibility.test.tsnew file mode 100644index 00000000000..8820cfd09d7--- /dev/null+++ b/studio/frontend/tests/system-poll-visibility.test.ts@@ -0,0 +1,132 @@+// 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 { vulkanRetryDelayMs } from "../src/hooks/system-discovery.ts";+import type * as SystemHooks from "../src/hooks/use-system.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++function stubDocument() {+ const target = new EventTarget();+ const doc = {+ hidden: false,+ addEventListener: target.addEventListener.bind(target),+ removeEventListener: target.removeEventListener.bind(target),+ dispatch: () => target.dispatchEvent(new Event("visibilitychange")),+ };+ const globals = globalThis as { document?: unknown; window?: unknown };+ globals.document = doc;+ globals.window = globalThis;+ return doc;+}++function loadSystem(body: unknown) {+ const requests: { url: string; init?: RequestInit }[] = [];+ let cleanup: (() => void) | undefined;+ const system = loadWithStubs<typeof SystemHooks>(+ new URL("../src/hooks/use-system.ts", import.meta.url),+ {+ react: {+ useState: (initial: unknown) => [initial, () => {}],+ useMemo: (factory: () => unknown) => factory(),+ useEffect: (effect: () => (() => void) | undefined) => {+ cleanup = effect();+ },+ },+ "@/features/auth": {+ authFetch: async (url: string, init?: RequestInit) => {+ requests.push({ url, init });+ return Response.json(body);+ },+ },+ },+ { relativePassthrough: true },+ );+ return { system, requests, cleanup: () => cleanup?.() };+}++const settle = async () => {+ for (let i = 0; i < 4; i++) {+ await new Promise<void>((resolve) => setImmediate(resolve));+ }+};++test("the system poll pauses in a hidden tab and resumes at once on return", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const doc = stubDocument();+ const { system, requests, cleanup } = loadSystem({+ memory: { available_gb: 8 },+ });+ try {+ system.useSystemInfo({ pollMs: 5000 });+ await settle();+ assert.equal(requests.length, 1);+ assert.ok(+ requests[0].init?.signal instanceof AbortSignal,+ "the fetch carries a timeout",+ );++ t.mock.timers.tick(5000);+ await settle();+ assert.equal(requests.length, 2);++ doc.hidden = true;+ t.mock.timers.tick(5000 * 4);+ await settle();+ assert.equal(requests.length, 2, "no polls while hidden");++ doc.hidden = false;+ doc.dispatch();+ await settle();+ assert.equal(requests.length, 3, "one poll on becoming visible");+ t.mock.timers.tick(5000);+ await settle();+ assert.equal(requests.length, 4, "and the loop runs again");+ } finally {+ cleanup();+ }+});++test("an unavailable Vulkan inventory is re-probed with backoff, not every 3 s", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ const doc = stubDocument();+ const { system, requests } = loadSystem({+ memory: { available_gb: 8 },+ inference_gpu: { backend: "vulkan", available: false, devices: [] },+ });+ const unsubscribe = system.subscribeSystemInfo(() => {}, {+ retryUnavailableVulkan: true,+ });+ try {+ await system.fetchSystemInfo();+ await settle();+ assert.equal(requests.length, 1);+ for (const [index, delay] of [3000, 6000, 12000].entries()) {+ t.mock.timers.tick(delay - 1);+ await settle();+ assert.equal(requests.length, index + 1, `not before ${delay} ms`);+ t.mock.timers.tick(1);+ await settle();+ assert.equal(requests.length, index + 2);+ }++ doc.hidden = true;+ t.mock.timers.tick(60_000);+ await settle();+ assert.equal(requests.length, 4, "a hidden tab defers its retry");+ doc.hidden = false;+ doc.dispatch();+ await settle();+ assert.equal(requests.length, 5);+ } finally {+ unsubscribe();+ }+});++test("Vulkan retry delay doubles from 3 s to a 60 s cap", () => {+ assert.deepEqual(+ [0, 1, 2, 3, 4, 5, 10].map(vulkanRetryDelayMs),+ [3000, 6000, 12000, 24000, 48000, 60000, 60000],+ );+});diff --git a/studio/frontend/tests/toast-offset.test.ts b/studio/frontend/tests/toast-offset.test.tsindex e06e1080bc5..04d73d6d4f9 100644--- a/studio/frontend/tests/toast-offset.test.ts+++ b/studio/frontend/tests/toast-offset.test.ts@@ -11,6 +11,7 @@ import {cornerInsets,getToastOffsets,insetPastChatSettings,+ subscribeCornerInsets,watchChatSettingsInset,} from "../src/lib/toast-offset.ts";import { readSrc } from "./helpers/kit.ts";@@ -267,6 +268,24 @@ test("the inset follows a drag through the corner scopes", (t) => {assert.equal(scope.vars.has(CHAT_SETTINGS_INSET_VAR), false);});+test("a corner inset change is announced once per new value", (t) => {+ let calls = 0;+ t.after(subscribeCornerInsets(() => calls++));+ t.after(() => cornerInsets.style.removeProperty(CHAT_SETTINGS_INSET_VAR));+ cornerInsets.style.setProperty(CHAT_SETTINGS_INSET_VAR, "320px");+ cornerInsets.style.setProperty(CHAT_SETTINGS_INSET_VAR, "320px");+ assert.equal(calls, 1, "the composer watcher rewrites the same lift on every resize");+ cornerInsets.style.removeProperty(CHAT_SETTINGS_INSET_VAR);+ cornerInsets.style.removeProperty(CHAT_SETTINGS_INSET_VAR);+ assert.equal(calls, 2);+});++test("the published corner card frame is re-read when the rail insets move the card", () => {+ const hook = readSrc("features/loaded-models/use-published-corner-frame.ts");+ assert.match(hook, /const unsubscribe = subscribeCornerInsets\(measure\);/, "a growing composer lifts the card without resizing it, and the Live monitor kept dodging its old box and covered it");+ assert.match(hook, /unsubscribe\(\);/);+});+test("panel insets are written to their consumers, never to <html>", () => {const sheet = readSrc("features/chat/chat-settings-sheet.tsx");assert.match(sheet, /return watchChatSettingsInset\(\s*cornerInsets,\s*asideRef\.current,/, "an inherited variable on <html> restyled the whole document on every drag frame");