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: Enable deleting fine-tuned chat models (#5234)
Lee Jackson8cbd16786ba4
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex cb5d9da34ae..428ecaa1c36 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -708,6 +708,17 @@ class InferenceOrchestrator:def unload_model(self, model_name: str) -> bool:"""Unload a model from the subprocess."""+ if model_name in self.loading_models:+ logger.info(+ "Cancelling in-flight load for model '%s' by terminating subprocess",+ model_name,+ )+ self._shutdown_subprocess(timeout = 0.5)+ self.loading_models.discard(model_name)+ self.active_model_name = None+ self.models.clear()+ return True+if not self._ensure_subprocess_alive():# No subprocess — just clear local stateself.models.pop(model_name, None)diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex c312b0ee1d6..d01e94b0c99 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -8,6 +8,7 @@ Model Management API routesimport hashlibimport jsonimport os+import shutilimport sysimport uuidfrom pathlib import Path@@ -1684,6 +1685,338 @@ async def scan_loras()+def _is_path_under(path: Path, root: Path) -> bool:+ try:+ path.resolve().relative_to(root.resolve())+ return True+ except ValueError:+ return False+++def _is_path_under_lexically(path: Path, root: Path) -> bool:+ """Check containment without resolving the final path's symlink target."""+ try:+ absolute_path = Path(os.path.abspath(str(path)))+ absolute_root = Path(os.path.abspath(str(root)))+ absolute_path.relative_to(absolute_root)+ return True+ except ValueError:+ return False+++def _loaded_model_matches_deleted_path(active_model: str, deleted_path: Path) -> bool:+ try:+ active = Path(active_model).expanduser().resolve()+ target = deleted_path.resolve()+ return active == target or (target.is_dir() and active.is_relative_to(target))+ except (OSError, RuntimeError, ValueError) as e:+ logger.debug(+ "Could not resolve loaded/deleted model paths; falling back to string comparison: %s",+ e,+ )+ active_lower = active_model.lower()+ target_lower = str(deleted_path).lower()+ return active_lower == target_lower or active_lower.startswith(+ f"{target_lower}{os.sep}"+ )+++def _loading_model_matches_deleted_path(+ loading_model: object,+ deleted_path: Path,+) -> bool:+ if not loading_model:+ return False+ return _loaded_model_matches_deleted_path(str(loading_model), deleted_path)+++def _prune_empty_parents(start: Path, stop_at: Path) -> None:+ """Remove empty ancestor directories of ``start`` up to (but not including) ``stop_at``.++ Used after deleting a model checkpoint so the enclosing run directory does+ not linger as an empty entry in scan results.+ """+ try:+ stop_resolved = stop_at.resolve()+ except OSError:+ return+ parent = start.parent+ while True:+ try:+ parent_resolved = parent.resolve()+ except OSError:+ return+ if parent_resolved == stop_resolved:+ return+ try:+ parent_resolved.relative_to(stop_resolved)+ except ValueError:+ return+ try:+ parent.rmdir()+ except OSError:+ return+ parent = parent.parent+++def _delete_gguf_variant_files(root: Path, variant: str) -> tuple[int, int]:+ deleted_count = 0+ deleted_bytes = 0+ for path in root.rglob("*"):+ if not path.is_file() or not _is_main_gguf_filename(path.name):+ continue+ if _extract_quant_label(path.name).lower() != variant.lower():+ continue+ try:+ deleted_bytes += path.stat().st_size+ except OSError:+ pass+ path.unlink()+ deleted_count += 1+ return deleted_count, deleted_bytes++[email protected]("/delete-finetuned")+async def delete_finetuned_model(+ model_path: str = Body(...),+ source: str = Body(...),+ export_type: Optional[str] = Body(None),+ gguf_variant: Optional[str] = Body(None),+ current_subject: str = Depends(get_current_subject),+):+ """Delete a Studio-trained or exported model from disk.++ Only paths under Studio's outputs/exports roots are accepted. Exported+ GGUF entries can delete one quantization variant at a time.+ """+ if source not in {"training", "exported"}:+ raise HTTPException(+ status_code = 400,+ detail = "Only trained or exported Studio models can be deleted",+ )++ if not model_path or not model_path.strip():+ raise HTTPException(status_code = 400, detail = "model_path is required")++ if export_type == "gguf" and not gguf_variant:+ raise HTTPException(+ status_code = 400,+ detail = "gguf_variant is required when export_type is 'gguf'",+ )++ raw_path = Path(model_path).expanduser()+ if source == "training":+ target_path = raw_path+ allowed_root = outputs_root()+ else:+ allowed_root = exports_root()+ target_path = (+ raw_path.parent+ if export_type == "gguf" and raw_path.suffix.lower() == ".gguf"+ else raw_path+ )++ allowed_root = allowed_root.resolve()+ delete_path = Path(os.path.abspath(str(target_path)))+ delete_path_is_symlink = delete_path.is_symlink()++ if delete_path_is_symlink:+ if not _is_path_under_lexically(delete_path, allowed_root):+ raise HTTPException(+ status_code = 400,+ detail = "Model path is outside Studio storage",+ )+ if export_type == "gguf" and gguf_variant:+ target_path = delete_path.resolve()+ if not _is_path_under(target_path, allowed_root):+ raise HTTPException(+ status_code = 400,+ detail = "Model path is outside Studio storage",+ )+ else:+ target_path = delete_path+ else:+ target_path = target_path.resolve()++ should_check_resolved_path = not delete_path_is_symlink or (+ export_type == "gguf" and gguf_variant+ )+ if should_check_resolved_path and not _is_path_under(target_path, allowed_root):+ raise HTTPException(+ status_code = 400,+ detail = "Model path is outside Studio storage",+ )+ if target_path == allowed_root:+ raise HTTPException(+ status_code = 400,+ detail = "Refusing to delete storage root",+ )+ if not target_path.exists() and not target_path.is_symlink():+ raise HTTPException(status_code = 404, detail = "Model not found on disk")++ if source == "training":+ try:+ from core.training import get_training_backend++ training_backend = get_training_backend()+ if training_backend.is_training_active():+ raise HTTPException(+ status_code = 409,+ detail = "Cannot delete trained models while training is running",+ )+ except HTTPException:+ raise+ except Exception as e:+ logger.warning("Could not check training status before delete: %s", e)+ raise HTTPException(+ status_code = 500,+ detail = "Could not verify training status before deleting",+ ) from e++ try:+ from routes.inference import get_llama_cpp_backend++ llama_backend = get_llama_cpp_backend()+ if (+ llama_backend.is_active+ and not llama_backend.is_loaded+ and llama_backend.model_identifier+ and _loaded_model_matches_deleted_path(+ llama_backend.model_identifier,+ target_path,+ )+ and (+ not gguf_variant+ or not llama_backend.hf_variant+ or llama_backend.hf_variant.lower() == gguf_variant.lower()+ )+ ):+ raise HTTPException(+ status_code = 409,+ detail = "Cannot delete a model while it is loading",+ )+ if (+ llama_backend.is_loaded+ and llama_backend.model_identifier+ and _loaded_model_matches_deleted_path(+ llama_backend.model_identifier,+ target_path,+ )+ and (+ not gguf_variant+ or not llama_backend.hf_variant+ or llama_backend.hf_variant.lower() == gguf_variant.lower()+ )+ ):+ raise HTTPException(+ status_code = 400,+ detail = "Unload the model before deleting",+ )+ except HTTPException:+ raise+ except Exception as e:+ logger.warning("Could not check llama.cpp loaded model before delete: %s", e)+ raise HTTPException(+ status_code = 503,+ detail = "Could not verify model load status before deleting",+ ) from e++ try:+ inference_backend = get_inference_backend()+ loading_models = getattr(inference_backend, "loading_models", set())+ if any(+ _loading_model_matches_deleted_path(loading_model, target_path)+ for loading_model in loading_models+ ):+ raise HTTPException(+ status_code = 409,+ detail = "Cannot delete a model while it is loading",+ )+ if inference_backend.active_model_name:+ if _loaded_model_matches_deleted_path(+ inference_backend.active_model_name,+ target_path,+ ):+ raise HTTPException(+ status_code = 400,+ detail = "Unload the model before deleting",+ )+ except HTTPException:+ raise+ except Exception as e:+ logger.warning(+ "Could not check inference backend loaded model before delete: %s", e+ )+ raise HTTPException(+ status_code = 503,+ detail = "Could not verify model load status before deleting",+ ) from e++ try:+ if export_type == "gguf" and gguf_variant:+ if not target_path.is_dir():+ raise HTTPException(+ status_code = 400,+ detail = "GGUF variant deletion requires an export directory",+ )+ deleted_count, deleted_bytes = _delete_gguf_variant_files(+ target_path,+ gguf_variant,+ )+ if deleted_count == 0:+ raise HTTPException(+ status_code = 404,+ detail = f"Variant {gguf_variant} not found on disk",+ )+ try:+ if not any(target_path.iterdir()):+ target_path.rmdir()+ _prune_empty_parents(target_path, allowed_root)+ except OSError:+ pass+ logger.info(+ "Deleted %s GGUF file(s) for exported model at %s variant %s (%0.1f MB freed)",+ deleted_count,+ target_path,+ gguf_variant,+ deleted_bytes / (1024 * 1024),+ )+ return {+ "status": "deleted",+ "path": str(target_path),+ "gguf_variant": gguf_variant,+ }++ if target_path.is_symlink() or target_path.is_file():+ target_path.unlink()+ else:+ shutil.rmtree(target_path)++ if target_path.exists() or target_path.is_symlink():+ raise HTTPException(+ status_code = 500,+ detail = "Deletion incomplete; some files could not be removed",+ )++ _prune_empty_parents(target_path, allowed_root)++ logger.info("Deleted fine-tuned model at %s", target_path)+ return {"status": "deleted", "path": str(target_path)}+ except HTTPException:+ raise+ except Exception as e:+ logger.error(+ "Error deleting fine-tuned model %s: %s",+ target_path,+ e,+ exc_info = True,+ )+ raise HTTPException(+ status_code = 500,+ detail = f"Failed to delete fine-tuned model: {str(e)}",+ )++@router.get("/loras/{lora_path:path}/base-model", response_model = LoRABaseModelResponse)async def get_lora_base_model(lora_path: str,diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex a2b0c90e592..7bfc74235f5 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -1227,9 +1227,11 @@ def _resolve_gguf_dir(p: Path) -> Optional[Path]:return pif p.is_file() and p.suffix.lower() == ".gguf":parent = p.parent- if (parent / "config.json").exists() or (- parent / "adapter_config.json"- ).exists():+ if (+ (parent / "config.json").exists()+ or (parent / "adapter_config.json").exists()+ or (parent / "export_metadata.json").exists()+ ):return parentreturn Nonediff --git a/studio/frontend/src/components/assistant-ui/model-selector.tsx b/studio/frontend/src/components/assistant-ui/model-selector.tsxindex 4fa39beff47..1ff946dd46f 100644--- a/studio/frontend/src/components/assistant-ui/model-selector.tsx+++ b/studio/frontend/src/components/assistant-ui/model-selector.tsx@@ -18,13 +18,19 @@ import {import { HugeiconsIcon } from "@hugeicons/react";import { useMemo, useState } from "react";import type {+ DeletedModelRef,LoraModelOption,ModelOption,ModelSelectorChangeMeta,} from "./model-selector/types";import { HubModelPicker, LoraModelPicker } from "./model-selector/pickers";-export type { LoraModelOption, ModelOption, ModelSelectorChangeMeta } from "./model-selector/types";+export type {+ DeletedModelRef,+ LoraModelOption,+ ModelOption,+ ModelSelectorChangeMeta,+} from "./model-selector/types";interface ModelSelectorProps {models: ModelOption[];@@ -35,6 +41,8 @@ interface ModelSelectorProps {onValueChange?: (value: string, meta: ModelSelectorChangeMeta) => void;onEject?: () => void;onFoldersChange?: () => void;+ onModelsChange?: (deletedModel?: DeletedModelRef) => void;+ deleteDisabled?: boolean;variant?: "outline" | "ghost" | "muted";size?: "sm" | "default" | "lg";className?: string;@@ -109,6 +117,8 @@ function ModelSelectorContent({onSelect,onEject,onFoldersChange,+ onModelsChange,+ deleteDisabled,className,dataTour,}: {@@ -118,6 +128,8 @@ function ModelSelectorContent({onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;onEject?: () => void;onFoldersChange?: () => void;+ onModelsChange?: (deletedModel?: DeletedModelRef) => void;+ deleteDisabled?: boolean;className?: string;dataTour?: string;}) {@@ -151,6 +163,8 @@ function ModelSelectorContent({loraModels={loraModels}value={value}onSelect={onSelect}+ onModelsChange={onModelsChange}+ deleteDisabled={deleteDisabled}/></TabsContent></Tabs>@@ -182,6 +196,8 @@ export function ModelSelector({onValueChange,onEject,onFoldersChange,+ onModelsChange,+ deleteDisabled,variant = "outline",size = "default",className,@@ -276,6 +292,8 @@ export function ModelSelector({onSelect={handleSelect}onEject={onEject ? handleEject : undefined}onFoldersChange={onFoldersChange}+ onModelsChange={onModelsChange}+ deleteDisabled={deleteDisabled}className={contentClassName}dataTour={contentDataTour}/>diff --git a/studio/frontend/src/components/assistant-ui/model-selector/model-delete-action.tsx b/studio/frontend/src/components/assistant-ui/model-selector/model-delete-action.tsxnew file mode 100644index 00000000000..58a62354545--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/model-selector/model-delete-action.tsx@@ -0,0 +1,112 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { cn } from "@/lib/utils";+import { Trash2Icon } from "lucide-react";+import { useCallback, useState, type ReactNode } from "react";+import { toast } from "sonner";++interface ModelDeleteActionProps {+ ariaLabel: string;+ title: string;+ description: ReactNode;+ successMessage: string;+ loadingLabel?: string;+ buttonClassName?: string;+ iconClassName?: string;+ disabled?: boolean;+ onConfirm: () => Promise<void> | void;+ onDeleted?: () => void;+}++export function ModelDeleteAction({+ ariaLabel,+ title,+ description,+ successMessage,+ loadingLabel = "Deleting...",+ buttonClassName,+ iconClassName,+ disabled = false,+ onConfirm,+ onDeleted,+}: ModelDeleteActionProps) {+ const [open, setOpen] = useState(false);+ const [deleting, setDeleting] = useState(false);++ const handleConfirm = useCallback(async () => {+ setDeleting(true);+ try {+ await onConfirm();+ toast.success(successMessage);+ onDeleted?.();+ setOpen(false);+ } catch (err) {+ toast.error(+ err instanceof Error ? err.message : "Failed to delete model",+ );+ } finally {+ setDeleting(false);+ }+ }, [onConfirm, onDeleted, successMessage]);++ return (+ <>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ if (disabled) return;+ setOpen(true);+ }}+ aria-label={ariaLabel}+ disabled={disabled}+ className={cn(+ "shrink-0 rounded-md p-1.5 text-muted-foreground/60 transition-colors hover:bg-destructive/10 hover:text-destructive",+ disabled && "cursor-not-allowed opacity-40 hover:bg-transparent hover:text-muted-foreground/60",+ buttonClassName,+ )}+ >+ <Trash2Icon className={cn("size-3.5", iconClassName)} />+ </button>++ <AlertDialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (!nextOpen && deleting) return;+ setOpen(nextOpen);+ }}+ >+ <AlertDialogContent size="sm">+ <AlertDialogHeader>+ <AlertDialogTitle>{title}</AlertDialogTitle>+ <AlertDialogDescription>{description}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={deleting}>No</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ disabled={deleting}+ onClick={(e) => {+ e.preventDefault();+ handleConfirm();+ }}+ >+ {deleting ? loadingLabel : "Yes"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}diff --git a/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx b/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsxindex 30b8fdecb83..fae3c22caf6 100644--- a/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx+++ b/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx@@ -1,16 +1,6 @@// 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 {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@/components/ui/alert-dialog";import { Input } from "@/components/ui/input";import { Spinner } from "@/components/ui/spinner";import {@@ -23,6 +13,7 @@ import {type ScanFolderInfo,addScanFolder,deleteCachedModel,+ deleteFineTunedModel,listCachedGguf,listCachedModels,listGgufVariants,@@ -50,7 +41,8 @@ import { checkVramFit, estimateLoadingVram } from "@/lib/vram";import { Add01Icon, Cancel01Icon, Folder02Icon, Search01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { FolderBrowser } from "./folder-browser";-import { ChevronDownIcon, ChevronRightIcon, DownloadIcon, StarIcon, Trash2Icon } from "lucide-react";+import { ModelDeleteAction } from "./model-delete-action";+import { ChevronDownIcon, ChevronRightIcon, DownloadIcon, StarIcon } from "lucide-react";import {type ReactNode,useCallback,@@ -60,6 +52,7 @@ import {} from "react";import { toast } from "sonner";import type {+ DeletedModelRef,LoraModelOption,ModelOption,ModelSelectorChangeMeta,@@ -211,12 +204,22 @@ function GgufVariantExpander({gpuGb,systemRamGb,onDeleteVariant,+ sourceOverride,+ deleteVariantTitle = "Delete cached model?",+ renderDeleteVariantDescription,+ getDeleteVariantSuccessMessage,+ deleteDisabled = false,}: {repoId: string;onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;gpuGb?: number;systemRamGb?: number;- onDeleteVariant?: (quant: string) => void;+ onDeleteVariant?: (quant: string) => Promise<void> | void;+ sourceOverride?: ModelSelectorChangeMeta["source"];+ deleteVariantTitle?: string;+ renderDeleteVariantDescription?: (quant: string) => ReactNode;+ getDeleteVariantSuccessMessage?: (quant: string) => string;+ deleteDisabled?: boolean;}) {const [variants, setVariants] = useState<GgufVariantDetail[] | null>(null);const [defaultVariant, setDefaultVariant] = useState<string | null>(null);@@ -259,14 +262,14 @@ function GgufVariantExpander({const handleVariantClick = useCallback((quant: string, downloaded?: boolean, sizeBytes?: number) => {onSelect(repoId, {- source: isLocalPath ? "local" : "hub",+ source: sourceOverride ?? (isLocalPath ? "local" : "hub"),isLora: false,ggufVariant: quant,isDownloaded: isLocalPath ? true : downloaded,expectedBytes: sizeBytes,});},- [repoId, isLocalPath, onSelect],+ [repoId, isLocalPath, onSelect, sourceOverride],);// GGUF fit classification matching llama-server's _select_gpus logic:@@ -408,16 +411,29 @@ function GgufVariantExpander({</span></button>{v.downloaded && onDeleteVariant && (- <button- type="button"- onClick={(e) => {- e.stopPropagation();- onDeleteVariant(v.quant);- }}- className="shrink-0 rounded-md p-1 text-muted-foreground/60 transition-colors hover:bg-destructive/10 hover:text-destructive"- >- <Trash2Icon className="size-3" />- </button>+ <ModelDeleteAction+ ariaLabel={`Delete ${repoId} ${v.quant}`}+ title={deleteVariantTitle}+ description={+ renderDeleteVariantDescription?.(v.quant) ?? (+ <>+ This will remove{" "}+ <span className="font-medium text-foreground">+ {repoId} ({v.quant})+ </span>{" "}+ from disk. You can re-download it later.+ </>+ )+ }+ successMessage={+ getDeleteVariantSuccessMessage?.(v.quant) ??+ `Deleted ${repoId} ${v.quant}`+ }+ buttonClassName="p-1"+ iconClassName="size-3"+ disabled={deleteDisabled}+ onConfirm={() => onDeleteVariant(v.quant)}+ />)}</div>);@@ -512,9 +528,6 @@ export function HubModelPicker({// Track which GGUF repo is expanded for variant selectionconst [expandedGguf, setExpandedGguf] = useState<string | null>(null);- // Delete confirmation dialog state- const [deleteTarget, setDeleteTarget] = useState<string | null>(null);- const [deleting, setDeleting] = useState(false);const [downloadedCollapsed, setDownloadedCollapsed] = useState(false);const [customFoldersCollapsed, setCustomFoldersCollapsed] = useState(false);const [recommendedCollapsed, setRecommendedCollapsed] = useState(false);@@ -675,27 +688,6 @@ export function HubModelPicker({.finally(check);}, [refreshLocalModelsList, refreshScanFolders]);- const handleDeleteConfirm = useCallback(async () => {- if (!deleteTarget) return;- setDeleting(true);- try {- // deleteTarget is "repo_id" or "repo_id::variant"- const sepIdx = deleteTarget.indexOf("::");- const repoId = sepIdx >= 0 ? deleteTarget.slice(0, sepIdx) : deleteTarget;- const variant = sepIdx >= 0 ? deleteTarget.slice(sepIdx + 2) : undefined;- await deleteCachedModel(repoId, variant);- toast.success(`Deleted ${variant ? `${repoId} ${variant}` : repoId}`);- refreshCachedLists();- } catch (err) {- toast.error(- err instanceof Error ? err.message : "Failed to delete model",- );- } finally {- setDeleting(false);- setDeleteTarget(null);- }- }, [deleteTarget, refreshCachedLists]);-// Deduplicate: don't show downloaded models in the recommended list.// Compare case-insensitively since HF cache lowercases repo IDs.const downloadedSet = useMemo(() => {@@ -952,9 +944,10 @@ export function HubModelPicker({systemRamGb={gpu.available ? gpu.systemRamAvailableGb : undefined}- onDeleteVariant={(quant) =>- setDeleteTarget(`${c.repo_id}::${quant}`)- }+ onDeleteVariant={async (quant) => {+ await deleteCachedModel(c.repo_id, quant);+ refreshCachedLists();+ }}/>)}</div>@@ -977,16 +970,22 @@ export function HubModelPicker({vramStatus={null}/></div>- <button- type="button"- onClick={(e) => {- e.stopPropagation();- setDeleteTarget(c.repo_id);- }}- className="shrink-0 rounded-md p-1.5 text-muted-foreground/60 transition-colors hover:bg-destructive/10 hover:text-destructive"- >- <Trash2Icon className="size-3.5" />- </button>+ <ModelDeleteAction+ ariaLabel={`Delete ${c.repo_id}`}+ title="Delete cached model?"+ description={+ <>+ This will remove{" "}+ <span className="font-medium text-foreground">+ {c.repo_id}+ </span>{" "}+ from disk. You can re-download it later.+ </>+ }+ successMessage={`Deleted ${c.repo_id}`}+ onConfirm={() => deleteCachedModel(c.repo_id)}+ onDeleted={refreshCachedLists}+ /></div>))}</>@@ -1409,40 +1408,6 @@ export function HubModelPicker({</div></div>- <AlertDialog- open={deleteTarget !== null}- onOpenChange={(open) => {- if (!open && !deleting) setDeleteTarget(null);- }}- >- <AlertDialogContent size="sm">- <AlertDialogHeader>- <AlertDialogTitle>Delete cached model?</AlertDialogTitle>- <AlertDialogDescription>- This will remove{" "}- <span className="font-medium text-foreground">- {deleteTarget?.includes("::")- ? `${deleteTarget.split("::")[0]} (${deleteTarget.split("::")[1]})`- : deleteTarget}- </span>{" "}- from disk. You can re-download it later.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel disabled={deleting}>No</AlertDialogCancel>- <AlertDialogAction- variant="destructive"- disabled={deleting}- onClick={(e) => {- e.preventDefault();- handleDeleteConfirm();- }}- >- {deleting ? "Deleting..." : "Yes"}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog></div>);}@@ -1451,10 +1416,14 @@ export function LoraModelPicker({loraModels,value,onSelect,+ onModelsChange,+ deleteDisabled = false,}: {loraModels: LoraModelOption[];value?: string;onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;+ onModelsChange?: (deletedModel?: DeletedModelRef) => void;+ deleteDisabled?: boolean;}) {const [query, setQuery] = useState("");const [expandedGguf, setExpandedGguf] = useState<string | null>(null);@@ -1541,6 +1510,8 @@ export function LoraModelPicker({const isExported = adapter.source === "exported";const isMerged = adapter.exportType === "merged";const isGguf = adapter.exportType === "gguf";+ const isExportedGguf = isExported && isGguf;+ const canDelete = (isTraining || isExported) && !isExportedGguf;const isTrainingFull = isTraining && isMerged;const isLocalGgufDir =isLocal &&@@ -1569,38 +1540,69 @@ export function LoraModelPicker({: tag;return (<div key={adapter.id}>- <ModelRow- label={adapter.name}- meta={meta}- selected={value === adapter.id}- onClick={() => {- if (isLocalGgufDir) {- setExpandedGguf((prev) =>- prev === adapter.id ? null : adapter.id,- );- } else {- onSelect(adapter.id, {- source: isLocal- ? "local"- : isExported- ? "exported"- : "lora",- isLora: !isLocal && !isMerged && !isGguf,- isDownloaded: true,- });- }- }}- tooltipText={- <>- <span className="block break-words">- {adapter.name}- </span>- <span className="block mt-1 text-[10px] text-muted-foreground break-all">- {adapter.id}- </span>- </>- }- />+ <div className="flex items-center gap-0.5">+ <div className="min-w-0 flex-1">+ <ModelRow+ label={adapter.name}+ meta={meta}+ selected={value === adapter.id}+ onClick={() => {+ if (isLocalGgufDir || isExportedGguf) {+ setExpandedGguf((prev) =>+ prev === adapter.id ? null : adapter.id,+ );+ } else {+ onSelect(adapter.id, {+ source: isLocal+ ? "local"+ : isExported+ ? "exported"+ : "lora",+ isLora: !isLocal && !isMerged && !isGguf,+ isDownloaded: true,+ });+ }+ }}+ tooltipText={+ <>+ <span className="block break-words">+ {adapter.name}+ </span>+ <span className="block mt-1 text-[10px] text-muted-foreground break-all">+ {adapter.id}+ </span>+ </>+ }+ />+ </div>+ {canDelete && (+ <ModelDeleteAction+ ariaLabel={`Delete ${adapter.name}`}+ title="Delete fine-tuned model?"+ description={+ <>+ This will remove{" "}+ <span className="font-medium text-foreground">+ {adapter.name}+ </span>{" "}+ from disk. This cannot be undone.+ </>+ }+ successMessage={`Deleted ${adapter.name}`}+ disabled={deleteDisabled}+ onConfirm={() =>+ deleteFineTunedModel({+ modelPath: adapter.id,+ source: isExported ? "exported" : "training",+ exportType: adapter.exportType,+ })+ }+ onDeleted={() =>+ onModelsChange?.({ id: adapter.id })+ }+ />+ )}+ </div>{expandedGguf === adapter.id && (<GgufVariantExpanderrepoId={adapter.id}@@ -1609,6 +1611,37 @@ export function LoraModelPicker({systemRamGb={gpu.available ? gpu.systemRamAvailableGb : undefined}+ sourceOverride={isExportedGguf ? "exported" : undefined}+ deleteVariantTitle="Delete exported GGUF variant?"+ renderDeleteVariantDescription={(quant) => (+ <>+ This will remove{" "}+ <span className="font-medium text-foreground">+ {adapter.name} ({quant})+ </span>{" "}+ from disk. This cannot be undone.+ </>+ )}+ getDeleteVariantSuccessMessage={(quant) =>+ `Deleted ${adapter.name} ${quant}`+ }+ deleteDisabled={deleteDisabled}+ onDeleteVariant={+ isExportedGguf+ ? async (quant) => {+ await deleteFineTunedModel({+ modelPath: adapter.id,+ source: "exported",+ exportType: "gguf",+ ggufVariant: quant,+ });+ onModelsChange?.({+ id: adapter.id,+ ggufVariant: quant,+ });+ }+ : undefined+ }/>)}</div>@@ -1619,6 +1652,7 @@ export function LoraModelPicker({)}</div></div>+</div>);}diff --git a/studio/frontend/src/components/assistant-ui/model-selector/types.ts b/studio/frontend/src/components/assistant-ui/model-selector/types.tsindex 215dd2b38e5..3da75b4d4ec 100644--- a/studio/frontend/src/components/assistant-ui/model-selector/types.ts+++ b/studio/frontend/src/components/assistant-ui/model-selector/types.ts@@ -25,3 +25,8 @@ export interface ModelSelectorChangeMeta {isDownloaded?: boolean;expectedBytes?: number;}++export interface DeletedModelRef {+ id: string;+ ggufVariant?: string;+}diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 15ac8748f00..32a03171ee6 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -219,6 +219,25 @@ export async function deleteCachedModel(repoId: string, variant?: string): Promiawait parseJsonOrThrow<unknown>(response);}+export async function deleteFineTunedModel(args: {+ modelPath: string;+ source: "training" | "exported";+ exportType?: "lora" | "merged" | "gguf";+ ggufVariant?: string;+}): Promise<void> {+ const response = await authFetch("/api/models/delete-finetuned", {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model_path: args.modelPath,+ source: args.source,+ export_type: args.exportType ?? null,+ gguf_variant: args.ggufVariant ?? null,+ }),+ });+ await parseJsonOrThrow<unknown>(response);+}+export interface ScanFolderInfo {id: number;path: string;diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 39683661c71..a239cae848d 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import {+ type DeletedModelRef,type LoraModelOption,type ModelOption,ModelSelector,@@ -129,6 +130,17 @@ type CompareModelSelection = {ggufVariant?: string;};+function modelMatchesDeleted(+ model: { id: string; ggufVariant?: string | null },+ deletedModel?: DeletedModelRef,+): boolean {+ if (!deletedModel || model.id !== deletedModel.id) return false;+ return (+ deletedModel.ggufVariant == null ||+ (model.ggufVariant ?? null) === deletedModel.ggufVariant+ );+}+/*** Detect if this is a LoRA base-vs-fine-tuned compare.* Returns true when the loaded checkpoint is a LoRA — in that case@@ -147,11 +159,15 @@ const CompareContent = memo(function CompareContent({models,loraModels,onFoldersChange,+ onModelsChange,+ deleteDisabled,}: {pairId: string;models: ModelOption[];loraModels: LoraModelOption[];onFoldersChange?: () => void;+ onModelsChange?: (deletedModel?: DeletedModelRef) => void;+ deleteDisabled?: boolean;}): ReactElement {const isLoraCompare = useIsLoraCompare();@@ -163,6 +179,8 @@ const CompareContent = memo(function CompareContent({models={models}loraModels={loraModels}onFoldersChange={onFoldersChange}+ onModelsChange={onModelsChange}+ deleteDisabled={deleteDisabled}/>);});@@ -331,6 +349,8 @@ function GeneralCompareHeader({value,onValueChange,onFoldersChange,+ onModelsChange,+ deleteDisabled,side,}: {models: ModelOption[];@@ -341,6 +361,8 @@ function GeneralCompareHeader({meta: { isLora: boolean; ggufVariant?: string },) => void;onFoldersChange?: () => void;+ onModelsChange?: (deletedModel?: DeletedModelRef) => void;+ deleteDisabled?: boolean;side: "left" | "right";}): ReactElement {return (@@ -356,6 +378,8 @@ function GeneralCompareHeader({value={value}onValueChange={onValueChange}onFoldersChange={onFoldersChange}+ onModelsChange={onModelsChange}+ deleteDisabled={deleteDisabled}variant="ghost"className="max-w-[80%] !h-[34px]"/>@@ -369,11 +393,15 @@ const GeneralCompareContent = memo(function GeneralCompareContent({models,loraModels,onFoldersChange,+ onModelsChange,+ deleteDisabled,}: {pairId: string;models: ModelOption[];loraModels: LoraModelOption[];onFoldersChange?: () => void;+ onModelsChange?: (deletedModel?: DeletedModelRef) => void;+ deleteDisabled?: boolean;}): ReactElement {const handlesRef = useRef<Record<string, CompareHandle>>({});const [model1ThreadId, setModel1ThreadId] = useState<string>();@@ -391,6 +419,19 @@ const GeneralCompareContent = memo(function GeneralCompareContent({isLora: false,});+ const handleModelsChange = useCallback(+ (deletedModel?: DeletedModelRef) => {+ if (modelMatchesDeleted(model1, deletedModel)) {+ setModel1({ id: "", isLora: false });+ }+ if (modelMatchesDeleted(model2, deletedModel)) {+ setModel2({ id: "", isLora: false });+ }+ onModelsChange?.(deletedModel);+ },+ [model1, model2, onModelsChange],+ );+useEffect(() => {let isActive = true;db.threads@@ -446,6 +487,8 @@ const GeneralCompareContent = memo(function GeneralCompareContent({})}onFoldersChange={onFoldersChange}+ onModelsChange={handleModelsChange}+ deleteDisabled={deleteDisabled}/>}/>@@ -469,6 +512,8 @@ const GeneralCompareContent = memo(function GeneralCompareContent({})}onFoldersChange={onFoldersChange}+ onModelsChange={handleModelsChange}+ deleteDisabled={deleteDisabled}/>}/>@@ -530,6 +575,9 @@ export function ChatPage(): ReactElement {const lorasFromStore = useChatRuntimeStore((state) => state.loras);const modelsError = useChatRuntimeStore((state) => state.modelsError);const activeThreadId = useChatRuntimeStore((state) => state.activeThreadId);+ const modelOperationInProgress = useChatRuntimeStore(+ (state) => state.modelLoading,+ );const {refresh,selectModel,@@ -734,6 +782,21 @@ export function ChatPage(): ReactElement {.catch(() => {});}, [navigate]);+ const refreshModelLists = useCallback((deletedModel?: DeletedModelRef) => {+ const { checkpoint } = useChatRuntimeStore.getState().params;+ const activeGgufVariant = useChatRuntimeStore.getState().activeGgufVariant;+ if (+ modelMatchesDeleted(+ { id: checkpoint, ggufVariant: activeGgufVariant },+ deletedModel,+ )+ ) {+ useChatRuntimeStore.getState().clearCheckpoint();+ }+ void refresh();+ refreshLocalModels();+ }, [refresh, refreshLocalModels]);+const loraModels = useMemo<LoraModelOption[]>(() => {const fromLoras = lorasFromStore.map((lora) => ({id: lora.id,@@ -877,6 +940,8 @@ export function ChatPage(): ReactElement {onValueChange={handleCheckpointChange}onEject={handleEject}onFoldersChange={refreshLocalModels}+ onModelsChange={refreshModelLists}+ deleteDisabled={modelOperationInProgress}variant="ghost"open={modelSelectorOpen}onOpenChange={handleModelSelectorOpenChange}@@ -962,6 +1027,8 @@ export function ChatPage(): ReactElement {models={models}loraModels={loraModels}onFoldersChange={refreshLocalModels}+ onModelsChange={refreshModelLists}+ deleteDisabled={modelOperationInProgress}/>)}</div>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 d9e817678bc..b9b6f0b5431 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@@ -21,11 +21,9 @@ import {mergeBackendRecommendedInference,resolveLoadMaxSeqLength,} from "../presets/preset-policy";-import type { InferenceStatusResponse, LoadModelResponse } from "../types/api";import type {ChatLoraSummary,ChatModelSummary,- InferenceParams,} from "../types/runtime";// The simplified Speculative Decoding control surfaces "default" (which@@ -167,6 +165,7 @@ export function useChatModelRuntime() {const loadingModelRef = useRef<typeof loadingModel>(null);const loadToastIdRef = useRef<string | number | null>(null);const loadToastDismissedRef = useRef(false);+ const cancelUnloadPendingRef = useRef(false);const setLoadToastDismissedState = useCallback((dismissed: boolean) => {loadToastDismissedRef.current = dismissed;@@ -180,7 +179,9 @@ export function useChatModelRuntime() {loadAbortRef.current = null;loadToastIdRef.current = null;setLoadToastDismissedState(false);- useChatRuntimeStore.getState().setModelLoading(false);+ if (!cancelUnloadPendingRef.current) {+ useChatRuntimeStore.getState().setModelLoading(false);+ }}, [setLoadToastDismissedState]);const renderLoadDescription = useCallback(@@ -219,27 +220,6 @@ export function useChatModelRuntime() {// Apply inference defaults on reconnect (page refresh with model already loaded)if (statusRes.inference) {const currentParams = useChatRuntimeStore.getState().params;- const reconnectResponse: LoadModelResponse = {- status: "already_loaded",- model: statusRes.active_model,- display_name: statusRes.active_model,- is_vision: statusRes.is_vision,- is_lora: false,- is_gguf: statusRes.is_gguf,- is_audio: statusRes.is_audio,- audio_type: statusRes.audio_type,- has_audio_input: statusRes.has_audio_input,- inference: statusRes.inference,- context_length: statusRes.context_length,- max_context_length: statusRes.max_context_length,- native_context_length: statusRes.native_context_length,- supports_reasoning: statusRes.supports_reasoning,- reasoning_style: statusRes.reasoning_style,- reasoning_always_on: statusRes.reasoning_always_on,- supports_preserve_thinking: statusRes.supports_preserve_thinking,- supports_tools: statusRes.supports_tools,- speculative_type: statusRes.speculative_type,- };setParams(mergeBackendRecommendedInference({current: currentParams,@@ -337,8 +317,18 @@ export function useChatModelRuntime() {? undefined: "The current download may still finish in the background.",});- // Fire-and-forget: tell backend to stop, don't block UI- unloadModel({ model_path: model.id }).catch(() => {});+ cancelUnloadPendingRef.current = true;+ useChatRuntimeStore.getState().setModelLoading(true);+ void (async () => {+ try {+ await unloadModel({ model_path: model.id }).catch(() => {});+ } finally {+ cancelUnloadPendingRef.current = false;+ if (!loadingModelRef.current) {+ useChatRuntimeStore.getState().setModelLoading(false);+ }+ }+ })();}, [clearCheckpoint, setLoadToastDismissedState]);const selectModel = useCallback(@@ -437,11 +427,13 @@ export function useChatModelRuntime() {if (validation.requires_trust_remote_code && !trustRemoteCode) {throw new Error(getTrustRemoteCodeRequiredMessage(displayName));}+ if (abortCtrl.signal.aborted) throw new Error("Cancelled");if (currentCheckpoint) {await unloadModel({ model_path: currentCheckpoint });previousWasUnloaded = true;}+ if (abortCtrl.signal.aborted) throw new Error("Cancelled");const {chatTemplateOverride,