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: add a loaded models indicator with per-model eject (#8082)
Michael Hanb3705f44b956
diff --git a/.github/scripts/run-studio-indicator-browser.sh b/.github/scripts/run-studio-indicator-browser.shnew file mode 100755index 00000000000..534101c9ec2--- /dev/null+++ b/.github/scripts/run-studio-indicator-browser.sh@@ -0,0 +1,72 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++# Boot an API-only Unsloth and run the loaded-models indicator suite against it+# in one browser engine. Sibling of run-studio-permission-browser.sh, same shape+# and same bootstrap; the suite stubs the four /status endpoints with+# page.route, so it needs no model, no GPU and no llama.cpp build.++set -euo pipefail++port="${1:?usage: $0 PORT BROWSER [CHANNEL]}"+browser="${2:?usage: $0 PORT BROWSER [CHANNEL]}"+channel="${3:-}"+slug="$browser${channel:+-$channel}"+artifact_dir="logs/playwright-indicator-$slug"+server_log="logs/studio-indicator-$slug.log"+studio_home="${UNSLOTH_STUDIO_HOME:-$HOME/.unsloth/studio}"+set --+if [ -n "${STUDIO_INDICATOR_FRONTEND:-}" ]; then+ set -- -f "$STUDIO_INDICATOR_FRONTEND"+fi++mkdir -p "$artifact_dir"+# Wipe rather than reset: the boot below must mint a fresh .bootstrap_password.+rm -rf "$studio_home/auth"+UNSLOTH_API_ONLY=1 unsloth studio -H 127.0.0.1 -p "$port" "$@" \+ >"$server_log" 2>&1 &+studio_pid=$!++cleanup() {+ kill "$studio_pid" 2>/dev/null || true+ wait "$studio_pid" 2>/dev/null || true+}+trap cleanup EXIT++healthy=0+for _ in $(seq 1 180); do+ if curl -fs "http://127.0.0.1:$port/api/health" >/dev/null; then+ healthy=1+ break+ fi+ if ! kill -0 "$studio_pid" 2>/dev/null; then+ tail -100 "$server_log" || true+ exit 1+ fi+ sleep 1+done+if [ "$healthy" -ne 1 ]; then+ tail -100 "$server_log" || true+ exit 1+fi++old_password=$(cat "$studio_home/auth/.bootstrap_password")+new_password="CIInd-$(python -c 'import secrets; print(secrets.token_urlsafe(16))')"+if [ "${GITHUB_ACTIONS:-}" = "true" ]; then+ echo "::add-mask::$old_password"+ echo "::add-mask::$new_password"+fi++export BASE_URL="http://127.0.0.1:$port"+export STUDIO_OLD_PW="$old_password"+export STUDIO_NEW_PW="$new_password"+export STUDIO_PLAYWRIGHT_BROWSER="$browser"+export PW_ART_DIR="$artifact_dir"+if [ -n "$channel" ]; then+ export STUDIO_PLAYWRIGHT_CHANNEL="$channel"+else+ unset STUDIO_PLAYWRIGHT_CHANNEL || true+fi++python tests/studio/playwright_loaded_models_indicator.pydiff --git a/.github/workflows/studio-mac-ui-smoke.yml b/.github/workflows/studio-mac-ui-smoke.ymlindex a20a230cf7d..b4bc78c3fee 100644--- a/.github/workflows/studio-mac-ui-smoke.yml+++ b/.github/workflows/studio-mac-ui-smoke.yml@@ -34,6 +34,7 @@ on:- 'pyproject.toml'- 'tests/studio/**'- '.github/scripts/run-studio-permission-browser.sh'+ - '.github/scripts/run-studio-indicator-browser.sh'- '.github/workflows/studio-mac-ui-smoke.yml'# Every server boot in this workflow shells out to that script, so an edit# to it changes what this workflow actually runs.@@ -303,6 +304,13 @@ jobs:run: |bash .github/scripts/run-studio-permission-browser.sh 18895 webkit+ # WKWebView is what the desktop app embeds here, so this is the closest+ # CI gets to the real macOS surface. The status reads are stubbed, which+ # also covers the mps and sd.cpp payloads a CUDA runner cannot produce.+ - name: Loaded-models indicator (WebKit)+ run: |+ bash .github/scripts/run-studio-indicator-browser.sh 18899 webkit+- name: Reset auth + boot Unsloth for extra UI tests (port 18897)run: |bash .github/scripts/boot-studio-api-only.sh \diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.ymlindex f638015978a..f24af98529c 100644--- a/.github/workflows/studio-ui-smoke.yml+++ b/.github/workflows/studio-ui-smoke.yml@@ -28,6 +28,7 @@ on:# the test must still trigger UI CI.- 'tests/studio/**'- '.github/scripts/run-studio-permission-browser.sh'+ - '.github/scripts/run-studio-indicator-browser.sh'- '.github/workflows/studio-ui-smoke.yml'# Every server boot in this workflow shells out to that script, so an edit# to it changes what this workflow actually runs.@@ -207,6 +208,18 @@ jobs:bash .github/scripts/run-studio-permission-browser.sh 18893 webkitbash .github/scripts/run-studio-permission-browser.sh 18893 chromium chrome+ # The indicator restores an absolute viewport position from localStorage,+ # so it needs a real layout and a real ResizeObserver to test at all --+ # a stored position from a wider screen once left the card off screen with+ # its own drag handle and collapse button unreachable. The four /status+ # reads are stubbed, so this needs no model and no GPU, which also lets it+ # replay the AMD / Apple / CPU-only payload shapes this runner never sees.+ - name: Cross-browser loaded-models indicator+ run: |+ bash .github/scripts/run-studio-indicator-browser.sh 18899 chromium+ bash .github/scripts/run-studio-indicator-browser.sh 18899 firefox+ bash .github/scripts/run-studio-indicator-browser.sh 18899 webkit+# The chat UI test ends by clicking the Shutdown menuitem, which# leaves the server dead. The extra UI test (Compare / Recipes /# Export / Unsloth / Settings) needs a fresh Unsloth, so we boot adiff --git a/.github/workflows/studio-windows-ui-smoke.yml b/.github/workflows/studio-windows-ui-smoke.ymlindex dcfc32a2cbd..3184ff10353 100644--- a/.github/workflows/studio-windows-ui-smoke.yml+++ b/.github/workflows/studio-windows-ui-smoke.yml@@ -20,6 +20,7 @@ on:- 'pyproject.toml'- 'tests/studio/**'- '.github/scripts/run-studio-permission-browser.sh'+ - '.github/scripts/run-studio-indicator-browser.sh'- '.github/workflows/studio-windows-ui-smoke.yml'# Every server boot in this workflow shells out to that script, so an edit# to it changes what this workflow actually runs.@@ -366,6 +367,11 @@ jobs:run: |bash .github/scripts/run-studio-permission-browser.sh 18895 chromium msedge+ # Real Edge, which is also the WebView2 the desktop app embeds on Windows.+ - name: Loaded-models indicator (Edge)+ run: |+ bash .github/scripts/run-studio-indicator-browser.sh 18899 chromium msedge+- name: Reset auth + boot Unsloth for extra UI tests (port 18897)run: |bash .github/scripts/boot-studio-api-only.sh \diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.pyindex 8a32544259d..b05ab7fcb92 100644--- a/studio/backend/loggers/handlers.py+++ b/studio/backend/loggers/handlers.py@@ -50,6 +50,12 @@ _QUIET_POLL_PATHS = {"/api/auth/status","/api/inference/status","/api/inference/monitor",+ # The loaded-models indicator polls all four runtimes every 5s for as long+ # as the app is open, and on the desktop every line is mirrored into+ # tauri.log. /api/inference/status is already above; these are its siblings.+ "/api/inference/images/status",+ "/api/inference/video/status",+ "/api/inference/audio/stt/status",# List polls the tabs refetch on a timer and on every tab switch."/api/train/runs","/api/models/checkpoints",diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 7665d5a5fca..890fbf87d45 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3557,6 +3557,18 @@ def _monitor_anthropic_response(return response+def _standard_models_still_held() -> list[str]:+ """Unsloth models the registry still holds, whoever is active.++ A GGUF load unloads only the ACTIVE Unsloth model, so a Transformers model+ cached behind it keeps its weights while llama.cpp answers. Reported so the+ memory is visible, and releasable, rather than stranded.+ """+ backend = _peek_inference_backend()+ models = getattr(backend, "models", None) if backend is not None else None+ return [name for name in models if isinstance(name, str)] if isinstance(models, dict) else []++def _peek_inference_backend() -> Any:"""The orchestrator if one already exists, else None. Never constructs one.@@ -8632,7 +8644,11 @@ async def get_status(current_subject: str = Depends(get_current_subject)):),gguf_variant = llama_backend.hf_variant,loading = [],- loaded = [_display_model_id] if _display_model_id else [],+ # Plus anything the Unsloth registry still holds: the GGUF load+ # only unloaded the ACTIVE one, so a model cached behind it is+ # still in VRAM and was invisible to every client reading this.+ loaded = ([_display_model_id] if _display_model_id else [])+ + [name for name in _standard_models_still_held() if name != _display_model_id],inference = _inference_cfg,**_runtime_fields,requested_context_length = llama_backend.requested_n_ctx,diff --git a/studio/backend/tests/test_inference_status_loaded_gguf.py b/studio/backend/tests/test_inference_status_loaded_gguf.pyindex e17a6058fbe..e1064348fe2 100644--- a/studio/backend/tests/test_inference_status_loaded_gguf.py+++ b/studio/backend/tests/test_inference_status_loaded_gguf.py@@ -118,6 +118,37 @@ def test_a_local_path_load_without_a_lease_is_still_local(status_route):assert status.is_local_model is True+def test_a_model_cached_behind_the_gguf_is_still_reported(status_route, monkeypatch):+ # Loading a GGUF unloads only the ACTIVE Unsloth model, so a Transformers+ # model cached behind it keeps its weights. Reporting only the GGUF left+ # that memory invisible to every client, and unreleasable from the UI.+ monkeypatch.setattr(+ inference_route,+ "_peek_inference_backend",+ lambda: type("_Reg", (), {"models": {"org/Cached": {}}})(),+ )+ status = status_route(_StatusBackend("org/A-GGUF", native_grant_backed = False))+ assert status.active_model == "org/A-GGUF"+ assert status.loaded == ["org/A-GGUF", "org/Cached"]+++def test_the_gguf_is_not_listed_twice_when_the_registry_names_it(status_route, monkeypatch):+ monkeypatch.setattr(+ inference_route,+ "_peek_inference_backend",+ lambda: type("_Reg", (), {"models": {"org/A-GGUF": {}}})(),+ )+ status = status_route(_StatusBackend("org/A-GGUF", native_grant_backed = False))+ assert status.loaded == ["org/A-GGUF"]+++def test_no_orchestrator_leaves_the_gguf_alone(status_route, monkeypatch):+ # Peek returns None before anything built one; the branch must not construct it.+ monkeypatch.setattr(inference_route, "_peek_inference_backend", lambda: None)+ status = status_route(_StatusBackend("org/A-GGUF", native_grant_backed = False))+ assert status.loaded == ["org/A-GGUF"]++def test_the_users_chat_template_override_wins_over_the_runtime_projection(status_route):# The field is on the shared runtime fields, so the projection carries it too.# It must be overridden, not passed alongside, or the call is a TypeError.diff --git a/studio/backend/tests/test_logging_middleware.py b/studio/backend/tests/test_logging_middleware.pyindex 1ca5b370f7f..0d873e6e54b 100644--- a/studio/backend/tests/test_logging_middleware.py+++ b/studio/backend/tests/test_logging_middleware.py@@ -402,7 +402,8 @@ def test_image_video_load_progress_heartbeats(logs, monkeypatch):def test_unrelated_image_routes_still_log(logs, monkeypatch):- # Only the timer-polled paths are quieted, not the event-driven reads.+ # Quieting only collapses repeats: the first hit on any path always logs,+ # including the status reads the loaded-models indicator now polls.monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)for path in ("/api/inference/images/status",@@ -417,6 +418,30 @@ def test_unrelated_image_routes_still_log(logs, monkeypatch):]+def test_indicator_status_polls_collapse_to_a_heartbeat(logs, monkeypatch):+ # The loaded-models indicator reads all four runtimes every 5s for as long+ # as the app is open, and on the desktop every line is mirrored into+ # tauri.log. /api/inference/status was already quiet; its three siblings+ # arrived with the indicator and have to be quiet for the same reason.+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 1000)++ mw = LoggingMiddleware(_status_app(200))+ polled = (+ "/api/inference/status",+ "/api/inference/images/status",+ "/api/inference/video/status",+ "/api/inference/audio/stt/status",+ )+ for _ in range(4):+ for path in polled:+ _run(mw(_http_scope(path), _noop_receive, _drop))++ paths = _paths_logged(logs)+ for path in polled:+ assert paths.count(path) == 1, f"{path} logged {paths.count(path)} times"++def test_verbose_restores_the_dropped_success_polls(logs, monkeypatch):# --verbose zeroes both windows, so the 2xx suppressor must stand down too.monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsxindex 07f50de7384..0d1e08e5472 100644--- a/studio/frontend/src/app/provider.tsx+++ b/studio/frontend/src/app/provider.tsx@@ -17,10 +17,12 @@ import { fetchDeviceType } from "@/config/env";import { getTauriAuthFailure, tauriAutoAuth } from "@/features/auth";import { DeepLinkHandler } from "@/features/deep-links";import { DownloadManagerPanel } from "@/features/hub/download-manager";+import { LoadedModelsIndicator } from "@/features/loaded-models";import { NativeIntentDrain } from "@/features/native-intents/native-intent-drain";import {applyCustomizationToDocument,useAppearanceCustomStore,+ useStackGeometry,useTheme,} from "@/features/settings";import { SttDownloadPrompt } from "@/features/settings/components/stt-download-prompt";@@ -372,6 +374,7 @@ function TauriUpdateLayer({appContent: ReactNode;}) {const update = useTauriUpdate(isExternalServer);+ const stack = useStackGeometry();const isUpdating =update.status === "updating-backend" ||update.status === "downloading" ||@@ -390,7 +393,10 @@ function TauriUpdateLayer({/>) : (// Capped like the browser stack: the download panel shares it, so both must fit.- <div className="pointer-events-none fixed bottom-4 right-4 z-[9998] flex max-h-[calc(100dvh_-_2rem)] flex-col items-end gap-2">+ <div+ className="pointer-events-none fixed right-4 z-[9998] flex flex-col items-end gap-2"+ style={{ bottom: stack.bottom, maxHeight: stack.maxHeight }}+ ><UpdateBannerstatus={update.status}info={update.info}@@ -503,6 +509,7 @@ function DesktopChromeVarsEffect({function TauriWrapper({ children }: { children: ReactNode }) {const pathname = useRouterState({ select: (s) => s.location.pathname });+ const stack = useStackGeometry();const {status,logs,@@ -667,7 +674,10 @@ function TauriWrapper({ children }: { children: ReactNode }) {corner, banners above, each owning its width. */}{/* Capped to the viewport, or a long download list plus expanded notespushes the top of the stack off screen. */}- <div className="pointer-events-none fixed bottom-4 right-4 z-[9998] flex max-h-[calc(100dvh_-_2rem)] flex-col items-end gap-2">+ <div+ className="pointer-events-none fixed right-4 z-[9998] flex flex-col items-end gap-2"+ style={{ bottom: stack.bottom, maxHeight: stack.maxHeight }}+ ><WebUpdateBannerpositioned={false}enabled={!WEB_UPDATE_HIDDEN_ROUTES.has(pathname)}@@ -677,6 +687,9 @@ function TauriWrapper({ children }: { children: ReactNode }) {enabled={!WEB_UPDATE_HIDDEN_ROUTES.has(pathname)}/><DownloadManagerPanel positioned={false} />+ {/* Last in the stack, so the persistent card sits at the corner and the+ transient banners above it never cover it. */}+ <LoadedModelsIndicator positioned={false} /></div></>);@@ -698,6 +711,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {><LlamaUpdateBanner positioned={false} enabled={!hidesTitlebarSidebar} /><DownloadManagerPanel positioned={false} />+ <LoadedModelsIndicator positioned={false} /></TauriUpdateLayer>) : (<StartupScreendiff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 92ed93001f0..6915815a329 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -167,6 +167,7 @@ import { ThreadDocumentsBar } from "@/features/rag/components/thread-documents-bimport { KnowledgeBaseComposerButton } from "@/features/rag/components/knowledge-base-composer-button";import { DocumentPreviewMount } from "@/features/rag/components/document-preview-mount";import { useUserProfileStore } from "@/features/profile/stores/user-profile-store";+import { usePublishedFrame } from "@/features/settings/hooks/use-published-frame";import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";import { isTauri } from "@/lib/api-base";@@ -3015,6 +3016,17 @@ const Composer: FC<{// lands. Going through the form keeps queueing, indexing holds and draft// clearing identical to a typed send.const formRef = useRef<HTMLFormElement | null>(null);+ // Mirrored into state so the publish effect re-runs when the node mounts: a+ // ref mutation does not re-render. See usePublishedFrame.+ const [composerEl, setComposerEl] = useState<HTMLFormElement | null>(null);+ const attachComposer = useCallback((node: HTMLFormElement | null) => {+ formRef.current = node;+ setComposerEl(node);+ }, []);+ // The composer docks to the bottom of the viewport once a thread has turns,+ // in the same column the corner overlay stack occupies. Published so the+ // stack lifts above it rather than covering the Send button.+ usePublishedFrame(composerEl);const dictationBaseTextRef = useRef("");const dictationComposerRef = useRef("");// Thread switches reuse this composer, so the send has to know where it@@ -3419,7 +3431,7 @@ const Composer: FC<{return (<PromptQueueContext.Provider value={queueContextValue}><ComposerPrimitive.Root- ref={formRef}+ ref={attachComposer}className="aui-composer-root relative flex w-full flex-col"aria-disabled={disabled}onSubmit={handleSubmit}diff --git a/studio/frontend/src/components/floating-monitor.tsx b/studio/frontend/src/components/floating-monitor.tsxindex e7fe7336af7..6eecca930c1 100644--- a/studio/frontend/src/components/floating-monitor.tsx+++ b/studio/frontend/src/components/floating-monitor.tsx@@ -3,7 +3,10 @@import { Button } from "@/components/ui/button";import { Progress } from "@/components/ui/progress";-import { useMonitorOverlayStore } from "@/features/settings";+import {+ useMonitorFrameStore,+ useMonitorOverlayStore,+} from "@/features/settings";import { aggregateGpuMemoryTotalGb, useSystemInfo } from "@/hooks/use-system";import { useT } from "@/i18n";import { cn } from "@/lib/utils";@@ -13,6 +16,7 @@ import {type PointerEvent,useEffect,useLayoutEffect,+ useMemo,useRef,useState,} from "react";@@ -36,6 +40,9 @@ interface DragSession {maxTop: number;constraintsWidth: number;constraintsHeight: number;+ /** The committed left/top the drag's transform offsets from. */+ baseLeft: number;+ baseTop: number;}function clamp(value: number, min: number, max: number): number {@@ -86,10 +93,15 @@ function naturalWidth(monitor: HTMLDivElement): number {}function useMonitorLayout(constraintsElement: HTMLDivElement | null) {+ // This panel's claim on the shared frame. Reopening the monitor mid-exit+ // mounts the replacement while the old panel is still animating out, and the+ // old one unmounts last, so its cleanup must only clear its own frame.+ const publisher = useMemo(() => ({}), []);const monitorRef = useRef<HTMLDivElement>(null);const scrollRef = useRef<HTMLDivElement>(null);const contentRef = useRef<HTMLDivElement>(null);const dragSessionRef = useRef<DragSession | null>(null);+ const dragFrameRef = useRef(0);const hasDraggedRef = useRef(false);const preferredWidthRef = useRef<number | null>(null);const preferredHeightRef = useRef<number | null>(null);@@ -167,14 +179,28 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {session.constraintsHeight = constraintsBox.height;}+ // Publish the real box so the overlay stack can keep clear of it.+ useMonitorFrameStore.getState().setFrame(publisher, {+ left: monitorBox.left,+ top: monitorBox.top,+ right: monitorBox.right,+ bottom: monitorBox.bottom,+ });+setLayout((current) => {+ // Mid-drag the offset lives in a transform, and the measured box+ // already includes it, so committing left/top here would apply it+ // twice. finishDrag lands the position instead.+ const held = session && current ? current : null;+ const restLeft = held?.left ?? left;+ const restTop = held?.top ?? top;const next = {- left,- top,+ left: restLeft,+ top: restTop,minWidth: preferredWidthRef.current ?? monitorBox.width,minHeight: preferredHeightRef.current ?? monitorBox.height,- maxWidth: constraintsBox.width - left,- maxHeight: constraintsBox.height - top,+ maxWidth: constraintsBox.width - restLeft,+ maxHeight: constraintsBox.height - restTop,};return current && sameLayout(current, next) ? current : next;});@@ -191,12 +217,37 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {}return () => {observer.disconnect();+ useMonitorFrameStore.getState().clearFrame(publisher);if (remeasureRef.current) {cancelAnimationFrame(remeasureRef.current);remeasureRef.current = 0;}+ if (dragFrameRef.current) {+ cancelAnimationFrame(dragFrameRef.current);+ dragFrameRef.current = 0;+ }};- }, [constraintsElement]);+ }, [constraintsElement, publisher]);++ // ResizeObserver never fires for a position-only change, so dragging alone+ // would leave the published frame at the monitor's old corner and the overlay+ // stack dodging where it used to be. Re-publish once each layout is committed,+ // which after a drag is on release: the frames in between are a transform, and+ // republishing through them would re-render every overlay in the stack for+ // each one, which is most of what made dragging feel heavy.+ useLayoutEffect(() => {+ const monitor = monitorRef.current;+ if (!(monitor && constraintsElement)) {+ return;+ }+ const box = monitor.getBoundingClientRect();+ useMonitorFrameStore.getState().setFrame(publisher, {+ left: box.left,+ top: box.top,+ right: box.right,+ bottom: box.bottom,+ });+ }, [layout, constraintsElement, publisher]);function startDrag(event: PointerEvent<HTMLDivElement>) {const monitor = monitorRef.current;@@ -239,10 +290,28 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {maxTop: Math.max(0, constraintsBox.height - monitorBox.height),constraintsWidth: constraintsBox.width,constraintsHeight: constraintsBox.height,+ baseLeft: left,+ baseTop: top,};event.currentTarget.setPointerCapture(event.pointerId);}+ // One paint per frame, and through a transform rather than left/top. The+ // panel is backdrop-blurred, so every layout-driven move re-sampled what is+ // behind it; a trackpad also reports moves faster than the display refreshes,+ // so most of those renders were never shown.+ function paintDrag() {+ dragFrameRef.current = 0;+ const session = dragSessionRef.current;+ const monitor = monitorRef.current;+ if (!(session && monitor)) {+ return;+ }+ monitor.style.transform = `translate3d(${session.left - session.baseLeft}px, ${+ session.top - session.baseTop+ }px, 0)`;+ }+function updateDrag(event: PointerEvent<HTMLDivElement>) {const session = dragSessionRef.current;if (!session || session.pointerId !== event.pointerId) {@@ -263,6 +332,30 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {session.startY = event.clientY;session.left = left;session.top = top;+ if (!dragFrameRef.current) {+ dragFrameRef.current = requestAnimationFrame(paintDrag);+ }+ }++ function finishDrag(event: PointerEvent<HTMLDivElement>) {+ const session = dragSessionRef.current;+ if (session?.pointerId !== event.pointerId) {+ return;+ }+ if (dragFrameRef.current) {+ cancelAnimationFrame(dragFrameRef.current);+ dragFrameRef.current = 0;+ }+ const { left, top, constraintsWidth, constraintsHeight } = session;+ dragSessionRef.current = null;+ // Written to the node as well as to state, in this order, so handing the+ // offset back to left/top cannot show a frame at the spot it started from.+ const monitor = monitorRef.current;+ if (monitor) {+ monitor.style.left = `${left}px`;+ monitor.style.top = `${top}px`;+ monitor.style.transform = "";+ }setLayout((current) =>!current || (current.left === left && current.top === top)? current@@ -270,18 +363,12 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {...current,left,top,- maxWidth: session.constraintsWidth - left,- maxHeight: session.constraintsHeight - top,+ maxWidth: constraintsWidth - left,+ maxHeight: constraintsHeight - top,},);}- function finishDrag(event: PointerEvent<HTMLDivElement>) {- if (dragSessionRef.current?.pointerId === event.pointerId) {- dragSessionRef.current = null;- }- }-return {monitorRef,scrollRef,diff --git a/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts b/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.tsindex 830052b5fb8..8dfb549e67f 100644--- a/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.ts+++ b/studio/frontend/src/features/chat/adapters/studio-model-dictation-adapter.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 { withModelLoadNotice } from "@/lib/model-lifecycle-events";import { authFetch } from "@/features/auth";import { hubTokenHeader } from "@/features/hub/lib/hub-token-header";import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";@@ -219,7 +220,9 @@ export async function validateSttModel(/** Load a selected model that is already downloaded. */export function loadSttModel(model: string, engine?: SttEngine): Promise<void> {const resolvedEngine = engine ?? sttEngineFor(model);- return queueSttLifecycle(async () => {+ // Announced so the indicator shows the load immediately, as the toast does.+ return queueSttLifecycle(() =>+ withModelLoadNotice("stt", model, async () => {const response = await authFetch("/api/inference/audio/stt/load", {method: "POST",headers: { "Content-Type": "application/json" },@@ -232,7 +235,8 @@ export function loadSttModel(model: string, engine?: SttEngine): Promise<void> {const detail = body?.detail ?? `HTTP ${response.status}`;throw sttRequestError(response.status, detail);}- });+ }),+ );}/** Start a background download of a dictation model. */diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex a98e27a7fc8..db914e16937 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.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 { withModelLoadNotice } from "@/lib/model-lifecycle-events";import { authFetch } from "@/features/auth";import { prepareHfTokenForUse } from "@/features/hf-auth";// These helpers are deliberately API-layer-only, not part of their features' public barrels.@@ -139,8 +140,10 @@ export async function listLoras(return parseJsonOrThrow<ListLorasResponse>(response);}-export async function getInferenceStatus(): Promise<InferenceStatusResponse> {- const response = await authFetch("/api/inference/status");+export async function getInferenceStatus(+ signal?: AbortSignal,+): Promise<InferenceStatusResponse> {+ const response = await authFetch("/api/inference/status", { signal });return parseJsonOrThrow<InferenceStatusResponse>(response);}@@ -192,17 +195,22 @@ export async function loadModel(throw Object.assign(new Error("Model load cancelled."), {unslothUserCancelled: true,});- const response = await authFetch("/api/inference/load", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- ...payload,- hf_token: preparedToken.token,- native_path_lease: payload.nativePathLease ?? null,- nativePathLease: undefined,- }),+ // Announced after the token prompt, so a cancelled load never shows a row.+ // The indicator otherwise had nothing to show until its next 5s poll, while+ // the toast reported the load immediately.+ return withModelLoadNotice("chat", payload.model_path ?? null, async () => {+ const response = await authFetch("/api/inference/load", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ ...payload,+ hf_token: preparedToken.token,+ native_path_lease: payload.nativePathLease ?? null,+ nativePathLease: undefined,+ }),+ });+ return parseJsonOrThrow<LoadModelResponse>(response, "Model load");});- return parseJsonOrThrow<LoadModelResponse>(response, "Model load");}export async function countChatInputTokens(payload: {diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 984425e9a3c..b2a67204a2a 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -71,6 +71,7 @@ import {} from "@/features/native-intents";import { GuidedTour, useGuidedTourController } from "@/features/tour";import { isTauri } from "@/lib/api-base";+import { chatModelLoaded } from "./lib/chat-model-loaded";import { isDownloadCancelled } from "@/lib/native-files";import { toast } from "@/lib/toast";import { cn } from "@/lib/utils";@@ -1930,6 +1931,9 @@ export function ChatPage({const activeGgufVariant = useChatRuntimeStore((state) => state.activeGgufVariant,);+ const residentCheckpoint = useChatRuntimeStore(+ (state) => state.residentCheckpoint,+ );const ggufContextLength = useChatRuntimeStore((state) => state.ggufContextLength,);@@ -3326,6 +3330,16 @@ export function ChatPage({loraModels={loraModels}externalModels={externalModels}value={inferenceParams.checkpoint}+ // Resident, not merely picked: an image or video load evicts+ // the chat model and leaves this selection behind, so the tick+ // stayed on a model the backend had already released.+ loaded={chatModelLoaded({+ checkpoint: inferenceParams.checkpoint,+ isExternalModel: isExternalModelId(+ inferenceParams.checkpoint,+ ),+ residentCheckpoint,+ })}activeGgufVariant={activeGgufVariant}activeModelConfig={activeModelConfig}activeGgufContextLength={ggufContextLength}diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsindex 8e31180cf5f..284764bae1d 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts@@ -2,8 +2,9 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { mlxRuntimeStateFrom } from "../lib/mlx-runtime-state";-import { createElement, useCallback, useRef, useState } from "react";+import { createElement, useCallback, useEffect, useRef, useState } from "react";import { toast } from "@/lib/toast";+import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";import { confirmRemoteCodeIfNeeded } from "@/features/security";import {confirmTransformersUpgradeIfNeeded,@@ -285,12 +286,23 @@ function getTransformersUpgradeRequiredMessage(modelName: string): string {* is a thin wrapper over it. External selections are left untouched since they* have no backend mirror.*/+// Bumped by every call. Two refreshes can be in flight at once -- a media load+// announces itself before its POST and again once the backend has committed the+// eviction -- and they read the status at different moments. Completion order is+// not the order they were issued in, so without this the older one could land+// last and re-pin the model the newer one had just seen released, leaving chat+// claiming a model that 400s on send until the load finally settled.+let syncGeneration = 0;+async function syncInferenceStatusToStore(options?: {signal?: AbortSignal;includeLoras?: boolean;}): Promise<void> {const signal = options?.signal;const includeLoras = options?.includeLoras ?? true;+ // Last issued wins: it read the freshest status, whichever answers first.+ const generation = ++syncGeneration;+ const superseded = () => generation !== syncGeneration;const { setModels, setLoras, setCheckpoint, setModelsError } =useChatRuntimeStore.getState();setModelsError(null);@@ -303,7 +315,9 @@ async function syncInferenceStatusToStore(options?: {// Cancellation can land while the requests above are in flight. Bail// before writing backend state back -- cancelLoading already cleared it.- if (signal?.aborted) return;+ // Same for a refresh that a later one has already superseded: its answer+ // describes a moment that has passed.+ if (signal?.aborted || superseded()) return;setModels(listRes.models.map(toChatModelSummary));if (lorasRes) {@@ -349,17 +363,41 @@ async function syncInferenceStatusToStore(options?: {}}} else if (!statusRes.active_model && !isExternalSelectionActive) {+ // Loading an image or video model evicts the chat one (the GPU arbiter+ // allows a single owner), and nothing else here would say so: the picker+ // keeps the selection, so the header would go on claiming it is loaded+ // and the next prompt would come back a bare 400.+ const { residentCheckpoint: wasResident, modelLoading } =+ useChatRuntimeStore.getState();// specFallbackReason survives here, so clearing activeModelIsLocal// alone would flip a local model's warning to "download failed". Every// load path and clearCheckpoint set it, so leave it consistent.useChatRuntimeStore.setState({+ residentCheckpoint: null,modelRequiresTrustRemoteCode: false,loadedIsMultimodal: false,loadedIsDiffusion: false,});+ // Known resident a moment ago, and nothing loading now. Both matter: a+ // load in flight has no active model yet either, and clearing there would+ // wipe the pick the user just made.+ if (wasResident && selectedCheckpoint && !modelLoading) {+ // Already the clean id the header shows: resolveInferenceCheckpointId+ // put it there, not a load path.+ toast.info(`${wasResident} is no longer loaded`, {+ description:+ "The server released it, which loading an image or video model does. Pick it again to keep chatting.",+ });+ // Drop the pick too, which is what a server-side unload already does.+ // Dimming the tick was not enough: the name alone reads as "this is my+ // model" whatever the tick does, and sending to it returns a bare 400.+ useChatRuntimeStore.getState().clearCheckpoint();+ }}} catch (error) {- if (signal?.aborted) return;+ // A superseded refresh reports nothing, or a stale failure would raise a+ // toast about a read whose answer would have been discarded anyway.+ if (signal?.aborted || superseded()) return;const message =error instanceof Error ? error.message : "Failed to load models";setModelsError(message);@@ -480,6 +518,26 @@ export function useChatModelRuntime() {[],);+ // Nothing here polls /status: refresh runs on mount and when the model lists+ // change, never on a timer. So an image or video load evicting the chat model+ // (the GPU arbiter allows one owner) went unseen, and the header went on+ // showing the evicted model as loaded until something else happened to+ // refresh. Re-read whenever another runtime finishes a load.+ useEffect(+ () =>+ subscribeModelLifecycle(({ runtime }) => {+ // Dictation is a sidecar and takes no GPU ownership, so it evicts+ // nothing. Chat's own loads already reconcile themselves.+ if (runtime === "chat" || runtime === "stt") return;+ // Both edges, not only the settle. The arbiter evicts chat inside the+ // image or video load POST, before the download starts, so waiting for+ // the load to finish left the picker and the header naming a model that+ // had already gone and that 400s on send, for the whole download.+ void refresh({ includeLoras: false });+ }),+ [refresh],+ );+const cancelLoading = useCallback(() => {const model = loadingModelRef.current;if (!model) return;diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 7579a47772e..51c50b75e8f 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -22,6 +22,7 @@ export {notifyChatHistoryUpdated,removeScanFolder,revealCachedModel,+ unloadModel,type BrowseFoldersResponse,type CachedGgufRepo,type CachedModelRepo,@@ -124,6 +125,8 @@ export {useChatModelRuntime,resyncInferenceStatusAfterServerModelChange,} from "./hooks/use-chat-model-runtime";+export { chatModelLoaded } from "./lib/chat-model-loaded";+export type { ChatModelLoadedInput } from "./lib/chat-model-loaded";export {customProviderDisplayName,isCustomProviderType,diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.tsindex ad0b63f64aa..a311c30f444 100644--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts@@ -143,6 +143,11 @@ export function applyActiveModelStatusToStore(const checkpointId = resolveInferenceCheckpointId(status);if (!checkpointId) return;+ // Only reached with a model actually active, so this is the one place both+ // the status poll and the readopt path can publish residency from. Without+ // it a load would look unloaded until the next poll, up to 10s later.+ useChatRuntimeStore.setState({ residentCheckpoint: checkpointId });+const store = useChatRuntimeStore.getState();const previousCheckpoint =options.previousCheckpoint ?? store.params.checkpoint;diff --git a/studio/frontend/src/features/chat/lib/chat-model-loaded.ts b/studio/frontend/src/features/chat/lib/chat-model-loaded.tsnew file mode 100644index 00000000000..5737d312e26--- /dev/null+++ b/studio/frontend/src/features/chat/lib/chat-model-loaded.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Whether the header may call the picked model loaded. Its own plain module so+// the node suite can drive it: runtime-provider.tsx pulls in the whole chat+// runtime.++export type ChatModelLoadedInput = {+ /** The picker selection, "" when nothing is picked. */+ checkpoint: string;+ /** Callers that show their own loading state can leave this out. */+ modelLoading?: boolean;+ /** An API model: served remotely, so nothing is resident here. */+ isExternalModel: boolean;+ /** What /api/inference/status holds; undefined before the first read. */+ residentCheckpoint: string | null | undefined;+};++/**+ * Resident, not merely picked. Loading an image or video model evicts the chat+ * model (the GPU arbiter allows a single GPU owner) and leaves the selection+ * alone, so a check on the selection reported a model the backend had already+ * released and the next prompt failed with a bare 400.+ *+ * `undefined` means the first status read has not landed: assume loaded, or the+ * header flashes "not loaded" on every startup.+ */+export function chatModelLoaded({+ checkpoint,+ modelLoading = false,+ isExternalModel,+ residentCheckpoint,+}: ChatModelLoadedInput): boolean {+ if (!checkpoint || modelLoading) return false;+ return isExternalModel || residentCheckpoint !== null;+}diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 51bfe1d5cec..9be1a4d4fed 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { authFetch } from "@/features/auth";+import { chatModelLoaded } from "./lib/chat-model-loaded";import {AssistantRuntimeProvider,type Attachment,@@ -173,7 +174,12 @@ class VisionImageAdapter implements AttachmentAdapter {const activeModel = state.models.find((m) => m.id === checkpoint);const externalSelection = parseExternalModelId(checkpoint);const isExternalModel = externalSelection !== null;- const modelLoaded = !!checkpoint && !state.modelLoading;+ const modelLoaded = chatModelLoaded({+ checkpoint,+ modelLoading: state.modelLoading,+ isExternalModel,+ residentCheckpoint: state.residentCheckpoint,+ });let externalSupportsVision: boolean | null = null;let externalModelLabel: string | null = null;if (externalSelection !== null) {diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 9c122aa58e2..34f62e3a938 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -910,6 +910,14 @@ type ChatRuntimeStore = {// lets the attach gates flag a failed load vs "no model picked".lastModelLoadError: string | null;activeGgufVariant: string | null;+ /**+ * What /api/inference/status says is resident, as opposed to what the picker+ * has selected. undefined until the first status read, so the header does not+ * flash "not loaded" before anything is known. Loading an image or video+ * model evicts the chat model (one GPU owner at a time), which is otherwise+ * invisible here: the selection survives it.+ */+ residentCheckpoint: string | null | undefined;/** Whether the backend loaded the active model from a filesystem path. */activeModelIsLocal: boolean;ggufContextLength: number | null;@@ -1557,6 +1565,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({modelsError: null,lastModelLoadError: null,activeGgufVariant: null,+ residentCheckpoint: undefined,activeModelIsLocal: false,ggufContextLength: null,ggufMaxContextLength: null,@@ -2052,6 +2061,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({checkpoint: "",},activeGgufVariant: null,+ // Nothing is picked, so there is nothing for residency to describe. Back+ // to unknown rather than null: null would be read as "was evicted".+ residentCheckpoint: undefined,activeModelIsLocal: false,activeLoadId: null,activeNativePathToken: null,diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsxindex 320f226d7db..e1c32c7d3ee 100644--- a/studio/frontend/src/features/hub/hub-page.tsx+++ b/studio/frontend/src/features/hub/hub-page.tsx@@ -382,8 +382,15 @@ export function ModelsPage() {const { selectModel, loadingModel, loadProgress, ejectModel } =useChatModelRuntime();const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);+ const residentCheckpoint = useChatRuntimeStore((s) => s.residentCheckpoint);+ // Resident, not merely picked. An image or video load evicts the chat model+ // and leaves the pick alone, so the cards kept saying "Loaded" for weights the+ // backend had already released. `undefined` is "no status read yet", which+ // stays as it was rather than flashing "On device" on every launch.const activeCheckpoint =- checkpoint && !isExternalModelId(checkpoint) ? checkpoint : null;+ checkpoint && !isExternalModelId(checkpoint) && residentCheckpoint !== null+ ? checkpoint+ : null;const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);const activeGgufContextLength = useChatRuntimeStore((s) => s.ggufContextLength,diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 97bf7a8b4d1..5ca600484f8 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.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 { withBackgroundLoadNotice } from "@/lib/model-lifecycle-events";import { authFetch } from "@/features/auth";import { readFastApiError } from "@/lib/format-fastapi-error";@@ -183,8 +184,10 @@ async function parseJson<T>(response: Response): Promise<T> {return (await response.json()) as T;}-export async function getDiffusionStatus(): Promise<DiffusionStatus> {- return parseJson(await authFetch("/api/inference/images/status"));+export async function getDiffusionStatus(+ signal?: AbortSignal,+): Promise<DiffusionStatus> {+ return parseJson(await authFetch("/api/inference/images/status", { signal }));}// One family's bf16 component sizes + estimated resident footprint per quant scheme. Hardware-independent, so it can be fetched before anything is loaded.@@ -206,8 +209,12 @@ export async function getDiffusionInferenceInfo(): Promise<DiffusionInferenceInfreturn parseJson(await authFetch("/api/inference/images/info"));}-export async function getDiffusionLoadProgress(): Promise<DiffusionLoadProgress> {- return parseJson(await authFetch("/api/inference/images/load-progress"));+export async function getDiffusionLoadProgress(+ signal?: AbortSignal,+): Promise<DiffusionLoadProgress> {+ return parseJson(+ await authFetch("/api/inference/images/load-progress", { signal }),+ );}export async function getGenerateProgress(): Promise<DiffusionGenerateProgress> {@@ -215,12 +222,21 @@ export async function getGenerateProgress(): Promise<DiffusionGenerateProgress>}export async function loadDiffusionModel(body: DiffusionLoadRequest): Promise<DiffusionStatus> {- return parseJson(- await authFetch("/api/inference/images/load", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- }),+ // Announced so the loaded models indicator shows the load for as long as the+ // toast does, rather than up to one 5s poll later. This POST only starts the+ // load, so the notice settles from load-progress, not from the response.+ return withBackgroundLoadNotice(+ "image",+ body.model_path,+ async () =>+ parseJson<DiffusionStatus>(+ await authFetch("/api/inference/images/load", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ }),+ ),+ async (signal) => (await getDiffusionLoadProgress(signal)).phase,);}diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 2e721617168..6752cc55a08 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -81,6 +81,7 @@ import {routedGgufLabel,} from "@/lib/diffusion-route-search";import { toast } from "@/lib/toast";+import { subscribeModelEjected } from "@/lib/model-lifecycle-events";import {type ControlNetSpecInput,@@ -1205,6 +1206,24 @@ export function ImagesPage({ active = true }: { active?: boolean }) {loadToastId.current = null;}, []);+ // Client-side state that only means anything while a model is resident: the+ // in-flight replacement load's tracking, and the Reapply target. Shared with+ // the indicator eject, which frees the runtime without going through the+ // page's own Unload.+ const dropResidentState = useCallback(() => {+ // Cancel, not release: a resolving pick or a staged download would load+ // back what was just ejected. In here rather than only in handleUnload, so+ // an eject driven from the loaded models card is covered by it too.+ pickGuard.cancel();+ if (pollTimer.current) clearTimeout(pollTimer.current);+ pollTimer.current = null;+ dismissLoadToast();+ lastLoadSig.current = null;+ // Leaving this set would let Reapply reload the model that was just freed.+ lastLoad.current = null;+ setCanReapply(false);+ }, [dismissLoadToast, pickGuard]);+// Mirror to the module cache so a tab switch re-renders instantly.useEffect(() => {galleryCache.images = images;@@ -1529,13 +1548,26 @@ export function ImagesPage({ active = true }: { active?: boolean }) {setPortrait((p) => !p);};+ // A status read started before an eject can answer after the one that+ // followed it, and this page has no periodic poll to correct it: the controls+ // would go on offering to generate against a runtime that is already free.+ // So every read takes a ticket and only the newest may write.+ const statusTicket = useRef(0);+ const setStatusIfNewest = useCallback(+ (ticket: number, next: DiffusionStatus) => {+ if (ticket === statusTicket.current) setStatus(next);+ },+ [],+ );+const refreshStatus = useCallback(async () => {+ const ticket = ++statusTicket.current;try {- setStatus(await getDiffusionStatus());+ setStatusIfNewest(ticket, await getDiffusionStatus());} catch {// Status is best-effort; a failed poll shouldn't surface an error toast.}- }, []);+ }, [setStatusIfNewest]);// Track mount so a long generate run stops issuing GPU work only on a true unmount; the page stays mounted across tab// switches, so a batch keeps generating off-tab. The mount-time refresh and cleanup live in the load-resume effect below.@@ -1554,6 +1586,28 @@ export function ImagesPage({ active = true }: { active?: boolean }) {})();}, [active, refreshStatus]);+ // Ejected from the loaded models indicator, which does not run handleUnload:+ // without this the controls keep offering to generate on a freed runtime, and+ // Reapply still points at the model that was just ejected. The runtime is+ // already free, so this is handleUnload without the unload call.+ useEffect(+ () =>+ subscribeModelEjected("image", () => {+ dropResidentState();+ // That eject cancelled the replacement load, and its progress poll is+ // the only thing that clears `busy` -- which dropResidentState has just+ // stopped. Leaving it set locks the page: the picker ignores every+ // choice while busy, and Unload is not offered once the status read+ // comes back empty, so only an app reload recovered. Narrowed to+ // "loading" so a generation in flight is left alone, as handleUnload's+ // own finally does.+ setBusy((prev) => (prev === "loading" ? null : prev));+ setQuant(null);+ void refreshStatus();+ }),+ [refreshStatus, dropResidentState],+ );+// Collapse the body-ported popovers when leaving the tab: the open flag stays set, so returning would pop them back open.useEffect(() => {if (active) return;@@ -1567,7 +1621,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {const p = await getDiffusionLoadProgress();if (p.phase === "ready") {dismissLoadToast();- setStatus(await getDiffusionStatus());+ setStatusIfNewest(++statusTicket.current, await getDiffusionStatus());toast.success("Model loaded");setBusy(null);// Load succeeded: the optimistic quant is now the real one, so drop the pending revert.@@ -2214,18 +2268,10 @@ export function ImagesPage({ active = true }: { active?: boolean }) {const handleUnload = useCallback(async () => {// Ejecting cancels any in-flight replacement load, so tear down its client-side tracking too, or the toast leaks forever.- // Cancel, not release: a resolving pick or a staged download would load back what was just ejected.- pickGuard.cancel();- if (pollTimer.current) clearTimeout(pollTimer.current);- pollTimer.current = null;- dismissLoadToast();- lastLoadSig.current = null;- // Drop the Reapply target with the model: the ejected pick is no longer resident, so leaving it set would let Reapply reload the ejected model.- lastLoad.current = null;- setCanReapply(false);+ dropResidentState();setBusy("unloading");try {- setStatus(await unloadDiffusionModel());+ setStatusIfNewest(++statusTicket.current, await unloadDiffusionModel());setQuant(null);} catch (err) {toast.error(err instanceof Error ? err.message : "Failed to unload model");@@ -2233,7 +2279,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {} finally {setBusy(null);}- }, [refreshStatus, dismissLoadToast, pickGuard]);+ }, [refreshStatus, dropResidentState]);const handleGenerate = useCallback(async () => {if (!prompt.trim()) {diff --git a/studio/frontend/src/features/loaded-models/eject-chat-model.ts b/studio/frontend/src/features/loaded-models/eject-chat-model.tsnew file mode 100644index 00000000000..94492025743--- /dev/null+++ b/studio/frontend/src/features/loaded-models/eject-chat-model.ts@@ -0,0 +1,106 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The eject sequence for one chat row. Its own plain module, taking its I/O as+// deps, because loaded-models-api.ts reaches the chat store and cannot be+// imported by the node --test suite. Mirrors api-monitor/unload-resident.ts.++// Extension-qualified so node --test resolves it, as merge-task-iterators.ts does.+import { unloadResident } from "../api-monitor/unload-resident.ts";++/** What /api/inference/status says is resident, already resolved. */+export type ResidentChatModel = {+ /** The id /unload matches on. */+ checkpoint: string;+ /** Every spelling of it: status reports the load path, the store the repo id. */+ aliases: string[];+};++export type EjectChatModelDeps = {+ readResident: () => Promise<ResidentChatModel | null>;+ unload: (modelPath: string) => Promise<void>;+ /** modelIdsMatch, injected so this module stays free of path aliases. */+ matches: (left: string, right: string) => boolean;+ /** True for a row the backend kept past the active model. Such a row is not+ * resident by definition, so it is the one case worth naming directly. */+ cachedRow?: boolean;+ /** Every model the runtime still holds, active or not: `loaded` from the same+ * status read. Both finds a target the active read cannot see and confirms+ * its unload. Omitted leaves the call its own evidence, as it was before. */+ readCached?: () => Promise<string[]>;+};++export type EjectChatModelResult = {+ /** Every spelling this run released, for clearing the picker selection. */+ unloadedAliases: string[];+ /** The target if it survived the run, else null. */+ stillResident: string | null;+ /** What the runtime holds instead, when the target was already gone and+ * nothing was unloaded. Null when the target was found, or when the runtime+ * holds nothing at all. */+ replacedBy: string | null;+};++/**+ * Release the model `target` names, and only that one.+ *+ * Read, unload, re-read, as the API monitor's Unload does, since an API+ * auto-switch can replace the model mid-eject and /unload naming a replaced+ * model is a documented 200 no-op. Unlike that single button, this is a per-row+ * control, so the read is scoped: a switch that landed before the click leaves+ * another model active, and unloading that frees something nobody asked to.+ */+export async function ejectChatModel(+ target: string,+ deps: EjectChatModelDeps,+): Promise<EjectChatModelResult> {+ // What the scoped read last saw, so a run that unloaded nothing can say+ // whether the runtime was idle or had already moved on to something else.+ const seen: { resident: ResidentChatModel | null } = { resident: null };+ const { unloadedAliases, stillResident } = await unloadResident({+ readResident: async () => {+ const resident = await deps.readResident();+ seen.resident = resident;+ if (!resident) return null;+ const namesTarget = resident.aliases.some((alias) =>+ deps.matches(target, alias),+ );+ return namesTarget ? resident : null;+ },+ unload: deps.unload,+ });+ if (unloadedAliases.length > 0) {+ return { unloadedAliases, stillResident, replacedBy: null };+ }+ // A row that was already cached, or an active one that has become cached+ // since the card last polled. A model replaced inside the five-second poll+ // window is not gone: the Transformers backend only moves+ // `active_model_name` and leaves the previous model in `backend.models`+ // (core/inference/inference.py:620), which /status still reports under+ // `loaded` (routes/inference.py:8112), still holding its weights. Either way+ // the scoped read above cannot match it, so ask what the runtime is really+ // holding before reporting the row as somebody else's.+ const holdsTarget = (names: string[] | undefined) =>+ names?.some((name) => deps.matches(target, name)) ?? false;+ if (deps.cachedRow || holdsTarget(await deps.readCached?.())) {+ // A cached row is never the active model, so the scoped read can never+ // match it. Name it directly: the Transformers backend can still hold it.+ await deps.unload(target);+ // Then confirm, for the same reason every other path does: /unload answers+ // 200 for a name the backend no longer holds, so the call is not evidence.+ const survived = holdsTarget(await deps.readCached?.());+ return {+ unloadedAliases: survived ? [] : [target],+ stillResident: survived ? target : null,+ replacedBy: null,+ };+ }+ // Nothing was unloaded. Either the model is already free, or a load replaced+ // it before the click -- and /unload naming a replaced model is a documented+ // 200 no-op, so firing it anyway would report an eject that never happened.+ return {+ unloadedAliases: [],+ stillResident: null,+ replacedBy: seen.resident?.checkpoint ?? null,+ };+}diff --git a/studio/frontend/src/features/loaded-models/index.ts b/studio/frontend/src/features/loaded-models/index.tsnew file mode 100644index 00000000000..9dbeed2ed83--- /dev/null+++ b/studio/frontend/src/features/loaded-models/index.ts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The preference module comes FIRST, and the order is load-bearing. The+// indicator imports the settings barrel, which eagerly evaluates SettingsDialog+// and so general-tab, whose top-level reset list dereferences+// LOADED_MODELS_PREFERENCE_KEYS through this same barrel. Export the indicator+// first and an app that reaches this barrel before the settings one enters+// general-tab while this module is still initialising, and startup dies with+// "Cannot access 'LOADED_MODELS_PREFERENCE_KEYS' before initialization".+// Evaluating the constant first makes the cycle harmless whichever side is+// entered first. Verified in Vite dev, which serves native ESM and so has no+// bundler to reorder this.+export {+ LOADED_MODELS_PREFERENCE_KEYS,+ getLoadedModelsDismissed,+ getShowLoadedModels,+ setLoadedModelsDismissed,+ setShowLoadedModels,+ useLoadedModelsDismissed,+ useShowLoadedModels,+} from "./show-loaded-models-pref";+export { LoadedModelsIndicator } from "./loaded-models-indicator";+export type {+ LoadedModelEntry,+ LoadedModelKind,+ LoadedModelSource,+} from "./loaded-models-sources";diff --git a/studio/frontend/src/features/loaded-models/loaded-models-api.ts b/studio/frontend/src/features/loaded-models/loaded-models-api.tsnew file mode 100644index 00000000000..09dc39b90af--- /dev/null+++ b/studio/frontend/src/features/loaded-models/loaded-models-api.ts@@ -0,0 +1,325 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Reads and ejects for the indicator. Reads are best-effort and independent: a+// chat-only host has no video runtime, and that must not blank the other rows.+// 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 {+ getInferenceStatus,+ isExternalModelId,+ resolveInferenceCheckpointId,+ unloadModel,+ useChatRuntimeStore,+} from "@/features/chat";+import { disposableTimeoutSignal } from "@/features/hub/lib/abort-signals";+import { modelIdsMatch } from "@/features/hub/lib/model-identity";+import {+ getDiffusionStatus,+ unloadDiffusionModel,+} from "@/features/images/api";+import { getVideoStatus, unloadVideoModel } from "@/features/video/api";+import { notifyModelEjected } from "@/lib/model-lifecycle-events";+import { ejectChatModel } from "./eject-chat-model";+import {+ type LoadedModelEntry,+ type LoadedModelSource,+ type SttStatusResponse,+ describeDiffusionStatus,+ describeInferenceStatus,+ describeSttStatus,+ describeVideoStatus,+ mergeLoadedModels,+ sttEngineStatus,+ verifyResident,+} from "./loaded-models-sources";++/** What describeInferenceStatus reads, without importing the chat types path. */+type InferenceStatus = NonNullable<+ Parameters<typeof describeInferenceStatus>[0]+>;++/** Read the chat runtime directly, as the dictation read below does, rather+ * than through the chat barrel. */+async function readInferenceStatus(+ signal?: AbortSignal,+): Promise<InferenceStatus | null> {+ const response = await authFetch("/api/inference/status", { signal });+ if (!response.ok) return null;+ return (await response.json()) as InferenceStatus;+}++async function readSttStatus(+ signal?: AbortSignal,+): Promise<SttStatusResponse | null> {+ const response = await authFetch("/api/inference/audio/stt/status", {+ signal,+ });+ if (!response.ok) return null;+ return (await response.json()) as SttStatusResponse;+}++// 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.+const READ_TIMEOUT_MS = 10_000;++/** null on failure or timeout: one stalled runtime must not empty the list. */+async function settled<T>(+ read: (signal: AbortSignal) => Promise<T>,+): Promise<T | null> {+ const timeout = disposableTimeoutSignal(READ_TIMEOUT_MS);+ try {+ return await read(timeout.signal);+ } catch {+ return null;+ } finally {+ timeout.dispose();+ }+}++/**+ * The same bound for the eject path's *reads*, but the failure is raised rather+ * than swallowed. Without it a runtime that accepts the connection and never+ * answers leaves the eject pending forever, so the row keeps its spinner and+ * stays disabled until the page is reloaded.+ *+ * Deliberately not applied to the unloads themselves. Those block on the+ * runtime's generate lock while the in-flight denoise or clip winds down, which+ * is routinely tens of seconds, and aborting the fetch would not cancel the+ * teardown: the eject would report a failure while the memory was being freed.+ * A stale read is cheap to retry; a half-reported unload is not.+ */+async function bounded<T>(+ read: (signal: AbortSignal) => Promise<T>,+): Promise<T> {+ const timeout = disposableTimeoutSignal(READ_TIMEOUT_MS);+ try {+ return await read(timeout.signal);+ } finally {+ timeout.dispose();+ }+}++/**+ * Everything resident right now, across all four runtimes.+ *+ * `previous` is what the card is showing. A read that failed or timed out comes+ * back as null, which is not evidence the runtime is empty: dropping its rows+ * would take the model off the card, and with all four failing on one blip of a+ * remote Studio the whole card would vanish while everything stayed loaded. So+ * an unreadable source keeps what it last showed and a readable one is always+ * replaced, including by an empty answer, which is how an unload still clears.+ */+export type LoadedModelsRead = {+ entries: LoadedModelEntry[];+ /** Sources whose status did not come back, so nothing in this read is+ * evidence about them. */+ unreadable: LoadedModelSource[];+};++export async function readLoadedModels(+ previous: readonly LoadedModelEntry[] = [],+): Promise<LoadedModelsRead> {+ const [inference, diffusion, video, stt] = await Promise.all([+ settled(readInferenceStatus),+ settled(getDiffusionStatus),+ settled(getVideoStatus),+ settled(readSttStatus),+ ]);+ const kept = (source: LoadedModelSource) =>+ previous.filter((row) => row.source === source);+ const unreadable: LoadedModelSource[] = [];+ const group = <T>(+ source: LoadedModelSource,+ status: T | null,+ describe: (value: T) => LoadedModelEntry[],+ ) => {+ if (status !== null) return describe(status);+ unreadable.push(source);+ return kept(source);+ };+ const entries = mergeLoadedModels([+ group("chat", inference, describeInferenceStatus),+ group("image", diffusion, describeDiffusionStatus),+ group("video", video, describeVideoStatus),+ group("stt", stt, describeSttStatus),+ ]);+ return { entries, unreadable };+}++/** Release the model this row names, and only that one. See eject-chat-model.ts. */+async function ejectChatRow(entry: LoadedModelEntry): Promise<EjectOutcome> {+ const { unloadedAliases, stillResident, replacedBy } = await ejectChatModel(+ entry.name,+ {+ readResident: async () => {+ const status = await bounded(getInferenceStatus);+ const checkpoint = resolveInferenceCheckpointId(status);+ if (!checkpoint) return null;+ // Both spellings: status reports the load path, the store the repo id.+ return {+ checkpoint,+ aliases: [checkpoint, status.active_model].filter(+ (alias): alias is string => alias != null,+ ),+ };+ },+ unload: (modelPath) => unloadModel({ model_path: modelPath }),+ matches: modelIdsMatch,+ cachedRow: entry.inactive === true,+ readCached: async () => (await bounded(getInferenceStatus)).loaded ?? [],+ },+ );+ if (stillResident) return { status: "stillResident", model: stillResident };+ if (replacedBy) return { status: "replaced", resident: replacedBy };+ // Nothing released and nothing in its place: the runtime was already idle.+ if (unloadedAliases.length === 0) return { status: "alreadyFree" };+ // Only when the row's model is really gone. A reload during the run leaves it+ // resident and still usable, so emptying the picker would be wrong.+ clearChatSelectionFor(unloadedAliases);+ 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 {+ const store = useChatRuntimeStore.getState();+ const selected = store.params.checkpoint;+ if (!selected || isExternalModelId(selected)) return;+ if (aliases.some((alias) => modelIdsMatch(selected, alias))) {+ store.clearCheckpoint();+ }+}++/**+ * How an eject ended. `replaced` means the row named a model the runtime no+ * longer holds, so nothing was unloaded: these endpoints carry no model id and+ * would have released whatever took its place. `alreadyFree` is the same read+ * of a runtime holding nothing at all, kept apart from `ejected` so a stale row+ * cannot report an unload that never ran.+ */+export type EjectOutcome =+ | { status: "ejected" }+ | { status: "alreadyFree" }+ | { status: "replaced"; resident: string }+ | { status: "stillResident"; model: string }+ // The unload was accepted but the read that confirms it did not answer, so+ // neither "done" nor "failed" is true. Reported as its own outcome rather+ // than collapsed into either, since the whole point of the confirming read is+ // that a 200 from this endpoint is not evidence.+ | { status: "unverified" };++/** `unload` could not confirm what the runtime holds, which is not the same as+ * confirming it holds nothing. */+const UNVERIFIED = Symbol("unverified");++/**+ * The three identity-less unloads, guarded by a fresh read of their runtime.+ * `unload` resolves to a model still resident afterwards, null once free, or+ * UNVERIFIED when the confirming read did not answer.+ *+ * This narrows the window to the round trip rather than closing it, since only+ * a backend that took the model id could do that, but the row itself is up to a+ * whole poll old and that is the part worth not trusting.+ */+async function ejectRuntimeRow(+ entry: LoadedModelEntry,+ resident: string | null,+ unload: () => Promise<string | null | typeof UNVERIFIED>,+): Promise<EjectOutcome> {+ const verdict = verifyResident(entry.name, resident, modelIdsMatch);+ // Nothing resident: the row is stale and its memory is already free. Said+ // plainly rather than as an eject, which would claim an unload never issued.+ if (!resident) return { status: "alreadyFree" };+ if (verdict !== "match") return { status: "replaced", resident };+ const stillResident = await unload();+ if (stillResident === UNVERIFIED) return { status: "unverified" };+ return stillResident+ ? { status: "stillResident", model: stillResident }+ : { status: "ejected" };+}++/** Release one row, after checking the runtime still holds what the row names. */+export async function ejectLoadedModel(+ entry: LoadedModelEntry,+): Promise<EjectOutcome> {+ switch (entry.source) {+ case "chat":+ return ejectChatRow(entry);+ case "image": {+ const before = await bounded(getDiffusionStatus);+ return ejectRuntimeRow(+ entry,+ before.loaded ? before.repo_id : null,+ async () => {+ const after = await unloadDiffusionModel();+ // The page owning this runtime keeps its own copy of the status.+ notifyModelEjected("image");+ return after.loaded ? (after.repo_id ?? entry.name) : null;+ },+ );+ }+ case "video": {+ const before = await bounded(getVideoStatus);+ return ejectRuntimeRow(+ entry,+ before.loaded ? before.repo_id : null,+ async () => {+ const after = await unloadVideoModel();+ notifyModelEjected("video");+ return after.loaded ? (after.repo_id ?? entry.name) : null;+ },+ );+ }+ case "stt": {+ const engine = entry.sttEngine;+ if (!engine) throw new Error("This row names no dictation engine.");+ // Dictation loads on demand and releases when idle, so the engine's+ // resident model can change with no user action at all.+ const before = await bounded(readSttStatus);+ // Unreadable status: say so rather than unload blind or claim success.+ if (!before) {+ throw new Error(+ "Could not read dictation status, so nothing was ejected.",+ );+ }+ const resident = sttEngineStatus(before, engine);+ return ejectRuntimeRow(+ entry,+ resident?.loaded_model ?? null,+ async () => {+ const query = new URLSearchParams({ engine }).toString();+ const response = await authFetch(+ `/api/inference/audio/stt/unload?${query}`,+ { method: "POST" },+ );+ if (!response.ok) throw new Error(await readErrorDetail(response));+ // The unload response body is a fixed {loaded_model: null}, and the+ // backend silently serves `gguf` from the transformers engine when+ // whisper-server is absent, so a 200 is not evidence this engine let+ // go. Re-read and report what it actually holds.+ const after = await bounded(readSttStatus);+ // A non-2xx read is null too, and reading that as "nothing left"+ // would toast success and drop the row for a model still holding+ // memory, which is the exact case this re-read exists to catch.+ if (!after) return UNVERIFIED;+ return sttEngineStatus(after, engine)?.loaded_model ?? null;+ },+ );+ }+ }+}++async function readErrorDetail(response: Response): Promise<string> {+ try {+ const body = (await response.json()) as { detail?: unknown };+ if (typeof body.detail === "string") return body.detail;+ } catch {+ // non-JSON error body+ }+ return `Request failed (${response.status})`;+}diff --git a/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsx b/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsxnew file mode 100644index 00000000000..888d6d430bb--- /dev/null+++ b/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsx@@ -0,0 +1,390 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A loaded model only shows on the page that loaded it, so memory stays held with+// nothing on screen saying so. This card lists what is resident from anywhere and+// ejects it in place. It joins the shared bottom-right stack instead of pinning+// itself, so the update banners and download panel never overlap it.++import { Spinner } from "@/components/ui/spinner";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { hasAuthToken, mustChangePassword } from "@/features/auth";+import { useSettingsDialogStore } from "@/features/settings";+import { usePersistedToggle } from "@/hooks/use-persisted-toggle";+import { isTauri } from "@/lib/api-base";+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";+import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";+import { SparkleIcon } from "@/lib/sparkle-icon";+import { cn } from "@/lib/utils";+import {+ Cancel01Icon,+ DragDropVerticalIcon,+ Image01Icon,+ Message01Icon,+ Mic01Icon,+ RemoveCircleIcon,+ Video01Icon,+ VolumeHighIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { useNavigate, useRouterState } from "@tanstack/react-router";+import { useCallback, useEffect, useRef } from "react";+import {+ LOADED_MODEL_KIND_LABELS,+ type LoadedModelEntry,+ type LoadedModelKind,+ loadedModelTarget,+ shortModelLabel,+} from "./loaded-models-sources";+import {+ LOADED_MODELS_PREFERENCE_KEYS,+ setLoadedModelsDismissed,+ useLoadedModelsDismissed,+ useShowLoadedModels,+} from "./show-loaded-models-pref";+import { useDragPosition } from "./use-drag-position";+import { useLoadedModels } from "./use-loaded-models";++// Collapsing to the pill is deliberate, so it survives reloads. Expanded by+// default: a card you have to open first answers nothing.+const COLLAPSED_KEY = LOADED_MODELS_PREFERENCE_KEYS.collapsed;++const KIND_ICONS: Record<LoadedModelKind, typeof SparkleIcon> = {+ text: Message01Icon,+ tts: VolumeHighIcon,+ image: Image01Icon,+ video: Video01Icon,+ stt: Mic01Icon,+};++// Nothing to report on the auth and onboarding 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",+ "/onboarding",+]);++function canShowIndicator(pathname: string): boolean {+ if (HIDDEN_ROUTES.has(pathname)) return false;+ if (isTauri) return true;+ return hasAuthToken() && !mustChangePassword();+}++function rowSubtitle(entry: LoadedModelEntry): string {+ const kind = LOADED_MODEL_KIND_LABELS[entry.kind];+ return entry.detail ? `${kind} · ${entry.detail}` : kind;+}++function LoadedModelRow({+ entry,+ ejecting,+ onEject,+ onOpen,+}: {+ entry: LoadedModelEntry;+ ejecting: boolean;+ onEject: () => void;+ onOpen: () => void;+}) {+ const label = shortModelLabel(entry.name);+ const target = loadedModelTarget(entry.source);+ return (+ <div className="flex items-center gap-2 rounded-[14px] px-1.5 py-1 transition-colors hover:bg-foreground/[0.04]">+ {/* Only the label half is the link: the eject button cannot nest inside it. */}+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ aria-label={`${label}. Open ${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-foreground/[0.05] text-muted-foreground">+ <HugeiconsIcon+ icon={KIND_ICONS[entry.kind]}+ strokeWidth={1.75}+ className="size-[15px]"+ />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-ui-12p5 font-medium text-foreground">+ {label}+ </span>+ <span className="block truncate text-ui-11 text-muted-foreground">+ {rowSubtitle(entry)}+ </span>+ </span>+ </button>+ </TooltipTrigger>+ <TooltipContent side="left" sideOffset={6}>+ <span className="block">{entry.name}</span>+ <span className="block text-muted-foreground">+ Open {target.label}+ </span>+ </TooltipContent>+ </Tooltip>+ {entry.loading ? (+ // 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" />+ </span>+ ) : (+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ aria-label={`Eject ${label}`}+ disabled={ejecting}+ onClick={onEject}+ className="flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-foreground/[0.07] hover:text-foreground disabled:pointer-events-none disabled:opacity-60"+ >+ {ejecting ? (+ <Spinner className="size-3.5" label="Ejecting" />+ ) : (+ // Eject, not dismiss: this releases the weights, which the+ // header's X does not. Same glyph the model picker's own eject+ // shortcut uses, so the action reads the same in both places.+ <HugeiconsIcon+ icon={RemoveCircleIcon}+ strokeWidth={1.75}+ className="size-3.5"+ />+ )}+ </button>+ </TooltipTrigger>+ <TooltipContent side="left" sideOffset={6}>+ Eject to free memory+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ );+}++export function LoadedModelsIndicator({+ positioned = true,+}: { positioned?: boolean } = {}) {+ const pathname = useRouterState({ select: (s) => s.location.pathname });+ const showIndicator = useShowLoadedModels();+ const dismissed = useLoadedModelsDismissed();+ const reachable = canShowIndicator(pathname);+ const enabled = showIndicator && !dismissed && reachable;+ // Dismissal is not part of this: a card the user closed must still hear the+ // load that brings it back. Reachability is, because it carries the auth gate+ // -- 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 [collapsed, setCollapsed] = usePersistedToggle(COLLAPSED_KEY);+ const navigate = useNavigate();+ const openEntry = useCallback(+ (entry: LoadedModelEntry) => {+ const target = loadedModelTarget(entry.source);+ if (target.open === "settings") {+ // Read on click, not at render: the settings barrel reaches back here+ // through the General tab, so the binding is only safe once both+ // modules have finished evaluating. The /settings route is no use, it+ // redirects home and would take the user off the page they are on.+ useSettingsDialogStore.getState().openDialog(target.tab);+ return;+ }+ // No search params: this only takes the user to the page, it does not+ // start a new thread or reload anything.+ void navigate({ to: target.to });+ },+ [navigate],+ );+ const { position, panelRef, startDrag, dragging, justDragged } =+ useDragPosition(LOADED_MODELS_PREFERENCE_KEYS.position);++ // 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 still listening for the load that+ // reopens it. On the start of the load, not the end, so it is up for the whole+ // time the toast is.+ useEffect(+ () =>+ subscribeModelLifecycle(({ loading }) => {+ if (loading) {+ setLoadedModelsDismissed(false);+ }+ }),+ [],+ );++ // A load started outside this tab raises no lifecycle event at all: the+ // OpenAI-compatible API and auto-switch go nowhere near the frontend wrappers+ // that announce one. The poll is the only witness, so a row appearing while+ // the card is closed reopens it too, which is what the tooltip promises.+ //+ // The first poll after closing is the baseline, never a reopen: the ids are+ // read fresh on mount, and a dismissal survives a reload, so treating what is+ // already resident as new would make the card impossible to close.+ const idsWhileClosedRef = useRef<Set<string> | null>(null);+ useEffect(() => {+ if (!dismissed) {+ idsWhileClosedRef.current = null;+ return;+ }+ const ids = new Set(polledEntries.map((entry) => entry.id));+ const before = idsWhileClosedRef.current;+ idsWhileClosedRef.current = ids;+ if (!before) return;+ for (const id of ids) {+ if (!before.has(id)) {+ setLoadedModelsDismissed(false);+ return;+ }+ }+ }, [dismissed, polledEntries]);++ if (!enabled || entries.length === 0) return null;++ const countLabel = `${entries.length} ${entries.length === 1 ? "model" : "models"} loaded`;++ return (+ <div+ ref={panelRef}+ className={cn(+ // Dragged: pinned where the user left it, out of the stack's flow.+ // Otherwise anchored bottom-right, or flowing as a right-aligned row+ // in the shared stack so overlays stack instead of overlapping.+ "pointer-events-none",+ position && "fixed z-[9999] w-fit",+ !position &&+ (positioned+ ? "fixed bottom-4 right-4 z-50"+ : "flex min-h-0 justify-end"),+ dragging && "select-none",+ )}+ style={position ? { left: position.left, top: position.top } : undefined}+ >+ {collapsed ? (+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ aria-label={`${countLabel}. Show details, or drag to move`}+ onPointerDown={startDrag}+ // The pill is its own drag handle, so a press that moved is a+ // drag and must not also expand the card.+ onClick={() => {+ if (!justDragged()) setCollapsed(false);+ }}+ className="menu-soft-surface 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}+ strokeWidth={1.75}+ className="size-[15px]"+ />+ <span className="text-ui-12p5 font-medium tabular-nums">+ {entries.length}+ </span>+ </button>+ </TooltipTrigger>+ <TooltipContent side="left" sideOffset={6}>+ {countLabel}+ </TooltipContent>+ </Tooltip>+ ) : (+ <div className="menu-soft-surface pointer-events-auto flex min-h-0 w-[268px] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-[20px] p-1.5 font-heading">+ <div className="flex items-center gap-1.5 px-1.5 pb-1 pt-0.5">+ <HugeiconsIcon+ icon={SparkleIcon}+ strokeWidth={1.75}+ className="size-[15px] shrink-0 text-muted-foreground"+ />+ <span className="min-w-0 flex-1 truncate text-ui-12p5 font-semibold text-foreground">+ Loaded models+ </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.+ 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-foreground/[0.07] hover:text-foreground active:cursor-grabbing"+ >+ <HugeiconsIcon+ icon={DragDropVerticalIcon}+ strokeWidth={1.75}+ className="size-3.5"+ />+ </div>+ </TooltipTrigger>+ <TooltipContent side="left" sideOffset={6}>+ Drag to move+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ aria-label="Collapse loaded models"+ onClick={() => setCollapsed(true)}+ className="flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-foreground/[0.07] hover:text-foreground"+ >+ <HugeiconsIcon+ icon={ChevronDownStandardIcon}+ strokeWidth={1.75}+ className="size-3.5"+ />+ </button>+ </TooltipTrigger>+ <TooltipContent side="left" sideOffset={6}>+ Collapse+ </TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ aria-label="Close loaded models"+ onClick={() => setLoadedModelsDismissed(true)}+ className="flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-foreground/[0.07] hover:text-foreground"+ >+ <HugeiconsIcon+ icon={Cancel01Icon}+ strokeWidth={2}+ className="size-3.5"+ />+ </button>+ </TooltipTrigger>+ <TooltipContent side="left" sideOffset={6}>+ <span className="block">Close</span>+ <span className="block text-muted-foreground">+ Back on the next model load+ </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">+ {entries.map((entry) => (+ <LoadedModelRow+ key={entry.id}+ entry={entry}+ ejecting={ejecting.has(entry.id)}+ onEject={() => void eject(entry)}+ onOpen={() => openEntry(entry)}+ />+ ))}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/studio/frontend/src/features/loaded-models/loaded-models-sources.ts b/studio/frontend/src/features/loaded-models/loaded-models-sources.tsnew file mode 100644index 00000000000..a550a67b9f5--- /dev/null+++ b/studio/frontend/src/features/loaded-models/loaded-models-sources.ts@@ -0,0 +1,373 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Chat, images, video and dictation each own a runtime and their own /status, and+// nothing publishes "everything resident" in one call. These map each payload to a+// common row shape. Pure and React-free so node --test can import them; the types+// come from each feature's own module because the indexes re-export their pages.++import type { InferenceStatusResponse } from "@/features/chat/types/api";+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";++/** Which runtime holds the weights, so which endpoint releases them. */+export type LoadedModelSource = "chat" | "image" | "video" | "stt";++/** The dictation sidecars, as /audio/stt/status names them. */+export type SttEngine = "transformers" | "mtmd" | "gguf";++export type LoadedModelEntry = {+ /** Stable across polls, so a row does not remount mid-eject. */+ id: string;+ kind: LoadedModelKind;+ source: LoadedModelSource;+ /** The id the backend reports; also what the eject call names. */+ name: string;+ /** One short line: quantisation, family, device. */+ detail: string;+ /** Only on `source: "stt"`: its unload takes an engine, not a model id. */+ sttEngine?: SttEngine;+ /** Cached by the chat runtime but not active, so no status flags describe it. */+ inactive?: boolean;+ /** Still loading: shown with a spinner and no eject, since there is nothing+ * resident to release yet. Matches the load toast rather than trailing it. */+ loading?: boolean;+};++/** The per-engine half of /api/inference/audio/stt/status. */+export type SttEngineStatus = {+ loaded_model?: string | null;+ device?: string | null;+ /** The sidecar is starting: reported per engine by /audio/stt/status. */+ loading?: boolean;+};++export type SttStatusResponse = SttEngineStatus & {+ transformers?: SttEngineStatus | null;+ mtmd?: SttEngineStatus | null;+ gguf?: SttEngineStatus | null;+};++const STT_ENGINE_LABELS: Record<SttEngine, string> = {+ transformers: "Transformers",+ mtmd: "llama.cpp",+ gguf: "whisper.cpp",+};++/**+ * Where a row's model is actually used, so clicking it goes there. Keyed on the+ * runtime holding the weights rather than the kind: a Whisper checkpoint in the+ * chat slot belongs to Chat, while the dictation sidecars belong to Voice.+ *+ * Dictation has no page of its own yet, so it opens the settings tab that+ * drives it. Point it at the Audio page once that lands.+ */+export type LoadedModelTarget =+ | { open: "route"; to: "/chat" | "/images" | "/video"; label: string }+ | { open: "settings"; tab: "voice"; label: string };++export function loadedModelTarget(source: LoadedModelSource): LoadedModelTarget {+ switch (source) {+ case "image":+ return { open: "route", to: "/images", label: "Images" };+ case "video":+ return { open: "route", to: "/video", label: "Video" };+ case "stt":+ return { open: "settings", tab: "voice", label: "Voice settings" };+ default:+ return { open: "route", to: "/chat", label: "Chat" };+ }+}++export const LOADED_MODEL_KIND_LABELS: Record<LoadedModelKind, string> = {+ text: "Chat",+ tts: "Speech",+ image: "Image",+ video: "Video",+ stt: "Dictation",+};++/**+ * Join the known parts, so no row shows a stray separator, and drop repeats:+ * the llama.cpp and whisper.cpp dictation sidecars report their engine name as+ * the device, which would otherwise print twice.+ */+function joinDetail(...parts: (string | null | undefined)[]): string {+ const seen = new Set<string>();+ const kept: string[] = [];+ for (const part of parts) {+ if (!part) continue;+ const key = part.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ kept.push(part);+ }+ return kept.join(" · ");+}++/** Keep a path's last two segments; a repo id is already short. */+export function shortModelLabel(name: string): string {+ const normalized = name.replace(/[\\/]+$/, "");+ const segments = normalized.split(/[\\/]+/).filter(Boolean);+ if (segments.length <= 2) return normalized;+ return segments.slice(-2).join("/");+}++/** 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(+ status: InferenceStatusResponse | null,+): LoadedModelEntry[] {+ if (!status) return [];+ const entries: LoadedModelEntry[] = [];+ const active = status.active_model;+ if (active) {+ const audioType = status.audio_type ?? null;+ // is_audio means TTS here, as mlx_inference documents ("audio_vlm (omni+ // audio input; is_audio stays False -- it means TTS and redirects in the+ // chat route)"). So the audio types split three ways, not two: whisper is+ // the ASR sidecar, audio_vlm is a chat model that happens to listen, and+ // the rest speak. Only the third kind belongs under Speech.+ const isTts =+ Boolean(status.is_audio) &&+ audioType !== "whisper" &&+ audioType !== "audio_vlm";+ const isStt = Boolean(status.is_audio) && audioType === "whisper";+ const runtime = status.is_gguf+ ? "GGUF"+ : status.is_mlx+ ? "MLX"+ : "Transformers";+ entries.push({+ id: `chat:${active}`,+ kind: isTts ? "tts" : isStt ? "stt" : "text",+ source: "chat",+ name: active,+ detail: joinDetail(+ runtime,+ status.gguf_variant,+ status.is_vision ? "Vision" : null,+ ),+ });+ }+ // Reported by /status for the whole load, so a load started in another tab or+ // before this page opened still shows, not only one driven from here.+ for (const name of status.loading ?? []) {+ if (entries.some((entry) => entry.name === name)) continue;+ entries.push({+ id: `chat:${name}`,+ kind: "text",+ source: "chat",+ name,+ detail: "Loading",+ loading: true,+ });+ }+ // Only the Transformers backend caches past the active model, but it is memory+ // nothing else surfaces or releases.+ for (const name of status.loaded ?? []) {+ if (name === active) continue;+ if (entries.some((entry) => entry.name === name)) continue;+ entries.push({+ id: `chat:${name}`,+ kind: "text",+ source: "chat",+ name,+ detail: "Still in memory",+ inactive: true,+ });+ }+ return entries;+}++/**+ * The precision a pipeline actually loaded at, short enough for the row. Images+ * report a torch dtype, video a resolved quantisation ("none" being plain+ * bf16). Anything unrecognised is shown as the backend spelled it, upper-cased.+ */+export function precisionLabel(value: string | null | undefined): string | null {+ if (!value || value === "none") return null;+ const known: Record<string, string> = {+ bfloat16: "BF16",+ float16: "FP16",+ float32: "FP32",+ };+ return known[value] ?? value.toUpperCase();+}++export function describeDiffusionStatus(+ status: DiffusionStatus | null,+): LoadedModelEntry[] {+ if (!status?.loaded || !status.repo_id) return [];+ return [+ {+ id: `image:${status.repo_id}`,+ kind: "image",+ source: "image",+ name: status.repo_id,+ detail: joinDetail(+ status.family,+ status.model_kind === "gguf" ? "GGUF" : null,+ // A GGUF load reports "gguf" here too; joinDetail drops the repeat.+ precisionLabel(status.dtype),+ status.device,+ ),+ },+ ];+}++export function describeVideoStatus(+ status: VideoStatus | null,+): LoadedModelEntry[] {+ if (!status?.loaded || !status.repo_id) return [];+ return [+ {+ id: `video:${status.repo_id}`,+ kind: "video",+ source: "video",+ name: status.repo_id,+ detail: joinDetail(+ status.family,+ status.model_kind === "gguf" ? "GGUF" : null,+ // The dense transformer's own precision when one engaged, since that is+ // what distinguishes the build; otherwise the pipeline dtype.+ precisionLabel(status.transformer_quant) ??+ precisionLabel(status.dtype),+ status.device,+ ),+ },+ ];+}++/** A server predating the engine split reports the resident Transformers model+ * only at the top level, so fall back to it rather than showing no row. */+export function sttEngineStatus(+ status: SttStatusResponse,+ engine: SttEngine,+): SttEngineStatus | null {+ const block = status[engine];+ if (block) return block;+ return engine === "transformers"+ ? { loaded_model: status.loaded_model, device: status.device }+ : null;+}++export function describeSttStatus(+ status: SttStatusResponse | null,+): LoadedModelEntry[] {+ if (!status) return [];+ const engines: SttEngine[] = ["transformers", "mtmd", "gguf"];+ const entries: LoadedModelEntry[] = [];+ for (const engine of engines) {+ const block = sttEngineStatus(status, engine);+ if (block?.loading && !block.loaded_model) {+ entries.push({+ id: `stt:${engine}`,+ kind: "stt",+ source: "stt",+ name: STT_ENGINE_LABELS[engine],+ detail: "Loading",+ sttEngine: engine,+ loading: true,+ });+ continue;+ }+ if (!block?.loaded_model) continue;+ entries.push({+ id: `stt:${engine}`,+ kind: "stt",+ source: "stt",+ name: block.loaded_model,+ detail: joinDetail(STT_ENGINE_LABELS[engine], block.device),+ sttEngine: engine,+ });+ }+ return entries;+}++/**+ * What a row's model turned out to be when the eject re-read its runtime.+ * "replaced" is the one that matters: /images/unload, /video/unload and the STT+ * unload carry no model id and release whatever the runtime holds, so a row up+ * to one poll old must not be trusted to name it.+ */+export type ResidentVerdict = "match" | "gone" | "replaced";++export function verifyResident(+ entryName: string,+ resident: string | null | undefined,+ matches: (left: string, right: string) => boolean,+): ResidentVerdict {+ if (!resident) return "gone";+ return matches(entryName, resident) ? "match" : "replaced";+}++/** One list in a fixed group order, so rows never jump between polls. Ids are+ * deduped defensively; two runtimes holding one repo id are two copies. */+export function mergeLoadedModels(+ groups: LoadedModelEntry[][],+): LoadedModelEntry[] {+ const seen = new Set<string>();+ const merged: LoadedModelEntry[] = [];+ for (const group of groups) {+ for (const entry of group) {+ if (seen.has(entry.id)) continue;+ seen.add(entry.id);+ merged.push(entry);+ }+ }+ return merged;+}++/**+ * Fold the loads announced by `withModelLoadNotice` into the polled rows.+ *+ * The poll is 5s, so a load that has only just started shows nothing while its+ * toast already says "loading". These rows come from the load call itself, and+ * a status row for the same runtime replaces them the moment one arrives: the+ * backend's answer always wins over the optimistic one.+ */+export function withPendingLoads(+ rows: LoadedModelEntry[],+ pending: Map<LoadedModelSource, string | null>,+): LoadedModelEntry[] {+ if (pending.size === 0) return rows;+ const extra: LoadedModelEntry[] = [];+ for (const [source, model] of pending) {+ // A status row wins only when it describes the same load. Images and video+ // keep the OLD pipeline resident while the replacement downloads, freeing it+ // only at the commit, so a source-only test hid the incoming model for the+ // whole pull: the card showed the model being replaced and no sign of the+ // one arriving. A row that is itself loading always wins, which is what+ // keeps chat and dictation from announcing the same load twice when the+ // backend spells its name differently.+ if (+ rows.some(+ (row) =>+ row.source === source &&+ (row.loading === true || model == null || row.name === model),+ )+ ) {+ continue;+ }+ extra.push({+ id: `${source}:pending`,+ kind: PENDING_KINDS[source],+ source,+ name: model ?? "Loading model",+ detail: "Loading",+ loading: true,+ });+ }+ return extra.length > 0 ? [...rows, ...extra] : rows;+}++const PENDING_KINDS: Record<LoadedModelSource, LoadedModelKind> = {+ chat: "text",+ image: "image",+ video: "video",+ stt: "stt",+};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.tsnew file mode 100644index 00000000000..91955daa934--- /dev/null+++ b/studio/frontend/src/features/loaded-models/show-loaded-models-pref.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Whether the corner indicator may appear. On by default; only an explicit+// "false" (Settings -> General -> Notifications) disables it. Same shape as the+// llama.cpp update banner pref.++import { useSyncExternalStore } from "react";++/** Every key this feature owns, so "Reset all local preferences" clears them. */+export const LOADED_MODELS_PREFERENCE_KEYS = {+ show: "unsloth_show_loaded_models_indicator",+ collapsed: "unsloth_loaded_models_collapsed",+ position: "unsloth_loaded_models_position",+ dismissed: "unsloth_loaded_models_dismissed",+} as const;++const STORAGE_KEY = LOADED_MODELS_PREFERENCE_KEYS.show;+const DISMISSED_KEY = LOADED_MODELS_PREFERENCE_KEYS.dismissed;++const listeners = new Set<() => void>();++/** Both flags feed the same subscribers, since both decide whether it shows. */+function notify(): void {+ for (const listener of listeners) {+ listener();+ }+}++export function getShowLoadedModels(): boolean {+ try {+ return localStorage.getItem(STORAGE_KEY) !== "false";+ } catch {+ return true;+ }+}++export function setShowLoadedModels(show: boolean): void {+ try {+ if (show) {+ // Remove rather than store "true" so the default stays on.+ localStorage.removeItem(STORAGE_KEY);+ } else {+ localStorage.setItem(STORAGE_KEY, "false");+ }+ } catch {+ // storage unavailable+ }+ notify();+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ // Sync toggles made in another tab.+ const onStorage = (event: StorageEvent) => {+ if (event.key === STORAGE_KEY || event.key === DISMISSED_KEY) listener();+ };+ window.addEventListener("storage", onStorage);+ return () => {+ listeners.delete(listener);+ window.removeEventListener("storage", onStorage);+ };+}++export function useShowLoadedModels(): boolean {+ return useSyncExternalStore(subscribe, getShowLoadedModels);+}++/**+ * Closed with the card's own X, which is not the same as switched off in+ * Settings. Kept apart on purpose: the next model load reopens a card the user+ * waved away, and must not reopen one they turned off.+ *+ * Stored rather than held in memory so a reload does not bring back a card that+ * was closed, the same as the collapsed state.+ */+export function getLoadedModelsDismissed(): boolean {+ try {+ return localStorage.getItem(DISMISSED_KEY) === "true";+ } catch {+ return false;+ }+}++export function setLoadedModelsDismissed(dismissed: boolean): void {+ // Nothing to announce when it already reads that way, and the reopen path+ // runs on every load start, so this would otherwise re-render the app's whole+ // overlay stack for each one.+ if (getLoadedModelsDismissed() === dismissed) {+ return;+ }+ try {+ if (dismissed) {+ localStorage.setItem(DISMISSED_KEY, "true");+ } else {+ // Removed rather than stored "false" so the default stays open.+ localStorage.removeItem(DISMISSED_KEY);+ }+ } catch {+ // storage unavailable+ }+ notify();+}++export function useLoadedModelsDismissed(): boolean {+ return useSyncExternalStore(subscribe, getLoadedModelsDismissed);+}diff --git a/studio/frontend/src/features/loaded-models/use-drag-position.ts b/studio/frontend/src/features/loaded-models/use-drag-position.tsnew file mode 100644index 00000000000..4b92a81c2a3--- /dev/null+++ b/studio/frontend/src/features/loaded-models/use-drag-position.ts@@ -0,0 +1,339 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Pointer drag for the indicator, in the Live monitor's idiom: anchored to its+// corner until the 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 { useCallback, useEffect, useRef, useState } from "react";++export type DragPosition = { left: number; top: number };++/** Keeps the panel fully on screen, and off the very edge. */+const MARGIN = 8;++// Below this the press is a click, so the collapsed pill can be both a drag+// handle and the button that expands it.+const DRAG_THRESHOLD_PX = 4;++function clamp(value: number, min: number, max: number): number {+ return Math.max(min, Math.min(max, value));+}++export type Viewport = { width: number; height: number };++/** Keeps the whole panel on screen. Exported pure for the node suite. */+export function clampToViewport(+ position: DragPosition,+ width: number,+ height: number,+ viewport: Viewport,+): DragPosition {+ return {+ left: clamp(+ position.left,+ MARGIN,+ Math.max(MARGIN, viewport.width - width - MARGIN),+ ),+ top: clamp(+ position.top,+ MARGIN,+ Math.max(MARGIN, viewport.height - height - MARGIN),+ ),+ };+}++/** Whether a press has moved far enough to be a drag rather than a click. */+export function passedDragThreshold(dx: number, dy: number): boolean {+ return Math.hypot(dx, dy) >= DRAG_THRESHOLD_PX;+}++function viewport(): Viewport {+ return { width: window.innerWidth, height: window.innerHeight };+}++function readStored(key: string): DragPosition | null {+ try {+ const raw = localStorage.getItem(key);+ if (!raw) return null;+ const parsed = JSON.parse(raw) as Partial<DragPosition>;+ return typeof parsed.left === "number" && typeof parsed.top === "number"+ ? { left: parsed.left, top: parsed.top }+ : null;+ } catch {+ return null;+ }+}++function store(key: string, position: DragPosition | null): void {+ try {+ if (position) {+ localStorage.setItem(key, JSON.stringify(position));+ } else {+ localStorage.removeItem(key);+ }+ } catch {+ // storage unavailable+ }+}++export type UseDragPosition = {+ /** null until the user moves it, so the default anchor still applies. */+ position: DragPosition | null;+ /** Callback ref, not a RefObject: the reclamp effect has to re-run when the+ * node appears, and a RefObject mutation does not re-render. */+ panelRef: (node: HTMLDivElement | null) => void;+ startDrag: (event: React.PointerEvent<HTMLElement>) => void;+ dragging: boolean;+ /** True once, for the click that ends a drag, so a handle can also be a+ * button. Reading it clears the flag, so a later keyboard activation on the+ * same button is not swallowed too. */+ justDragged: () => boolean;+};+++export function useDragPosition(storageKey: string): UseDragPosition {+ const [position, setPosition] = useState<DragPosition | null>(() => {+ if (typeof window === "undefined") return null;+ const stored = readStored(storageKey);+ // Clamp on read as well as on resize. The observer below cannot fire until+ // after the first paint, so a position saved on a wider screen would flash+ // off screen once; zero width/height keeps at least the top-left corner in+ // view, and the first measurement refines it.+ return stored ? clampToViewport(stored, 0, 0, viewport()) : null;+ });+ // Held from pointerdown to pointerup; dragging only once past the threshold.+ const [pressing, setPressing] = useState(false);+ const [dragging, setDragging] = useState(false);+ const movedRef = useRef(false);+ const panelRef = useRef<HTMLDivElement | null>(null);+ // Mirrored into state because the reclamp effect must re-subscribe when the+ // node mounts: the card renders nothing until the first poll returns a row,+ // so the effect's first run sees a null ref.+ const [panelEl, setPanelEl] = useState<HTMLDivElement | null>(null);+ const attachPanel = useCallback((node: HTMLDivElement | null) => {+ panelRef.current = node;+ setPanelEl(node);+ }, []);+ const sessionRef = useRef<{+ pointerId: number;+ startX: number;+ startY: number;+ left: number;+ top: number;+ width: number;+ height: number;+ /** Where the last painted frame put it, committed to state on release. */+ lastLeft: number;+ lastTop: number;+ } | 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.+ const frameRef = useRef(0);+ const pendingRef = useRef<{ dx: number; dy: number } | null>(null);++ // Returning the same object when nothing changed matters: this also runs from+ // a ResizeObserver, and a fresh object every time would re-render forever.+ const reclamp = useCallback((width: number, height: number) => {+ setPosition((current) => {+ if (!current) return current;+ const next = clampToViewport(current, width, height, viewport());+ return next.left === current.left && next.top === current.top+ ? current+ : next;+ });+ }, []);++ // A window that shrank, or a panel that grew when expanded, would otherwise+ // strand it off screen with nothing able to bring it back.+ //+ // Deliberately not keyed on `position`: it used to be, so every frame of a+ // drag tore the observer down and built a new one, and observing re-measures,+ // which forced a synchronous layout each time. reclamp is a no-op until the+ // panel has a position, so attaching on mount costs nothing.+ useEffect(() => {+ if (!panelEl) return;+ const measure = () => {+ const box = panelEl.getBoundingClientRect();+ reclamp(box.width, box.height);+ };+ window.addEventListener("resize", measure);+ const observer =+ typeof ResizeObserver === "undefined"+ ? null+ : new ResizeObserver(measure);+ observer?.observe(panelEl);+ // No observer (an engine old enough to lack it) still gets the resize path,+ // plus this one measurement of whatever is on screen right now.+ if (!observer) measure();+ return () => {+ window.removeEventListener("resize", measure);+ observer?.disconnect();+ };+ }, [panelEl, reclamp]);++ const startDrag = useCallback(+ (event: React.PointerEvent<HTMLElement>) => {+ const panel = panelRef.current;+ if (event.button !== 0 || !panel) return;+ // Without capture a pointerup over another window is never delivered, so+ // the card would keep tracking the cursor. Same as the Live monitor's drag.+ try {+ event.currentTarget.setPointerCapture(event.pointerId);+ } catch {+ // Capture is best effort; the window listeners below still drive the drag.+ }+ const box = panel.getBoundingClientRect();+ sessionRef.current = {+ pointerId: event.pointerId,+ startX: event.clientX,+ startY: event.clientY,+ left: box.left,+ top: box.top,+ width: box.width,+ height: box.height,+ lastLeft: box.left,+ lastTop: box.top,+ };+ movedRef.current = false;+ setPressing(true);+ },+ [],+ );++ // One paint per frame, off the offset pointermove last recorded. A trackpad+ // reports faster than the display refreshes, so a move-per-event was work the+ // screen never showed, and translate3d keeps it off the layout path: the card+ // carries a wide blurred shadow that left/top repainted every single frame.+ const applyPending = useCallback(() => {+ const session = sessionRef.current;+ const move = pendingRef.current;+ const panel = panelRef.current;+ pendingRef.current = null;+ if (!(session && move && panel)) {+ return;+ }+ const next = clampToViewport(+ { left: session.left + move.dx, top: session.top + move.dy },+ session.width,+ session.height,+ viewport(),+ );+ session.lastLeft = next.left;+ session.lastTop = next.top;+ panel.style.transform = `translate3d(${next.left - session.left}px, ${+ next.top - session.top+ }px, 0)`;+ }, []);++ const paint = useCallback(() => {+ frameRef.current = 0;+ applyPending();+ }, [applyPending]);++ // Hand the offset back to left/top, which React owns between drags. Both are+ // written here as well as through state: the node keeps the exact spot the+ // last frame put it in, so dropping it cannot flash at the old one.+ const settle = useCallback(() => {+ if (frameRef.current) {+ cancelAnimationFrame(frameRef.current);+ frameRef.current = 0;+ }+ // A frame was still owed: fold it in rather than drop it, or letting go+ // mid-flick would land the card a few pixels behind the pointer.+ applyPending();+ const session = sessionRef.current;+ const panel = panelRef.current;+ const moved = Boolean(session && movedRef.current);+ if (panel) {+ if (moved && session) {+ panel.style.left = `${session.lastLeft}px`;+ panel.style.top = `${session.lastTop}px`;+ }+ panel.style.transform = "";+ }+ if (moved && session) {+ const landed = { left: session.lastLeft, top: session.lastTop };+ setPosition(landed);+ // Stored here rather than from an effect on `position`, so only a place+ // the user chose is kept. A reclamp is the window adapting at display+ // time, and persisting one let a small window permanently overwrite a+ // position saved on a large one; the read path clamps anyway.+ store(storageKey, landed);+ }+ sessionRef.current = null;+ setPressing(false);+ setDragging(false);+ }, [applyPending, storageKey]);++ // The press turned into a drag. Pin the panel where it already sits, so the+ // transform offsets from the spot the anchor had it in and the first move+ // does not jump.+ const beginDrag = useCallback((left: number, top: number) => {+ movedRef.current = true;+ setDragging(true);+ setPosition((current) => current ?? { left, top });+ }, []);++ // Records the offset and asks for a frame; the frame does the moving.+ const onMove = useCallback(+ (event: PointerEvent) => {+ const session = sessionRef.current;+ if (!session || session.pointerId !== event.pointerId) return;+ // The button was released somewhere we never saw it: end the drag rather+ // than following the cursor around.+ if (event.buttons === 0) {+ settle();+ return;+ }+ const dx = event.clientX - session.startX;+ const dy = event.clientY - session.startY;+ if (!movedRef.current) {+ if (!passedDragThreshold(dx, dy)) return;+ beginDrag(session.left, session.top);+ }+ // Text selection would otherwise start mid-drag on the pill's label.+ event.preventDefault();+ pendingRef.current = { dx, dy };+ if (!frameRef.current) {+ frameRef.current = requestAnimationFrame(paint);+ }+ },+ [settle, beginDrag, paint],+ );++ const onEnd = useCallback(+ (event: PointerEvent) => {+ const session = sessionRef.current;+ if (session && session.pointerId !== event.pointerId) return;+ settle();+ },+ [settle],+ );++ useEffect(() => {+ if (!pressing) return;+ window.addEventListener("pointermove", onMove, { passive: false });+ window.addEventListener("pointerup", onEnd);+ window.addEventListener("pointercancel", onEnd);+ return () => {+ window.removeEventListener("pointermove", onMove);+ window.removeEventListener("pointerup", onEnd);+ window.removeEventListener("pointercancel", onEnd);+ if (frameRef.current) {+ cancelAnimationFrame(frameRef.current);+ frameRef.current = 0;+ }+ };+ }, [pressing, onMove, onEnd]);++ const justDragged = useCallback(() => {+ const moved = movedRef.current;+ movedRef.current = false;+ return moved;+ }, []);++ return { position, panelRef: attachPanel, startDrag, dragging, justDragged };+}diff --git a/studio/frontend/src/features/loaded-models/use-loaded-models.ts b/studio/frontend/src/features/loaded-models/use-loaded-models.tsnew file mode 100644index 00000000000..10d2f34af57--- /dev/null+++ b/studio/frontend/src/features/loaded-models/use-loaded-models.ts@@ -0,0 +1,268 @@+// 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 { toast } from "@/lib/toast";+import { useCallback, useEffect, useRef, useState } from "react";+import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";+import { ejectLoadedModel, readLoadedModels } from "./loaded-models-api";+import {+ type LoadedModelEntry,+ type LoadedModelSource,+ shortModelLabel,+ withPendingLoads,+} from "./loaded-models-sources";++// Free next to chat's own status poll, still current on a tab switch.+const POLL_INTERVAL_MS = 5000;++const NO_ENTRIES: LoadedModelEntry[] = [];++const ALL_SOURCES: LoadedModelSource[] = ["chat", "image", "video", "stt"];++export type UseLoadedModels = {+ entries: LoadedModelEntry[];+ /** What the polls actually found, whether or not the card is showing it. The+ * card is closed, not deaf: this is how it notices a load it was not told+ * about and honours "Back on the next model load". */+ polledEntries: LoadedModelEntry[];+ /** Row ids with an eject in flight. */+ ejecting: ReadonlySet<string>;+ eject: (entry: LoadedModelEntry) => Promise<void>;+ refresh: () => void;+};++/**+ * Poll every runtime for what it holds. Paused while disabled or hidden.+ *+ * `track` is the narrower of the two: it says whether to RECORD the loads the+ * API calls announce, where `enabled` says whether to show anything. They come+ * apart for a card the user closed, which must still hear the load that reopens+ * it, and for a route the card is hidden on. Only the Settings toggle turns+ * recording off, since that is the one that means "stop telling me".+ */+export function useLoadedModels(+ enabled: boolean,+ track: boolean = enabled,+): UseLoadedModels {+ const [polled, setEntries] = useState<LoadedModelEntry[]>([]);+ // 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);+ // Reported empty rather than cleared: clearing would be a setState in an+ // effect, and the last read is right again the moment the pref returns.+ // Loads announced by the API call itself, so a row appears with the toast+ // rather than up to one poll later.+ const [pending, setPending] = useState<Map<LoadedModelSource, string | null>>(+ () => new Map(),+ );+ const entries = enabled ? withPendingLoads(polled, pending) : NO_ENTRIES;+ const [ejecting, setEjecting] = useState<ReadonlySet<string>>(+ () => new Set<string>(),+ );+ // One read at a time, and none applied after unmount.+ const inFlightRef = useRef(false);+ const mountedRef = useRef(true);+ // Bumped whenever an eject changes the list. A read issued before that lands+ // after it and would otherwise put the ejected row straight back.+ const generationRef = useRef(0);+ // A refresh asked for while one was in flight, so the trailing refresh after+ // an eject is not swallowed by the very read it needs to supersede.+ const pendingRef = useRef(false);++ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);++ // Runtimes whose load has settled but whose row is still the optimistic one.+ // Retired only once a read has landed, so the row never blinks out in the gap+ // between the load finishing and the status that replaces it arriving.+ const settledRef = useRef<Set<LoadedModelSource>>(new Set());+ /**+ * Drop the optimistic rows for loads that have finished, now that a read has+ * replaced them. `unreadable` names the sources that read could say nothing+ * about: retiring those would take away the row for a model that has just+ * finished loading, on the strength of a request that failed. They stay+ * settled, so the next readable poll retires them instead.+ */+ const retireSettled = useCallback((unreadable: LoadedModelSource[] = []) => {+ if (settledRef.current.size === 0) return;+ const done = [...settledRef.current].filter(+ (source) => !unreadable.includes(source),+ );+ if (done.length === 0) return;+ settledRef.current = new Set(+ [...settledRef.current].filter((source) => !done.includes(source)),+ );+ setPending((prev) => {+ const next = new Map(prev);+ for (const source of done) next.delete(source);+ return next.size === prev.size ? prev : next;+ });+ }, []);++ const refreshRef = useRef<() => void>(() => {});+ const refresh = useCallback(() => {+ // Keyed on recording, not showing: a closed card keeps polling so a load+ // started outside this tab, which raises no lifecycle event at all, still+ // brings it back.+ if (!track) return;+ if (inFlightRef.current) {+ // Remember the ask instead of dropping it: the refresh an eject queues+ // collides with the poll it has to correct more often than not.+ pendingRef.current = true;+ return;+ }+ inFlightRef.current = true;+ const generation = generationRef.current;+ // What the card shows now, so a source that fails to answer keeps its rows+ // rather than being read as empty.+ let unreadable: LoadedModelSource[] = [];+ void readLoadedModels(polledRef.current)+ .then((next) => {+ unreadable = next.unreadable;+ if (mountedRef.current && generation === generationRef.current) {+ setEntries(next.entries);+ }+ })+ .catch(() => {+ // The whole read failed, so it is evidence about nothing at all.+ unreadable = ALL_SOURCES;+ })+ .finally(() => {+ inFlightRef.current = false;+ if (pendingRef.current) {+ pendingRef.current = false;+ refreshRef.current();+ return;+ }+ // This read is the one that supersedes them, so retire only once no+ // further read is already queued, and only for the sources it could+ // actually see.+ if (mountedRef.current) retireSettled(unreadable);+ });+ }, [track, retireSettled]);+ useEffect(() => {+ polledRef.current = polled;+ }, [polled]);+ useEffect(() => {+ refreshRef.current = refresh;+ }, [refresh]);++ // Nothing is listening once recording stops, so the terminal event for a load+ // in flight is missed and its optimistic row would come back as one no poll+ // can retire: `withPendingLoads` only yields to a status row for the same+ // runtime, and a failed or since-unloaded load has none. Drop them and let the+ // poll say what is really resident. Keyed on `track`, not `enabled`: a closed+ // card is still recording, and clearing there would throw away the very load+ // that is about to reopen it.+ //+ // Adjusted during render rather than in an effect: React re-runs this render+ // before committing, so the stale rows never reach the DOM, and the guard+ // makes it run once per transition.+ const [wasTracking, setWasTracking] = useState(track);+ if (wasTracking !== track) {+ setWasTracking(track);+ if (!track && pending.size > 0) setPending(new Map());+ }++ // The load call announces itself, so the row and the toast appear together+ // and a finished load is re-read at once instead of on the next tick.+ useEffect(() => {+ if (!track) return;+ return subscribeModelLifecycle(({ runtime, loading, model }) => {+ if (loading) {+ settledRef.current.delete(runtime);+ setPending((prev) => new Map(prev).set(runtime, model));+ return;+ }+ // Kept, not dropped: clearing here and waiting for the read to answer+ // left the card with one row fewer for that gap, and with nothing at all+ // when it was the only one, which read as the row randomly vanishing.+ settledRef.current.add(runtime);+ refresh();+ });+ }, [track, refresh]);++ useEffect(() => {+ if (!track) return;+ refresh();+ const timer = window.setInterval(() => {+ if (document.hidden) return;+ refresh();+ }, POLL_INTERVAL_MS);+ // Pick up a load or unload done in another tab.+ const onWake = () => {+ if (!document.hidden) refresh();+ };+ window.addEventListener("focus", onWake);+ document.addEventListener("visibilitychange", onWake);+ return () => {+ window.clearInterval(timer);+ window.removeEventListener("focus", onWake);+ document.removeEventListener("visibilitychange", onWake);+ };+ }, [track, refresh]);++ const eject = useCallback(+ async (entry: LoadedModelEntry) => {+ setEjecting((prev) => new Set(prev).add(entry.id));+ const label = shortModelLabel(entry.name);+ try {+ const outcome = await ejectLoadedModel(entry);+ if (outcome.status === "stillResident") {+ toast.warning(+ `"${shortModelLabel(outcome.model)}" was loaded while ejecting, so it is still using memory. Eject again to release it.`,+ );+ } 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.`,+ );+ } 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.`);+ generationRef.current += 1;+ if (mountedRef.current) {+ setEntries((prev) => prev.filter((row) => row.id !== entry.id));+ }+ } else if (outcome.status === "replaced") {+ // 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.`,+ );+ } else {+ toast.success(`Ejected ${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;+ if (mountedRef.current) {+ setEntries((prev) => prev.filter((row) => row.id !== entry.id));+ }+ }+ } catch (error: unknown) {+ toast.error(+ error instanceof Error ? error.message : `Failed to eject ${label}`,+ );+ } finally {+ if (mountedRef.current) {+ setEjecting((prev) => {+ const next = new Set(prev);+ next.delete(entry.id);+ return next;+ });+ }+ refresh();+ }+ },+ [refresh],+ );++ return { entries, polledEntries: polled, ejecting, eject, refresh };+}diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsxindex 5a439d1447f..90cd48897cb 100644--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx@@ -134,6 +134,12 @@ interface ModelSelectorProps {externalModels?: ExternalModelOption[];value?: string;defaultValue?: string;+ /**+ * Whether the selection is actually resident. Omitted means "a selection is+ * a load", which is what every caller assumed until an image or video load+ * started evicting the chat model out from under this tick.+ */+ loaded?: boolean;activeGgufVariant?: string | null;activeModelConfig?: PerModelConfig | null;activeGgufContextLength?: number | null;@@ -695,6 +701,7 @@ export function ModelSelector({task,catalog,placeholder,+ loaded,}: ModelSelectorProps) {const [uncontrolledOpen, setUncontrolledOpen] = useState(false);const open = controlledOpen ?? uncontrolledOpen;@@ -703,7 +710,9 @@ export function ModelSelector({const [uncontrolled, setUncontrolled] = useState(defaultValue ?? "");const selected = value ?? uncontrolled;- const isLoaded = selected !== "";+ // A selection is only a load when the caller has not said otherwise: the chat+ // model can be evicted by an image or video load while the pick survives.+ const isLoaded = selected !== "" && (loaded ?? true);const optionById = useMemo(() => {const all = new Map<string, ModelOption>();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 54e2816f4f0..857e25da011 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@@ -22,7 +22,11 @@ import {listScanFolders,removeScanFolder,} from "@/features/chat";-import { useChatRuntimeStore } from "@/features/chat";+import {+ chatModelLoaded,+ isExternalModelId,+ useChatRuntimeStore,+} from "@/features/chat";import type {CachedGgufRepo,CachedModelRepo,@@ -1889,9 +1893,20 @@ export function HubModelPicker({}) {const gpu = useGpuInfo();const inferenceGpu = useInferenceGpuInfo();- // Live model id from the runtime store (backend-mirrored active_model), not the dropdown- // highlight which can be a staged pick. Disables the update action for it.- const loadedModelId = useChatRuntimeStore((s) => s.params.checkpoint);+ // What the backend actually holds, not the dropdown highlight, which can be a+ // staged pick. The selection alone was wrong: an image or video load evicts+ // the chat model and leaves the pick untouched, so its rows kept the "Loaded"+ // badge with nothing resident. Same predicate as the header tick, so the two+ // cannot disagree.+ const selectedCheckpoint = useChatRuntimeStore((s) => s.params.checkpoint);+ const residentCheckpoint = useChatRuntimeStore((s) => s.residentCheckpoint);+ const loadedModelId = chatModelLoaded({+ checkpoint: selectedCheckpoint,+ isExternalModel: isExternalModelId(selectedCheckpoint),+ residentCheckpoint,+ })+ ? selectedCheckpoint+ : undefined;// Loaded GGUF quant of the active model; marks the matching pinned row.const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);// Last-loaded timestamps power the "Recent" sort (vs "Downloaded" = file date).diff --git a/studio/frontend/src/features/settings/hooks/use-published-frame.ts b/studio/frontend/src/features/settings/hooks/use-published-frame.tsnew file mode 100644index 00000000000..3bdae0198bf--- /dev/null+++ b/studio/frontend/src/features/settings/hooks/use-published-frame.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Publish an element's box to the overlay-frame store, so the bottom-right+// stack keeps clear of it. The Live monitor does this by hand inside its own+// layout effect; anything else that must not be covered uses this.++import { useEffect, useMemo } from "react";++import { useMonitorFrameStore } from "../stores/monitor-frame-store";++/**+ * Keep the corner stack off `element` for as long as it is mounted.+ *+ * The chat composer is the case this exists for: it docks to the bottom of the+ * viewport once a thread has turns, in the same column the stack occupies, and+ * the loaded models card is the first overlay there that is persistent rather+ * than transient. It sat over the Send button and swallowed the click.+ *+ * Re-measured on resize and through a ResizeObserver, because the composer+ * grows with its input and moves from centred to docked with no resize event.+ */+export function usePublishedFrame(element: HTMLElement | null): void {+ // This caller's claim on the store, stable for the life of the component.+ const publisher = useMemo(() => ({}), []);+ const setFrame = useMonitorFrameStore((state) => state.setFrame);+ const clearFrame = useMonitorFrameStore((state) => state.clearFrame);++ useEffect(() => {+ if (!element) {+ clearFrame(publisher);+ return;+ }+ const measure = () => {+ const box = element.getBoundingClientRect();+ // A hidden composer measures 0x0; publishing that would pin the stack to+ // the top-left corner rather than leave it where it belongs.+ if (box.width === 0 && box.height === 0) {+ clearFrame(publisher);+ return;+ }+ setFrame(publisher, {+ left: box.left,+ top: box.top,+ right: box.right,+ bottom: box.bottom,+ });+ };+ measure();+ window.addEventListener("resize", measure);+ const observer =+ typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);+ observer?.observe(element);+ return () => {+ window.removeEventListener("resize", measure);+ observer?.disconnect();+ clearFrame(publisher);+ };+ }, [element, publisher, setFrame, clearFrame]);+}diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.tsindex 6a9b838af72..a6d908733fc 100644--- a/studio/frontend/src/features/settings/index.ts+++ b/studio/frontend/src/features/settings/index.ts@@ -44,6 +44,15 @@ export type {SidebarNavItemPref,} from "./stores/appearance-custom-store";export { useMonitorOverlayStore } from "./stores/monitor-overlay-store";+export {+ type MonitorFrame,+ type StackGeometry,+ stackBottomInset,+ stackGeometry,+ stackMaxHeight,+ useMonitorFrameStore,+ useStackGeometry,+} from "./stores/monitor-frame-store";export type {Personalization,PersonalizationAppearance,diff --git a/studio/frontend/src/features/settings/stores/monitor-frame-store.ts b/studio/frontend/src/features/settings/stores/monitor-frame-store.tsnew file mode 100644index 00000000000..93ad8a10c10--- /dev/null+++ b/studio/frontend/src/features/settings/stores/monitor-frame-store.ts@@ -0,0 +1,184 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// What the bottom-right overlay stack has to keep clear of, in viewport+// coordinates. The Live monitor is draggable and resizable and defaults to that+// same corner; the chat composer docks to the bottom of the same column once a+// thread has turns. Each publishes its box here while it is mounted.++import { useEffect, useMemo, useState } from "react";+import { create } from "zustand";++export type MonitorFrame = {+ left: number;+ top: number;+ right: number;+ bottom: number;+};++/**+ * Whose box this is. Identity matters twice over: reopening the monitor during+ * its exit animation leaves two panels mounted at once and the one on its way+ * out unmounts last, so its cleanup must clear only its own; and the monitor+ * and the composer are published side by side.+ */+export type MonitorFramePublisher = object;++interface MonitorFrameState {+ /** Every published box, kept apart. Deliberately not merged into one: the+ * rectangle around a left-hand monitor and a bottom-right composer spans+ * the empty space between them, and reading that as a single obstacle+ * lifted the stack to its cap for a monitor nowhere near its column.+ * `stackGeometry` folds them one at a time. */+ frames: ReadonlyMap<MonitorFramePublisher, MonitorFrame>;+ setFrame: (publisher: MonitorFramePublisher, frame: MonitorFrame) => void;+ /** Drops only this publisher's box; the others still count. */+ clearFrame: (publisher: MonitorFramePublisher) => void;+}++function sameFrame(a: MonitorFrame | null, b: MonitorFrame | null): boolean {+ if (a === null || b === null) return a === b;+ return (+ a.left === b.left &&+ a.top === b.top &&+ a.right === b.right &&+ a.bottom === b.bottom+ );+}++export const useMonitorFrameStore = create<MonitorFrameState>((set) => ({+ frames: new Map(),+ // Written from a layout effect on every reconcile, so no-op writes must not+ // notify: the overlay stack re-renders on this.+ setFrame: (publisher, frame) =>+ set((state) => {+ if (sameFrame(state.frames.get(publisher) ?? null, frame)) return state;+ return { frames: new Map(state.frames).set(publisher, frame) };+ }),+ clearFrame: (publisher) =>+ set((state) => {+ if (!state.frames.has(publisher)) return state;+ const frames = new Map(state.frames);+ frames.delete(publisher);+ return { frames };+ }),+}));++// The corner stack's own inset, and the gap left between it and the monitor.+const STACK_INSET = 16;+const STACK_GAP = 8;+// Widest overlay the stack holds: the update banners, at max-w-[448px].+const STACK_WIDTH = 448;+// Never lift so far that the stack itself is pushed off the top.+const MIN_STACK_ROOM = 120;++/**+ * How far above the bottom edge the overlay stack must sit to clear the Live+ * monitor. The monitor defaults to the same corner, so without this the+ * update banners, the download panel and the loaded models card all land+ * underneath it.+ */+/** Whether the monitor overlaps the column the stack's overlays occupy. */+function inStackColumn(frame: MonitorFrame, viewportWidth: number): boolean {+ const columnLeft = viewportWidth - STACK_INSET - STACK_WIDTH;+ return (+ frame.right > columnLeft && frame.left < viewportWidth - STACK_INSET+ );+}++export function stackBottomInset(+ frame: MonitorFrame | null,+ viewportWidth: number,+ viewportHeight: number,+): number {+ if (!frame) return STACK_INSET;+ // Only dodge a monitor that is actually in the stack's column and low+ // enough to be in its way; one dragged elsewhere leaves the corner free.+ const lowEnough = frame.bottom > viewportHeight / 2;+ if (!(inStackColumn(frame, viewportWidth) && lowEnough)) return STACK_INSET;+ const lifted = viewportHeight - frame.top + STACK_GAP;+ return Math.max(+ STACK_INSET,+ Math.min(lifted, viewportHeight - MIN_STACK_ROOM),+ );+}++/**+ * How tall the stack may grow while sitting on `bottomInset`, keeping its own+ * margin at the top. Lifting the stack over the monitor shortens it by the same+ * amount, or a long download list plus the card runs off the top of the screen.+ *+ * A monitor parked high in the same column is not lifted over, because the free+ * space is underneath it. It still has to be dodged: the stack grows upwards+ * from the bottom, and a full download list plus the card is easily tall enough+ * to reach it. Cap the height at the gap below it instead.+ */+export function stackMaxHeight(+ frame: MonitorFrame | null,+ viewportWidth: number,+ viewportHeight: number,+ bottomInset: number,+): number {+ const ownMargin = viewportHeight - bottomInset - STACK_INSET;+ if (!frame || !inStackColumn(frame, viewportWidth)) return ownMargin;+ if (frame.bottom > viewportHeight / 2) return ownMargin;+ const belowMonitor = viewportHeight - bottomInset - frame.bottom - STACK_GAP;+ return Math.max(MIN_STACK_ROOM, Math.min(ownMargin, belowMonitor));+}++export type StackGeometry = { bottom: number; maxHeight: number };++/**+ * Where the overlay stack sits and how tall it may be, given everything it has+ * to keep clear of.+ *+ * Folded per box, never over their union: a tall monitor and the wide docked+ * composer share almost no area, and the rectangle around the pair covers most+ * of the viewport. Reading that as one obstacle pinned the stack to the top of+ * the screen and put it back over the monitor it was dodging. Each box asks for+ * the lift it needs; the stack takes the largest, and the shortest height.+ */+export function stackGeometry(+ frames: MonitorFrame | null | readonly MonitorFrame[],+ viewportWidth: number,+ viewportHeight: number,+): StackGeometry {+ const list = frames === null ? [] : Array.isArray(frames) ? frames : [frames];+ if (list.length === 0) {+ const bottom = stackBottomInset(null, viewportWidth, viewportHeight);+ return {+ bottom,+ maxHeight: stackMaxHeight(null, viewportWidth, viewportHeight, bottom),+ };+ }+ const bottom = Math.max(+ ...list.map((f) => stackBottomInset(f, viewportWidth, viewportHeight)),+ );+ return {+ bottom,+ maxHeight: Math.min(+ ...list.map((f) =>+ stackMaxHeight(f, viewportWidth, viewportHeight, bottom),+ ),+ ),+ };+}++/** `stackGeometry` in px, recomputed as the monitor moves or resizes. */+export function useStackGeometry(): StackGeometry {+ const frames = useMonitorFrameStore((state) => state.frames);+ // Every published box, not their union: see stackGeometry.+ const published = useMemo(() => [...frames.values()], [frames]);+ const [viewport, setViewport] = useState(() => ({+ width: typeof window === "undefined" ? 0 : window.innerWidth,+ height: typeof window === "undefined" ? 0 : window.innerHeight,+ }));+ useEffect(() => {+ const onResize = () =>+ setViewport({ width: window.innerWidth, height: window.innerHeight });+ onResize();+ window.addEventListener("resize", onResize);+ return () => window.removeEventListener("resize", onResize);+ }, []);+ return stackGeometry(published, viewport.width, viewport.height);+}diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex 3e28cff31b1..1c9ac43141e 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -15,6 +15,11 @@ import { Switch } from "@/components/ui/switch";import { usePlatformStore } from "@/config/env";import { resetOnboardingDone } from "@/features/auth";import { PermissionModeDropdown, useChatRuntimeStore } from "@/features/chat";+import {+ LOADED_MODELS_PREFERENCE_KEYS,+ setShowLoadedModels,+ useShowLoadedModels,+} from "@/features/loaded-models";import {emitTrainingRunsChanged,TRAINING_UI_PREFERENCE_KEYS,@@ -125,6 +130,10 @@ const PREFS_KEYS: string[] = [// Update notifications"unsloth_show_llama_update_banner","unsloth_monitor_overlay",+ LOADED_MODELS_PREFERENCE_KEYS.show,+ LOADED_MODELS_PREFERENCE_KEYS.collapsed,+ LOADED_MODELS_PREFERENCE_KEYS.position,+ LOADED_MODELS_PREFERENCE_KEYS.dismissed,// Voice settings"unsloth_voice_settings",];@@ -163,6 +172,7 @@ export function GeneralTab() {const setHfToken = useChatRuntimeStore((s) => s.setHfToken);const chatOnly = usePlatformStore((s) => s.chatOnly);const showLlamaUpdates = useShowLlamaUpdateBanner();+ const showLoadedModels = useShowLoadedModels();const redirectTo = `${pathname}${search}`;const [draftToken, setDraftToken] = useState(hfToken ?? "");@@ -647,6 +657,17 @@ export function GeneralTab() {) : null}<SettingsSection title={t("settings.general.notifications.sectionTitle")}>+ <SettingsRow+ label={t("settings.general.notifications.showLoadedModels")}+ description={t(+ "settings.general.notifications.showLoadedModelsDescription",+ )}+ >+ <Switch+ checked={showLoadedModels}+ onCheckedChange={setShowLoadedModels}+ />+ </SettingsRow><SettingsRowlabel={t("settings.general.notifications.showLlamaUpdates")}description={t(diff --git a/studio/frontend/src/features/studio/wizard/training-wizard.tsx b/studio/frontend/src/features/studio/wizard/training-wizard.tsxindex 49fed072881..3e4c833efed 100644--- a/studio/frontend/src/features/studio/wizard/training-wizard.tsx+++ b/studio/frontend/src/features/studio/wizard/training-wizard.tsx@@ -29,7 +29,7 @@ import { useT } from "@/i18n";import { cn } from "@/lib/utils";import type { TrainingMethod } from "@/types/training";import {- BrainIcon,+ AiBrain01Icon,Database02Icon,FloppyDiskIcon,Settings05Icon,@@ -286,7 +286,7 @@ export function TrainingWizard({<SectionBoxtitle={t("studio.wizard.modelTitle")}description={t("studio.wizard.modelDescription")}- icon={BrainIcon}+ icon={AiBrain01Icon}chipTint="var(--chart-1)"><ModelPanel />diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.tsindex 0eba907b8be..e8ce11858ef 100644--- a/studio/frontend/src/features/video/api.ts+++ b/studio/frontend/src/features/video/api.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 { withBackgroundLoadNotice } from "@/lib/model-lifecycle-events";import { authFetch } from "@/features/auth";// Same plan shape as the images backend: both /download-plan routes share a response model.import type { DiffusionDownloadPlan } from "@/features/images/api";@@ -159,12 +160,18 @@ async function parseJson<T>(response: Response): Promise<T> {return (await response.json()) as T;}-export async function getVideoStatus(): Promise<VideoStatus> {- return parseJson(await authFetch("/api/inference/video/status"));+export async function getVideoStatus(+ signal?: AbortSignal,+): Promise<VideoStatus> {+ return parseJson(await authFetch("/api/inference/video/status", { signal }));}-export async function getVideoLoadProgress(): Promise<VideoLoadProgress> {- return parseJson(await authFetch("/api/inference/video/load-progress"));+export async function getVideoLoadProgress(+ signal?: AbortSignal,+): Promise<VideoLoadProgress> {+ return parseJson(+ await authFetch("/api/inference/video/load-progress", { signal }),+ );}export async function getVideoGenerateProgress(): Promise<VideoGenerateProgress> {@@ -172,12 +179,20 @@ export async function getVideoGenerateProgress(): Promise<VideoGenerateProgress>}export async function loadVideoModel(body: VideoLoadRequest): Promise<VideoStatus> {- return parseJson(- await authFetch("/api/inference/video/load", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- }),+ // Announced so the indicator shows the load while the toast does, and settled+ // from load-progress because this POST only starts it. See images.+ return withBackgroundLoadNotice(+ "video",+ body.model_path,+ async () =>+ parseJson<VideoStatus>(+ await authFetch("/api/inference/video/load", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ }),+ ),+ async (signal) => (await getVideoLoadProgress(signal)).phase,);}diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex dd2bd832a0f..a09f61d590b 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -73,6 +73,7 @@ import {routedGgufLabel,} from "@/lib/diffusion-route-search";import { toast } from "@/lib/toast";+import { subscribeModelEjected } from "@/lib/model-lifecycle-events";import {type GalleryVideo,@@ -646,6 +647,24 @@ function VideoGenerator({ active = true }: { active?: boolean }) {loadToastId.current = null;}, []);+ // Client-side state that only means anything while a model is resident: the+ // in-flight replacement load's tracking, and the Reapply target. Shared with+ // the indicator eject, which frees the runtime without going through the+ // page's own Unload.+ const dropResidentState = useCallback(() => {+ // Cancel, not release: a resolving pick or a staged download would load+ // back what was just ejected. In here rather than only in handleUnload, so+ // an eject driven from the loaded models card is covered by it too.+ pickGuard.cancel();+ if (pollTimer.current) clearTimeout(pollTimer.current);+ pollTimer.current = null;+ dismissLoadToast();+ lastLoadSig.current = null;+ // Leaving this set would let Reapply reload the model that was just freed.+ lastLoad.current = null;+ setCanReapply(false);+ }, [dismissLoadToast, pickGuard]);+// Mirror to the module cache so a tab switch re-renders instantly.useEffect(() => {galleryCache.videos = videos;@@ -925,13 +944,26 @@ function VideoGenerator({ active = true }: { active?: boolean }) {[resolutionPresets, durationOptions],);+ // A status read started before an eject can answer after the one that+ // followed it, and this page has no periodic poll to correct it: the controls+ // would go on offering to generate against a runtime that is already free.+ // So every read takes a ticket and only the newest may write.+ const statusTicket = useRef(0);+ const setStatusIfNewest = useCallback(+ (ticket: number, next: VideoStatus) => {+ if (ticket === statusTicket.current) setStatus(next);+ },+ [],+ );+const refreshStatus = useCallback(async () => {+ const ticket = ++statusTicket.current;try {- setStatus(await getVideoStatus());+ setStatusIfNewest(ticket, await getVideoStatus());} catch {// Status is best-effort; a failed poll shouldn't surface an error toast.}- }, []);+ }, [setStatusIfNewest]);// Track mount so a long generate stops issuing GPU work when the page is truly unmounted.useEffect(() => {@@ -949,6 +981,28 @@ function VideoGenerator({ active = true }: { active?: boolean }) {})();}, [active, refreshStatus]);+ // Ejected from the loaded models indicator, which does not run handleUnload:+ // without this the controls keep offering to generate on a freed runtime, and+ // Reapply still points at the model that was just ejected. The runtime is+ // already free, so this is handleUnload without the unload call.+ useEffect(+ () =>+ subscribeModelEjected("video", () => {+ dropResidentState();+ // That eject cancelled the replacement load, and its progress poll is+ // the only thing that clears `busy` -- which dropResidentState has just+ // stopped. Leaving it set locks the page: the picker ignores every+ // choice while busy, and Unload is not offered once the status read+ // comes back empty, so only an app reload recovered. Narrowed to+ // "loading" so a generation in flight is left alone, as handleUnload's+ // own finally does.+ setBusy((prev) => (prev === "loading" ? null : prev));+ setQuant(null);+ void refreshStatus();+ }),+ [refreshStatus, dropResidentState],+ );+// Collapse the body-ported model selector when leaving the tab so returning to /video does not pop it back open unprompted.useEffect(() => {if (active) return;@@ -961,7 +1015,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {const p = await getVideoLoadProgress();if (p.phase === "ready") {dismissLoadToast();- setStatus(await getVideoStatus());+ setStatusIfNewest(++statusTicket.current, await getVideoStatus());toast.success("Model loaded");setBusy(null);quantRevert.current = null;@@ -1503,17 +1557,10 @@ function VideoGenerator({ active = true }: { active?: boolean }) {);const handleUnload = useCallback(async () => {- // Cancel, not release: a resolving pick or a staged download would load back what was just ejected.- pickGuard.cancel();- if (pollTimer.current) clearTimeout(pollTimer.current);- pollTimer.current = null;- dismissLoadToast();- lastLoadSig.current = null;- lastLoad.current = null;- setCanReapply(false);+ dropResidentState();setBusy("unloading");try {- setStatus(await unloadVideoModel());+ setStatusIfNewest(++statusTicket.current, await unloadVideoModel());setQuant(null);} catch (err) {toast.error(err instanceof Error ? err.message : "Failed to unload model");@@ -1521,7 +1568,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {} finally {setBusy(null);}- }, [refreshStatus, dismissLoadToast, pickGuard]);+ }, [refreshStatus, dropResidentState]);const handleCancelGenerate = useCallback(async () => {try {diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 5b991aa135f..6af97686066 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -401,6 +401,9 @@ export const ar = {showLlamaUpdates: "إشعارات تحديث llama.cpp",showLlamaUpdatesDescription:"التنبيه عند توفر إصدار أحدث من llama.cpp لتشغيل نماذج جديدة. أوقف التشغيل إذا كنت تُدرّب فقط.",+ showLoadedModels: "مؤشر النماذج المحمّلة",+ showLoadedModelsDescription:+ "إظهار بطاقة صغيرة في الزاوية السفلية اليمنى تعرض كل نموذج موجود حاليًا في الذاكرة (الدردشة، الكلام، الصور، الفيديو)، مع زر لإخراج كل منها.",},startup: {sectionTitle: "بدء التشغيل",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 70905e0bb8d..63de4631956 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -418,6 +418,9 @@ export const de = {showLlamaUpdates: "llama.cpp-Update-Benachrichtigungen",showLlamaUpdatesDescription:"Benachrichtigt, wenn ein neuerer llama.cpp-Build verfügbar ist, um neue Modelle auszuführen. Deaktivieren Sie dies, wenn Sie nur trainieren.",+ showLoadedModels: "Anzeige geladener Modelle",+ showLoadedModelsDescription:+ "Zeigt unten rechts eine kleine Karte mit allen derzeit im Speicher befindlichen Modellen (Chat, Sprache, Bild, Video) und einer Schaltfläche, um jedes einzeln zu entladen.",},startup: {sectionTitle: "Autostart",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 1e9042c4332..15e4eecce68 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -400,6 +400,9 @@ export const en = {showLlamaUpdates: "llama.cpp update notifications",showLlamaUpdatesDescription:"Notify when a newer llama.cpp build is available to run new models. Turn off if you only train.",+ showLoadedModels: "Loaded models indicator",+ showLoadedModelsDescription:+ "Show a small card in the bottom-right corner listing every model currently in memory (chat, speech, image, video), with a button to eject each one.",},startup: {sectionTitle: "Startup",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex aafff3ddd82..c804a06237d 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -414,6 +414,9 @@ export const es = {showLlamaUpdates: "Notificaciones de actualización de llama.cpp",showLlamaUpdatesDescription:"Avisa cuando haya una compilación más reciente de llama.cpp para ejecutar nuevos modelos. Desactívalo si solo entrenas.",+ showLoadedModels: "Indicador de modelos cargados",+ showLoadedModelsDescription:+ "Muestra una pequeña tarjeta en la esquina inferior derecha con todos los modelos actualmente en memoria (chat, voz, imagen, vídeo), con un botón para expulsar cada uno.",},startup: {sectionTitle: "Inicio",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 3e460ce9fea..64c6393f983 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -416,6 +416,9 @@ export const fr = {showLlamaUpdates: "Notifications de mise à jour de llama.cpp",showLlamaUpdatesDescription:"Notifier lorsqu'une nouvelle version de llama.cpp est disponible pour exécuter de nouveaux modèles. Désactivez si vous ne faites que de l'entraînement.",+ showLoadedModels: "Indicateur des modèles chargés",+ showLoadedModelsDescription:+ "Affiche une petite carte en bas à droite listant tous les modèles actuellement en mémoire (chat, voix, image, vidéo), avec un bouton pour éjecter chacun d'eux.",},startup: {sectionTitle: "Démarrage",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 0d28ced3177..02168000a1c 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -404,6 +404,9 @@ export const hi = {showLlamaUpdates: "llama.cpp अपडेट सूचनाएं",showLlamaUpdatesDescription:"नए मॉडल चलाने के लिए जब कोई नया llama.cpp बिल्ड उपलब्ध हो तो सूचित करें। यदि आप केवल ट्रेन करते हैं तो बंद कर दें।",+ showLoadedModels: "लोड किए गए मॉडल का संकेतक",+ showLoadedModelsDescription:+ "नीचे दाएं कोने में एक छोटा कार्ड दिखाएं जिसमें वर्तमान में मेमोरी में मौजूद हर मॉडल (चैट, स्पीच, इमेज, वीडियो) सूचीबद्ध हो, और हर एक को हटाने के लिए एक बटन हो।",},startup: {sectionTitle: "स्टार्टअप",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex d0eb6001fb2..2e1c412fba6 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -391,6 +391,9 @@ export const it = {showLlamaUpdates: "Notifiche di aggiornamento di llama.cpp",showLlamaUpdatesDescription:"Avvisa quando è disponibile una build più recente di llama.cpp per eseguire nuovi modelli. Disattiva le notifiche se usi Unsloth solo per l'addestramento.",+ showLoadedModels: "Indicatore dei modelli caricati",+ showLoadedModelsDescription:+ "Mostra una piccola scheda in basso a destra con tutti i modelli attualmente in memoria (chat, voce, immagini, video), con un pulsante per rimuovere ciascuno.",},startup: {sectionTitle: "Avvio",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex f1f146c07e0..97bda39a814 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -392,6 +392,8 @@ export const ja = {sectionTitle: "通知",showLlamaUpdates: "llama.cpp のアップデート通知",showLlamaUpdatesDescription: "新しいモデルを実行するための新しい llama.cpp ビルドが利用可能になったときに通知します。トレーニングのみを行う場合はオフにしてください。",+ showLoadedModels: "読み込み済みモデルのインジケーター",+ showLoadedModelsDescription: "現在メモリ上にあるすべてのモデル(チャット、音声、画像、動画)を一覧表示する小さなカードを右下に表示します。各モデルを解放するボタンが付いています。",},startup: {sectionTitle: "起動",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 3c696d88593..89051d7dfcd 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -398,6 +398,9 @@ export const ko = {showLlamaUpdates: "llama.cpp 업데이트 알림",showLlamaUpdatesDescription:"새 모델을 실행할 수 있는 최신 llama.cpp 빌드가 있으면 알립니다. 학습만 사용한다면 끄세요.",+ showLoadedModels: "로드된 모델 표시기",+ showLoadedModelsDescription:+ "현재 메모리에 있는 모든 모델(채팅, 음성, 이미지, 비디오)을 오른쪽 아래 작은 카드에 표시하고, 각각을 해제하는 버튼을 제공합니다.",},startup: {sectionTitle: "시작",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex e13569e0e38..96cefd9cdf2 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -405,6 +405,9 @@ export const ptBR = {showLlamaUpdates: "Notificações de atualização do llama.cpp",showLlamaUpdatesDescription:"Notifica quando uma versão mais recente do llama.cpp está disponível para executar novos modelos. Desative se você só treina modelos.",+ showLoadedModels: "Indicador de modelos carregados",+ showLoadedModelsDescription:+ "Mostra um pequeno cartão no canto inferior direito listando todos os modelos atualmente na memória (chat, fala, imagem, vídeo), com um botão para liberar cada um.",},startup: {sectionTitle: "Inicialização",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 5477d6f468d..4a2ac3a13e0 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -403,6 +403,9 @@ export const ru = {showLlamaUpdates: "Уведомления об обновлениях llama.cpp",showLlamaUpdatesDescription:"Уведомлять о доступности новой сборки llama.cpp для запуска новых моделей. Отключите, если вы только обучаете модели.",+ showLoadedModels: "Индикатор загруженных моделей",+ showLoadedModelsDescription:+ "Показывает в правом нижнем углу небольшую карточку со всеми моделями, находящимися сейчас в памяти (чат, речь, изображения, видео), и кнопку для выгрузки каждой из них.",},startup: {sectionTitle: "Автозапуск",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 0f23f790f04..cfe84b9af3b 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -385,6 +385,9 @@ export const zhCN = {showLlamaUpdates: "llama.cpp 更新通知",showLlamaUpdatesDescription:"当有可用于运行新模型的新版 llama.cpp 构建时通知你。如果只进行训练,可以关闭此项。",+ showLoadedModels: "已加载模型指示器",+ showLoadedModelsDescription:+ "在右下角显示一张小卡片,列出当前位于内存中的所有模型(聊天、语音、图像、视频),并为每个模型提供卸载按钮。",},startup: {sectionTitle: "启动",diff --git a/studio/frontend/src/lib/model-lifecycle-events.ts b/studio/frontend/src/lib/model-lifecycle-events.tsnew file mode 100644index 00000000000..a1a9588eb2c--- /dev/null+++ b/studio/frontend/src/lib/model-lifecycle-events.ts@@ -0,0 +1,214 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// One announcement per model load or release, raised from the API call itself+// so every caller is covered without each page remembering to.+//+// Two things listen. The Images and Video pages hold their own `status` and+// re-read it on tab activation rather than on a timer, so a release from+// anywhere else leaves their controls claiming a model is still loaded. And the+// loaded models indicator polls every 5s, which is long enough that a load+// looked like it had not started: the toast said "loading" while the card said+// nothing. Both now hear the moment it happens.+//+// In lib/, not a feature, since the emitters and the listeners are both features.++export const MODEL_EJECTED_EVENT = "unsloth:model-ejected";+export const MODEL_LIFECYCLE_EVENT = "unsloth:model-lifecycle";++/** Which runtime was released. Only these two own a page holding its status. */+export type EjectedModelRuntime = "image" | "video";++/** Every runtime the indicator lists. */+export type ModelRuntime = "chat" | "image" | "video" | "stt";++export type ModelLifecycle = {+ runtime: ModelRuntime;+ /** True while the load is in flight, false once it settled either way. */+ loading: boolean;+ /** What is being loaded, for the row shown before any status confirms it. */+ model: string | null;+};++export function notifyModelEjected(runtime: EjectedModelRuntime): void {+ if (typeof window === "undefined") return;+ window.dispatchEvent(+ new CustomEvent(MODEL_EJECTED_EVENT, { detail: { runtime } }),+ );+}++/** Calls back when `runtime` is released elsewhere. Returns an unsubscriber. */+export function subscribeModelEjected(+ runtime: EjectedModelRuntime,+ onEjected: () => void,+): () => void {+ if (typeof window === "undefined") return () => {};+ const handler = (event: Event) => {+ const detail = (event as CustomEvent<{ runtime?: string }>).detail;+ if (detail?.runtime === runtime) onEjected();+ };+ window.addEventListener(MODEL_EJECTED_EVENT, handler);+ return () => window.removeEventListener(MODEL_EJECTED_EVENT, handler);+}++export function notifyModelLifecycle(detail: ModelLifecycle): void {+ if (typeof window === "undefined") return;+ window.dispatchEvent(new CustomEvent(MODEL_LIFECYCLE_EVENT, { detail }));+}++/** Calls back on every load start and finish, whichever runtime. */+export function subscribeModelLifecycle(+ onChange: (detail: ModelLifecycle) => void,+): () => void {+ if (typeof window === "undefined") return () => {};+ const handler = (event: Event) => {+ const detail = (event as CustomEvent<ModelLifecycle>).detail;+ if (detail?.runtime) onChange(detail);+ };+ window.addEventListener(MODEL_LIFECYCLE_EVENT, handler);+ return () => window.removeEventListener(MODEL_LIFECYCLE_EVENT, handler);+}++/**+ * Announce a load around `run`, so the indicator shows it for the whole time+ * the toast does. Settles on failure too, or a failed load would leave the row+ * spinning until the next poll disagreed.+ */+export async function withModelLoadNotice<T>(+ runtime: ModelRuntime,+ model: string | null,+ run: () => Promise<T>,+): Promise<T> {+ notifyModelLifecycle({ runtime, loading: true, model });+ try {+ return await run();+ } finally {+ notifyModelLifecycle({ runtime, loading: false, model });+ }+}++/**+ * What a `load-progress` endpoint reports. `null` is terminal once a load has+ * started: all three engines return it only for "nothing loading and nothing+ * loaded", and `begin_load` records its loading state before the POST answers,+ * so a read before the first byte moves says `downloading`. It is what a+ * cancelled or evicted load leaves behind -- the Images page's own poll treats+ * it the same way, and must, "else this loop spins forever".+ */+export type LoadPhase = "downloading" | "finalizing" | "ready" | "error" | null;++/** How often the settle poll asks; overridable so a test need not sleep. */+export const BACKGROUND_LOAD_POLL_MS = 2000;+/** Well past a healthy load-progress read, so only a real hang trips it. */+export const BACKGROUND_READ_TIMEOUT_MS = 10_000;+/**+ * How long a run of unreadable polls may last before the row is retired. Timed+ * from the last healthy read rather than from the start of the load: a 100 GB+ * video checkpoint on a slow link legitimately takes hours, and an absolute+ * deadline would have hidden a download that was still visibly progressing.+ */+export const BACKGROUND_STALL_TIMEOUT_MS = 60 * 60 * 1000;++/** Cadences, all optional: the defaults are what production uses. */+export type BackgroundLoadTiming = {+ pollMs?: number;+ readTimeoutMs?: number;+ stallMs?: number;+};++/**+ * The same announcement for the two loads that only *start* the work: images+ * and video hand off to a background thread and return at once, while /status+ * keeps reporting `loaded: false` for the whole load. Settling on the POST would+ * flash the row for one round trip and then drop it, leaving the toast saying+ * "loading" alone for minutes -- the very gap this notice exists to close.+ *+ * So settle from the same `load-progress` endpoint the page toast watches. The+ * poll belongs to the load call rather than to a page, so the row still settles+ * when the user navigates away mid-load.+ */+export async function withBackgroundLoadNotice<T>(+ runtime: ModelRuntime,+ model: string | null,+ start: () => Promise<T>,+ readPhase: (signal: AbortSignal) => Promise<LoadPhase>,+ timing: BackgroundLoadTiming = {},+): Promise<T> {+ notifyModelLifecycle({ runtime, loading: true, model });+ let started = false;+ try {+ const result = await start();+ started = true;+ // Announce a second time, now that the POST has returned. That is the+ // instant the GPU arbiter has committed: acquire_for evicts whoever held+ // the GPU inside this call, ahead of a download that can run for hours, so+ // the first announcement was raised while the status it displaces was still+ // correct. Listeners that re-read another runtime need this edge, and the+ // rows this drives are keyed by runtime, so a repeat is a no-op for them.+ notifyModelLifecycle({ runtime, loading: true, model });+ void settleWhenLoadEnds(runtime, model, readPhase, timing);+ return result;+ } finally {+ // A load that never started settles here; one that did settles from the+ // poll, so exactly one of the two paths ends the notice.+ if (!started) notifyModelLifecycle({ runtime, loading: false, model });+ }+}++async function settleWhenLoadEnds(+ runtime: ModelRuntime,+ model: string | null,+ readPhase: (signal: AbortSignal) => Promise<LoadPhase>,+ timing: BackgroundLoadTiming,+): Promise<void> {+ const pollMs = timing.pollMs ?? BACKGROUND_LOAD_POLL_MS;+ const readTimeoutMs = timing.readTimeoutMs ?? BACKGROUND_READ_TIMEOUT_MS;+ const stallMs = timing.stallMs ?? BACKGROUND_STALL_TIMEOUT_MS;+ let lastHealthy = Date.now();+ try {+ for (;;) {+ await new Promise((resolve) => setTimeout(resolve, pollMs));+ // An unreadable read is not proof the load ended: a restarting backend or+ // one dropped request would end the row early and hide a live load. That+ // is `undefined`, kept distinct from the `null` phase precisely so the two+ // are not conflated here.+ const phase = await boundedRead(readPhase, readTimeoutMs);+ if (phase === undefined) {+ // Only a sustained run of unreadable polls gives up. A load that is+ // still reporting progress is never abandoned, however long it takes.+ if (Date.now() - lastHealthy >= stallMs) return;+ continue;+ }+ if (phase !== "downloading" && phase !== "finalizing") return;+ lastHealthy = Date.now();+ }+ } finally {+ notifyModelLifecycle({ runtime, loading: false, model });+ }+}++/**+ * One read, abandoned if it does not answer. A backend that accepts the+ * connection and never replies would otherwise park this `await` forever, so+ * the loop would never test its deadline again and the row would stay loading+ * for the life of the tab -- the deadline only bounds the loop if every turn of+ * it terminates.+ *+ * A plain AbortController rather than AbortSignal.timeout, which the older+ * WebKitGTK builds Tauri embeds do not have.+ */+async function boundedRead(+ readPhase: (signal: AbortSignal) => Promise<LoadPhase>,+ readTimeoutMs: number,+): Promise<LoadPhase | undefined> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), readTimeoutMs);+ try {+ return await readPhase(controller.signal);+ } catch {+ return undefined;+ } finally {+ clearTimeout(timer);+ }+}+diff --git a/studio/frontend/src/lib/sparkle-icon.ts b/studio/frontend/src/lib/sparkle-icon.tsnew file mode 100644index 00000000000..66690b1e579--- /dev/null+++ b/studio/frontend/src/lib/sparkle-icon.ts@@ -0,0 +1,25 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { IconSvgElement } from "@hugeicons/react";++// Hugeicons "Sparkle" (stroke-rounded): one four-point star, not the two-star+// "Sparkles". https://hugeicons.com/icon/sparkle+//+// Local because @hugeicons/core-free-icons 4.1.1 predates it, and pulling a+// newer icon set in would move every other glyph in the app for one shape. The+// path is the published stroke-rounded outline with its fixed #141B34 stroke+// swapped for currentColor, the same as the other icons in lib/.+export const SparkleIcon: IconSvgElement = [+ [+ "path",+ {+ d: "M10.5279 7.13967C11.3077 5.71322 11.6977 5 11.9958 5C12.294 5 12.6839 5.71322 13.4638 7.13967C14.2665 8.60787 15.3392 9.69316 16.8489 10.52C18.2778 11.3026 18.9922 11.6938 18.9922 11.9923C18.9922 12.2908 18.2773 12.6825 16.8475 13.4658C15.3808 14.2693 14.2966 15.3432 13.4706 16.8545C12.6889 18.2848 12.298 19 11.9998 19C11.7017 19 11.3104 18.2844 10.5279 16.853C9.7252 15.3848 8.65247 14.2995 7.14272 13.4727C5.70903 12.6875 4.99219 12.2949 4.99219 11.9964C4.99219 11.6978 5.70903 11.3052 7.14272 10.52C8.65247 9.69316 9.7252 8.60787 10.5279 7.13967Z",+ stroke: "currentColor",+ strokeLinecap: "round",+ strokeLinejoin: "round",+ strokeWidth: "1.5",+ key: "0",+ },+ ],+];diff --git a/studio/frontend/tests/background-load-notice.test.ts b/studio/frontend/tests/background-load-notice.test.tsnew file mode 100644index 00000000000..a1c3b178f52--- /dev/null+++ b/studio/frontend/tests/background-load-notice.test.ts@@ -0,0 +1,372 @@+import assert from "node:assert/strict";+import test from "node:test";++// The images and video loads only START the work: the POST returns as soon as+// the background thread is running. These cover that the "loading" notice+// outlives the POST and settles from load-progress instead, which is what keeps+// the indicator row and the page toast on screen for the same span.+//+// Two `loading: true` announcements per load, deliberately: one before the POST+// so the row appears with the toast, and one after it returns, which is the+// instant the GPU arbiter has committed its eviction. Listeners that re-read+// another runtime need that second edge, so these assert both.+//+// model-lifecycle-events dispatches on `window`, so stand one up as an+// EventTarget and import the module after it exists.+class FakeWindow extends EventTarget {}++const originalWindow = (globalThis as { window?: unknown }).window;+(globalThis as { window?: unknown }).window = new FakeWindow();++const { subscribeModelLifecycle, withBackgroundLoadNotice } = await import(+ "../src/lib/model-lifecycle-events.ts"+);++/** The real cadences are 2s / 10s; these drive the same loop without waiting. */+const TIMING = { pollMs: 1, readTimeoutMs: 25, stallMs: 5000 };++type Seen = { runtime: string; loading: boolean; model: string | null };++/**+ * Record every announcement, and expose a promise that resolves on the settle.+ * Waiting on the event rather than on a sleep keeps these deterministic however+ * slowly the runner schedules the poll.+ */+function record(): { seen: Seen[]; settled: Promise<void>; stop: () => void } {+ const seen: Seen[] = [];+ let onSettled: () => void = () => {};+ const settled = new Promise<void>((resolve) => {+ onSettled = resolve;+ });+ const stop = subscribeModelLifecycle((detail) => {+ seen.push({+ runtime: detail.runtime,+ loading: detail.loading,+ model: detail.model,+ });+ if (!detail.loading) onSettled();+ });+ return { seen, settled, stop };+}++test.after(() => {+ (globalThis as { window?: unknown }).window = originalWindow;+});++test("the notice outlives the POST and settles when the load reports ready", async () => {+ const { seen, settled, stop } = record();+ const phases: ("downloading" | "ready")[] = [+ "downloading",+ "downloading",+ "ready",+ ];+ let read = 0;++ const result = await withBackgroundLoadNotice(+ "image",+ "unsloth/flux",+ async () => "started",+ async () => {+ const phase = phases[Math.min(read++, phases.length - 1)];+ // Every non-terminal read must leave the row loading: the whole point is+ // that the notice spans the background load, not just the POST.+ if (phase !== "ready") assert.equal(seen.length, 2);+ return phase;+ },+ TIMING,+ );++ // The POST has resolved, and the row must still say loading: the second+ // announcement is the post-commit one, not a settle.+ assert.equal(result, "started");+ assert.deepEqual(seen, [+ { runtime: "image", loading: true, model: "unsloth/flux" },+ { runtime: "image", loading: true, model: "unsloth/flux" },+ ]);++ await settled;+ assert.equal(read, 3);+ assert.deepEqual(seen, [+ { runtime: "image", loading: true, model: "unsloth/flux" },+ { runtime: "image", loading: true, model: "unsloth/flux" },+ { runtime: "image", loading: false, model: "unsloth/flux" },+ ]);+ stop();+});++test("an errored load settles the notice too", async () => {+ const { seen, settled, stop } = record();+ await withBackgroundLoadNotice(+ "video",+ "unsloth/wan",+ async () => null,+ async () => "error",+ TIMING,+ );+ await settled;+ assert.deepEqual(seen, [+ { runtime: "video", loading: true, model: "unsloth/wan" },+ { runtime: "video", loading: true, model: "unsloth/wan" },+ { runtime: "video", loading: false, model: "unsloth/wan" },+ ]);+ stop();+});++test("a load that never started settles at once, not from the poll", async () => {+ const { seen, stop } = record();+ let polled = false;++ await assert.rejects(+ withBackgroundLoadNotice(+ "image",+ "unsloth/flux",+ async () => {+ throw new Error("422 unsupported model kind");+ },+ async () => {+ polled = true;+ return "ready";+ },+ TIMING,+ ),+ /unsupported model kind/,+ );++ assert.deepEqual(seen, [+ { runtime: "image", loading: true, model: "unsloth/flux" },+ { runtime: "image", loading: false, model: "unsloth/flux" },+ ]);+ // Exactly one settle, and no poll: the two paths must not both fire.+ await new Promise((resolve) => setTimeout(resolve, 40));+ assert.equal(polled, false);+ assert.equal(seen.length, 2);+ stop();+});++test("an unreadable progress read does not end a live load", async () => {+ const { seen, settled, stop } = record();+ const answers: (Error | "downloading" | "ready")[] = [+ new Error("backend restarting"),+ "downloading",+ "ready",+ ];+ let read = 0;++ await withBackgroundLoadNotice(+ "image",+ "unsloth/flux",+ async () => null,+ async () => {+ const answer = answers[Math.min(read++, answers.length - 1)];+ // A failed read is not proof the load ended, so the row is still up.+ assert.equal(seen.length, 2);+ if (answer instanceof Error) throw answer;+ return answer;+ },+ TIMING,+ );++ await settled;+ assert.equal(read, 3);+ assert.deepEqual(seen.at(-1), {+ runtime: "image",+ loading: false,+ model: "unsloth/flux",+ });+ stop();+});++test("a null phase is terminal, since it means the load left nothing behind", async () => {+ const { seen, settled, stop } = record();+ let read = 0;++ await withBackgroundLoadNotice(+ "video",+ "unsloth/wan",+ async () => null,+ async () => {+ read += 1;+ return null;+ },+ TIMING,+ );++ // An eject or an eviction cancels the background worker, and load-progress+ // then reports null for good: nothing loading and nothing loaded. Treating it+ // as non-terminal left a "Loading" row with no eject on it for an hour.+ await settled;+ assert.equal(read, 1);+ assert.deepEqual(seen, [+ { runtime: "video", loading: true, model: "unsloth/wan" },+ { runtime: "video", loading: true, model: "unsloth/wan" },+ { runtime: "video", loading: false, model: "unsloth/wan" },+ ]);+ stop();+});++test("only downloading and finalizing keep the row up", async () => {+ const { seen, settled, stop } = record();+ const phases: ("downloading" | "finalizing" | "ready")[] = [+ "downloading",+ "finalizing",+ "ready",+ ];+ let read = 0;++ await withBackgroundLoadNotice(+ "image",+ "unsloth/flux",+ async () => null,+ async () => {+ const phase = phases[Math.min(read++, phases.length - 1)];+ if (phase !== "ready") assert.equal(seen.length, 2);+ return phase;+ },+ TIMING,+ );++ await settled;+ assert.equal(read, 3);+ assert.equal(seen.length, 3);+ assert.equal(seen[2].loading, false);+ stop();+});++test("a hung read is abandoned, so the deadline still bounds the loop", async () => {+ const { seen, settled, stop } = record();+ let aborts = 0;+ let read = 0;++ await withBackgroundLoadNotice(+ "image",+ "unsloth/flux",+ async () => null,+ // Accepts the connection and never answers, which is what parks the loop+ // and defeats the deadline unless each read is bounded on its own.+ (signal) =>+ new Promise<never>((_resolve, reject) => {+ read += 1;+ signal.addEventListener("abort", () => {+ aborts += 1;+ reject(new Error("aborted"));+ });+ }),+ { pollMs: 1, readTimeoutMs: 10, stallMs: 60 },+ );++ await settled;+ // Several reads were started and every one was cut loose, and the notice+ // settled at the deadline rather than never.+ assert.ok(read >= 2, `expected repeated reads, got ${read}`);+ assert.equal(aborts, read);+ assert.deepEqual(seen.at(-1), {+ runtime: "image",+ loading: false,+ model: "unsloth/flux",+ });+ stop();+});++test("the read signal is not aborted when the read answers in time", async () => {+ const { settled, stop } = record();+ let aborted = false;++ await withBackgroundLoadNotice(+ "video",+ "unsloth/wan",+ async () => null,+ async (signal) => {+ signal.addEventListener("abort", () => {+ aborted = true;+ });+ return "ready";+ },+ TIMING,+ );++ await settled;+ // The per-read timer is cleared on the way out, so a healthy read leaves no+ // abort behind for a later turn of the loop to trip over.+ await new Promise((resolve) => setTimeout(resolve, 60));+ assert.equal(aborted, false);+ stop();+});++test("a long but healthy download is never abandoned", async () => {+ const { seen, settled, stop } = record();+ let read = 0;++ await withBackgroundLoadNotice(+ "video",+ "unsloth/wan",+ async () => null,+ async () => {+ read += 1;+ // Far more polls than the stall window would allow if it were timed from+ // the start of the load: a 100 GB checkpoint on a slow link is hours.+ return read < 12 ? "downloading" : "ready";+ },+ // A stall window shorter than the run of healthy polls it must survive.+ { pollMs: 1, readTimeoutMs: 25, stallMs: 4 },+ );++ await settled;+ assert.equal(read, 12);+ assert.deepEqual(seen, [+ { runtime: "video", loading: true, model: "unsloth/wan" },+ { runtime: "video", loading: true, model: "unsloth/wan" },+ { runtime: "video", loading: false, model: "unsloth/wan" },+ ]);+ stop();+});++test("a healthy read resets the stall window", async () => {+ const { settled, stop } = record();+ let read = 0;++ await withBackgroundLoadNotice(+ "image",+ "unsloth/flux",+ async () => null,+ async () => {+ read += 1;+ // Unreadable, then healthy, then unreadable again. Without the reset the+ // second run of failures would inherit the first one's elapsed time.+ if (read === 1 || read === 2) throw new Error("backend restarting");+ if (read === 3) return "downloading";+ throw new Error("backend restarting");+ },+ { pollMs: 1, readTimeoutMs: 25, stallMs: 30 },+ );++ await settled;+ // It survived past the point an unreset window would have expired.+ assert.ok(read > 4, `expected the window to restart, got ${read} reads`);+ stop();+});++test("the load is announced again once the POST has committed", async () => {+ const { seen, stop } = record();+ let announcedBeforeStart = 0;++ await withBackgroundLoadNotice(+ "image",+ "unsloth/flux",+ async () => {+ // The arbiter has not run yet, so a listener re-reading another runtime+ // here would still see the model this load is about to evict.+ announcedBeforeStart = seen.length;+ return null;+ },+ async () => "ready",+ TIMING,+ );++ assert.equal(announcedBeforeStart, 1, "announced optimistically first");+ assert.equal(seen.length, 2, "and again once the backend has taken the GPU");+ assert.deepEqual(+ seen.map((s) => s.loading),+ [true, true],+ );+ stop();+});diff --git a/studio/frontend/tests/chat-model-residency.test.ts b/studio/frontend/tests/chat-model-residency.test.tsnew file mode 100644index 00000000000..0042de30cfa--- /dev/null+++ b/studio/frontend/tests/chat-model-residency.test.ts@@ -0,0 +1,214 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The header used to read "loaded" off the picker selection alone. Loading an+// image or video model evicts the chat model (the GPU arbiter allows one owner),+// which leaves the selection untouched, so the header kept its tick and the next+// prompt came back a bare 400. These pin the rule the header now uses.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import { chatModelLoaded } from "../src/features/chat/lib/chat-model-loaded.ts";++const PICKED = "unsloth/Qwen3.5-9B-GGUF";++test("a resident model reads as loaded", () => {+ assert.equal(+ chatModelLoaded({+ checkpoint: PICKED,+ modelLoading: false,+ isExternalModel: false,+ residentCheckpoint: PICKED,+ }),+ true,+ );+});++// The reported bug: the image load evicted it, the picker kept the name.+test("a model evicted for an image load does not read as loaded", () => {+ assert.equal(+ chatModelLoaded({+ checkpoint: PICKED,+ modelLoading: false,+ isExternalModel: false,+ residentCheckpoint: null,+ }),+ false,+ );+});++// Startup: assume loaded rather than flash "not loaded" on every launch.+test("residency not yet read is not treated as evicted", () => {+ assert.equal(+ chatModelLoaded({+ checkpoint: PICKED,+ modelLoading: false,+ isExternalModel: false,+ residentCheckpoint: undefined,+ }),+ true,+ );+});++// An API model has no local weights, so residency says nothing about it.+test("an external model is loaded whatever the backend holds", () => {+ assert.equal(+ chatModelLoaded({+ checkpoint: "openai:gpt-5",+ modelLoading: false,+ isExternalModel: true,+ residentCheckpoint: null,+ }),+ true,+ );+});++test("nothing picked is never loaded", () => {+ assert.equal(+ chatModelLoaded({+ checkpoint: "",+ modelLoading: false,+ isExternalModel: false,+ residentCheckpoint: PICKED,+ }),+ false,+ );+});++// The header tick is the selector's own isLoaded, which was `selected !== ""`.+// Reading the rule out of the source keeps the prop wired to the fix: the first+// attempt at this changed a different modelLoaded and the tick never moved.+test("the selector's tick asks the caller, and defaults to the old rule", () => {+ const source = readFileSync(+ new URL(+ "../src/features/model-picker/components/model-selector.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ source,+ /const isLoaded = selected !== "" && \(loaded \?\? true\)/,+ );+ const page = readFileSync(+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ page,+ /loaded=\{chatModelLoaded\(\{/,+ "the chat header must pass it",+ );+ assert.match(page, /residentCheckpoint,/);+});++test("a model still loading is not loaded yet", () => {+ assert.equal(+ chatModelLoaded({+ checkpoint: PICKED,+ modelLoading: true,+ isExternalModel: false,+ residentCheckpoint: PICKED,+ }),+ false,+ );+});++// The trigger tick was only one of three places claiming "loaded", and all three+// read the picker selection. The dropdown's own green "Loaded" badge and the+// Model hub cards kept it after an eviction, which is the same lie in a second+// and third spot.+test("the picker's Loaded badge asks residency, not the selection", () => {+ const pickers = readFileSync(+ new URL(+ "../src/features/model-picker/components/model-selector/pickers.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(pickers, /const loadedModelId = chatModelLoaded\(\{/);+ assert.match(pickers, /residentCheckpoint,/);+ assert.doesNotMatch(+ pickers,+ /const loadedModelId = useChatRuntimeStore\(\(s\) => s\.params\.checkpoint\)/,+ );+});++test("the hub cards ask residency before saying Loaded", () => {+ const hub = readFileSync(+ new URL("../src/features/hub/hub-page.tsx", import.meta.url),+ "utf8",+ );+ assert.match(hub, /residentCheckpoint !== null\s*\n?\s*\? checkpoint/);+});++// Nothing in the chat runtime polls /status: refresh runs on mount and when the+// model lists change, never on a timer. So an eviction caused by the Images+// page was never observed and residentCheckpoint stayed undefined, which reads+// as loaded. The re-read has to be driven by the lifecycle event.+//+// On the START of the other runtime's load, not only its finish. The GPU+// arbiter evicts chat inside the image or video load POST, before the download+// begins, and that download can run for hours: measured against a live backend,+// /api/inference/status reported active_model null 1.8s after the POST returned,+// and sending to the model the picker still named answered 400 "No model+// loaded". Waiting for the settle left that gap open for the whole load.+test("another runtime loading re-reads the chat status", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/chat/hooks/use-chat-model-runtime.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(hook, /subscribeModelLifecycle\(\(\{ runtime \}\) => \{/);+ // Dictation holds no GPU ownership, so it is the one that stays excluded.+ assert.match(hook, /if \(runtime === "chat" \|\| runtime === "stt"\) return;/);+ assert.doesNotMatch(+ hook,+ /if \(loading \|\| runtime === "chat"\) return;/,+ "the settle-only guard is what left the picker naming an evicted model",+ );+ assert.match(hook, /void refresh\(\{ includeLoras: false \}\)/);+ // And the branch it feeds still clears residency.+ assert.match(hook, /residentCheckpoint: null,/);+});++// Dimming the tick and the badges was not enough: the model's name on its own+// reads as "this is my model", and sending to it returns a bare 400. An+// eviction now drops the pick, exactly as a server-side unload already did.+test("an eviction drops the pick, not just the loaded marks", () => {+ const hook = readFileSync(+ new URL(+ "../src/features/chat/hooks/use-chat-model-runtime.ts",+ import.meta.url,+ ),+ "utf8",+ );+ const branch = hook.slice(+ hook.indexOf("} else if (!statusRes.active_model"),+ hook.indexOf("} catch (error) {"),+ );+ assert.match(branch, /clearCheckpoint\(\)/);+ // Guarded twice: a model that was never confirmed resident has nothing to+ // lose, and a load in flight reports no active model either.+ assert.match(+ branch,+ /if \(wasResident && selectedCheckpoint && !modelLoading\)/,+ );+});++// The pick survives a load, which also reports no active model while it runs.+test("the eviction clear reads the store's loading flag", () => {+ const store = readFileSync(+ new URL(+ "../src/features/chat/stores/chat-runtime-store.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(store, /modelLoading: boolean;/);+ assert.match(store, /set\(\{ modelLoading: true \}\)/);+});diff --git a/studio/frontend/tests/chat-status-refresh-sequencing.test.ts b/studio/frontend/tests/chat-status-refresh-sequencing.test.tsnew file mode 100644index 00000000000..109eb5af507--- /dev/null+++ b/studio/frontend/tests/chat-status-refresh-sequencing.test.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A media load announces itself twice: once before its POST, so the row appears+// with the toast, and once after, which is the instant the GPU arbiter has+// committed the eviction. Chat re-reads its status on both, so two refreshes+// are in flight within the POST's own duration -- measured at 1.8s against a+// live backend, which is far wider than the gap between the two reads.+//+// They read the status at different moments and answer in whatever order the+// network gives, so the older one landing last would re-pin the model the newer+// one had just seen released: chat would claim a model that 400s on send, until+// the load finally settled hours later. Last issued has to win.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++const SOURCE = readFileSync(+ fileURLToPath(+ new URL("../src/features/chat/hooks/use-chat-model-runtime.ts", import.meta.url),+ ),+ "utf8",+);++const SYNC = SOURCE.slice(+ SOURCE.indexOf("async function syncInferenceStatusToStore("),+ SOURCE.indexOf("/**\n * Reconcile the UI after the SERVER unloaded"),+);++test("every refresh takes a generation, and the newest one wins", () => {+ assert.match(SOURCE, /let syncGeneration = 0;/);+ assert.match(SYNC, /const generation = \+\+syncGeneration;/);+ assert.match(SYNC, /const superseded = \(\) => generation !== syncGeneration;/);+});++test("a superseded refresh writes nothing back to the store", () => {+ const guard = SYNC.slice(0, SYNC.indexOf("setModels("));+ assert.match(+ guard,+ /if \(signal\?\.aborted \|\| superseded\(\)\) return;/,+ "the check must sit between the await and the first write",+ );+});++test("a superseded refresh does not report its failure either", () => {+ const catchBlock = SYNC.slice(SYNC.indexOf("} catch (error) {"));+ assert.match(catchBlock, /if \(signal\?\.aborted \|\| superseded\(\)\) return;/);+ // Otherwise a read nobody would have applied still raises a toast.+ assert.ok(+ catchBlock.indexOf("superseded()") < catchBlock.indexOf("toast.error"),+ "the guard must precede the error toast",+ );+});++test("the eviction branch is behind the same guard", () => {+ // This is the branch that clears residency and drops the pick, so a stale+ // answer reaching it is the expensive case.+ const evictionAt = SYNC.indexOf("residentCheckpoint: null,");+ const guardAt = SYNC.indexOf("superseded()");+ assert.ok(guardAt !== -1 && guardAt < evictionAt);+});diff --git a/studio/frontend/tests/drag-costs-no-render.test.ts b/studio/frontend/tests/drag-costs-no-render.test.tsnew file mode 100644index 00000000000..9a9956841c8--- /dev/null+++ b/studio/frontend/tests/drag-costs-no-render.test.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Both floating panels dragged through React state and through left/top, which+// is the layout path: the card carries a wide blurred shadow and the monitor is+// backdrop-blurred, so every frame re-laid-out and repainted them. A trackpad+// also reports moves faster than the display refreshes, so much of that work+// was never shown. These pin the cheap path, since the cost is invisible to a+// unit test and only shows up under the hand.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++function source(path: string): string {+ return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");+}++test("the card paints a drag frame through a transform", () => {+ const hook = source("features/loaded-models/use-drag-position.ts");+ assert.match(hook, /panel\.style\.transform = `translate3d\(/);+ assert.match(hook, /frameRef\.current = requestAnimationFrame\(paint\)/);+ // The old path: one setPosition per pointermove, so one render per event.+ assert.doesNotMatch(hook, /setPosition\(\s*clampToViewport\(/);+});++// This one is the sharpest: the effect was keyed on `position`, so every frame+// disconnected the observer and built a new one, and observing re-measures,+// which forces a synchronous layout.+test("the card's reclamp observer outlives a drag frame", () => {+ const hook = source("features/loaded-models/use-drag-position.ts");+ assert.match(hook, /\}, \[panelEl, reclamp\]\);/);+ assert.doesNotMatch(hook, /\}, \[position, panelEl, reclamp\]\);/);+});++test("the card hands the offset back to left/top on release", () => {+ const hook = source("features/loaded-models/use-drag-position.ts");+ assert.match(hook, /panel\.style\.left = `\$\{session\.lastLeft\}px`/);+ assert.match(hook, /panel\.style\.transform = ""/);+ assert.match(+ hook,+ /const landed = \{ left: session\.lastLeft, top: session\.lastTop \};/,+ );+ assert.match(hook, /setPosition\(landed\)/);+});++test("the monitor paints a drag frame through a transform", () => {+ const panel = source("components/floating-monitor.tsx");+ assert.match(panel, /monitor\.style\.transform = `translate3d\(/);+ assert.match(+ panel,+ /dragFrameRef\.current = requestAnimationFrame\(paintDrag\)/,+ );+});++test("the monitor commits its position once, on release", () => {+ const panel = source("components/floating-monitor.tsx");+ const finish = panel.slice(panel.indexOf("function finishDrag"));+ assert.match(finish, /monitor\.style\.transform = ""/);+ assert.match(finish, /setLayout\(\(current\) =>/);+});++// The measured box carries the drag's transform, so committing it mid-drag+// would move the panel twice as far as the pointer went.+test("a resize mid-drag does not commit the transformed box", () => {+ const panel = source("components/floating-monitor.tsx");+ assert.match(panel, /const held = session && current \? current : null;/);+ assert.match(panel, /left: restLeft,/);+ assert.match(panel, /maxWidth: constraintsBox\.width - restLeft,/);+});++// Every frame published the monitor's box to a shared store, and each write+// re-rendered every overlay subscribed to it, the loaded models card included.+test("dragging the monitor does not republish its frame per frame", () => {+ const panel = source("components/floating-monitor.tsx");+ const update = panel.slice(+ panel.indexOf("function updateDrag"),+ panel.indexOf("function finishDrag"),+ );+ assert.doesNotMatch(update, /setFrame/);+ assert.doesNotMatch(update, /getBoundingClientRect/);+});diff --git a/studio/frontend/tests/loaded-models-backcompat.test.ts b/studio/frontend/tests/loaded-models-backcompat.test.tsnew file mode 100644index 00000000000..ba54107855d--- /dev/null+++ b/studio/frontend/tests/loaded-models-backcompat.test.ts@@ -0,0 +1,220 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The browser SPA is served by the same process that answers /api, so it can+// never be older than its backend. The desktop app can: it ships its own+// frontend bundle, is versioned separately from the pip wheel, and adopts an+// already-running server (commands.rs, start_managed_server). Against that, the+// indicator is the widest reader in the app -- it touches four /status+// endpoints, and /video/status plus the STT mtmd block are only days old.+//+// So every one of these is a real desktop-app-newer-than-backend shape, plus the+// forward direction: a backend that grows a field must not break a frontend that+// has never heard of it.++import assert from "node:assert/strict";+import test from "node:test";++import {+ type SttStatusResponse,+ describeDiffusionStatus,+ describeInferenceStatus,+ describeSttStatus,+ describeVideoStatus,+ mergeLoadedModels,+ sttEngineStatus,+} from "../src/features/loaded-models/loaded-models-sources.ts";++// A read that failed for any reason -- 404 on a route that did not exist yet,+// 401/403 on an expired token, a 500, or the 10s timeout -- reaches the mappers+// as null, because settled() collapses them all.+const UNREACHABLE = null;++test("a backend with no video route at all still lists the other runtimes", () => {+ // /api/inference/video/status landed 2026-08-04. Before that it 404s, which+ // parseJson throws on and settled() turns into null.+ const rows = mergeLoadedModels([+ describeInferenceStatus({+ active_model: "unsloth/Qwen3-4B-GGUF",+ loaded: ["unsloth/Qwen3-4B-GGUF"],+ is_gguf: true,+ gguf_variant: "Q4_K_M",+ } as never),+ describeDiffusionStatus(UNREACHABLE),+ describeVideoStatus(UNREACHABLE),+ describeSttStatus(UNREACHABLE),+ ]);+ assert.equal(rows.length, 1, "one dead runtime must not blank the others");+ assert.equal(rows[0].name, "unsloth/Qwen3-4B-GGUF");+});++test("every runtime unreachable is an empty list, never a crash", () => {+ assert.deepEqual(+ mergeLoadedModels([+ describeInferenceStatus(UNREACHABLE),+ describeDiffusionStatus(UNREACHABLE),+ describeVideoStatus(UNREACHABLE),+ describeSttStatus(UNREACHABLE),+ ]),+ [],+ );+});++test("a pre-split dictation backend reports through the legacy fields", () => {+ // Before 2026-07-23 there were no per-engine blocks: the resident Transformers+ // model appeared only at the top level.+ const rows = describeSttStatus({+ loaded_model: "large-v3",+ device: "cuda",+ } as SttStatusResponse);+ assert.equal(rows.length, 1);+ assert.equal(rows[0].name, "large-v3");+ assert.equal(rows[0].sttEngine, "transformers");+ assert.equal(rows[0].detail, "Transformers · cuda");+});++test("a current backend does not double the dictation row", () => {+ // Both the legacy top level and the engine block are present on every current+ // server, and they hold the same model. The block must win.+ const rows = describeSttStatus({+ loaded_model: "large-v3",+ device: "cuda",+ transformers: { loaded_model: "large-v3", device: "cuda" },+ } as SttStatusResponse);+ assert.equal(rows.length, 1);+});++test("the legacy fallback is transformers-only", () => {+ // The top-level fields are the Transformers sidecar's, character for+ // character -- not a "last engine used" -- so they must not stand in for the+ // llama.cpp or whisper.cpp sidecars.+ const status = { loaded_model: "large-v3", device: "cuda" } as SttStatusResponse;+ assert.equal(sttEngineStatus(status, "transformers")?.loaded_model, "large-v3");+ assert.equal(sttEngineStatus(status, "mtmd"), null);+ assert.equal(sttEngineStatus(status, "gguf"), null);+});++test("a dictation backend without the mtmd engine skips it", () => {+ // The mtmd (Qwen3-ASR) block arrived 2026-08-04, after the other two.+ const rows = describeSttStatus({+ transformers: { loaded_model: null, device: null },+ gguf: { loaded_model: "ggml-base.en", device: "whisper.cpp" },+ } as SttStatusResponse);+ assert.deepEqual(+ rows.map((row) => row.sttEngine),+ ["gguf"],+ );+});++test("an engine block explicitly nulled is skipped, not read as legacy", () => {+ const rows = describeSttStatus({+ loaded_model: "large-v3",+ device: "cuda",+ transformers: null,+ } as SttStatusResponse);+ // transformers: null means "no such block", so the legacy fallback applies.+ assert.equal(rows.length, 1);+ assert.equal(rows[0].name, "large-v3");+});++test("a chat payload missing every optional field still renders", () => {+ // The oldest shape this has to survive: a name and nothing else.+ const rows = describeInferenceStatus({+ active_model: "unsloth/Qwen3-4B",+ } as never);+ assert.equal(rows.length, 1);+ assert.equal(rows[0].detail, "Transformers", "the ladder needs no flags");+ assert.equal(rows[0].kind, "text");+});++test("a diffusion payload missing dtype, device and family still renders", () => {+ const rows = describeDiffusionStatus({+ loaded: true,+ repo_id: "black-forest-labs/FLUX.1-dev",+ } as never);+ assert.equal(rows.length, 1);+ assert.equal(rows[0].detail, "", "no parts is an empty line, not a stray dot");+ assert.equal(rows[0].name, "black-forest-labs/FLUX.1-dev");+});++test("undefined and null are the same absence", () => {+ const withNulls = describeVideoStatus({+ loaded: true,+ repo_id: "Wan-AI/Wan2.2-T2V-A14B",+ family: null,+ device: null,+ dtype: null,+ transformer_quant: null,+ } as never);+ const withUndefined = describeVideoStatus({+ loaded: true,+ repo_id: "Wan-AI/Wan2.2-T2V-A14B",+ } as never);+ assert.deepEqual(withNulls, withUndefined);+});++test("empty strings are dropped rather than printed as separators", () => {+ const rows = describeDiffusionStatus({+ loaded: true,+ repo_id: "x/y",+ family: "",+ device: "cuda",+ dtype: "",+ } as never);+ assert.equal(rows[0].detail, "cuda");+});++test("fields a future backend adds are ignored, not rendered", () => {+ // Forward compatibility: an old desktop bundle against a newer wheel.+ const rows = describeDiffusionStatus({+ loaded: true,+ repo_id: "x/y",+ family: "flux",+ device: "cuda",+ dtype: "bfloat16",+ some_future_field: "should not appear",+ nested: { also: "ignored" },+ } as never);+ assert.equal(rows[0].detail, "flux · BF16 · cuda");+});++test("an unrecognised precision is passed through rather than dropped", () => {+ // precisionLabel upper-cases anything it does not know, so a quant added+ // later still tells the user something instead of vanishing.+ const rows = describeVideoStatus({+ loaded: true,+ repo_id: "x/y",+ family: "wan",+ device: "cuda",+ transformer_quant: "nvfp4",+ } as never);+ assert.equal(rows[0].detail, "wan · NVFP4 · cuda");+});++test("a chat runtime caching past the active model marks the extras inactive", () => {+ // Only the Transformers backend can do this, and only the active model is+ // ejectable by the normal path -- the rest need naming directly.+ const rows = describeInferenceStatus({+ active_model: "unsloth/Qwen3-4B",+ loaded: ["unsloth/Qwen3-4B", "unsloth/Llama-3.2-3B"],+ } as never);+ assert.equal(rows.length, 2);+ assert.equal(rows[0].inactive, undefined);+ assert.equal(rows[1].inactive, true);+ assert.equal(rows[1].detail, "Still in memory");+});++test("a duplicate in the loaded list is not listed twice", () => {+ const rows = describeInferenceStatus({+ active_model: "unsloth/Qwen3-4B",+ loaded: ["unsloth/Qwen3-4B", "unsloth/Llama-3.2-3B", "unsloth/Llama-3.2-3B"],+ } as never);+ assert.equal(rows.length, 2);+});++test("the same row arriving from two sources is merged once", () => {+ const row = describeInferenceStatus({+ active_model: "unsloth/Qwen3-4B",+ } as never);+ assert.equal(mergeLoadedModels([row, row]).length, 1);+});diff --git a/studio/frontend/tests/loaded-models-barrel-order.test.ts b/studio/frontend/tests/loaded-models-barrel-order.test.tsnew file mode 100644index 00000000000..c3cde354d70--- /dev/null+++ b/studio/frontend/tests/loaded-models-barrel-order.test.ts@@ -0,0 +1,64 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// There is a genuine import cycle here, and the barrel's export order is what+// keeps it harmless:+//+// loaded-models/index -> loaded-models-indicator -> features/settings/index+// -> settings-dialog -> tabs/general-tab -> loaded-models/index+//+// general-tab's reset list dereferences LOADED_MODELS_PREFERENCE_KEYS at module+// scope, so if the barrel hands control to the indicator before the preference+// module has initialised, that read hits the temporal dead zone and startup+// fails with "Cannot access 'LOADED_MODELS_PREFERENCE_KEYS' before+// initialization". Reproduced in Vite dev, which serves native ESM: entering+// the loaded-models barrel first threw exactly that.+//+// Exporting the preference module first evaluates the constant before the+// indicator is touched, so either entry order is safe. A bundler may hide this,+// which is why it is pinned here rather than left to the build.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++function read(path: string): string {+ return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");+}++const BARREL = read("../src/features/loaded-models/index.ts");+const GENERAL_TAB = read("../src/features/settings/tabs/general-tab.tsx");+const INDICATOR = read(+ "../src/features/loaded-models/loaded-models-indicator.tsx",+);++test("the preference module is exported before the indicator", () => {+ const pref = BARREL.indexOf("./show-loaded-models-pref");+ const indicator = BARREL.indexOf("./loaded-models-indicator");+ assert.ok(pref !== -1 && indicator !== -1, "expected both exports");+ assert.ok(+ pref < indicator,+ "show-loaded-models-pref must be evaluated first, or general-tab reads the keys in the temporal dead zone",+ );+});++test("the cycle this order defends against is still present", () => {+ // If any of these three links is ever cut the ordering stops mattering, but+ // while they hold, the order above is the only thing making startup safe.+ assert.match(INDICATOR, /from "@\/features\/settings"/);+ assert.match(GENERAL_TAB, /from "@\/features\/loaded-models"/);+ assert.match(GENERAL_TAB, /LOADED_MODELS_PREFERENCE_KEYS\./);+});++test("general-tab reads the keys at module scope, not inside a component", () => {+ // A read inside a component body would run long after both modules settled,+ // and the ordering would be cosmetic. It is not: this is a top-level const.+ const keysAt = GENERAL_TAB.indexOf("LOADED_MODELS_PREFERENCE_KEYS.show");+ const firstComponent = GENERAL_TAB.search(/\nexport function |\nfunction \w+\(/);+ assert.ok(keysAt !== -1, "expected the reset list to name the keys");+ assert.ok(+ firstComponent === -1 || keysAt < firstComponent,+ "the keys are read at module scope, so evaluation order decides the outcome",+ );+});diff --git a/studio/frontend/tests/loaded-models-dismiss.test.ts b/studio/frontend/tests/loaded-models-dismiss.test.tsnew file mode 100644index 00000000000..46306e16234--- /dev/null+++ b/studio/frontend/tests/loaded-models-dismiss.test.ts@@ -0,0 +1,178 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Closing the card and switching it off in Settings are two different wishes,+// and they must not share a flag: the next model load reopens a card that was+// waved away, and would otherwise also reopen one deliberately turned off.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import { installLocalStorageFake } from "./helpers/kit.ts";++const { store } = installLocalStorageFake();++const {+ LOADED_MODELS_PREFERENCE_KEYS,+ getLoadedModelsDismissed,+ getShowLoadedModels,+ setLoadedModelsDismissed,+ setShowLoadedModels,+} = await import("../src/features/loaded-models/show-loaded-models-pref.ts");++function reset(): void {+ store.clear();+}++test("the card is open until something closes it", () => {+ reset();+ assert.equal(getLoadedModelsDismissed(), false);+});++test("closing it stores the dismissal, reopening removes the key", () => {+ reset();+ setLoadedModelsDismissed(true);+ assert.equal(getLoadedModelsDismissed(), true);+ assert.equal(store.get(LOADED_MODELS_PREFERENCE_KEYS.dismissed), "true");+ setLoadedModelsDismissed(false);+ assert.equal(getLoadedModelsDismissed(), false);+ // Removed, not stored as "false", so the default stays open.+ assert.equal(store.has(LOADED_MODELS_PREFERENCE_KEYS.dismissed), false);+});++// The point of keeping them apart.+test("closing the card does not switch the setting off", () => {+ reset();+ setLoadedModelsDismissed(true);+ assert.equal(getShowLoadedModels(), true);+});++test("switching the setting off is not a dismissal a load can undo", () => {+ reset();+ setShowLoadedModels(false);+ setLoadedModelsDismissed(false);+ assert.equal(+ getShowLoadedModels(),+ false,+ "a load reopening the card must not re-enable a disabled one",+ );+});++// Every load start reopens the card, so a set to the value it already holds+// must be inert: otherwise each load re-renders the whole overlay stack.+test("setting the dismissal to what it already is changes nothing", () => {+ reset();+ setLoadedModelsDismissed(false);+ assert.equal(store.size, 0, "an unchanged set must not write");+ setLoadedModelsDismissed(true);+ assert.equal(store.size, 1);+ setLoadedModelsDismissed(true);+ assert.equal(store.size, 1);+});++test("the dismissal key is cleared by Reset all local preferences", () => {+ const generalTab = readFileSync(+ new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),+ "utf8",+ );+ assert.match(generalTab, /LOADED_MODELS_PREFERENCE_KEYS\.dismissed,/);+});++test("the card carries a close button, and a load brings it back", () => {+ const indicator = readFileSync(+ new URL(+ "../src/features/loaded-models/loaded-models-indicator.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(indicator, /aria-label="Close loaded models"/);+ assert.match(+ indicator,+ /onClick=\{\(\) => setLoadedModelsDismissed\(true\)\}/,+ );+ // Reopened on the START of a load, so the card is up for as long as the toast.+ assert.match(+ indicator,+ /subscribeModelLifecycle\(\(\{ loading \}\) => \{\s*if \(loading\) \{\s*setLoadedModelsDismissed\(false\);/,+ );+ // And the gate reads it. Reachability is hoisted so tracking can share it.+ assert.match(+ indicator,+ /const enabled = showIndicator && !dismissed && reachable;/,+ );+});++// Requested by name: hugeicons.com/icon/sparkle. Singular, so NOT the free+// set's SparklesIcon (two stars) nor lib/sparkles-icon, which is a shield.+test("the card is badged with the single sparkle, not the brain", () => {+ const indicator = readFileSync(+ new URL(+ "../src/features/loaded-models/loaded-models-indicator.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(indicator, /icon=\{SparkleIcon\}/);+ assert.match(indicator, /from "@\/lib\/sparkle-icon"/);+ assert.doesNotMatch(indicator, /AiBrain01Icon|SparklesIcon/);+});++// Releasing the weights is not the same act as closing the card, so it must not+// wear the same X.+test("a row ejects with the eject glyph, the header closes with an X", () => {+ const indicator = readFileSync(+ new URL(+ "../src/features/loaded-models/loaded-models-indicator.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ const row = indicator.slice(+ indicator.indexOf("function LoadedModelRow"),+ indicator.indexOf("export function LoadedModelsIndicator"),+ );+ assert.match(row, /icon=\{RemoveCircleIcon\}/);+ assert.doesNotMatch(row, /icon=\{Cancel01Icon\}/);+ // The close button keeps the X, as the Live monitor's does.+ const header = indicator.slice(+ indicator.indexOf('aria-label="Close loaded models"'),+ );+ assert.match(header, /icon=\{Cancel01Icon\}/);+});++// Recording had to widen past `enabled` so a card the user closed still hears+// the load that reopens it. It widened one step too far: `canShowIndicator`+// carries the auth gate as well as the hidden routes, so tracking on the+// preference alone polled four protected endpoints every 5s on /login, and each+// 401 ran authFetch's refresh-then-redirect ladder against no session at all.+// Asserted by reading the source, since the node suite has no DOM to mount in.+test("recording follows the route and auth gate, but not the dismissal", () => {+ const INDICATOR = readFileSync(+ new URL(+ "../src/features/loaded-models/loaded-models-indicator.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ // The auth gate lives in canShowIndicator, so `reachable` is what carries it.+ assert.match(INDICATOR, /const reachable = canShowIndicator\(pathname\);/);+ assert.match(+ INDICATOR,+ /hasAuthToken\(\) && !mustChangePassword\(\)/,+ "canShowIndicator must still be the thing that gates on auth",+ );+ const call = INDICATOR.slice(+ INDICATOR.indexOf("useLoadedModels("),+ INDICATOR.indexOf("useLoadedModels(") + 200,+ );+ assert.match(call, /showIndicator && reachable/, "track must be gated too");+ assert.doesNotMatch(+ call,+ /\n\s*showIndicator,\n/,+ "the preference alone is what polled /login",+ );+ // And dismissal stays out of it, or a closed card could never reopen itself.+ assert.doesNotMatch(call, /dismissed/);+});diff --git a/studio/frontend/tests/loaded-models-drag-restore.test.ts b/studio/frontend/tests/loaded-models-drag-restore.test.tsnew file mode 100644index 00000000000..38d723b6d73--- /dev/null+++ b/studio/frontend/tests/loaded-models-drag-restore.test.ts@@ -0,0 +1,238 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The card stores an absolute viewport position, so a position saved on a wide+// monitor is meaningless on a laptop screen. Nothing else can rescue it: the+// card is position:fixed, so an off-screen one creates no scroll to reach it,+// and its own drag handle and collapse button go with it.+//+// Two separate guards, and they are needed together:+// - the read is clamped, so it can never PAINT off screen, and+// - the reclamp effect is wired to the panel node, so it keeps up afterwards.+// The second is the one that regressed: the effect captured panelRef.current+// once, while the card was still returning null for an empty list, so it always+// saw null, never built a ResizeObserver, and never re-ran once the node+// existed. Both are asserted here -- the geometry directly, the wiring by+// reading the source, since the node suite has no DOM to mount into.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import { clampToViewport } from "../src/features/loaded-models/use-drag-position.ts";++const SOURCE = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/loaded-models/use-drag-position.ts",+ import.meta.url,+ ),+ ),+ "utf8",+);++const CARD = { width: 268, height: 160 };+const LAPTOP = { width: 1280, height: 800 };++// What the initialiser does: clamp before the first paint, with no measurement+// available yet, so zero width and height.+function restore(+ stored: { left: number; top: number },+ viewport: { width: number; height: number },+) {+ return clampToViewport(stored, 0, 0, viewport);+}++test("a position saved on a wider monitor lands back on screen", () => {+ // Dragged to the bottom-right of a 2560x1440 display, reopened on a laptop.+ const restored = restore({ left: 2280, top: 1250 }, LAPTOP);+ assert.ok(restored.left < LAPTOP.width, "must be within the viewport");+ assert.ok(restored.top < LAPTOP.height, "must be within the viewport");+ assert.deepEqual(restored, { left: 1272, top: 792 });+});++test("a position already on screen is left exactly where it was", () => {+ // The common case must not drift by a pixel, or the card would creep each+ // time the app opens.+ const stored = { left: 900, top: 400 };+ assert.deepEqual(restore(stored, LAPTOP), stored);+});++test("a negative stored position is pulled back to the margin", () => {+ // Reachable by dragging on a multi-monitor desktop where the secondary screen+ // sits left of or above the primary.+ assert.deepEqual(restore({ left: -400, top: -90 }, LAPTOP), {+ left: 8,+ top: 8,+ });+});++test("once measured, the whole card is kept on screen, not just its corner", () => {+ // The initialiser clamps with zero size because nothing has been laid out+ // yet; the first ResizeObserver delivery refines it using the real box.+ const corner = restore({ left: 2280, top: 1250 }, LAPTOP);+ const measured = clampToViewport(corner, CARD.width, CARD.height, LAPTOP);+ assert.deepEqual(measured, {+ left: LAPTOP.width - CARD.width - 8,+ top: LAPTOP.height - CARD.height - 8,+ });+});++test("a viewport narrower than the card still leaves it reachable", () => {+ // A phone-width window, or a desktop window dragged very small.+ const tiny = { width: 200, height: 300 };+ const restored = clampToViewport({ left: 900, top: 900 }, CARD.width, 400, tiny);+ assert.deepEqual(restored, { left: 8, top: 8 });+});++test("clamping is idempotent, so the observer cannot feed itself", () => {+ // reclamp() returns the identical object when nothing moved, which is what+ // stops the ResizeObserver -> setPosition -> resubscribe loop from spinning.+ const once = clampToViewport({ left: 5000, top: 5000 }, CARD.width, CARD.height, LAPTOP);+ const twice = clampToViewport(once, CARD.width, CARD.height, LAPTOP);+ assert.deepEqual(once, twice);+});++// ── The wiring the geometry depends on ──────────────────────────────────++test("the stored position is clamped as it is read", () => {+ // Without this the card paints once at the stored coordinates. On a smaller+ // screen that single frame is off screen, and if the observer ever fails to+ // attach it stays there.+ assert.match(+ SOURCE,+ /const stored = readStored[\s\S]{0,500}?clampToViewport\(stored,/,+ "useState initialiser must clamp what it reads",+ );+});++test("the reclamp effect re-runs when the panel node appears", () => {+ // The card renders nothing until the first poll returns a row, so the effect's+ // first run sees no node. A RefObject mutation does not re-render, so the node+ // has to arrive through state for the effect to ever see it.+ const guard = SOURCE.indexOf("!panelEl) return;");+ assert.notEqual(+ guard,+ -1,+ "the reclamp effect must guard on the panel node, not read a ref",+ );+ const effect = SOURCE.slice(guard);+ const deps = effect.slice(0, effect.indexOf("]") + 1);+ assert.match(+ deps,+ /\bpanelEl\b/,+ "panelEl must be a dependency or the effect never re-subscribes",+ );+ assert.ok(+ !/const panel = panelRef\.current;\s*\n\s*const measure/.test(SOURCE),+ "the effect must not snapshot the ref, which is null on its first run",+ );+ assert.match(+ SOURCE,+ /setPanelEl\(node\)/,+ "the ref has to be a callback that sets state",+ );+});++test("a missing ResizeObserver still leaves the card clampable", () => {+ // WebKitGTK old enough to lack it would otherwise get no clamp at all, and+ // this file's siblings already ponyfill for exactly that vintage.+ assert.match(+ SOURCE,+ /typeof ResizeObserver === "undefined"/,+ "construction must be guarded",+ );+ assert.match(+ SOURCE,+ /window\.addEventListener\("resize", measure\)/,+ "the resize path is the fallback and must not be conditional on it",+ );+});++test("the drag captures the pointer", () => {+ // Without capture a pointerup over another window is never delivered and the+ // card follows the cursor afterwards.+ assert.match(SOURCE, /setPointerCapture\(event\.pointerId\)/);+ assert.match(+ SOURCE,+ /event\.buttons === 0/,+ "and a move with no button held must end the drag",+ );+});++// The expanded grip and the collapsed pill share one drag sentinel, and it is+// startDrag that keeps it honest: every handle's pointerdown zeroes the flag+// before that handle's own click can read it. So a drag by the grip cannot+// leave a stale flag for the pill, and the pill's click always reads its own+// press. Verified in a real browser: dragging by the grip, collapsing, and+// clicking the pill once reopens the card.+const INDICATOR = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/loaded-models/loaded-models-indicator.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+);++test("every drag handle goes through startDrag, which resets the sentinel", () => {+ const HOOK = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/loaded-models/use-drag-position.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ // The reset lives in startDrag's body, so it runs for the pill and the grip+ // alike. Move it out and a stale flag becomes reachable.+ const startDrag = HOOK.slice(+ HOOK.indexOf("const startDrag = useCallback("),+ HOOK.indexOf("// One paint per frame"),+ );+ assert.match(startDrag, /movedRef\.current = false;/);+ // Both handles, so neither can start a drag without arming that reset.+ const handles = INDICATOR.match(/onPointerDown=\{startDrag\}/g);+ assert.equal(handles?.length, 2);+});++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,+ );+ assert.match(pill, /onPointerDown=\{startDrag\}/);+ assert.match(pill, /if \(!justDragged\(\)\) setCollapsed\(false\)/);+});++// The clamp is a display-time adaptation, not a choice the user made. Writing+// one back meant opening the app on a laptop rewrote a position saved on a+// large monitor, and going back to that monitor left the card where the laptop+// had put it. Only a landed drag is stored; the read path clamps anyway.+test("only a drag persists a position, never a reclamp", () => {+ const HOOK = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/loaded-models/use-drag-position.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ const settleAt = HOOK.indexOf("const settle = useCallback(");+ const settle = HOOK.slice(+ settleAt,+ HOOK.indexOf("}, [applyPending, storageKey]);", settleAt),+ );+ assert.match(settle, /store\(storageKey, landed\)/);+ // The old shape: an effect on `position`, which every reclamp also changed.+ assert.doesNotMatch(HOOK, /useEffect\(\(\) => \{\s*if \(pressing\) return;\s*store\(/);+ assert.equal(+ HOOK.split("store(storageKey").length - 1,+ 1,+ "one write, in settle",+ );+});diff --git a/studio/frontend/tests/loaded-models-drag.test.ts b/studio/frontend/tests/loaded-models-drag.test.tsnew file mode 100644index 00000000000..d3f300fef8b--- /dev/null+++ b/studio/frontend/tests/loaded-models-drag.test.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import {+ clampToViewport,+ passedDragThreshold,+} from "../src/features/loaded-models/use-drag-position.ts";++const VIEWPORT = { width: 1440, height: 900 };+const CARD = { width: 268, height: 160 };++// The collapsed pill is both the drag handle and the button that expands the+// card, so a press that barely moves has to stay a click.+test("a press that barely moves is a click, not a drag", () => {+ assert.equal(passedDragThreshold(0, 0), false);+ assert.equal(passedDragThreshold(2, 2), false);+});++test("a press that moves is a drag", () => {+ assert.equal(passedDragThreshold(10, 0), true);+ assert.equal(passedDragThreshold(0, -10), true);+ assert.equal(passedDragThreshold(3, 3), true);+});++test("a position inside the viewport is left alone", () => {+ const position = { left: 400, top: 300 };+ assert.deepEqual(+ clampToViewport(position, CARD.width, CARD.height, VIEWPORT),+ position,+ );+});++test("dragging past an edge keeps the whole card on screen", () => {+ const offRight = clampToViewport(+ { left: 5000, top: 5000 },+ CARD.width,+ CARD.height,+ VIEWPORT,+ );+ assert.equal(offRight.left, VIEWPORT.width - CARD.width - 8);+ assert.equal(offRight.top, VIEWPORT.height - CARD.height - 8);++ const offTopLeft = clampToViewport(+ { left: -500, top: -500 },+ CARD.width,+ CARD.height,+ VIEWPORT,+ );+ assert.deepEqual(offTopLeft, { left: 8, top: 8 });+});++// Expanding a pill that was dragged to the bottom edge grows the card+// downwards, which is what the re-clamp on resize has to catch.+test("a card taller than the space left is pulled back up", () => {+ const grown = clampToViewport(+ { left: 100, top: VIEWPORT.height - 60 },+ CARD.width,+ 320,+ VIEWPORT,+ );+ assert.equal(grown.top, VIEWPORT.height - 320 - 8);+});++test("a window smaller than the card still leaves it reachable", () => {+ const tiny = { width: 200, height: 120 };+ const clamped = clampToViewport(+ { left: 400, top: 400 },+ CARD.width,+ CARD.height,+ tiny,+ );+ assert.deepEqual(clamped, { left: 8, top: 8 });+});diff --git a/studio/frontend/tests/loaded-models-eject-chat.test.ts b/studio/frontend/tests/loaded-models-eject-chat.test.tsnew file mode 100644index 00000000000..e91db4df6cb--- /dev/null+++ b/studio/frontend/tests/loaded-models-eject-chat.test.ts@@ -0,0 +1,232 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++// The real comparator, not a stand-in: scoping the eject to one row is the whole+// behaviour, and a permissive fake would prove nothing about it.+import { modelIdsMatch } from "../src/features/hub/lib/model-identity.ts";+import {+ type ResidentChatModel,+ ejectChatModel,+} from "../src/features/loaded-models/eject-chat-model.ts";++function resident(checkpoint: string): ResidentChatModel {+ return { checkpoint, aliases: [checkpoint] };+}++/** A backend whose resident model follows `timeline`, one entry per status read.+ * An entry after the first is what an API auto-switch left there. */+function backend(+ timeline: (ResidentChatModel | null)[],+ cachedRow = false,+ /** What the runtime still holds after a cached row's unload. */+ cachedAfter: string[] | null = null,+) {+ const unloaded: string[] = [];+ let read = 0;+ return {+ unloaded,+ deps: {+ readResident: async () => timeline[Math.min(read++, timeline.length - 1)],+ unload: async (modelPath: string) => {+ unloaded.push(modelPath);+ },+ matches: modelIdsMatch,+ cachedRow,+ ...(cachedAfter === null ? {} : { readCached: async () => cachedAfter }),+ },+ };+}++test("the row's model is unloaded and reported free", async () => {+ const { unloaded, deps } = backend([resident("unsloth/Qwen3-4B"), null]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(unloaded, ["unsloth/Qwen3-4B"]);+ assert.deepEqual(result.unloadedAliases, ["unsloth/Qwen3-4B"]);+ assert.equal(result.stillResident, null);+});++// The reason this is scoped: the row is up to one poll old, so an auto-switch+// can land between the poll and the click.+test("a model that replaced the row's before the click is left alone", async () => {+ const { unloaded, deps } = backend([resident("unsloth/Llama-3.2-3B")]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.ok(+ !unloaded.includes("unsloth/Llama-3.2-3B"),+ "the model nobody clicked must survive",+ );+ // Nothing at all is unloaded. /unload naming a model the backend does not+ // hold answers 200 "unloaded", so firing it would report an eject that never+ // happened and clear the picker off the back of it.+ assert.deepEqual(unloaded, []);+ assert.deepEqual(result.unloadedAliases, []);+ assert.equal(result.stillResident, null);+ assert.equal(+ result.replacedBy,+ "unsloth/Llama-3.2-3B",+ "the caller needs the replacement's name to say what took its place",+ );+});++test("an idle runtime reports the row already gone, not a fresh eject", async () => {+ const { unloaded, deps } = backend([null]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(unloaded, [], "nothing is resident, so nothing to unload");+ assert.deepEqual(result.unloadedAliases, []);+ assert.equal(result.stillResident, null);+ // Null rather than a name: the runtime holds nothing, so there is no+ // replacement to name and the row is simply stale.+ assert.equal(result.replacedBy, null);+});++test("a switch landing mid-eject is not chased", async () => {+ const { unloaded, deps } = backend([+ resident("unsloth/Qwen3-4B"),+ resident("unsloth/Llama-3.2-3B"),+ ]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(unloaded, ["unsloth/Qwen3-4B"]);+ assert.equal(result.stillResident, null);+});++test("a target that survives its own unload is reported still resident", async () => {+ const { unloaded, deps } = backend([resident("unsloth/Qwen3-4B")]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ // Two passes, then it gives up and names it rather than looping.+ assert.deepEqual(unloaded, ["unsloth/Qwen3-4B", "unsloth/Qwen3-4B"]);+ assert.equal(result.stillResident, "unsloth/Qwen3-4B");+ // Both are set together here, so the caller must key the picker clear on+ // stillResident: the aliases alone would empty it while the model still runs.+ assert.ok(result.unloadedAliases.length > 0);+});++// A row the backend kept past the active model is never what a status read+// reports, so it is the one case that has to be named directly.+test("a cached row with nothing resident is still unloaded by name", async () => {+ const { unloaded, deps } = backend([null], true);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(unloaded, ["unsloth/Qwen3-4B"]);+ assert.deepEqual(result.unloadedAliases, ["unsloth/Qwen3-4B"]);+ assert.equal(result.replacedBy, null);+});++test("a cached row is unloaded even while another model is active", async () => {+ const { unloaded, deps } = backend([resident("unsloth/Llama-3.2-3B")], true);+ await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(+ unloaded,+ ["unsloth/Qwen3-4B"],+ "the cached copy goes, the active model stays",+ );+});++// /unload answers 200 for a name the backend no longer holds, and the cached+// row is the one path with no scoped read to catch that, so the reported+// success was the call itself rather than any evidence of a release.+test("a cached row the backend kept is reported still resident", async () => {+ const { unloaded, deps } = backend([null], true, ["unsloth/Qwen3-4B"]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(unloaded, ["unsloth/Qwen3-4B"], "the unload was attempted");+ assert.equal(result.stillResident, "unsloth/Qwen3-4B");+ assert.deepEqual(result.unloadedAliases, [], "nothing to clear the picker on");+});++test("a cached row the backend released is reported ejected", async () => {+ const { deps } = backend([null], true, ["unsloth/Llama-3.2-3B"]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.equal(result.stillResident, null);+ assert.deepEqual(result.unloadedAliases, ["unsloth/Qwen3-4B"]);+});++// Both the row and the confirmation come from the same `loaded` list, so the+// names line up by construction; the comparator is there for the day they do not.+test("a backend that cannot be re-read leaves the old reading alone", async () => {+ const { unloaded, deps } = backend([null], true);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(unloaded, ["unsloth/Qwen3-4B"]);+ assert.deepEqual(result.unloadedAliases, ["unsloth/Qwen3-4B"]);+ assert.equal(result.stillResident, null);+});++test("the load path and the advertised repo id are the same row", async () => {+ const loadPath = "/models/hub/models--unsloth--Qwen3-4B/snapshots/abc";+ const { unloaded, deps } = backend([+ { checkpoint: loadPath, aliases: [loadPath, "unsloth/Qwen3-4B"] },+ null,+ ]);+ await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(unloaded, [loadPath], "matched by identity, not by string");+});++/** A backend whose `loaded` list follows `timeline`, one entry per cached read,+ * with `active` resident throughout. What an eject sees when a load landed+ * between the card's last poll and the click. */+function replacedBackend(+ active: ResidentChatModel | null,+ timeline: string[][],+) {+ const unloaded: string[] = [];+ let read = 0;+ return {+ unloaded,+ deps: {+ readResident: async () => active,+ unload: async (modelPath: string) => {+ unloaded.push(modelPath);+ },+ matches: modelIdsMatch,+ readCached: async () => timeline[Math.min(read++, timeline.length - 1)],+ },+ };+}++// The row is up to one poll old, and a replacement does not evict what it+// replaced: the standard backend moves active_model_name and leaves the+// previous model in its registry, which /status goes on reporting under+// `loaded`. So another model being active is not evidence the row's is gone,+// and taking it as such freed nothing while telling the user it had.+test("a row replaced while still cached is unloaded, not written off", async () => {+ const { unloaded, deps } = replacedBackend(resident("unsloth/Llama-3.2-3B"), [+ ["unsloth/Qwen3-4B", "unsloth/Llama-3.2-3B"],+ ["unsloth/Llama-3.2-3B"],+ ]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(+ unloaded,+ ["unsloth/Qwen3-4B"],+ "the memory the click asked for is the memory released",+ );+ assert.deepEqual(result.unloadedAliases, ["unsloth/Qwen3-4B"]);+ assert.equal(result.stillResident, null);+ assert.equal(+ result.replacedBy,+ null,+ "an eject that ran is not a row that had already gone",+ );+});++// The other half of the same read: a runtime that really did let go still+// reports the replacement and unloads nothing, which is the whole point of+// scoping the eject to one row.+test("a row replaced and really gone is still left alone", async () => {+ const { unloaded, deps } = replacedBackend(resident("unsloth/Llama-3.2-3B"), [+ ["unsloth/Llama-3.2-3B"],+ ]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(unloaded, [], "nothing but the row's own model may go");+ assert.deepEqual(result.unloadedAliases, []);+ assert.equal(result.replacedBy, "unsloth/Llama-3.2-3B");+});++// Same window, with the replacement since unloaded: nothing is active, but the+// row's model is still held, so "already free" would have been wrong too.+test("an idle runtime still holding the row releases it", async () => {+ const { unloaded, deps } = replacedBackend(null, [["unsloth/Qwen3-4B"], []]);+ const result = await ejectChatModel("unsloth/Qwen3-4B", deps);+ assert.deepEqual(unloaded, ["unsloth/Qwen3-4B"]);+ assert.deepEqual(result.unloadedAliases, ["unsloth/Qwen3-4B"]);+ assert.equal(result.stillResident, null);+ assert.equal(result.replacedBy, null);+});diff --git a/studio/frontend/tests/loaded-models-eject-unverified.test.ts b/studio/frontend/tests/loaded-models-eject-unverified.test.tsnew file mode 100644index 00000000000..d5f358e7f44--- /dev/null+++ b/studio/frontend/tests/loaded-models-eject-unverified.test.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The dictation unload answers {loaded_model: null} whatever it did, and the+// backend serves `gguf` from the transformers engine when whisper-server is+// absent, so the eject re-reads the status to find out what actually happened.+// That re-read returns null on any non-2xx as well as on an empty runtime, and+// reading those two as the same thing defeats the check: a transient 404 on the+// verification would toast "Ejected" and drop a row whose model is still+// holding memory.+//+// The eject path is bound to authFetch and the chat store, so this asserts the+// shape of the decision rather than driving it: the three branches must be+// distinguishable, and the unreadable one must not be spelled `null`.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++const SOURCE = readFileSync(+ fileURLToPath(+ new URL("../src/features/loaded-models/loaded-models-api.ts", import.meta.url),+ ),+ "utf8",+);++test("an unreadable verification is its own outcome, not `ejected`", () => {+ assert.match(+ SOURCE,+ /\|\s*\{ status: "unverified" \}/,+ "EjectOutcome must be able to say the unload was not confirmed",+ );+ assert.match(+ SOURCE,+ /if \(stillResident === UNVERIFIED\) return \{ status: "unverified" \};/,+ "the runtime eject must map the sentinel before the null check",+ );+});++test("the STT re-read returns the sentinel rather than null on a failed read", () => {+ const stt = SOURCE.slice(SOURCE.indexOf('case "stt": {'), SOURCE.length);+ assert.match(stt, /const after = await bounded\(readSttStatus\);/);+ assert.match(+ stt,+ /if \(!after\) return UNVERIFIED;/,+ "a null status read is unreadable, not proof the engine is empty",+ );+ assert.doesNotMatch(+ stt.slice(stt.indexOf("const after")),+ /if \(!after\) return null;/,+ );+});++test("the sentinel is checked before the truthiness test that would hide it", () => {+ // A Symbol is truthy, so an UNVERIFIED reaching the `stillResident` branch+ // would report the runtime as still holding something called "Symbol()".+ const fn = SOURCE.slice(+ SOURCE.indexOf("const stillResident = await unload();"),+ SOURCE.indexOf("/** Release one row"),+ );+ assert.ok(+ fn.indexOf("UNVERIFIED") < fn.indexOf("stillResident\n"),+ "the sentinel check must precede the resident check",+ );+});++test("the user is told it was not confirmed, not that it worked", () => {+ const HOOK = readFileSync(+ fileURLToPath(+ new URL("../src/features/loaded-models/use-loaded-models.ts", import.meta.url),+ ),+ "utf8",+ );+ const branch = HOOK.slice(+ HOOK.indexOf('outcome.status === "unverified"'),+ HOOK.indexOf('outcome.status === "replaced"'),+ );+ assert.match(branch, /toast\.warning/, "neither success nor failure");+ assert.doesNotMatch(branch, /toast\.success/);+});diff --git a/studio/frontend/tests/loaded-models-pending-reset.test.ts b/studio/frontend/tests/loaded-models-pending-reset.test.tsnew file mode 100644index 00000000000..a813f677f00--- /dev/null+++ b/studio/frontend/tests/loaded-models-pending-reset.test.ts@@ -0,0 +1,214 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// An optimistic "Loading" row is only ever retired by the terminal lifecycle+// event, and nothing listens for that while the indicator is disabled. So a+// load in flight when the pref goes off leaves a pending entry that survives+// into the next enable, and `withPendingLoads` will keep rendering it: it+// yields only to a polled row for the same runtime, and a load that failed or+// was since unloaded has none. The result is a loading row no refresh can+// remove.+//+// The behaviour half is asserted against `withPendingLoads` directly; the+// wiring half by reading the source, since the node suite has no DOM to mount+// the hook into.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import {+ type LoadedModelEntry,+ type LoadedModelSource,+ withPendingLoads,+} from "../src/features/loaded-models/loaded-models-sources.ts";++const SOURCE = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/loaded-models/use-loaded-models.ts",+ import.meta.url,+ ),+ ),+ "utf8",+);++test("a stale pending entry outlives every poll, so it must not survive a disable", () => {+ const pending = new Map<LoadedModelSource, string | null>([+ ["image", "unsloth/flux"],+ ]);+ // What the poll reports after the load failed: this runtime holds nothing.+ const polled: LoadedModelEntry[] = [+ {+ id: "chat:qwen",+ kind: "text",+ source: "chat",+ name: "qwen",+ detail: "GGUF",+ },+ ];++ const rows = withPendingLoads(polled, pending);+ const image = rows.filter((row) => row.source === "image");+ assert.equal(image.length, 1);+ assert.equal(image[0].loading, true);++ // Only an empty pending map clears it; no status refresh can.+ assert.deepEqual(withPendingLoads(polled, new Map()), polled);+});++test("the hook drops pending loads once recording is turned off", () => {+ const guard = SOURCE.slice(+ SOURCE.indexOf("if (wasTracking !== track)"),+ SOURCE.indexOf("// The load call announces itself"),+ );+ assert.ok(guard.length > 0, "expected the enable-transition guard");+ assert.match(+ guard,+ /if \(!track && pending\.size > 0\) setPending\(new Map\(\)\)/,+ "turning recording off must empty the pending map",+ );+});++test("the clear runs once per transition, not on every render", () => {+ // Adjusting state during render only terminates if it is guarded by a change+ // in the value it tracks; an unguarded setPending would re-render forever.+ assert.match(+ SOURCE,+ /const \[wasTracking, setWasTracking\] = useState\(track\);\s*if \(wasTracking !== track\) \{\s*setWasTracking\(track\);/,+ "the adjustment must be gated on the previous tracking value",+ );+});++test("pending rows are cleared when recording stops, not when it starts", () => {+ // Clearing on the way back in would race the subscription: a load started+ // from another tab could be announced and then wiped.+ const guard = SOURCE.slice(+ SOURCE.indexOf("if (wasTracking !== track)"),+ SOURCE.indexOf("// The load call announces itself"),+ );+ assert.doesNotMatch(guard, /if \(track\) setPending/);+ assert.match(guard, /!track &&/);+});++// A replacement load is the case the source-only suppression got wrong. The+// backend keeps the old pipeline in _state and frees it only at the commit,+// after the whole download, so /images/status reports the OLD model for+// minutes while the announcement names the new one.+test("a replacement load shows alongside the model it is replacing", () => {+ const resident: LoadedModelEntry[] = [+ {+ id: "image:unsloth/flux-old",+ kind: "image",+ source: "image",+ name: "unsloth/flux-old",+ detail: "FLUX · BF16 · cuda",+ },+ ];+ const pending = new Map<LoadedModelSource, string | null>([+ ["image", "unsloth/flux-new"],+ ]);++ const rows = withPendingLoads(resident, pending);+ assert.equal(rows.length, 2);+ assert.equal(rows[1].name, "unsloth/flux-new");+ assert.equal(rows[1].loading, true);+});++test("the resident row wins once the replacement has committed", () => {+ const committed: LoadedModelEntry[] = [+ {+ id: "image:unsloth/flux-new",+ kind: "image",+ source: "image",+ name: "unsloth/flux-new",+ detail: "FLUX · BF16 · cuda",+ },+ ];+ const pending = new Map<LoadedModelSource, string | null>([+ ["image", "unsloth/flux-new"],+ ]);+ assert.deepEqual(withPendingLoads(committed, pending), committed);+});++test("a status loading row still suppresses the announcement", () => {+ // Chat and dictation report their own loading rows, and the backend may spell+ // the name differently, so those must not double up.+ const loadingRow: LoadedModelEntry[] = [+ {+ id: "chat:models/qwen3-0.6b.gguf",+ kind: "text",+ source: "chat",+ name: "models/qwen3-0.6b.gguf",+ detail: "Loading",+ loading: true,+ },+ ];+ const pending = new Map<LoadedModelSource, string | null>([+ ["chat", "unsloth/Qwen3-0.6B-GGUF"],+ ]);+ assert.deepEqual(withPendingLoads(loadingRow, pending), loadingRow);+});++test("an unnamed announcement defers to any row for its runtime", () => {+ const resident: LoadedModelEntry[] = [+ {+ id: "video:unsloth/wan",+ kind: "video",+ source: "video",+ name: "unsloth/wan",+ detail: "WAN",+ },+ ];+ const pending = new Map<LoadedModelSource, string | null>([["video", null]]);+ assert.deepEqual(withPendingLoads(resident, pending), resident);+});++// Closing the card means "not now", so the next load reopens it. That only+// works if the announcement is still being RECORDED while the card is closed:+// the indicator clears the dismissal from its own subscription, but the rows+// come from this hook's, and gating that one on `enabled` lost the very event+// that was meant to bring the card back. Chat and dictation would have limped+// on, since the poll synthesises their loading rows; images and video have no+// such fallback, so the card stayed hidden for the whole load.+test("recording is gated on the preference, not on whether the card shows", () => {+ const SOURCE = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/loaded-models/use-loaded-models.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ assert.match(+ SOURCE,+ /track: boolean = enabled/,+ "the hook must take a recording flag distinct from the showing flag",+ );+ const subscribe = SOURCE.slice(+ SOURCE.indexOf("// The load call announces itself"),+ SOURCE.indexOf("}, [track, refresh]);") + 22,+ );+ assert.match(subscribe, /if \(!track\) return;/);+ assert.doesNotMatch(subscribe, /if \(!enabled\) return;/);++ const INDICATOR = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/loaded-models/loaded-models-indicator.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ // Dismissal must not stop the recording, or the card cannot reopen for the+ // load. Reachability must, since it carries the auth gate: tracking on the+ // preference alone polled four protected endpoints every 5s on /login.+ assert.match(+ INDICATOR,+ /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-platform-matrix.test.ts b/studio/frontend/tests/loaded-models-platform-matrix.test.tsnew file mode 100644index 00000000000..1cd5df14fd8--- /dev/null+++ b/studio/frontend/tests/loaded-models-platform-matrix.test.ts@@ -0,0 +1,399 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The indicator is the only screen that reads all four runtimes at once, so it+// is also the only one that sees every hardware shape the backend can report.+// None of that is visible from a CUDA dev box: ROCm reports itself as "cuda"+// (diffusion_device.py, "Apple Silicon maps to MPS and ROCm to cuda"), Apple+// reports "mps" and never "mlx", Intel XPU reports "xpu" for images but "cpu"+// for dictation because stt_sidecar._pick_device never checks torch.xpu, and the+// sd.cpp engine Macs and CPU-only hosts fall back to omits model_kind entirely+// and puts "gguf" in dtype instead.+//+// So this walks the payloads [Windows, Linux, WSL, macOS] x [NVIDIA, AMD ROCm,+// Intel XPU, CPU-only, Apple] actually produce, and asserts the row each one+// renders. The OS axis is not a separate assertion for the chat/images/video+// rows because the backend emits identical JSON for it -- what the OS changes is+// which accelerator branch is reachable, and that is the axis enumerated here.++import assert from "node:assert/strict";+import test from "node:test";++import type { InferenceStatusResponse } from "../src/features/chat/types/api.ts";+import type { DiffusionStatus } from "../src/features/images/api.ts";+import {+ type SttStatusResponse,+ describeDiffusionStatus,+ describeInferenceStatus,+ describeSttStatus,+ describeVideoStatus,+ mergeLoadedModels,+} from "../src/features/loaded-models/loaded-models-sources.ts";+import type { VideoStatus } from "../src/features/video/api.ts";++// The handler returns a bare model with every flag false when nothing is+// loaded, so a partial fixture stands in for the full response.+function chat(+ overrides: Partial<InferenceStatusResponse>,+): InferenceStatusResponse {+ return {+ active_model: null,+ loaded: [],+ is_gguf: false,+ is_mlx: false,+ is_vision: false,+ is_audio: false,+ audio_type: null,+ gguf_variant: null,+ ...overrides,+ } as InferenceStatusResponse;+}++function diffusion(overrides: Partial<DiffusionStatus>): DiffusionStatus {+ return {+ loaded: false,+ repo_id: null,+ family: null,+ device: null,+ dtype: null,+ model_kind: null,+ ...overrides,+ } as DiffusionStatus;+}++function video(overrides: Partial<VideoStatus>): VideoStatus {+ return {+ loaded: false,+ repo_id: null,+ family: null,+ device: null,+ dtype: null,+ model_kind: null,+ transformer_quant: null,+ ...overrides,+ } as VideoStatus;+}++// ── Chat runtime: the accelerator axis ──────────────────────────────────++test("a GGUF chat model reads the same on every accelerator", () => {+ // llama.cpp runs on NVIDIA, AMD, Intel, Apple and plain CPU, and the GGUF+ // branch is chosen purely by llama_backend.is_loaded with no hardware gate.+ // is_mlx is force-set false there, so it must never win the runtime ladder.+ for (const host of ["nvidia", "rocm", "xpu", "cpu-only", "apple"]) {+ const rows = describeInferenceStatus(+ chat({+ active_model: "unsloth/Qwen3-4B-GGUF",+ loaded: ["unsloth/Qwen3-4B-GGUF"],+ is_gguf: true,+ gguf_variant: "Q4_K_M",+ }),+ );+ assert.equal(rows.length, 1, host);+ assert.equal(rows[0].kind, "text", host);+ assert.equal(rows[0].detail, "GGUF · Q4_K_M", host);+ }+});++test("Apple Silicon MLX is labelled MLX, and only there", () => {+ const mlx = describeInferenceStatus(+ chat({ active_model: "mlx-community/Qwen3-4B-4bit", is_mlx: true }),+ );+ assert.equal(mlx[0].detail, "MLX");+ // An Intel Mac, or Apple Silicon whose MLX stack is unusable, falls back to+ // DeviceType.CPU and reports is_mlx false -- so it must read as Transformers.+ const intelMac = describeInferenceStatus(+ chat({ active_model: "unsloth/Qwen3-4B", is_mlx: false }),+ );+ assert.equal(intelMac[0].detail, "Transformers");+});++test("GGUF wins over MLX if a payload ever claims both", () => {+ // Defensive: the backend force-sets is_mlx false on the GGUF branch, but the+ // ladder must not depend on that to avoid mislabelling the runtime.+ const rows = describeInferenceStatus(+ chat({+ active_model: "unsloth/Qwen3-4B-GGUF",+ is_gguf: true,+ is_mlx: true,+ gguf_variant: "UD-Q4_K_XL",+ }),+ );+ assert.equal(rows[0].detail, "GGUF · UD-Q4_K_XL");+});++test("a vision model is marked on any backend", () => {+ const rows = describeInferenceStatus(+ chat({+ active_model: "unsloth/gemma-3-4b-it",+ is_vision: true,+ }),+ );+ assert.equal(rows[0].detail, "Transformers · Vision");+ assert.equal(rows[0].kind, "text", "vision is still a chat row");+});++// ── Chat runtime: every audio_type the backend can emit ─────────────────++test("audio models split three ways, not two", () => {+ // VALID_AUDIO_TYPES in model_config.py. is_audio means TTS here, as+ // mlx_inference documents, so the split is not simply in-vs-out: whisper is+ // the ASR sidecar, audio_vlm is a chat model that listens and still answers+ // prompts, and the remaining four speak.+ const speaks = ["snac", "csm", "bicodec", "dac"];+ for (const audioType of speaks) {+ const rows = describeInferenceStatus(+ chat({ active_model: `m/${audioType}`, is_audio: true, audio_type: audioType }),+ );+ assert.equal(rows[0].kind, "tts", `${audioType} produces audio`);+ }+ const whisper = describeInferenceStatus(+ chat({ active_model: "m/whisper", is_audio: true, audio_type: "whisper" }),+ );+ assert.equal(whisper[0].kind, "stt", "whisper transcribes, it does not answer");+ // Gemma 3n. The Transformers path can report is_audio true for it (the codec+ // load at inference.py:520 is skipped by name, not by the flag), so filing it+ // by the flag alone would hide a chat model under Speech or Dictation.+ const vlm = describeInferenceStatus(+ chat({ active_model: "unsloth/gemma-3n-E4B-it", is_audio: true, audio_type: "audio_vlm" }),+ );+ assert.equal(vlm[0].kind, "text", "an audio VLM is a chat model that listens");+});++test("an audio flag with no type still reads as speech", () => {+ // audio_type detection can come back null on a model the tokenizer scan could+ // not classify. It is not an input type, so the TTS default is right.+ const rows = describeInferenceStatus(+ chat({ active_model: "m/unknown", is_audio: true, audio_type: null }),+ );+ assert.equal(rows[0].kind, "tts");+});++test("audio_type without is_audio does not make an audio row", () => {+ const rows = describeInferenceStatus(+ chat({ active_model: "m/x", is_audio: false, audio_type: "whisper" }),+ );+ assert.equal(rows[0].kind, "text");+});++// ── Diffusion: the device vocabulary, and the two engines ───────────────++test("every device the diffusion resolver can report renders", () => {+ // resolve_diffusion_device_target() emits exactly these four, never cuda:0.+ const expected: Record<string, string> = {+ cuda: "flux · BF16 · cuda", // NVIDIA, and AMD ROCm, which reports cuda too+ xpu: "flux · BF16 · xpu", // Intel Arc / Data Center GPU+ mps: "flux · BF16 · mps", // Apple Silicon under the diffusers engine+ cpu: "flux · BF16 · cpu", // no accelerator, or no torch at all+ };+ for (const [device, detail] of Object.entries(expected)) {+ const rows = describeDiffusionStatus(+ diffusion({+ loaded: true,+ repo_id: "black-forest-labs/FLUX.1-dev",+ family: "flux",+ device,+ dtype: "bfloat16",+ model_kind: "pipeline",+ }),+ );+ assert.equal(rows[0].detail, detail, device);+ assert.equal(rows[0].source, "image", device);+ }+});++test("the sd.cpp engine still says GGUF without a model_kind", () => {+ // sd_cpp_backend.status() has no model_kind key at all and puts the literal+ // "gguf" in dtype. This is the Mac / CPU-only shape, so it is the one most+ // likely to go untested on a CUDA box.+ const rows = describeDiffusionStatus(+ diffusion({+ loaded: true,+ repo_id: "unsloth/FLUX.1-dev-GGUF",+ family: "flux",+ device: "cpu",+ dtype: "gguf",+ }),+ );+ assert.equal(rows[0].detail, "flux · GGUF · cpu");+});++test("a GGUF image model under the diffusers engine is not doubled", () => {+ // Here model_kind IS "gguf" and dtype is a real precision, so both the kind+ // and the precision have something to say and neither should repeat.+ const rows = describeDiffusionStatus(+ diffusion({+ loaded: true,+ repo_id: "unsloth/FLUX.1-dev-GGUF",+ family: "flux",+ device: "cuda",+ dtype: "gguf",+ model_kind: "gguf",+ }),+ );+ assert.equal(rows[0].detail, "flux · GGUF · cuda");+});++test("a diffusion runtime with no repo id yields no row", () => {+ // loaded and repo_id are always set together, but a row with no name would be+ // unejectable, so refusing it is worth pinning.+ assert.deepEqual(+ describeDiffusionStatus(diffusion({ loaded: true, repo_id: null })),+ [],+ );+});++// ── Video: NVIDIA/Intel only in practice, but the payload is the contract ──++test("video precision prefers the transformer quant over the dtype", () => {+ const rows = describeVideoStatus(+ video({+ loaded: true,+ repo_id: "Wan-AI/Wan2.2-T2V-A14B",+ family: "wan",+ device: "cuda",+ dtype: "bfloat16",+ transformer_quant: "fp8",+ }),+ );+ assert.equal(rows[0].detail, "wan · FP8 · cuda");+ assert.equal(rows[0].kind, "video");+});++test("video falls back to the dtype when unquantised", () => {+ const rows = describeVideoStatus(+ video({+ loaded: true,+ repo_id: "Wan-AI/Wan2.2-T2V-A14B",+ family: "wan",+ device: "cuda",+ dtype: "bfloat16",+ transformer_quant: null,+ }),+ );+ assert.equal(rows[0].detail, "wan · BF16 · cuda");+});++test('a "none" quant is not printed as a precision', () => {+ const rows = describeVideoStatus(+ video({+ loaded: true,+ repo_id: "Wan-AI/Wan2.2-T2V-A14B",+ family: "wan",+ device: "cuda",+ dtype: "none",+ transformer_quant: "none",+ }),+ );+ assert.equal(rows[0].detail, "wan · cuda");+});++test("a host that can never run video reports an empty runtime, not an error", () => {+ // The video router is registered unconditionally and imports torch lazily, so+ // macOS and CPU-only hosts get a clean loaded:false rather than a 404.+ assert.deepEqual(describeVideoStatus(video({ loaded: false })), []);+});++// ── Dictation: three engines, and a "device" that is not a device ────────++test("each dictation engine reports its own row", () => {+ const rows = describeSttStatus({+ transformers: { loaded_model: "large-v3", device: "cuda" },+ mtmd: { loaded_model: "qwen3-asr-0.6b", device: "llama.cpp" },+ gguf: { loaded_model: "ggml-base.en", device: "whisper.cpp" },+ } as SttStatusResponse);+ assert.deepEqual(+ rows.map((row) => row.detail),+ // The sidecars put their engine name in device, so it must not print twice.+ ["Transformers · cuda", "llama.cpp", "whisper.cpp"],+ );+ assert.deepEqual(+ rows.map((row) => row.sttEngine),+ ["transformers", "mtmd", "gguf"],+ );+});++test("dictation on Apple and on CPU-only hosts", () => {+ // _pick_device() in stt_sidecar.py knows only cuda/mps/cpu -- notably NOT xpu,+ // so an Intel GPU host reports cpu here while images report xpu.+ for (const device of ["mps", "cpu"]) {+ const rows = describeSttStatus({+ transformers: { loaded_model: "small", device },+ } as SttStatusResponse);+ assert.equal(rows[0].detail, `Transformers · ${device}`, device);+ }+});++test("an engine holding nothing contributes no row", () => {+ const rows = describeSttStatus({+ transformers: { loaded_model: null, device: null },+ mtmd: { loaded_model: null, device: null },+ gguf: { loaded_model: null, device: null },+ } as SttStatusResponse);+ assert.deepEqual(rows, []);+});++// ── The merge, across a fully loaded host ───────────────────────────────++test("a host holding all four runtimes lists them in a fixed order", () => {+ const rows = mergeLoadedModels([+ describeInferenceStatus(+ chat({+ active_model: "unsloth/Qwen3-4B-GGUF",+ is_gguf: true,+ gguf_variant: "Q4_K_M",+ }),+ ),+ describeDiffusionStatus(+ diffusion({+ loaded: true,+ repo_id: "black-forest-labs/FLUX.1-dev",+ family: "flux",+ device: "cuda",+ dtype: "bfloat16",+ }),+ ),+ describeVideoStatus(+ video({+ loaded: true,+ repo_id: "Wan-AI/Wan2.2-T2V-A14B",+ family: "wan",+ device: "cuda",+ dtype: "bfloat16",+ }),+ ),+ describeSttStatus({+ transformers: { loaded_model: "large-v3", device: "cuda" },+ } as SttStatusResponse),+ ]);+ assert.deepEqual(+ rows.map((row) => row.source),+ ["chat", "image", "video", "stt"],+ "a stable order stops rows jumping between polls",+ );+ assert.equal(new Set(rows.map((row) => row.id)).size, 4, "ids are unique");+});++test("a whisper model in chat and in dictation is two rows, not one", () => {+ // These really are two resident copies: chat loads it inside the inference+ // subprocess, dictation in its own in-process sidecar. Collapsing them would+ // hide a copy the user cannot then free.+ const rows = mergeLoadedModels([+ describeInferenceStatus(+ chat({+ active_model: "openai/whisper-large-v3",+ is_audio: true,+ audio_type: "whisper",+ }),+ ),+ describeSttStatus({+ transformers: { loaded_model: "openai/whisper-large-v3", device: "cuda" },+ } as SttStatusResponse),+ ]);+ assert.equal(rows.length, 2);+ assert.deepEqual(+ rows.map((row) => row.source),+ ["chat", "stt"],+ "each row must eject through its own runtime",+ );+});diff --git a/studio/frontend/tests/loaded-models-settled-retire.test.ts b/studio/frontend/tests/loaded-models-settled-retire.test.tsnew file mode 100644index 00000000000..4549c8e92bf--- /dev/null+++ b/studio/frontend/tests/loaded-models-settled-retire.test.ts@@ -0,0 +1,61 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A finished load is retired from `pending` once a status read has replaced its+// optimistic row with a real one. If that read could not see the source, there+// is no real row to replace it with: `readLoadedModels` is handed the polled+// rows only, and an optimistic row lives in `pending`, so it has nothing to+// preserve. Retiring anyway takes the row for a model that has just finished+// loading off the card, on the strength of a request that failed.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++function read(path: string): string {+ return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");+}++const HOOK = read("../src/features/loaded-models/use-loaded-models.ts");+const API = read("../src/features/loaded-models/loaded-models-api.ts");++test("the read reports which sources it could not see", () => {+ assert.match(API, /export type LoadedModelsRead = \{/);+ assert.match(API, /unreadable: LoadedModelSource\[\];/);+ // Every source that fell back to the previous rows is named, so the caller+ // can tell "still there" from "confirmed gone".+ assert.match(API, /unreadable\.push\(source\);/);+ assert.match(API, /return \{ entries, unreadable \};/);+});++test("an unreadable source keeps its settled row", () => {+ const retire = HOOK.slice(+ HOOK.indexOf("const retireSettled = useCallback("),+ HOOK.indexOf("const refreshRef ="),+ );+ assert.match(retire, /unreadable: LoadedModelSource\[\] = \[\]/);+ assert.match(retire, /\.filter\(\s*\(source\) => !unreadable\.includes\(source\)/);+ // And it stays settled, so the next readable poll is the one that retires it.+ assert.match(retire, /settledRef\.current = new Set\(/);+});++test("a read that failed outright is evidence about nothing", () => {+ assert.match(HOOK, /const ALL_SOURCES: LoadedModelSource\[\] = \["chat", "image", "video", "stt"\]/);+ const refresh = HOOK.slice(+ HOOK.indexOf("void readLoadedModels(polledRef.current)"),+ HOOK.indexOf("}, [track, retireSettled]);"),+ );+ assert.match(refresh, /unreadable = ALL_SOURCES;/);+ assert.match(refresh, /retireSettled\(unreadable\)/);+});++test("a readable source is still retired, or the row would never go", () => {+ const retire = HOOK.slice(+ HOOK.indexOf("const retireSettled = useCallback("),+ HOOK.indexOf("const refreshRef ="),+ );+ // The early return is on nothing left to retire, not on anything unreadable.+ assert.match(retire, /if \(done\.length === 0\) return;/);+ assert.match(retire, /for \(const source of done\) next\.delete\(source\);/);+});diff --git a/studio/frontend/tests/loaded-models-sources.test.ts b/studio/frontend/tests/loaded-models-sources.test.tsnew file mode 100644index 00000000000..e9f98ab470b--- /dev/null+++ b/studio/frontend/tests/loaded-models-sources.test.ts@@ -0,0 +1,459 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++// The indicator .tsx pulls in the router, motion and hugeicons, so it cannot be+// imported here. The status to row mapping lives in a plain module, driven directly.+import { modelIdsMatch } from "../src/features/hub/lib/model-identity.ts";+import {+ type LoadedModelEntry,+ describeDiffusionStatus,+ describeInferenceStatus,+ describeSttStatus,+ describeVideoStatus,+ loadedModelTarget,+ mergeLoadedModels,+ withPendingLoads,+ shortModelLabel,+ verifyResident,+} from "../src/features/loaded-models/loaded-models-sources.ts";++// Only the fields the mapping reads; the real responses carry dozens more.+function inferenceStatus(+ overrides: Record<string, unknown> = {},+): Parameters<typeof describeInferenceStatus>[0] {+ return {+ active_model: null,+ is_vision: false,+ loading: [],+ loaded: [],+ ...overrides,+ } as Parameters<typeof describeInferenceStatus>[0];+}++test("no runtime loaded produces no rows", () => {+ assert.deepEqual(describeInferenceStatus(inferenceStatus()), []);+ assert.deepEqual(describeDiffusionStatus({ loaded: false } as never), []);+ assert.deepEqual(describeVideoStatus({ loaded: false } as never), []);+ assert.deepEqual(describeSttStatus({}), []);+});++test("an unreachable runtime yields no rows rather than throwing", () => {+ assert.deepEqual(describeInferenceStatus(null), []);+ assert.deepEqual(describeDiffusionStatus(null), []);+ assert.deepEqual(describeVideoStatus(null), []);+ assert.deepEqual(describeSttStatus(null), []);+});++test("a GGUF chat model reports its variant", () => {+ const [row] = describeInferenceStatus(+ inferenceStatus({+ active_model: "unsloth/gemma-3-4b-it-GGUF",+ is_gguf: true,+ gguf_variant: "Q4_K_M",+ loaded: ["unsloth/gemma-3-4b-it-GGUF"],+ }),+ );+ assert.equal(row.kind, "text");+ assert.equal(row.source, "chat");+ assert.equal(row.detail, "GGUF · Q4_K_M");+});++// Same picker, same memory, but only one of them answers prompts.+test("an audio model is a speech row, and a whisper one is dictation", () => {+ const [tts] = describeInferenceStatus(+ inferenceStatus({+ active_model: "unsloth/orpheus-3b-0.1-ft",+ is_audio: true,+ audio_type: "tts",+ }),+ );+ assert.equal(tts.kind, "tts");+ const [stt] = describeInferenceStatus(+ inferenceStatus({+ active_model: "openai/whisper-large-v3",+ is_audio: true,+ audio_type: "whisper",+ }),+ );+ assert.equal(stt.kind, "stt");+ // Still the chat runtime's, so it ejects through /api/inference/unload.+ assert.equal(stt.source, "chat");+});++test("a model the runtime still holds besides the active one gets its own row", () => {+ const rows = describeInferenceStatus(+ inferenceStatus({+ active_model: "unsloth/Llama-3.2-3B",+ loaded: ["unsloth/Llama-3.2-3B", "unsloth/Qwen3-4B"],+ }),+ );+ assert.equal(rows.length, 2);+ assert.equal(rows[0].inactive, undefined);+ assert.equal(rows[1].name, "unsloth/Qwen3-4B");+ assert.equal(rows[1].inactive, true);+});++// A server predating the engine split reports only the top-level fields.+test("a legacy STT status still shows its resident Transformers model", () => {+ const rows = describeSttStatus({+ loaded_model: "openai/whisper-large-v3",+ device: "cuda",+ });+ assert.deepEqual(+ rows.map((row) => [row.sttEngine, row.name, row.detail]),+ [["transformers", "openai/whisper-large-v3", "Transformers · cuda"]],+ );+});++test("an engine block wins over the legacy fields, and never doubles a row", () => {+ const rows = describeSttStatus({+ loaded_model: "openai/whisper-large-v3",+ device: "cuda",+ transformers: { loaded_model: null },+ });+ assert.deepEqual(rows, []);+});++test("each STT engine that has a model resident gets a row naming its engine", () => {+ const rows = describeSttStatus({+ transformers: { loaded_model: null },+ mtmd: { loaded_model: "unsloth/voxtral-mini", device: "cuda" },+ gguf: { loaded_model: "ggml-base.en", device: "metal" },+ });+ assert.deepEqual(+ rows.map((row) => [row.sttEngine, row.name]),+ [+ ["mtmd", "unsloth/voxtral-mini"],+ ["gguf", "ggml-base.en"],+ ],+ );+ assert.equal(rows[0].detail, "llama.cpp · cuda");+});++// Those two sidecars report their engine name as the device, so the label and+// the device are the same string and must not print twice.+test("an engine that reports itself as its device is named once", () => {+ const rows = describeSttStatus({+ mtmd: { loaded_model: "qwen3-asr-0.6b", device: "llama.cpp" },+ gguf: { loaded_model: "ggml-base.en", device: "whisper.cpp" },+ });+ assert.deepEqual(+ rows.map((row) => row.detail),+ ["llama.cpp", "whisper.cpp"],+ );+});++test("a real device is still reported next to its engine", () => {+ const [row] = describeSttStatus({+ transformers: { loaded_model: "openai/whisper-large-v3", device: "cuda" },+ });+ assert.equal(row.detail, "Transformers · cuda");+});++test("image and video rows omit the parts the backend did not report", () => {+ const [image] = describeDiffusionStatus({+ loaded: true,+ repo_id: "unsloth/FLUX.1-dev",+ family: "flux",+ device: null,+ } as never);+ assert.equal(image.detail, "flux");+ const [video] = describeVideoStatus({+ loaded: true,+ repo_id: "unsloth/Wan2.2-T2V-A14B",+ family: "wan",+ model_kind: "gguf",+ device: "cuda",+ } as never);+ assert.equal(video.detail, "wan · GGUF · cuda");+});++test("a row names the precision the pipeline actually loaded at", () => {+ const [image] = describeDiffusionStatus({+ loaded: true,+ repo_id: "unsloth/FLUX.1-dev",+ family: "flux",+ dtype: "bfloat16",+ device: "cuda",+ } as never);+ assert.equal(image.detail, "flux · BF16 · cuda");++ // The dense transformer's quantisation is what tells the builds apart, so it+ // wins over the pipeline dtype.+ const [video] = describeVideoStatus({+ loaded: true,+ repo_id: "unsloth/Wan2.2-T2V-A14B",+ family: "wan",+ dtype: "bfloat16",+ transformer_quant: "fp8",+ device: "cuda",+ } as never);+ assert.equal(video.detail, "wan · FP8 · cuda");+});++test("a bf16 video load falls back to the pipeline dtype", () => {+ const [video] = describeVideoStatus({+ loaded: true,+ repo_id: "unsloth/Wan2.2-T2V-A14B",+ family: "wan",+ dtype: "bfloat16",+ // "none" is the backend's word for plain bf16, not a precision to print.+ transformer_quant: "none",+ device: "cuda",+ } as never);+ assert.equal(video.detail, "wan · BF16 · cuda");+});++test("a GGUF image load does not print GGUF twice", () => {+ const [image] = describeDiffusionStatus({+ loaded: true,+ repo_id: "unsloth/FLUX.1-dev-GGUF",+ family: "flux",+ model_kind: "gguf",+ dtype: "gguf",+ device: "cuda",+ } as never);+ assert.equal(image.detail, "flux · GGUF · cuda");+});++// Gemma 3n and friends take audio in but answer as chat. Every backend sets+// is_audio from `audio_type is not None and audio_type != "audio_vlm"`+// (model_config.py, mlx_inference.py; llama_cpp.py keeps _is_audio False for+// csm/whisper/audio_vlm), so the TTS test never sees one.+test("an audio-input VLM stays a chat row, not Speech", () => {+ const [row] = describeInferenceStatus(+ inferenceStatus({+ active_model: "unsloth/gemma-3n-E4B-it",+ is_audio: false,+ audio_type: "audio_vlm",+ has_audio_input: true,+ }),+ );+ assert.equal(row.kind, "text");+});++test("a row opens the page its runtime is used on", () => {+ assert.deepEqual(loadedModelTarget("chat"), {+ open: "route",+ to: "/chat",+ label: "Chat",+ });+ assert.deepEqual(loadedModelTarget("image"), {+ open: "route",+ to: "/images",+ label: "Images",+ });+ assert.deepEqual(loadedModelTarget("video"), {+ open: "route",+ to: "/video",+ label: "Video",+ });+});++// Dictation has no page of its own, so it opens the tab that drives it.+test("a dictation row opens Voice settings", () => {+ assert.deepEqual(loadedModelTarget("stt"), {+ open: "settings",+ tab: "voice",+ label: "Voice settings",+ });+});++// A Whisper checkpoint in the chat slot is Chat's, not dictation's: the target+// follows the runtime holding the weights, not what the model does.+test("the target follows the runtime, not the kind", () => {+ const [chatWhisper] = describeInferenceStatus(+ inferenceStatus({+ active_model: "unsloth/whisper-large-v3",+ is_audio: true,+ audio_type: "whisper",+ }),+ );+ assert.equal(chatWhisper.kind, "stt");+ assert.equal(loadedModelTarget(chatWhisper.source).label, "Chat");+});++test("every runtime's rows appear together, in a fixed order", () => {+ const merged = mergeLoadedModels([+ describeInferenceStatus(+ inferenceStatus({+ active_model: "unsloth/orpheus-3b-0.1-ft",+ is_audio: true,+ }),+ ),+ describeDiffusionStatus({+ loaded: true,+ repo_id: "unsloth/FLUX.1-dev",+ } as never),+ describeVideoStatus(null),+ describeSttStatus({ gguf: { loaded_model: "ggml-base.en" } }),+ ]);+ assert.deepEqual(+ merged.map((row) => row.kind),+ ["tts", "image", "stt"],+ );+});++test("one runtime naming the same model twice is still one row", () => {+ const duplicated: LoadedModelEntry[] = [+ {+ id: "chat:unsloth/Qwen3-4B",+ kind: "text",+ source: "chat",+ name: "unsloth/Qwen3-4B",+ detail: "GGUF",+ },+ ];+ assert.equal(mergeLoadedModels([duplicated, duplicated]).length, 1);+});++// /images/unload, /video/unload and the STT unload carry no model id, so a row+// up to one poll old must be checked against the runtime before either fires.+test("a runtime holding the row's model is safe to unload", () => {+ assert.equal(+ verifyResident("unsloth/FLUX.1-dev", "unsloth/FLUX.1-dev", modelIdsMatch),+ "match",+ );+});++test("a runtime holding something else must not be unloaded", () => {+ assert.equal(+ verifyResident("unsloth/FLUX.1-dev", "unsloth/Qwen-Image", modelIdsMatch),+ "replaced",+ );+});++test("an idle runtime is already free, so there is nothing to unload", () => {+ assert.equal(+ verifyResident("unsloth/FLUX.1-dev", null, modelIdsMatch),+ "gone",+ );+ assert.equal(+ verifyResident("unsloth/FLUX.1-dev", undefined, modelIdsMatch),+ "gone",+ );+});++// These runtimes report repo_id / loaded_model, the same fields the rows were+// built from, so matching is exact bar the tolerance modelIdsMatch already has.+// A spurious "replaced" would refuse a legitimate eject, so pin that too.+test("a trailing separator or casing difference is not a replacement", () => {+ assert.equal(+ verifyResident("/models/flux", "/models/flux/", modelIdsMatch),+ "match",+ );+ assert.equal(+ verifyResident("unsloth/FLUX.1-dev", "unsloth/flux.1-dev", modelIdsMatch),+ "match",+ );+});++test("a local load shows its model folder rather than leading directories", () => {+ assert.equal(+ shortModelLabel("unsloth/gemma-3-4b-it"),+ "unsloth/gemma-3-4b-it",+ );+ assert.equal(+ shortModelLabel("/Users/me/models/hub/gemma-3-4b-it"),+ "hub/gemma-3-4b-it",+ );+ // Windows path, trailing separator: still the last two segments.+ assert.equal(shortModelLabel("C:\\models\\hub\\gemma\\"), "hub/gemma");+});++// The load toast appears at once, the poll is 5s behind it. /status reports a+// load for its whole duration, so the row can match the toast.+test("a chat model still loading gets its own row", () => {+ const rows = describeInferenceStatus(+ inferenceStatus({ loading: ["unsloth/Qwen3.5-9B-GGUF"] }),+ );+ assert.equal(rows.length, 1);+ assert.equal(rows[0].loading, true);+ assert.equal(rows[0].detail, "Loading");+});++test("a model that finished loading is not listed twice", () => {+ const rows = describeInferenceStatus(+ inferenceStatus({+ active_model: "unsloth/Qwen3.5-9B-GGUF",+ is_gguf: true,+ loading: ["unsloth/Qwen3.5-9B-GGUF"],+ }),+ );+ assert.equal(rows.length, 1);+ assert.notEqual(rows[0].loading, true);+});++test("a dictation sidecar that is starting shows as loading", () => {+ const [row] = describeSttStatus({ mtmd: { loading: true } });+ assert.equal(row.loading, true);+ assert.equal(row.sttEngine, "mtmd");+});++test("an announced load shows before any status confirms it", () => {+ const rows = withPendingLoads(+ [],+ new Map([["image", "unsloth/Z-Image-Turbo-GGUF"]]),+ );+ assert.equal(rows.length, 1);+ assert.equal(rows[0].kind, "image");+ assert.equal(rows[0].loading, true);+ assert.equal(rows[0].name, "unsloth/Z-Image-Turbo-GGUF");+});++// The backend's answer wins: otherwise a finished load shows twice for the+// moment between the status arriving and the settle event.+test("a status row for that runtime replaces the announced one", () => {+ const loaded = describeDiffusionStatus({+ loaded: true,+ repo_id: "unsloth/Z-Image-Turbo-GGUF",+ family: "z-image",+ } as never);+ const rows = withPendingLoads(+ loaded,+ new Map([["image", "unsloth/Z-Image-Turbo-GGUF"]]),+ );+ assert.equal(rows.length, 1);+ assert.notEqual(rows[0].loading, true);+});++test("nothing announced leaves the polled rows untouched", () => {+ const rows: LoadedModelEntry[] = [];+ assert.equal(withPendingLoads(rows, new Map()), rows);+});++// Swapping one image model for another: the outgoing one stays resident until+// the backend drops it, so yielding on source alone showed nothing loading for+// the whole swap, which is exactly when the toast says it is working.+test("a swap shows the incoming model alongside the outgoing one", () => {+ const resident = describeDiffusionStatus({+ loaded: true,+ repo_id: "unsloth/FLUX.1-dev",+ family: "flux",+ } as never);+ const rows = withPendingLoads(+ resident,+ new Map([["image", "unsloth/Z-Image-Turbo-GGUF"]]),+ );+ assert.equal(rows.length, 2);+ const incoming = rows.find((row) => row.loading);+ assert.equal(incoming?.name, "unsloth/Z-Image-Turbo-GGUF");+ assert.ok(rows.some((row) => row.name === "unsloth/FLUX.1-dev"));+});++test("the announced row yields once that same model is resident", () => {+ const resident = describeDiffusionStatus({+ loaded: true,+ repo_id: "unsloth/Z-Image-Turbo-GGUF",+ family: "z-image",+ } as never);+ const rows = withPendingLoads(+ resident,+ new Map([["image", "unsloth/Z-Image-Turbo-GGUF"]]),+ );+ assert.equal(rows.length, 1);+ assert.notEqual(rows[0].loading, true);+});diff --git a/studio/frontend/tests/media-eject-busy-state.test.ts b/studio/frontend/tests/media-eject-busy-state.test.tsnew file mode 100644index 00000000000..2bf3a35b99d--- /dev/null+++ b/studio/frontend/tests/media-eject-busy-state.test.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Images and video keep the old pipeline resident while a replacement+// downloads, so the indicator shows the resident row (ejectable) next to the+// incoming one (a spinner). Ejecting the resident row makes the backend cancel+// that replacement, and the page's own listener then tears down its tracking --+// including the load-progress poll, which is the ONLY thing that clears `busy`.+//+// Left set, `busy` locks the page: the picker ignores every choice, Generate+// and Reapply are disabled, and Unload is not even rendered once the status+// read comes back empty. Both pages are mounted for the whole app session, so+// navigating away and back does not reset it either -- only a reload did.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++// The runtime name is singular ("image"), the page is not: keep them apart, or+// the listener lookup silently finds nothing and every check passes vacuously.+const PAGES = [+ ["Images", "image", "../src/features/images/images-page.tsx"],+ ["Video", "video", "../src/features/video/video-page.tsx"],+] as const;++function read(path: string): string {+ return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");+}++for (const [page, runtime, path] of PAGES) {+ const SOURCE = read(path);+ const listener = SOURCE.slice(+ SOURCE.indexOf(`subscribeModelEjected("${runtime}"`),+ SOURCE.indexOf(`subscribeModelEjected("${runtime}"`) + 900,+ );++ test(`the ${page} page settles its busy state on an external eject`, () => {+ assert.ok(listener.length > 0, "expected the eject listener");+ assert.match(+ listener,+ /setBusy\(\(prev\) => \(prev === "loading" \? null : prev\)\)/,+ "the listener must clear a load that its own teardown just orphaned",+ );+ });++ test(`the ${page} page still stops the poll it is replacing`, () => {+ // The clear only matters because dropResidentState kills the poll; if that+ // ever stops being true the two lines should be revisited together.+ assert.match(listener, /dropResidentState\(\)/);+ const drop = SOURCE.slice(+ SOURCE.indexOf("const dropResidentState = useCallback("),+ SOURCE.indexOf("const dropResidentState = useCallback(") + 500,+ );+ assert.match(drop, /clearTimeout\(pollTimer\.current\)/);+ assert.doesNotMatch(+ drop,+ /setBusy/,+ "kept in the listener: handleUnload sets busy right after calling this",+ );+ });++ test(`the ${page} page leaves a generation alone`, () => {+ // An unconditional clear would also drop "generating". The backend unload+ // blocks on the generate lock so that is near unreachable, but narrowing it+ // costs nothing.+ assert.doesNotMatch(listener, /setBusy\(null\)/);+ });+}diff --git a/studio/frontend/tests/media-status-sequencing.test.ts b/studio/frontend/tests/media-status-sequencing.test.tsnew file mode 100644index 00000000000..269435134aa--- /dev/null+++ b/studio/frontend/tests/media-status-sequencing.test.ts@@ -0,0 +1,61 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The Images and Video pages hold their own status and re-read it on tab+// activation and on their own actions, never on a timer. So two reads can be in+// flight across an eject: an activation read that saw the pipeline loaded, and+// the post-eject read that saw it gone. Responses have no order, and the older+// one landing last left the page offering to generate against a freed runtime,+// with no poll coming to correct it.+//+// Asserted by reading the source: both pages pull in the whole media runtime,+// which the node suite cannot mount.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++function source(path: string): string {+ return readFileSync(fileURLToPath(new URL(`../src/${path}`, import.meta.url)), "utf8");+}++const PAGES = [+ ["images", "features/images/images-page.tsx", "getDiffusionStatus", "unloadDiffusionModel"],+ ["video", "features/video/video-page.tsx", "getVideoStatus", "unloadVideoModel"],+] as const;++for (const [name, path, read, unload] of PAGES) {+ test(`the ${name} page lets only the newest status read write`, () => {+ const page = source(path);+ assert.match(page, /const statusTicket = useRef\(0\);/);+ assert.match(+ page,+ /if \(ticket === statusTicket\.current\) setStatus\(next\);/,+ "a superseded read must not write",+ );+ // Every writer goes through it, so none can be the one that slips past.+ assert.doesNotMatch(+ page,+ new RegExp(`setStatus\\(await ${read}\\(\\)\\)`),+ "the bare read must not write directly",+ );+ assert.doesNotMatch(+ page,+ new RegExp(`setStatus\\(await ${unload}\\(\\)\\)`),+ "nor the unload",+ );+ assert.equal(+ (page.match(/setStatusIfNewest\(/g) ?? []).length,+ 3,+ "the refresh, the load-progress read and the unload all go through it",+ );+ });++ test(`the ${name} page claims its ticket before awaiting, not after`, () => {+ const page = source(path);+ // Claiming after the await would hand every read the newest ticket and+ // defeat the whole thing.+ assert.match(page, /const ticket = \+\+statusTicket\.current;\s*\n\s*try \{/);+ });+}diff --git a/studio/frontend/tests/monitor-frame-ownership.test.ts b/studio/frontend/tests/monitor-frame-ownership.test.tsnew file mode 100644index 00000000000..905074a894d--- /dev/null+++ b/studio/frontend/tests/monitor-frame-ownership.test.ts@@ -0,0 +1,193 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Closing and reopening the Live monitor inside its exit animation leaves two+// panels mounted at once: AnimatePresence keeps the leaving child rendered and+// drops it in a later commit (framer-motion's AnimatePresence calls+// setRenderedChildren(pendingPresentChildren.current) only once every exit has+// completed), so the replacement mounts and publishes first and the old panel+// unmounts last. Its cleanup must not take the replacement's frame with it.++// The store's half is asserted directly; the panel's half by reading the+// source, since the node suite has no DOM to mount two panels into.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import {+ type MonitorFrame,+ useMonitorFrameStore,+} from "../src/features/settings/stores/monitor-frame-store.ts";++const PANEL_SOURCE = readFileSync(+ fileURLToPath(+ new URL("../src/components/floating-monitor.tsx", import.meta.url),+ ),+ "utf8",+);++/** The Live monitor where it opens by default: bottom-right, w-64, inset-4. */+function corner(height = 300): MonitorFrame {+ return { left: 1168, top: 884 - height, right: 1424, bottom: 884 };+}++/** Every published box, in publish order. Replaces the merged rectangle the+ * store used to expose: it merged obstacles that do not touch. */+function published(): MonitorFrame[] {+ return [...useMonitorFrameStore.getState().frames.values()];+}++function reset(): void {+ useMonitorFrameStore.setState({ frames: new Map() });+}++test("a panel publishes its own box", () => {+ reset();+ const panel = {};+ useMonitorFrameStore.getState().setFrame(panel, corner());+ assert.deepEqual(published(), [corner()]);+});++test("closing the only monitor clears the frame", () => {+ reset();+ const panel = {};+ useMonitorFrameStore.getState().setFrame(panel, corner());+ useMonitorFrameStore.getState().clearFrame(panel);+ assert.deepEqual(published(), []);+});++// The regression: reopened during the exit animation, so the replacement+// publishes before the panel it replaced is torn down.+test("an exiting panel does not clear the replacement's frame", () => {+ reset();+ const closing = {};+ const reopened = {};+ useMonitorFrameStore.getState().setFrame(closing, corner(300));+ useMonitorFrameStore.getState().setFrame(reopened, corner(220));++ useMonitorFrameStore.getState().clearFrame(closing);++ assert.deepEqual(+ published(),+ [corner(220)],+ "the open monitor's frame must survive the old panel's unmount",+ );+ // A monitor that then sits still resizes nothing and republishes nothing, so+ // a lost frame would stay lost and the stack would sit back on top of it.+ assert.deepEqual(+ [...useMonitorFrameStore.getState().frames.keys()],+ [reopened],+ "only the panel that is still open may still be published",+ );+});++test("the replacement can still clear its own frame when closed", () => {+ reset();+ const closing = {};+ const reopened = {};+ useMonitorFrameStore.getState().setFrame(closing, corner(300));+ useMonitorFrameStore.getState().setFrame(reopened, corner(220));+ useMonitorFrameStore.getState().clearFrame(closing);+ useMonitorFrameStore.getState().clearFrame(reopened);+ assert.deepEqual(published(), []);+});++// The overlay stack re-renders on every notification, and reconcileGeometry+// runs on each ResizeObserver delivery, so an unchanged box must not notify.+test("republishing the same box from the same panel does not notify", () => {+ reset();+ const panel = {};+ let notifications = 0;+ const unsubscribe = useMonitorFrameStore.subscribe(() => {+ notifications += 1;+ });+ useMonitorFrameStore.getState().setFrame(panel, corner());+ useMonitorFrameStore.getState().setFrame(panel, corner());+ useMonitorFrameStore.getState().setFrame(panel, corner());+ unsubscribe();+ assert.equal(notifications, 1);+});++// This is what regressed: the unmount cleanup nulled the shared frame outright.+test("the panel's unmount cleanup goes through clearFrame", () => {+ assert.match(+ PANEL_SOURCE,+ /clearFrame\(publisher\)/,+ "the teardown must release only this panel's claim",+ );+ assert.doesNotMatch(+ PANEL_SOURCE,+ /setFrame\(\s*null\s*\)/,+ "no unconditional clear of the shared frame",+ );+ // Every publish carries the owner, so a frame can never be left unowned.+ assert.equal(+ PANEL_SOURCE.match(/setFrame\(publisher,/g)?.length,+ 2,+ "both the reconcile and the drag republish name their panel",+ );+});++test("clearing on behalf of a panel that owns nothing does not notify", () => {+ reset();+ const panel = {};+ useMonitorFrameStore.getState().setFrame(panel, corner());+ let notifications = 0;+ const unsubscribe = useMonitorFrameStore.subscribe(() => {+ notifications += 1;+ });+ useMonitorFrameStore.getState().clearFrame({});+ unsubscribe();+ assert.equal(notifications, 0);+ assert.deepEqual(published(), [corner()]);+});++// The card is the first overlay in that corner that is persistent rather than+// transient, and the chat composer docks to the bottom of the same column once+// a thread has turns. The card sat on the Send button and swallowed the click,+// which the chat UI Playwright suite caught as a 60s timeout on a button it+// could see. So the store carries every published box, not just the newest.+test("two publishers are dodged together, not one at a time", () => {+ reset();+ const monitor = {};+ const composer = {};+ useMonitorFrameStore.getState().setFrame(monitor, corner(300));+ useMonitorFrameStore+ .getState()+ .setFrame(composer, { left: 300, top: 780, right: 1100, bottom: 860 });+ assert.deepEqual(+ published(),+ [corner(300), { left: 300, top: 780, right: 1100, bottom: 860 }],+ "both are kept, apart, for stackGeometry to fold one at a time",+ );+});++test("dropping one publisher leaves the other's box intact", () => {+ reset();+ const monitor = {};+ const composer = {};+ const composerBox = { left: 300, top: 780, right: 1100, bottom: 860 };+ useMonitorFrameStore.getState().setFrame(monitor, corner(300));+ useMonitorFrameStore.getState().setFrame(composer, composerBox);+ useMonitorFrameStore.getState().clearFrame(monitor);+ assert.deepEqual(published(), [composerBox]);+});++// A composer that is hidden measures 0x0, and publishing that would pull the+// union out to the top-left corner and pin the stack there.+test("the publish hook drops an unmeasurable box rather than publishing it", () => {+ const HOOK = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/settings/hooks/use-published-frame.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ assert.match(HOOK, /box\.width === 0 && box\.height === 0/);+ assert.match(HOOK, /observer\?\.disconnect\(\)/, "and it must unsubscribe");+ assert.match(HOOK, /clearFrame\(publisher\);\s*\n\s*\};/, "and clear on unmount");+});diff --git a/studio/frontend/tests/monitor-stack-inset.test.ts b/studio/frontend/tests/monitor-stack-inset.test.tsnew file mode 100644index 00000000000..4c2e77ec65e--- /dev/null+++ b/studio/frontend/tests/monitor-stack-inset.test.ts@@ -0,0 +1,167 @@+// 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 MonitorFrame,+ stackBottomInset,+ stackGeometry,+} from "../src/features/settings/stores/monitor-frame-store.ts";++const W = 1440;+const H = 900;++/** The Live monitor where it opens by default: bottom-right, w-64, inset-4. */+function corner(height = 300): MonitorFrame {+ return {+ left: W - 16 - 256,+ top: H - 16 - height,+ right: W - 16,+ bottom: H - 16,+ };+}++test("with no monitor open the stack keeps its own inset", () => {+ assert.equal(stackBottomInset(null, W, H), 16);+});++// The reported overlap: both default to the same corner.+test("a monitor in its default corner lifts the stack clear of it", () => {+ const frame = corner(300);+ const inset = stackBottomInset(frame, W, H);+ // The stack's bottom edge now sits above the monitor's top edge.+ assert.ok(inset > 16, "the stack must move");+ assert.ok(H - inset <= frame.top, "no vertical overlap remains");+});++test("a monitor dragged to the left is not dodged", () => {+ const frame: MonitorFrame = {+ left: 16,+ top: H - 316,+ right: 272,+ bottom: H - 16,+ };+ assert.equal(stackBottomInset(frame, W, H), 16);+});++test("a monitor dragged to the top right is not dodged", () => {+ const frame: MonitorFrame = {+ left: W - 272,+ top: 16,+ right: W - 16,+ bottom: 316,+ };+ assert.equal(stackBottomInset(frame, W, H), 16);+});++// The update banners are max-w-[448px], wider than the download panel, so the+// column has to be measured from them.+test("a monitor beside the download panel but under a banner is dodged", () => {+ const frame: MonitorFrame = {+ left: W - 16 - 430,+ top: H - 316,+ right: W - 16 - 410,+ bottom: H - 16,+ };+ assert.ok(stackBottomInset(frame, W, H) > 16);+});++// Lifting the stack without shortening it pushes its top off the screen.+test("lifting the stack shortens it by the same amount", () => {+ assert.equal(stackGeometry(null, W, H).maxHeight, H - 32);+ const lifted = stackGeometry(corner(300), W, H);+ assert.ok(lifted.bottom > 16);+ assert.equal(lifted.maxHeight, H - lifted.bottom - 16);+});++// A monitor parked high is not lifted over, since the room is beneath it, but+// the stack grows upwards and would still run into it.+test("a monitor high in the column caps the stack instead of lifting it", () => {+ const frame: MonitorFrame = {+ left: W - 272,+ top: 16,+ right: W - 16,+ bottom: 316,+ };+ const geometry = stackGeometry(frame, W, H);+ // Nothing to lift over: the free space is below it.+ assert.equal(geometry.bottom, 16);+ // The stack's top edge stays clear of the monitor's bottom edge.+ assert.ok(H - geometry.bottom - geometry.maxHeight >= frame.bottom);+ assert.ok(geometry.maxHeight < H - 32, "it must actually be capped");+});++test("a monitor high but outside the column does not cap the stack", () => {+ const frame: MonitorFrame = { left: 16, top: 16, right: 272, bottom: 316 };+ assert.equal(stackGeometry(frame, W, H).maxHeight, H - 32);+});++// A monitor filling almost the whole column would otherwise leave no stack.+test("the cap never shrinks the stack below its floor", () => {+ const frame: MonitorFrame = {+ left: W - 272,+ top: 0,+ right: W - 16,+ bottom: H / 2 - 1,+ };+ assert.ok(stackGeometry(frame, W, H).maxHeight >= 120);+});++test("a monitor filling the height still leaves the stack room", () => {+ const frame: MonitorFrame = {+ left: W - 272,+ top: 16,+ right: W - 16,+ bottom: H - 16,+ };+ assert.ok(stackBottomInset(frame, W, H) <= H - 120);+});++// The union was the trap. A tall monitor and the wide docked composer share+// almost no area, so the rectangle around the pair covers most of the viewport;+// reading that as one obstacle lifted the stack to the top of the screen and+// dropped it back onto the monitor it was meant to dodge, which the chat UI+// suite caught as the card swallowing the monitor's Close button.+test("two obstacles are folded one at a time, not as their bounding box", () => {+ // The monitor dragged up the column, as the chat UI suite does before it+ // clicks Close: too high to be lifted over, so on its own it asks for+ // nothing. The composer, docked, asks for a modest lift.+ const monitor = { left: W - 16 - 256, top: 40, right: W - 16, bottom: 340 };+ const composer = { left: 300, top: H - 120, right: W - 340, bottom: H - 40 };+ const both = stackGeometry([monitor, composer], W, H);+ const monitorOnly = stackGeometry(monitor, W, H);+ const composerOnly = stackGeometry(composer, W, H);+ assert.equal(+ both.bottom,+ Math.max(monitorOnly.bottom, composerOnly.bottom),+ "the stack takes the largest lift either one asks for",+ );+ // The union's own answer, which is what went wrong.+ const unioned = stackGeometry(+ {+ left: Math.min(monitor.left, composer.left),+ top: Math.min(monitor.top, composer.top),+ right: Math.max(monitor.right, composer.right),+ bottom: Math.max(monitor.bottom, composer.bottom),+ },+ W,+ H,+ );+ assert.notEqual(+ both.bottom,+ unioned.bottom,+ "folding must not agree with the bounding box, or nothing was fixed",+ );+ assert.ok(both.bottom < unioned.bottom, "and it must lift less, not more");+});++test("an empty list behaves exactly like nothing published", () => {+ assert.deepEqual(stackGeometry([], W, H), stackGeometry(null, W, H));+});++test("one box in a list matches passing it on its own", () => {+ const frame = corner(300);+ assert.deepEqual(stackGeometry([frame], W, H), stackGeometry(frame, W, H));+});diff --git a/tests/studio/playwright_loaded_models_indicator.py b/tests/studio/playwright_loaded_models_indicator.pynew file mode 100644index 00000000000..3ef615ce6d9--- /dev/null+++ b/tests/studio/playwright_loaded_models_indicator.py@@ -0,0 +1,720 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Cross-browser checks for the loaded-models indicator.++The four /status endpoints are stubbed with page.route, so this runs on any+host: no GPU, no model download, no llama.cpp build. That is the point -- the+payload shapes the card has to survive come from hardware most CI runners do not+have (AMD reporting itself as "cuda", Apple's "mps", the sd.cpp engine that omits+model_kind), and stubbing is the only way to exercise all of them anywhere.++What genuinely needs a real engine, and is therefore checked here rather than in+the node suite:++ * the position restore. The card is position:fixed and stores absolute+ viewport coordinates, so one saved on a wide monitor lands off screen on a+ laptop -- taking its own drag handle and collapse button with it. That needs+ a real ResizeObserver, a real layout and a real localStorage.+ * pointer capture during a drag.+ * that polling actually stops when the preference is off.++Run: BASE_URL, STUDIO_OLD_PW and STUDIO_NEW_PW as the other suites take them.+STUDIO_PLAYWRIGHT_BROWSER selects chromium (also Chrome/Edge/WebView2),+firefox, or webkit (also Safari and the Linux WebKitGTK Tauri embeds).+"""++from __future__ import annotations++import json+import os+import sys+import urllib.error+import urllib.request+from pathlib import Path++from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ install_view_transition_killer,+ wait_for_health,+)++BASE = os.environ["BASE_URL"]+OLD = os.environ["STUDIO_OLD_PW"]+NEW = os.environ["STUDIO_NEW_PW"]+ART = Path(os.environ.get("PW_ART_DIR", "logs/playwright-loaded-models"))+ART.mkdir(parents = True, exist_ok = True)++PLAYWRIGHT_BROWSER = os.environ.get("STUDIO_PLAYWRIGHT_BROWSER", "chromium").lower()+PLAYWRIGHT_CHANNEL = os.environ.get("STUDIO_PLAYWRIGHT_CHANNEL") or None++# The card polls every 5s; two ticks plus slack is enough to see a change land.+SETTLE_MS = int(os.environ.get("STUDIO_UI_INDICATOR_SETTLE_MS", "12000"))++CARD = 'text="Loaded models"'+EJECT = '[aria-label^="Eject "]'+HANDLE = '[aria-label="Drag to move"]'+POSITION_KEY = "unsloth_loaded_models_position"+COLLAPSED_KEY = "unsloth_loaded_models_collapsed"+SHOW_KEY = "unsloth_show_loaded_models_indicator"++failures: list[str] = []+checks = [0]+++def info(s: str) -> None:+ print(f"[indicator] {s}", flush = True)+++def check(+ name: str,+ ok: bool,+ detail: str = "",+) -> None:+ checks[0] += 1+ if ok:+ info(f"PASS {name}")+ return+ failures.append(f"{name} ({detail})" if detail else name)+ info(f"FAIL {name} {detail}")+++def api(+ path: str,+ payload: dict | None = None,+ token: str | None = None,+) -> dict:+ data = None if payload is None else json.dumps(payload).encode()+ request = urllib.request.Request(+ f"{BASE}{path}",+ data = data,+ method = "POST" if data else "GET",+ headers = {"Content-Type": "application/json"}+ | ({"Authorization": f"Bearer {token}"} if token else {}),+ )+ with urllib.request.urlopen(request, timeout = 30) as response:+ return json.loads(response.read().decode())+++# ── Stub payloads, straight from the backend's own response models ───────++NOTHING_CHAT = {+ "active_model": None,+ "loaded": [],+ "is_gguf": False,+ "is_mlx": False,+ "is_vision": False,+ "is_audio": False,+ "audio_type": None,+ "gguf_variant": None,+}+NOTHING_DIFFUSION = {+ "loaded": False,+ "repo_id": None,+ "family": None,+ "device": None,+ "dtype": None,+ "model_kind": None,+}+NOTHING_VIDEO = dict(NOTHING_DIFFUSION, transformer_quant = None)+NOTHING_STT = {+ "available": True,+ "loaded_model": None,+ "device": None,+ "transformers": {"loaded_model": None, "device": None},+ "mtmd": {"loaded_model": None, "device": None},+ "gguf": {"loaded_model": None, "device": None},+}+++def chat(**overrides) -> dict:+ return dict(NOTHING_CHAT, **overrides)+++class Runtime:+ """Mutable stub state, so a scenario can change what a runtime holds+ between polls without tearing the routes down."""++ def __init__(self) -> None:+ self.reset()++ def reset(self) -> None:+ self.chat = dict(NOTHING_CHAT)+ self.diffusion = dict(NOTHING_DIFFUSION)+ self.video = dict(NOTHING_VIDEO)+ self.stt = json.loads(json.dumps(NOTHING_STT))+ self.hang: set[str] = set()+ self.status_reads = 0+ self.unloads: list[str] = []+ # Routes deliberately left unanswered, kept so teardown can settle them+ # instead of cancelling them out from under the handler.+ self.parked: list = []+++def install_routes(context, state: Runtime) -> None:+ def stub(key: str, body):+ def handler(route):+ state.status_reads += 1+ if key in state.hang:+ # Accept the connection and never answer: the read must time+ # out rather than wedge the card forever.+ state.parked.append(route)+ return+ route.fulfill(+ status = 200,+ content_type = "application/json",+ body = json.dumps(body() if callable(body) else body),+ )++ return handler++ context.route("**/api/inference/status", stub("chat", lambda: state.chat))+ context.route("**/api/inference/images/status", stub("image", lambda: state.diffusion))+ context.route("**/api/inference/video/status", stub("video", lambda: state.video))+ context.route("**/api/inference/audio/stt/status", stub("stt", lambda: state.stt))++ def unload_chat(route):+ state.unloads.append("chat")+ state.chat = dict(NOTHING_CHAT)+ route.fulfill(+ status = 200, content_type = "application/json", body = json.dumps({"status": "unloaded"})+ )++ def unload_images(route):+ state.unloads.append("image")+ state.diffusion = dict(NOTHING_DIFFUSION)+ route.fulfill(status = 200, content_type = "application/json", body = json.dumps(state.diffusion))++ def unload_video(route):+ state.unloads.append("video")+ state.video = dict(NOTHING_VIDEO)+ route.fulfill(status = 200, content_type = "application/json", body = json.dumps(state.video))++ def unload_stt(route):+ state.unloads.append("stt")+ state.stt["transformers"] = {"loaded_model": None, "device": None}+ state.stt["loaded_model"] = None+ route.fulfill(+ status = 200,+ content_type = "application/json",+ body = json.dumps({"loaded_model": None, "device": None}),+ )++ context.route("**/api/inference/unload", unload_chat)+ context.route("**/api/inference/images/unload", unload_images)+ context.route("**/api/inference/video/unload", unload_video)+ context.route("**/api/inference/audio/stt/unload**", unload_stt)+++def rows(page) -> list[str]:+ # One round trip, deliberately. Reading count() and then indexing nth(i)+ # races the very thing the eject checks watch for: the row disappears+ # between the two calls, and nth(1) then blocks for the whole locator+ # timeout. evaluate_all snapshots the list in a single evaluation.+ return page.locator(EJECT).evaluate_all(+ "els => els.map((el) => el.getAttribute('aria-label') || '')"+ )+++def card_text(page) -> str:+ # Bounded and absence-tolerant rather than count()-then-read, which has the+ # same race as rows() when the card is mid-change.+ try:+ return page.locator(CARD).locator("xpath=ancestor::div[3]").first.inner_text(timeout = 5000)+ except Exception:+ return ""+++def boot(+ page,+ state: Runtime,+ *,+ seed: dict | None = None,+) -> None:+ """Reload with a known localStorage, then wait for the card to settle."""+ page.goto(BASE, wait_until = "domcontentloaded")+ page.evaluate(+ """([seed, keys]) => {+ for (const k of keys) localStorage.removeItem(k);+ for (const [k, v] of Object.entries(seed || {}))+ localStorage.setItem(k, v);+ }""",+ [seed or {}, [POSITION_KEY, COLLAPSED_KEY, SHOW_KEY]],+ )+ page.reload(wait_until = "domcontentloaded")+ page.wait_for_timeout(SETTLE_MS // 2)+ # The card is deliberately hidden on /login, so an auth slip would make+ # every "no card" check pass for the wrong reason.+ path = page.evaluate("location.pathname")+ if path.startswith(("/login", "/onboarding", "/change-password")):+ raise AssertionError(f"not authenticated: landed on {path}")+++def main() -> int:+ wait_for_health(BASE, timeout = 60.0, info = info)+ # Bootstrap exactly as the other suites do: the first login forces a change.+ token = api("/api/auth/login", {"username": "unsloth", "password": OLD})["access_token"]+ try:+ api("/api/auth/change-password", {"current_password": OLD, "new_password": NEW}, token)+ except urllib.error.HTTPError as exc:+ # Already rotated by a previous run on the same install.+ if exc.code not in (400, 401, 403):+ raise+ session = api("/api/auth/login", {"username": "unsloth", "password": NEW})+ if session.get("must_change_password"):+ info("FAIL bootstrap left must_change_password set")+ return 1++ # add_init_script takes raw source, not a function to call: an arrow+ # expression here would evaluate to a function nobody invokes, the SPA would+ # find no token, and every check would silently run against /login.+ seed_js = (+ "(() => {"+ f" localStorage.setItem('unsloth_auth_token', {json.dumps(session['access_token'])});"+ f" localStorage.setItem('unsloth_refresh_token', {json.dumps(session.get('refresh_token', ''))});"+ "})();"+ )++ state = Runtime()+ if PLAYWRIGHT_BROWSER not in ("chromium", "firefox", "webkit"):+ info(f"FAIL unsupported STUDIO_PLAYWRIGHT_BROWSER={PLAYWRIGHT_BROWSER!r}")+ return 1++ with sync_playwright() as p:+ browser_type = getattr(p, PLAYWRIGHT_BROWSER)+ launch_kwargs: dict = {"headless": True}+ if PLAYWRIGHT_BROWSER == "chromium":+ launch_kwargs["args"] = chromium_launch_args()+ if PLAYWRIGHT_CHANNEL:+ launch_kwargs["channel"] = PLAYWRIGHT_CHANNEL+ elif PLAYWRIGHT_CHANNEL:+ info("FAIL STUDIO_PLAYWRIGHT_CHANNEL requires chromium")+ return 1+ browser = browser_type.launch(**launch_kwargs)+ context = browser.new_context(+ viewport = {"width": 1440, "height": 900},+ reduced_motion = "reduce",+ )+ install_view_transition_killer(context)+ context.add_init_script(seed_js)+ install_routes(context, state)+ page = context.new_page()+ page.set_default_timeout(60_000)+ try:+ run(page, state)+ finally:+ page.screenshot(path = str(ART / f"final-{PLAYWRIGHT_BROWSER}.png"))+ # Settle the deliberately-hung routes before tearing down: closing+ # over a parked one dumps a CancelledError traceback that reads+ # like a failure.+ for parked in state.parked:+ try:+ parked.abort()+ except Exception:+ pass+ state.parked.clear()+ try:+ page.goto("about:blank", wait_until = "domcontentloaded")+ except Exception:+ pass+ context.unroute_all(behavior = "ignoreErrors")+ context.close()+ browser.close()++ info(f"{checks[0] - len(failures)}/{checks[0]} checks passed")+ for failure in failures:+ info(f" FAILED: {failure}")+ return 1 if failures else 0+++def run(page, state: Runtime) -> None:+ # ── Nothing loaded ──────────────────────────────────────────────────+ state.reset()+ boot(page, state)+ check("no card when nothing is loaded", page.locator(CARD).count() == 0)++ # ── The common two-runtime host ─────────────────────────────────────+ state.chat = chat(+ active_model = "unsloth/Qwen3-4B-GGUF",+ loaded = ["unsloth/Qwen3-4B-GGUF"],+ is_gguf = True,+ gguf_variant = "Q4_K_M",+ )+ state.stt["transformers"] = {"loaded_model": "large-v3", "device": "cuda"}+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ check("card lists both runtimes", len(rows(page)) == 2, str(rows(page)))+ text = card_text(page)+ check("chat row names its quant", "Q4_K_M" in text)+ check("dictation row is distinguished", "Dictation" in text)++ # The card mounts from the root, so it must survive a route change.+ for route in ("/hub", "/train", "/images"):+ page.goto(BASE + route, wait_until = "domcontentloaded")+ page.wait_for_timeout(3000)+ check(f"card survives {route}", page.locator(CARD).count() > 0)++ # ── Hardware shapes a CUDA runner never produces ────────────────────+ matrix = [+ (+ "AMD ROCm reports cuda",+ dict(+ loaded = True,+ repo_id = "black-forest-labs/FLUX.1-dev",+ family = "flux",+ device = "cuda",+ dtype = "bfloat16",+ model_kind = "pipeline",+ ),+ "flux · BF16 · cuda",+ ),+ (+ "Apple Silicon reports mps",+ dict(+ loaded = True,+ repo_id = "black-forest-labs/FLUX.1-dev",+ family = "flux",+ device = "mps",+ dtype = "bfloat16",+ model_kind = "pipeline",+ ),+ "flux · BF16 · mps",+ ),+ (+ "Intel XPU",+ dict(+ loaded = True,+ repo_id = "black-forest-labs/FLUX.1-dev",+ family = "flux",+ device = "xpu",+ dtype = "float16",+ model_kind = "pipeline",+ ),+ "flux · FP16 · xpu",+ ),+ # sd.cpp has no model_kind key at all and puts "gguf" in dtype.+ (+ "the sd.cpp engine on a CPU-only host",+ dict(+ loaded = True,+ repo_id = "unsloth/FLUX.1-dev-GGUF",+ family = "flux",+ device = "cpu",+ dtype = "gguf",+ ),+ "flux · GGUF · cpu",+ ),+ ]+ for name, payload, expected in matrix:+ state.chat = dict(NOTHING_CHAT)+ state.stt = json.loads(json.dumps(NOTHING_STT))+ state.diffusion = dict(NOTHING_DIFFUSION, **payload)+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ check(name, expected in card_text(page), card_text(page).replace("\n", " | "))++ # An audio VLM answers prompts, so it is a chat model that happens to+ # listen -- neither Speech nor Dictation.+ state.diffusion = dict(NOTHING_DIFFUSION)+ state.chat = chat(active_model = "unsloth/gemma-3n-E4B-it", is_audio = True, audio_type = "audio_vlm")+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ text = card_text(page)+ check(+ "an audio VLM stays a Chat row",+ "Chat" in text and "Speech" not in text and "Dictation" not in text,+ text.replace("\n", " | "),+ )++ # ── A backend too old to have the video route ───────────────────────+ state.chat = chat(active_model = "unsloth/Qwen3-4B", loaded = ["unsloth/Qwen3-4B"])+ page.context.route(+ "**/api/inference/video/status",+ lambda route: route.fulfill(+ status = 404, content_type = "application/json", body = json.dumps({"detail": "Not Found"})+ ),+ )+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ check("a 404 video route does not blank the other rows", len(rows(page)) == 1, str(rows(page)))+ install_routes(page.context, state) # restore the stub++ # ── A runtime that accepts the connection and never answers ─────────+ state.hang = {"video"}+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ check("a hung runtime still lets the other rows render", len(rows(page)) == 1, str(rows(page)))+ state.hang = set()++ # ── A blip on a runtime that IS holding something ───────────────────+ # A failed read is not evidence the runtime is empty. Dropping the rows for+ # it takes a loaded model off the card, and on a remote Studio a blip can+ # take all four at once, so the whole card would go while everything stayed+ # resident. The row must survive the failure and outlive it.+ state.chat = chat(active_model = "unsloth/Qwen3-4B", loaded = ["unsloth/Qwen3-4B"])+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ check("the chat row is up before the blip", len(rows(page)) == 1, str(rows(page)))+ failing = {"count": 0}++ def fail_chat_status(route):+ failing["count"] += 1+ route.fulfill(+ status = 503, content_type = "application/json", body = json.dumps({"detail": "upstream"})+ )++ page.context.route("**/api/inference/status", fail_chat_status)+ # Long enough for several polls at the 5s cadence, so this is the steady+ # state rather than a single unlucky read.+ page.wait_for_timeout(12_000)+ check(+ "a failing status read keeps the row it cannot confirm",+ failing["count"] > 0 and len(rows(page)) == 1,+ f"{failing['count']} failed reads, rows={rows(page)}",+ )+ install_routes(page.context, state) # restore the stub++ # ── And a readable empty answer still clears it ─────────────────────+ state.chat = chat()+ page.wait_for_timeout(8000)+ check(+ "a readable empty status still retires the row",+ len(rows(page)) == 0,+ str(rows(page)),+ )+ state.chat = chat(active_model = "unsloth/Qwen3-4B", loaded = ["unsloth/Qwen3-4B"])+ state.hang = set()++ # ── The position restore: the bug this suite exists for ─────────────+ state.chat = chat(active_model = "unsloth/Qwen3-4B-GGUF", is_gguf = True, gguf_variant = "Q4_K_M")+ # As if dragged to the corner of a 2560x1440 monitor, then reopened here.+ boot(page, state, seed = {POSITION_KEY: json.dumps({"left": 2300, "top": 1300})})+ page.wait_for_selector(CARD, timeout = 30_000)+ box = page.locator(HANDLE).first.bounding_box()+ check(+ "a position saved on a bigger screen is pulled back into view",+ box is not None and 0 <= box["x"] < 1440 and 0 <= box["y"] < 900,+ f"handle={box}",+ )+ page.screenshot(path = str(ART / f"restore-{PLAYWRIGHT_BROWSER}.png"))++ # And it keeps up with a window that shrinks under it.+ page.set_viewport_size({"width": 720, "height": 560})+ page.wait_for_timeout(3000)+ box = page.locator(HANDLE).first.bounding_box()+ check(+ "a shrinking window drags the card back with it",+ box is not None and 0 <= box["x"] < 720 and 0 <= box["y"] < 560,+ f"handle={box}",+ )+ page.set_viewport_size({"width": 1440, "height": 900})+ page.wait_for_timeout(1500)++ # ── Drag, and the pointer release the window never sees ─────────────+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ box = page.locator(HANDLE).first.bounding_box()+ page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)+ page.mouse.down()+ page.mouse.move(box["x"] - 400, box["y"] - 300, steps = 20)+ page.mouse.up()+ page.wait_for_timeout(1500)+ stored = page.evaluate(f"localStorage.getItem({json.dumps(POSITION_KEY)})")+ check("a drag is persisted", stored is not None, str(stored))+ page.reload(wait_until = "domcontentloaded")+ page.wait_for_selector(CARD, timeout = 30_000)+ page.wait_for_timeout(2000)+ check(+ "the dragged position survives a reload",+ page.evaluate(f"localStorage.getItem({json.dumps(POSITION_KEY)})") == stored,+ )++ # A move with no button held must not keep dragging the card.+ before = page.locator(HANDLE).first.bounding_box()+ page.mouse.move(before["x"] + 200, before["y"] + 200, steps = 10)+ page.wait_for_timeout(500)+ after = page.locator(HANDLE).first.bounding_box()+ check(+ "the card does not follow a released pointer",+ abs(after["x"] - before["x"]) < 2 and abs(after["y"] - before["y"]) < 2,+ f"{before} -> {after}",+ )++ # ── Collapse ────────────────────────────────────────────────────────+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ page.locator('[aria-label="Collapse loaded models"]').first.click()+ page.wait_for_timeout(1500)+ pill = 'button[aria-label*="Show details"]'+ check("collapses to a pill", page.locator(pill).count() > 0)+ page.reload(wait_until = "domcontentloaded")+ page.wait_for_timeout(SETTLE_MS // 2)+ check("the collapsed state survives a reload", page.locator(pill).count() > 0)++ # ── Closed, then a load nobody announced ────────────────────────────+ # "Back on the next model load" is what the close tooltip promises, and a+ # load through the OpenAI-compatible API or auto-switch raises no lifecycle+ # event at all: the poll is the only witness. Closing must also not be+ # undone by whatever is already resident, or the card could never be shut.+ state.chat = chat(active_model = "unsloth/Qwen3-4B", loaded = ["unsloth/Qwen3-4B"])+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ page.locator('[aria-label="Close loaded models"]').first.click()+ page.wait_for_timeout(SETTLE_MS)+ check(+ "closing hides the card while a model is still resident",+ page.locator(CARD).count() == 0,+ )+ # Several polls with nothing new: it must stay closed.+ page.wait_for_timeout(11_000)+ check(+ "a closed card stays closed over what was already loaded",+ page.locator(CARD).count() == 0,+ )+ # Now a second model appears with no announcement, as a server-side load does.+ state.diffusion = dict(+ NOTHING_DIFFUSION,+ loaded = True,+ repo_id = "black-forest-labs/FLUX.1-dev",+ family = "flux",+ device = "cuda",+ dtype = "bfloat16",+ )+ page.wait_for_timeout(11_000)+ check(+ "a load nobody announced reopens the closed card",+ page.locator(CARD).count() > 0,+ "the poll is the only witness for a load started outside the frontend",+ )+ state.diffusion = NOTHING_DIFFUSION++ # The expanded grip and the collapsed pill share one drag sentinel, but only+ # the pill has a click to consume it. Drag by the grip, collapse, then click+ # the pill ONCE: without the sentinel being dropped when a click-less handle+ # finishes its drag, that first click reads someone else's drag and refuses+ # to expand, so the user has to click twice. No reload in between, since a+ # reload would clear the in-memory flag and hide the bug.+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ grip = page.locator(HANDLE).first.bounding_box()+ page.mouse.move(grip["x"] + grip["width"] / 2, grip["y"] + grip["height"] / 2)+ page.mouse.down()+ page.mouse.move(grip["x"] - 120, grip["y"] - 80, steps = 12)+ page.mouse.up()+ page.wait_for_timeout(SETTLE_MS // 2)+ page.locator('[aria-label="Collapse loaded models"]').first.click()+ page.wait_for_timeout(SETTLE_MS // 2)+ collapsed_ok = page.locator(CARD).count() == 0 and page.locator(pill).count() > 0+ check("the grip drag still collapses to a pill", collapsed_ok)+ page.locator(pill).first.click()+ page.wait_for_timeout(SETTLE_MS // 2)+ check(+ "one click reopens the pill after dragging by the grip",+ collapsed_ok and page.locator(CARD).count() > 0,+ "the grip's drag was still held against the pill's first click",+ )++ # ── Eject ───────────────────────────────────────────────────────────+ state.chat = chat(active_model = "unsloth/Qwen3-4B-GGUF", is_gguf = True, gguf_variant = "Q4_K_M")+ state.diffusion = dict(+ NOTHING_DIFFUSION,+ loaded = True,+ repo_id = "black-forest-labs/FLUX.1-dev",+ family = "flux",+ device = "cuda",+ dtype = "bfloat16",+ )+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ labels = rows(page)+ index = next((i for i, label in enumerate(labels) if "Qwen3" in label), None)+ check("the chat row is present before ejecting", index is not None, str(labels))+ if index is not None:+ page.locator(EJECT).nth(index).click()+ # Watch across more than one poll: a read already in flight when the+ # eject lands used to put the row straight back.+ reappeared = False+ gone = False+ for _ in range(60):+ present = any("Qwen3" in label for label in rows(page))+ if not present:+ gone = True+ elif gone:+ reappeared = True+ page.wait_for_timeout(200)+ check("the ejected row disappears", gone)+ check("the ejected row does not come back", not reappeared)+ check(+ "the other runtime is untouched",+ "chat" in state.unloads and "image" not in state.unloads,+ str(state.unloads),+ )++ # A row the runtime has already replaced must not unload the replacement.+ state.reset()+ state.diffusion = dict(+ NOTHING_DIFFUSION,+ loaded = True,+ repo_id = "black-forest-labs/FLUX.1-dev",+ family = "flux",+ device = "cuda",+ dtype = "bfloat16",+ )+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ # Swap the model behind the card's back, as a load from another tab would.+ state.diffusion = dict(state.diffusion, repo_id = "Qwen/Qwen-Image")+ page.locator(EJECT).first.click()+ page.wait_for_timeout(4000)+ check(+ "a replaced image row is not ejected on the replacement's behalf",+ "image" not in state.unloads,+ str(state.unloads),+ )++ # A row over a runtime that is already idle: nothing is unloaded, so the+ # toast must not report an eject. The row is up to one poll old and the+ # dictation sidecars release themselves, so this is reached without anyone+ # doing anything.+ state.reset()+ state.diffusion = dict(+ NOTHING_DIFFUSION,+ loaded = True,+ repo_id = "black-forest-labs/FLUX.1-dev",+ family = "flux",+ device = "cuda",+ dtype = "bfloat16",+ )+ boot(page, state)+ page.wait_for_selector(CARD, timeout = 30_000)+ state.diffusion = dict(NOTHING_DIFFUSION)+ page.locator(EJECT).first.click()+ page.wait_for_timeout(4000)+ said = page.locator("[data-sonner-toast]").evaluate_all(+ "els => els.map((el) => el.innerText || '').join(' | ')"+ )+ check(+ "a stale row does not claim an eject it never performed",+ "image" not in state.unloads and "Ejected" not in said,+ f"unloads={state.unloads} toasts={said!r}",+ )++ # ── The preference ──────────────────────────────────────────────────+ state.reset()+ state.chat = chat(active_model = "unsloth/Qwen3-4B", loaded = ["unsloth/Qwen3-4B"])+ boot(page, state, seed = {SHOW_KEY: "false"})+ check("the preference hides the card", page.locator(CARD).count() == 0)+ state.status_reads = 0+ page.wait_for_timeout(SETTLE_MS)+ check(+ "the preference stops the poll",+ state.status_reads <= 1,+ f"{state.status_reads} status reads while off",+ )+++if __name__ == "__main__":+ sys.exit(main())