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
import { useHfEndpoint } from "@/lib/hf-endpoint";
import { revealCachedModel } from "@/features/chat";
import { useRevealLabel } from "@/features/library/reveal";
import { toast } from "@/lib/toast";
import { ModelMemoryBarFor } from "@/components/model-memory-bar";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useVramBudgetFraction } from "@/hooks/use-vram-budget-fraction";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { cn } from "@/lib/utils";
import {
Alert02Icon,
LayerIcon,
LinkSquare02Icon,
} from "@hugeicons/core-free-icons";
import { Folder01Icon } from "@/lib/folder-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useCallback, useMemo, useState } from "react";
import {
downloadManager,
jobKeyOf,
selectActiveJob,
useDownloadManagerStore,
} from "../download-manager";
import { useOnlineStatus } from "../hooks/use-online-status";
import {
type BaseModelSource,
type LocalModelInfo,
type ModelInventoryFormat,
DELETABLE_LOCAL_SOURCES,
deleteCachedModel,
deleteLocalModel,
revealLocalModel,
} from "../inventory";
import { formatBytes } from "../lib/format";
import type { HubModelRunSelection } from "../lib/model-run-selection";
import {
ggufFilenamesMatch,
ggufSelectionOverrideMatchesIntent,
} from "../lib/gguf-filename";
import {
ggufVariantDisplayLabel,
localGgufMemoryBarVariant,
resolveLocalGgufVariant,
sortLocalGgufVariants,
} from "../lib/gguf-variant-sort";
import { ggufVariantsMatch } from "../lib/model-identity";
import { confirmExternalLink } from "../stores/external-link-confirm";
import { useHfTokenStore } from "../stores/hf-token-store";
import { DeleteImpactSummary, useDeleteImpact } from "./delete-impact";
import { DotTag } from "./dot-tag";
import {
CardDeleteButton,
CardUpdateButton,
DeleteConfirmDialog,
ModelRunActionButton,
UpdateConfirmDialog,
} from "./download-card";
import { PathInfoButton } from "./path-info-button";
import { TransportConflictDialog } from "./transport-conflict-dialog";
import { useCardDelete } from "./use-card-delete";
import { useGgufVariantFetchState } from "./use-gguf-variant-fetch-state";
import { ggufVariantLookupTableBytes } from "@/lib/gguf-fit";
interface LocalOnDeviceCardProps {
modelId: string;
displayName: string;
repoId: string | null;
sourceLabel: string;
source: LocalModelInfo["source"];
path: string;
/** False for media GGUFs: they run through the media planner, so the KV estimate is wrong. */
showMemoryBar?: boolean;
isGguf: boolean;
requiresVariant?: boolean;
modelFormat: ModelInventoryFormat | null;
baseModel?: string | null;
baseModelSource?: BaseModelSource | null;
baseModelHubId?: string | null;
baseModelSummary?: string | null;
adapterType?: string | null;
trainingMethod?: string | null;
isActive: boolean;
activeGgufVariant?: string | null;
isLoading: boolean;
preferredFile?: string | null;
preferredFileIntent?: number;
gpuGb?: number;
gpuCount?: number;
audioCppCardGb?: number;
systemRamGb?: number;
unsupportedReason?: string | null;
onRun?: (selection: HubModelRunSelection) => void;
runPending?: boolean;
onChange?: () => void;
}
function formatAdapterLabel(
adapterType?: string | null,
trainingMethod?: string | null,
): string {
const method = trainingMethod?.trim().toLowerCase();
if (method === "qlora") return "QLoRA adapter";
if (method === "lora") return "LoRA adapter";
const type = adapterType?.trim();
return type ? `${type.toUpperCase()} adapter` : "Adapter";
}
function baseModelSourceLabel(source?: BaseModelSource | null): string {
if (source === "huggingface") return "Hugging Face base model";
if (source === "local") return "Local base model";
return "Base model";
}
function BaseModelReference({
baseModel,
baseModelSource,
baseModelHubId,
baseModelSummary,
}: {
baseModel: string;
baseModelSource?: BaseModelSource | null;
baseModelHubId?: string | null;
baseModelSummary?: string | null;
}) {
const canOpenHub = baseModelSource === "huggingface" && !!baseModelHubId;
const hfEndpoint = useHfEndpoint();
const hubUrl = `${hfEndpoint}/${baseModelHubId}`;
return (
<div className="flex min-w-0 items-center gap-2 rounded-lg border border-border/55 bg-muted/35 px-3 py-2">
<div className="flex size-7 shrink-0 items-center justify-center rounded-sm bg-background/70 text-muted-foreground">
<HugeiconsIcon
icon={LayerIcon}
strokeWidth={1.75}
className="size-3.5"
/>
</div>
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-1.5">
<span className="shrink-0 text-ui-11 font-medium text-muted-foreground">
{baseModelSourceLabel(baseModelSource)}
</span>
<span className="truncate text-ui-12 font-medium text-foreground">
{baseModel}
</span>
</div>
{baseModelSummary && (
<p className="mt-0.5 truncate text-ui-11 text-muted-foreground">
{baseModelSummary}
</p>
)}
</div>
{canOpenHub && (
<Tooltip>
<TooltipTrigger asChild={true}>
<a
href={hubUrl}
target="_blank"
rel="noopener noreferrer"
aria-label={`Open ${baseModelHubId} on Hugging Face`}
className="inline-flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
onClick={(event) => {
event.stopPropagation();
if (confirmExternalLink(hubUrl)) {
event.preventDefault();
}
}}
>
<HugeiconsIcon
icon={LinkSquare02Icon}
strokeWidth={1.75}
className="size-3.5"
/>
</a>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
Open base model
</TooltipContent>
</Tooltip>
)}
</div>
);
}
/** Null unless this is the owner on the backend's own machine with a file manager. */
function CardRevealButton({ onReveal }: { onReveal: () => Promise<unknown> }) {
const revealLabel = useRevealLabel();
if (!revealLabel) return null;
return (
<Tooltip>
<TooltipTrigger asChild={true}>
<button
type="button"
aria-label={revealLabel}
onClick={(e) => {
e.stopPropagation();
onReveal().catch((err) => {
toast.error(
err instanceof Error ? err.message : "Failed to open file manager",
);
});
}}
className="inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground opacity-0 transition-[opacity,background-color,color] duration-150 hover:bg-muted hover:text-foreground focus-visible:opacity-100 group-hover/dl:opacity-100"
>
<HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-4" />
</button>
</TooltipTrigger>
<TooltipContent side="bottom" className="tooltip-compact">
{revealLabel}
</TooltipContent>
</Tooltip>
);
}
export function LocalOnDeviceCard({
modelId,
displayName,
repoId,
sourceLabel,
source,
path,
showMemoryBar = true,
isGguf,
requiresVariant = false,
modelFormat,
baseModel,
baseModelSource,
baseModelHubId,
baseModelSummary,
adapterType,
trainingMethod,
isActive,
activeGgufVariant = null,
isLoading,
preferredFile = null,
preferredFileIntent = 0,
gpuGb,
gpuCount,
audioCppCardGb,
systemRamGb,
unsupportedReason,
onRun,
runPending = false,
onChange,
}: LocalOnDeviceCardProps) {
const [deleteOpen, setDeleteOpen] = useState(false);
const [updateOpen, setUpdateOpen] = useState(false);
const [variantOpen, setVariantOpen] = useState(false);
const [updateConflictKey, setUpdateConflictKey] = useState<string | null>(
null,
);
const updateTransportConflict = useDownloadManagerStore((state) =>
updateConflictKey
? (state.conflicts[updateConflictKey]?.info ?? null)
: null,
);
const cancelUpdateConflict = useCallback(() => {
if (updateConflictKey) downloadManager.cancelConflict(updateConflictKey);
setUpdateConflictKey(null);
}, [updateConflictKey]);
const resumeUpdateConflict = useCallback(() => {
if (!updateConflictKey) return;
downloadManager.resumeConflict(updateConflictKey);
setUpdateConflictKey(null);
}, [updateConflictKey]);
const restartUpdateConflict = useCallback(() => {
if (!updateConflictKey) return;
downloadManager.restartConflict(updateConflictKey);
setUpdateConflictKey(null);
}, [updateConflictKey]);
const hfToken = useHfTokenStore((s) => s.token);
const online = useOnlineStatus();
const isCacheRow = source === "hf_cache";
const deleteImpact = useDeleteImpact(
deleteOpen && isCacheRow && Boolean(repoId),
repoId ?? "",
);
const { deleting, runDelete } = useCardDelete({
action: async () => {
if (!isCacheRow) {
await deleteLocalModel(path, modelId);
return;
}
if (!repoId) return;
// Pass the cache snapshot path so delete targets this card's cache, not the active one.
await deleteCachedModel(repoId, undefined, hfToken || undefined, path);
},
resourceName: "model",
successMessage: () => `Deleted ${isCacheRow ? repoId : displayName}`,
onSuccess: () => {
setDeleteOpen(false);
onChange?.();
},
});
const localGgufPath = path.trim();
const needsVariantSelection =
isGguf && requiresVariant && !localGgufPath.toLowerCase().endsWith(".gguf");
const currentVariantState = useGgufVariantFetchState({
repoId: modelId,
hfToken,
preferLocalCache: true,
localPath: localGgufPath,
enabled: needsVariantSelection,
errorFallback: "Failed to load quantizations",
});
const remoteVariantState = useGgufVariantFetchState({
repoId: repoId ?? modelId,
hfToken,
enabled:
online && source === "hf_cache" && needsVariantSelection && !!repoId,
errorFallback: "Failed to check for updates",
});
const variantKey = currentVariantState.key;
const [selectedVariantState, setSelectedVariantState] = useState<{
key: string;
quant: string | null;
preferredFile?: string | null;
preferredFileIntent?: number;
}>(() => ({
key: variantKey,
quant: null,
}));
const canDelete =
(isCacheRow ? !!repoId : DELETABLE_LOCAL_SOURCES.has(source) && !!path) &&
!isActive &&
!isLoading &&
!runPending;
const variants = useMemo(() => {
const localVariants = currentVariantState.variants;
const remoteVariants = remoteVariantState.variants;
if (!localVariants || !remoteVariants) return localVariants;
return localVariants.map((variant) => {
const remoteVariant = remoteVariants.find((remote) =>
ggufVariantsMatch(remote.quant, variant.quant),
);
if (!remoteVariant) return variant;
return {
...variant,
download_size_bytes:
remoteVariant.download_size_bytes || variant.download_size_bytes,
// An update's reading wins, even 0: the local header is the old revision.
lookup_table_bytes: remoteVariant.update_available
? (remoteVariant.lookup_table_bytes ?? 0)
: variant.lookup_table_bytes || remoteVariant.lookup_table_bytes,
// Both sides measure the same cache; prefer local, fall back to remote.
download_remaining_bytes:
variant.download_remaining_bytes ??
remoteVariant.download_remaining_bytes,
update_available: remoteVariant.update_available === true,
};
});
}, [currentVariantState.variants, remoteVariantState.variants]);
// Same live VRAM budget the memory bar reads, so the quant menu ranks consistently.
const budgetFraction = useVramBudgetFraction() ?? undefined;
const sortedVariants = useMemo(
() =>
variants
? sortLocalGgufVariants(variants, {
defaultVariant: currentVariantState.defaultVariant,
gpuGb,
gpuCount,
audioCppCardGb,
systemRamGb,
budgetFraction,
})
: null,
[
variants,
currentVariantState.defaultVariant,
gpuGb,
gpuCount,
audioCppCardGb,
systemRamGb,
budgetFraction,
],
);
const preferredQuant = preferredFile
? (variants?.find((variant) =>
ggufFilenamesMatch(variant.filename, preferredFile),
)?.quant ?? null)
: null;
const selectedVariantOverride =
selectedVariantState.key === variantKey &&
ggufSelectionOverrideMatchesIntent(
preferredFile,
preferredFileIntent,
selectedVariantState.preferredFile,
selectedVariantState.preferredFileIntent,
)
? selectedVariantState.quant
: preferredQuant;
const selectedVariant = resolveLocalGgufVariant(sortedVariants, {
selectedVariant: selectedVariantOverride,
activeVariant: isActive ? activeGgufVariant : null,
defaultVariant: currentVariantState.defaultVariant,
});
const selectedQuant = selectedVariant?.quant ?? null;
const memoryBarVariant = localGgufMemoryBarVariant(
selectedVariant,
currentVariantState.variants,
);
const updateJobActive = useDownloadManagerStore((s) =>
repoId
? Boolean(
selectActiveJob(
s,
"model",
repoId,
needsVariantSelection ? selectedQuant : null,
),
)
: false,
);
const updateTargetVariant = needsVariantSelection ? selectedQuant : null;
const updateExpectedBytes =
selectedVariant?.download_size_bytes ?? selectedVariant?.size_bytes ?? 0;
const updateAvailable =
needsVariantSelection &&
selectedVariant?.downloaded === true &&
selectedVariant.update_available === true;
const canUpdate =
online &&
source === "hf_cache" &&
!!repoId &&
!isActive &&
!isLoading &&
!runPending &&
!updateJobActive &&
updateAvailable;
// Update runs as a managed download so it gets Downloads-panel progress and Cancel.
const handleConfirmUpdate = () => {
if (!repoId || !updateTargetVariant) return;
setUpdateOpen(false);
void downloadManager
.requestStart({
kind: "model",
repoId,
variant: updateTargetVariant,
expectedBytes: updateExpectedBytes,
})
.then((outcome) => {
if (outcome === "conflict") {
setUpdateConflictKey(jobKeyOf("model", repoId, updateTargetVariant));
}
void currentVariantState.refresh();
void remoteVariantState.refresh();
});
};
const formatLabel =
modelFormat === "gguf"
? "GGUF"
: modelFormat === "adapter"
? formatAdapterLabel(adapterType, trainingMethod)
: modelFormat === "checkpoint"
? "Checkpoint"
: modelFormat === "safetensors"
? "Safetensors"
: "Model";
const formatTone =
modelFormat === "adapter" ? "adapter" : isGguf ? "gguf" : "checkpoint";
const showOldCacheHint = source === "hf_cache" && !!unsupportedReason;
const selectedVariantReady =
!needsVariantSelection ||
(selectedVariant?.downloaded === true && selectedVariant.partial !== true);
const showRunAction =
Boolean(onRun) && selectedVariantReady && !updateJobActive && !isLoading;
return (
<div className="flex w-full flex-col gap-2">
{showOldCacheHint && (
<div className="flex items-start gap-2 rounded-lg border border-amber-500/20 bg-amber-500/8 px-3 py-2 text-ui-12 leading-5 text-amber-700 dark:text-amber-300">
<HugeiconsIcon
icon={Alert02Icon}
strokeWidth={1.75}
className="mt-[1px] size-3.5 shrink-0"
/>
<span>
This looks like an older Hub cache. It may use a format that Unsloth
no longer loads (missing config or unsupported quantization). You
can still keep it on disk, or delete it to free space.
</span>
</div>
)}
<div className="hub-download-card">
<div className="group/dl flex items-center">
<div className="relative flex h-9 min-w-0 flex-1 items-center pl-3 pr-2">
<span className="flex min-w-0 items-center gap-1.5 text-ui-12 text-muted-foreground">
<DotTag tone="success" label="On device" />
<DotTag tone={formatTone} label={formatLabel} />
{needsVariantSelection && (
<Popover
open={runPending ? false : variantOpen}
onOpenChange={(nextOpen) => {
if (!runPending) setVariantOpen(nextOpen);
}}
>
<PopoverTrigger asChild={true}>
<button
type="button"
disabled={currentVariantState.loading || runPending}
className="inline-flex h-6 max-w-[calc(170px*var(--ui-space-scale,1))] shrink-0 cursor-pointer items-center gap-1.5 rounded-full border border-format-gguf/35 px-2 font-mono text-ui-10p5 leading-none text-format-gguf transition-colors hover:bg-format-gguf/8 disabled:cursor-not-allowed disabled:opacity-60"
>
<span className="truncate">
{currentVariantState.loading
? "Loading"
: currentVariantState.error
? "Unavailable"
: selectedVariant
? ggufVariantDisplayLabel(selectedVariant)
: "Select"}
</span>
{selectedVariant && (
<span className="shrink-0 font-sans text-ui-10 text-muted-foreground tabular-nums">
{formatBytes(selectedVariant.size_bytes)}
</span>
)}
<HugeiconsIcon
icon={ChevronDownStandardIcon}
className="size-3 shrink-0"
/>
</button>
</PopoverTrigger>
<PopoverContent
align="start"
side="bottom"
sideOffset={8}
avoidCollisions={false}
className="hub-menu-instant menu-soft-surface w-[var(--radix-popover-trigger-width)] min-w-[min(calc(220px*var(--ui-space-scale,1)),calc(100vw-32px))] gap-0 overflow-hidden p-0 py-2 ring-0"
>
<div className="max-h-[calc(280px*var(--ui-space-scale,1))] overflow-y-auto [scrollbar-width:thin]">
{sortedVariants?.map((variant) => {
const label = ggufVariantDisplayLabel(variant);
const isSelected = ggufVariantsMatch(
variant.quant,
selectedQuant,
);
return (
<button
key={variant.filename}
type="button"
onClick={() => {
setSelectedVariantState({
key: variantKey,
quant: variant.quant,
preferredFile,
preferredFileIntent,
});
setVariantOpen(false);
}}
className={cn(
"mx-2 flex w-[calc(100%-1rem*var(--ui-space-scale,1))] min-w-0 cursor-pointer items-center gap-2 rounded-md px-2.5 py-2 text-left transition-colors",
isSelected
? "bg-[color-mix(in_oklab,var(--foreground)_calc(7%*var(--contrast-wash-gain,1)),transparent)] dark:bg-[color-mix(in_oklab,var(--foreground)_calc(12%*var(--contrast-wash-gain,1)),transparent)]"
: "hover:bg-[color-mix(in_oklab,var(--foreground)_calc(5%*var(--contrast-wash-gain,1)),transparent)] dark:hover:bg-[color-mix(in_oklab,var(--foreground)_calc(6%*var(--contrast-wash-gain,1)),transparent)]",
)}
>
<span className="min-w-0 flex-1 truncate font-mono text-ui-12 text-format-gguf">
{label}
</span>
<span className="flex shrink-0 items-center gap-1.5">
<span className="text-ui-10 text-muted-foreground tabular-nums">
{formatBytes(variant.size_bytes)}
</span>
</span>
</button>
);
})}
{!currentVariantState.loading &&
!currentVariantState.error &&
sortedVariants?.length === 0 && (
<div className="px-4 py-2 text-xs text-muted-foreground">
No quantizations found.
</div>
)}
{currentVariantState.error && (
<div className="px-4 py-2 text-xs text-destructive">
{currentVariantState.error}
</div>
)}
</div>
</PopoverContent>
</Popover>
)}
{source !== "hf_cache" && (
<span className="truncate text-muted-foreground/85">
{sourceLabel}
</span>
)}
</span>
<div className="ml-auto flex items-center gap-0.5">
{canUpdate && (
<CardUpdateButton
label={`Update ${repoId}`}
emphasized={true}
onClick={() => setUpdateOpen(true)}
/>
)}
{canDelete && (
<CardDeleteButton
label={`Delete ${isCacheRow ? repoId : displayName}`}
onClick={() => setDeleteOpen(true)}
/>
)}
{(isCacheRow ? repoId : path) && (
<CardRevealButton
onReveal={() =>
isCacheRow && repoId
? revealCachedModel(repoId)
: revealLocalModel(path, modelId)
}
/>
)}
<PathInfoButton path={path} />
</div>
</div>
{showRunAction && onRun && (
<ModelRunActionButton
label={`Configure and run ${displayName.trim() || "this model"}`}
loading={runPending}
onClick={() =>
onRun(
needsVariantSelection && selectedVariant
? {
ggufVariant: selectedVariant.quant,
ggufFilename: selectedVariant.filename,
expectedBytes:
selectedVariant.download_size_bytes &&
selectedVariant.download_size_bytes > 0
? selectedVariant.download_size_bytes
: selectedVariant.size_bytes,
}
: {},
)
}
/>
)}
</div>
{/* Render the full-width memory bar below the horizontal card row so it
does not compete with row controls for width. */}
{/* A direct .gguf path skips variant selection, so selectedQuant is null.
The path itself still supplies the local artifact identity. */}
{showMemoryBar &&
(repoId || localGgufPath) &&
(selectedQuant || localGgufPath.toLowerCase().endsWith(".gguf")) ? (
<ModelMemoryBarFor
// The exact path identifies the artifact across caches; it is the only id for local GGUFs.
repoId={repoId || localGgufPath}
loadId={localGgufPath}
quant={selectedQuant ?? ""}
sizeBytes={memoryBarVariant?.size_bytes}
lookupTableBytes={
memoryBarVariant
? ggufVariantLookupTableBytes(memoryBarVariant)
: 0
}
gpuGb={gpuGb}
className="px-3 pb-2"
/>
) : null}
</div>
{baseModel && (
<BaseModelReference
baseModel={baseModel}
baseModelSource={baseModelSource}
baseModelHubId={baseModelHubId}
baseModelSummary={baseModelSummary}
/>
)}
<DeleteConfirmDialog
open={deleteOpen}
onOpenChange={(o) => {
if (!o && !deleting) setDeleteOpen(false);
}}
title={isCacheRow ? "Delete cached model?" : "Delete local model?"}
deleting={deleting}
// Same gate as the row menu: blocked deletes would otherwise just return a 400.
blocked={(deleteImpact?.blocked_by.length ?? 0) > 0}
onConfirm={() => void runDelete()}
description={
isCacheRow ? (
<>
This will remove{" "}
<span className="font-medium text-foreground">{repoId}</span> and
its downloaded files from disk. You can re-download it later.
<DeleteImpactSummary impact={deleteImpact} />
</>
) : (
<>
This will permanently remove{" "}
<span className="font-medium text-foreground">{displayName}</span>{" "}
from{" "}
<span className="break-all font-mono text-xs">{path}</span>.
</>
)
}
/>
<UpdateConfirmDialog
open={updateOpen}
onOpenChange={(o) => {
if (!o) setUpdateOpen(false);
}}
title={`Update ${repoId}?`}
updating={false}
onConfirm={handleConfirmUpdate}
description="Re-download the latest version of this model from Hugging Face. Progress shows in the Downloads panel."
/>
<TransportConflictDialog
conflict={updateTransportConflict}
onCancel={cancelUpdateConflict}
onKeepTransport={resumeUpdateConflict}
onSwitchTransport={restartUpdateConflict}
/>
</div>
);
}