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
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
// Pure and React-free so node --test can import them.
import {
AUDIO_CPP_AUDIO_TYPES,
audioCppDictationModelFor,
audioCppDisplayName,
isAudioCppFolderId,
} from "../audio/audio-cpp-catalog.ts";
import {
type AudioWorkflowId,
audioWorkflowForAudioType,
isAudioWorkflowId,
} from "../audio/workflows.ts";
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"
| "embedding";
/** Which runtime holds the weights, so which endpoint releases them. */
export type LoadedModelSource =
| "chat"
| "image"
| "video"
| "stt"
| "embedding";
export type SttEngine = "transformers" | "mtmd" | "gguf" | "audiocpp";
export type LoadedModelEntry = {
/** Stable across polls, so a row does not remount mid-eject. */
id: string;
kind: LoadedModelKind;
source: LoadedModelSource;
name: string;
label?: string;
servingCheckpoint?: string;
residentMib?: number;
residentOnGpu?: boolean;
/** One short line: quantisation, family, device. */
detail: string;
/** Only on a `tts` row: the Audio page workflows that run the model, first one first. */
workflows?: AudioWorkflowId[];
/** Only on `source: "stt"`: its unload takes an engine, not a model id. */
sttEngine?: SttEngine;
inactive?: boolean;
loading?: boolean;
};
export type SttEngineStatus = {
loaded_model?: string | null;
device?: string | null;
loading?: boolean;
};
export type SttStatusResponse = SttEngineStatus & {
transformers?: SttEngineStatus | null;
mtmd?: SttEngineStatus | null;
gguf?: SttEngineStatus | null;
audiocpp?: SttEngineStatus | null;
};
const STT_ENGINE_LABELS: Record<SttEngine, string> = {
transformers: "Transformers",
mtmd: "llama.cpp",
gguf: "whisper.cpp",
audiocpp: "GGUF",
};
/**
* 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.
*
* An audio model in the chat slot opens the Audio page on its workflow, since
* Chat refuses it. The dictation sidecars are shared with chat dictation, so
* they open the settings tab that drives them.
*/
export type LoadedModelTarget =
| {
open: "route";
to: "/chat" | "/images" | "/video" | "/audio";
search?: { workflow: AudioWorkflowId };
label: string;
}
| { open: "settings"; tab: "voice" | "data"; label: string };
export function loadedModelTarget(
source: LoadedModelSource,
workflows?: readonly AudioWorkflowId[],
currentAudioWorkflow?: AudioWorkflowId,
): LoadedModelTarget {
if (source === "chat" && workflows?.length) {
// An Audio page already on a workflow this model runs stays there: switching it would
// also stop a generation running on that workflow.
if (currentAudioWorkflow && workflows.includes(currentAudioWorkflow)) {
return { open: "route", to: "/audio", label: "Audio" };
}
return {
open: "route",
to: "/audio",
search: { workflow: workflows[0] },
label: "Audio",
};
}
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" };
case "embedding":
return { open: "settings", tab: "data", label: "Data 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",
embedding: "Embeddings",
};
const AUDIO_WORKFLOW_KIND_LABELS: Partial<Record<AudioWorkflowId, string>> = {
music: "Music",
separate: "Separation",
convert: "Voice conversion",
};
export function loadedModelKindLabel(
entry: Pick<LoadedModelEntry, "kind" | "workflows">,
): string {
const workflow = entry.workflows?.[0];
return (
(workflow && AUDIO_WORKFLOW_KIND_LABELS[workflow]) ??
LOADED_MODEL_KIND_LABELS[entry.kind]
);
}
/**
* 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(" · ");
}
export function shortModelLabel(name: string): string {
const dictation = audioCppDictationModelFor(name);
if (dictation) return audioCppDisplayName(dictation.id);
if (isAudioCppFolderId(name)) return audioCppDisplayName(name);
const normalized = name.replace(/[\\/]+$/, "");
const segments = normalized.split(/[\\/]+/).filter(Boolean);
if (segments.length <= 2) return normalized;
return segments.slice(-2).join("/");
}
export function loadedModelLabel(
entry: Pick<LoadedModelEntry, "name" | "label">,
): string {
return shortModelLabel(entry.label || entry.name);
}
export function formatResidentMib(mib: number | null | undefined): string | null {
if (typeof mib !== "number" || !Number.isFinite(mib) || mib <= 0) return null;
const gib = mib / 1024;
return `${gib >= 10 ? gib.toFixed(0) : gib.toFixed(1)} GiB`;
}
function residentMib(value: unknown): { residentMib?: number } {
return typeof value === "number" && Number.isFinite(value) && value > 0
? { residentMib: value }
: {};
}
/** Rows for whatever the chat runtime holds. `audio_type` splits TTS and whisper
* out of the chat row: same picker, but neither answers prompts. */
export function describeInferenceStatus(
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 (see mlx_inference); whisper is ASR and audio_vlm is a chat model,
// so only the remaining audio types belong under Speech.
const isTts =
Boolean(status.is_audio) &&
audioType !== "whisper" &&
audioType !== "audio_vlm";
const isStt = Boolean(status.is_audio) && audioType === "whisper";
const audioWorkflows = (status.audio_workflows ?? []).filter(
isAudioWorkflowId,
);
// The GGUF audio runtime reports is_gguf false, but it serves GGUFs too.
const runtime =
status.is_gguf || AUDIO_CPP_AUDIO_TYPES.has(audioType ?? "")
? "GGUF"
: status.is_mlx
? "MLX"
: "Transformers";
entries.push({
id: `chat:${active}`,
kind: isTts ? "tts" : isStt ? "stt" : "text",
source: "chat",
// An older backend sends no workflows: the audio type still tells Music from Speak.
...(isTts
? {
workflows:
audioWorkflows.length > 0
? audioWorkflows
: [audioWorkflowForAudioType(audioType)],
}
: {}),
name: active,
detail: joinDetail(
runtime,
status.gguf_variant,
status.is_vision ? "Vision" : null,
),
...residentMib(status.resident_mib),
...(typeof status.resident_on_gpu === "boolean" ? { residentOnGpu: status.resident_on_gpu } : {}),
});
}
// /status reports the whole load, so loads started in another tab still show.
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,
});
}
// Matched by checkpoint, which /unload routes on: two local files can share a label.
const serving = status.serving ?? [];
const checkpoints = status.serving_checkpoints ?? [];
const activeCheckpoint = status.model_identifier || active;
for (let i = 0; i < serving.length; i++) {
const name = serving[i];
const checkpoint = checkpoints[i] || name;
// By checkpoint when both are known: a kept model may share the active one's label.
const isActive =
checkpoints[i] && status.model_identifier
? checkpoint === status.model_identifier
: checkpoint === activeCheckpoint || name === active;
if (!name || (active && isActive)) continue;
if (entries.some((entry) => entry.id === `chat:${checkpoint}`)) continue;
entries.push({
id: `chat:${checkpoint}`,
kind: "text",
source: "chat",
name,
detail: "Also serving",
servingCheckpoint: checkpoint,
});
}
// Only the Transformers backend caches past the active model, but it is memory
// nothing else surfaces or releases.
for (const name of status.loaded ?? []) {
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;
}
export function withServingResident(
entry: LoadedModelEntry,
status: InferenceStatusResponse | null,
): LoadedModelEntry {
if (!status || !entry.servingCheckpoint) return entry;
// By checkpoint when known: the primary wins a routing tie and may share this row's label.
const answered = status.model_identifier
? status.model_identifier === entry.servingCheckpoint
: status.active_model === entry.name;
if (!answered) return entry;
return {
...entry,
...residentMib(status.resident_mib),
...(typeof status.resident_on_gpu === "boolean" ? { residentOnGpu: status.resident_on_gpu } : {}),
};
}
/** Unrecognised values are shown upper-cased, which keeps quants like "Q8_0" readable. */
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 quantBackendLabel(
value: string | null | undefined,
): string | null {
if (!value) return null;
const known: Record<string, string> = {
flashinfer: "FlashInfer",
torchao: "torchao",
};
return known[value.toLowerCase()] ?? value;
}
export function describeDiffusionStatus(
status: DiffusionStatus | null,
): LoadedModelEntry[] {
if (!status?.loaded || !status.repo_id) return [];
const isGguf =
status.model_kind === "gguf" ||
status.dtype?.toLowerCase() === "gguf" ||
Boolean(status.gguf_variant);
return [
{
id: `image:${status.repo_id}`,
kind: "image",
source: "image",
name: status.repo_id,
...(status.display_repo_id ? { label: status.display_repo_id } : {}),
...residentMib(status.resident_mib),
...(status.device ? { residentOnGpu: status.device !== "cpu" } : {}),
detail: joinDetail(
status.family,
// Only when the GGUF ran: a dense fast path replaces it with a torchao build.
isGguf && !status.transformer_quant ? "GGUF" : null,
// `dtype` is the compute dtype (bf16 on every CUDA load), so prefer the actual quant.
precisionLabel(status.transformer_quant) ??
precisionLabel(status.gguf_variant) ??
precisionLabel(status.dtype),
quantBackendLabel(status.transformer_quant_backend),
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,
...(status.display_repo_id ? { label: status.display_repo_id } : {}),
...residentMib(status.resident_mib),
...(status.device ? { residentOnGpu: status.device !== "cpu" } : {}),
detail: joinDetail(
status.family,
status.model_kind === "gguf" || status.gguf_variant ? "GGUF" : null,
// `dtype` is compute precision, so it would label a Q4_K_M as BF16.
precisionLabel(status.gguf_variant) ??
precisionLabel(status.transformer_quant) ??
precisionLabel(status.dtype),
quantBackendLabel(status.transformer_quant_backend),
status.device,
),
},
];
}
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", "audiocpp"];
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,
// The audio runtime reports its own name as the device, which is not one.
detail: joinDetail(
STT_ENGINE_LABELS[engine],
engine === "audiocpp" && block.device?.startsWith("audio.cpp")
? null
: block.device,
),
sttEngine: engine,
});
}
return entries;
}
/** "replaced" matters: image/video/STT unloads carry no model id and free whatever is held. */
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";
}
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;
}
/** Optimistic rows for loads announced before the 5s poll; a status row always wins. */
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 for the same load: images and video keep the old pipeline resident
// while the new one downloads. A loading row always wins, to avoid double announcements.
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",
embedding: "embedding",
};
export type EmbeddingStatusResponse = {
// biome-ignore lint/style/useNamingConvention: API schema
embedding_model?: string;
loaded?: boolean;
// biome-ignore lint/style/useNamingConvention: API schema
backend_loaded?: boolean;
};
export function describeEmbeddingStatus(
status: EmbeddingStatusResponse | null,
): LoadedModelEntry[] {
const resident = status?.backend_loaded ?? status?.loaded ?? false;
if (!resident) return [];
return [
{
id: "embedding:rag",
kind: "embedding",
source: "embedding",
name: embeddingRowName(status),
detail: "Documents",
},
];
}
export function embeddingRowName(
status: EmbeddingStatusResponse | null,
): string {
return (status?.loaded ? status.embedding_model : undefined) || "Embedding model";
}
export function heldByAnotherAccount(
statuses: readonly ({ yours?: boolean } | null | undefined)[],
): boolean {
return statuses.some((status) => status?.yours === false);
}
export function sameLoadedModels(
left: readonly LoadedModelEntry[],
right: readonly LoadedModelEntry[],
): boolean {
if (left === right) return true;
if (left.length !== right.length) return false;
return left.every((entry, i) => {
const other = right[i];
return (
entry.id === other.id &&
entry.kind === other.kind &&
entry.source === other.source &&
entry.name === other.name &&
entry.label === other.label &&
entry.detail === other.detail &&
entry.inactive === other.inactive &&
entry.loading === other.loading &&
entry.sttEngine === other.sttEngine &&
entry.servingCheckpoint === other.servingCheckpoint &&
entry.residentMib === other.residentMib &&
entry.residentOnGpu === other.residentOnGpu &&
(entry.workflows ?? []).join() === (other.workflows ?? []).join()
);
});
}
export type LoadedModelsCardState = "rows" | "otherAccount" | "empty" | null;
export function loadedModelsCardState(
rowCount: number,
heldByOther: boolean,
justEnabled: boolean,
): LoadedModelsCardState {
if (rowCount > 0) return "rows";
if (heldByOther) return "otherAccount";
return justEnabled ? "empty" : null;
}