Skip to content

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.

46.9 KB
Raw Blame
// 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 { useHubDownloadPlan } from "../download-manager/use-hub-download-queue";
import { HubPlanProgress } from "../download-manager/hub-plan-progress";
import { useRequiredAssetsDownload } from "./use-required-assets-download";
import { ModelMemoryBarFor } from "@/components/model-memory-bar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Spinner } from "@/components/ui/spinner";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { usePlatformStore } from "@/config/env";
import { useT } from "@/i18n";
import { getCachedModelPath, revealCachedModel } from "@/features/chat";
import {
  formatFootprintBytes,
  pinKey,
  usePinnedModelsStore,
} from "@/features/model-picker";
import { useVramBudgetFraction } from "@/hooks/use-vram-budget-fraction";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import {
  type GgufFitClass,
  classifyGgufVariantFit,
  ggufVariantLookupTableBytes,
} from "@/lib/gguf-fit";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { TrashIcon } from "@/lib/hugeicons-derived";
import {
  Refresh01Icon,
  Download01Icon,
  HelpCircleIcon,
  InformationCircleIcon,
  MoreVerticalIcon,
  PinIcon,
  PinOffIcon,
} from "@hugeicons/core-free-icons";
import { Folder01Icon } from "@/lib/folder-icons";
import { Copy01Icon } from "@/lib/copy-icon";
import { HugeiconsIcon } from "@hugeicons/react";
import {
  type KeyboardEventHandler,
  memo,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from "react";
import {
  downloadManager,
  pendingDrafterPresentation,
  useDownloadManagerStore,
  useHttpPartialsResumable,
  useRepoDownload,
} from "../download-manager";
import {
  type GgufVariantFootprint,
  type MediaStudioPage,
  awaitsCompanions,
  ggufVariantFootprint,
  useMediaCompanionBytes,
} from "../hooks/use-media-companion-bytes";
import { useOnlineStatus } from "../hooks/use-online-status";
import { type GgufVariantDetail, deleteCachedModel } from "../inventory";
import { formatBytes } from "../lib/format";
import {
  ggufFilenamesMatch,
  ggufSelectionOverrideMatchesIntent,
} from "../lib/gguf-filename";
import {
  ggufVariantDisplayLabel,
  ggufVariantTransferLabel,
  sortDownloadableGgufVariants,
} from "../lib/gguf-variant-sort";
import {
  ggufVariantsMatch,
  normalizeGgufVariantIdentity,
} from "../lib/model-identity";
import type { HubModelRunSelection } from "../lib/model-run-selection";
import { useHfTokenStore } from "../stores/hf-token-store";
import { DotTag } from "./dot-tag";
import { DownloadStopIndicator } from "./download-cancel-indicator";
import {
  CardDivider,
  DeleteConfirmDialog,
  DownloadCard,
  ModelRunActionButton,
  UpdateConfirmDialog,
} from "./download-card";
import {
  activeDownloadState,
  applyLiveGgufVariantStates,
  createLiveGgufVariantStatesSelector,
  createScopedLiveGgufFilesSelector,
  isScopedLiveVariant,
} from "./gguf-live-variant-states";
import {
  GgufDownloadStatusCard,
  GgufDownloadingFallbackCard,
} from "./gguf-status-cards";
import { DeleteImpactSummary, useDeleteImpact } from "./delete-impact";
import { useDeleteConfirmAction } from "./use-delete-confirm-action";
import { useDownloadCardState } from "./use-download-card-state";
import { useGgufVariantFetchState } from "./use-gguf-variant-fetch-state";

interface FitBadgeMeta {
  label: string;
  tooltip: string;
  iconClassName: string;
}

const FIT_BADGE: Record<GgufFitClass, FitBadgeMeta> = {
  fits: {
    label: "Full GPU offload",
    tooltip: "Full offload likely possible on your system.",
    iconClassName: "text-emerald-600 dark:text-emerald-400",
  },
  marginal: {
    label: "Over budget",
    // Unconditional: on an idle card this tier always loads with --fit. Matches the chat picker.
    tooltip:
      "Larger than your VRAM Budget allows, so part of it offloads even on an idle GPU. It is still smaller than the card, so raising the budget can keep it resident.",
    iconClassName: "text-amber-600 dark:text-amber-400",
  },
  partial: {
    label: "Partial offload",
    tooltip:
      "Model may not fit but still works with offloading. Expect slower inference.",
    iconClassName: "text-sky-600 dark:text-sky-400",
  },
  ram: {
    label: "RAM fallback",
    tooltip:
      "No GPU VRAM detected. This GGUF may run with system RAM and CPU offload. Inference will be slower.",
    iconClassName: "text-sky-600 dark:text-sky-400",
  },
  streamed: {
    label: "Fits (lookup tables streamed from disk)",
    tooltip:
      "Fits with its lookup tables streamed from disk, llama.cpp's default for them. Prefill and decode can be slower and vary with disk speed.",
    iconClassName: "text-sky-600 dark:text-sky-400",
  },
  oom: {
    label: "Does not fit",
    // Not "won't fit": llama-server never refuses on size, it uses --fit. Matches the chat picker.
    tooltip:
      "Model may not fit but still works with offloading. Expect slower inference.",
    iconClassName: "text-rose-600 dark:text-rose-400",
  },
};

const CHIP_BASE =
  "inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded-full border px-2 text-ui-11p5 font-medium tabular-nums leading-3 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]";
const CHIP_DEFAULT =
  "border-[color-mix(in_oklab,var(--foreground)_calc(15%*var(--contrast-edge-gain,1)),transparent)] bg-muted text-foreground/85 dark:border-border/60 dark:bg-[rgb(255_255_255_/_calc(0.04*var(--contrast-wash-gain,1)))] dark:text-foreground/85";

function QuantBadge({
  quant,
  fit,
  lookupTableBytes = 0,
  showFit = true,
  unifiedBudget = false,
  variant = "trigger",
  tooltipMode = "eager",
}: {
  quant: string;
  fit: GgufFitClass;
  lookupTableBytes?: number;
  showFit?: boolean;
  unifiedBudget?: boolean;
  variant?: "trigger" | "menu";
  tooltipMode?: "eager" | "lazy" | "none";
}) {
  const t = useT();
  const meta = FIT_BADGE[fit];
  const [tooltipArmed, setTooltipArmed] = useState(false);
  const [tooltipOpen, setTooltipOpen] = useState(false);
  const armTooltip = useCallback(() => {
    setTooltipArmed((armed) => (armed ? armed : true));
    if (tooltipMode === "lazy") setTooltipOpen(true);
  }, [tooltipMode]);
  const tooltipActive = tooltipMode === "eager" || tooltipArmed;
  const inner =
    variant === "menu" ? (
      <span
        className={cn(
          CHIP_BASE,
          "min-w-0 max-w-full shrink gap-1.5 cursor-help",
          CHIP_DEFAULT,
        )}
      >
        {showFit && (
          <HugeiconsIcon
            icon={InformationCircleIcon}
            strokeWidth={2.25}
            className={cn("size-3.5 shrink-0", meta.iconClassName)}
          />
        )}
        <span className="min-w-0 truncate">{quant}</span>
      </span>
    ) : (
      // Keep the quant label from collapsing; trailing status tags are clipped instead.
      <span className="inline-flex shrink-0 cursor-help items-center gap-1.5 whitespace-nowrap text-ui-12p5 font-medium tracking-tight tabular-nums text-foreground">
        {showFit && (
          <HugeiconsIcon
            icon={InformationCircleIcon}
            strokeWidth={2.25}
            className={cn("size-3.5 shrink-0", meta.iconClassName)}
          />
        )}
        <span>{quant}</span>
      </span>
    );
  if (!showFit || tooltipMode === "none") return inner;
  if (!tooltipActive) {
    return (
      <span
        className="inline-flex min-w-0"
        onPointerEnter={armTooltip}
        onFocusCapture={armTooltip}
      >
        {inner}
      </span>
    );
  }
  return (
    <Tooltip
      open={tooltipMode === "lazy" ? tooltipOpen : undefined}
      onOpenChange={tooltipMode === "lazy" ? setTooltipOpen : undefined}
    >
      <TooltipTrigger
        asChild={true}
        onFocusCapture={tooltipMode === "lazy" ? armTooltip : undefined}
        onPointerEnter={tooltipMode === "lazy" ? armTooltip : undefined}
      >
        {inner}
      </TooltipTrigger>
      <TooltipContent side="top" sideOffset={4}>
        {fit === "marginal" && unifiedBudget
          ? t("picker.unifiedTightFitHint")
          : meta.tooltip}
        {lookupTableBytes > 0 && (
          <span className="mt-1 block text-muted-foreground">
            Lookup tables: {formatFootprintBytes(lookupTableBytes)}
            {/* Streamed only when RAM cannot hold them; otherwise the load keeps them resident. */}
            {fit === "streamed" ? ", read from disk" : ", kept in RAM when it fits"}
          </span>
        )}
      </TooltipContent>
    </Tooltip>
  );
}

interface GgufVariantMenuItem {
  filename: string;
  key: string;
  quant: string;
  label: string;
  fit: GgufFitClass;
  lookupTableBytes: number;
  downloaded: boolean;
  partial: boolean;
  downloadSizeLabel: string;
  footprint: GgufVariantFootprint | null;
}

/** Model plus uncached companion size, with the breakdown on hover; on disk, only what Run still fetches. */
function GgufVariantSizeLabel({
  label,
  footprint,
  downloaded = false,
}: {
  label: string;
  footprint: GgufVariantFootprint | null;
  downloaded?: boolean;
}) {
  if (!footprint) return <>{label}</>;
  const companion = formatFootprintBytes(footprint.companionBytes);
  return (
    <Tooltip delayDuration={0}>
      <TooltipTrigger asChild={true}>
        <span
          data-model-download-footprint={true}
          data-model-needs-required-assets={downloaded || undefined}
          className="inline-flex items-center gap-1"
        >
          {downloaded
            ? `${companion} more to run`
            : formatFootprintBytes(
                footprint.checkpointBytes + footprint.companionBytes,
              )}
          {/* Align the icon with the digits. */}
          <HugeiconsIcon
            icon={HelpCircleIcon}
            aria-hidden={true}
            className="size-3 shrink-0 -translate-y-[0.08em] text-muted-foreground/80"
            strokeWidth={1.8}
          />
        </span>
      </TooltipTrigger>
      <TooltipContent side="top" className="tooltip-compact">
        <span className="font-medium">
          {formatFootprintBytes(footprint.checkpointBytes)} model
          {downloaded ? " on device" : ""} + {companion} required assets
        </span>
        <span className="ml-1 text-muted-foreground">
          {downloaded
            ? "· assets download on Run, once, shared across compatible variants"
            : "· assets download on Run"}
        </span>
      </TooltipContent>
    </Tooltip>
  );
}

function CompanionsPendingTag({
  companionBytes,
  compact = false,
}: {
  companionBytes: number;
  compact?: boolean;
}) {
  return (
    <Tooltip>
      <TooltipTrigger asChild={true}>
        <span className="inline-flex">
          <DotTag
            tone="warning"
            label="Partial"
            className={compact ? "max-sm:border-0 max-sm:px-0" : undefined}
            labelClassName={compact ? "max-sm:sr-only" : undefined}
          />
        </span>
      </TooltipTrigger>
      <TooltipContent side="top" sideOffset={4}>
        Model on device. {formatFootprintBytes(companionBytes)} of required
        assets download on Run.
      </TooltipContent>
    </Tooltip>
  );
}

function createGgufVariantMenuItems(
  variants: readonly GgufVariantDetail[] | null,
  resources: {
    gpuGb?: number;
    gpuCount?: number;
    audioCppCardGb?: number;
    systemRamGb?: number;
    budgetFraction?: number;
    unifiedLoadBudgetGb?: number | null;
  },
  companionBytesByKey: ReadonlyMap<string, number>,
): GgufVariantMenuItem[] {
  if (!variants) return [];
  return variants.map((variant) => ({
    filename: variant.filename,
    key: normalizeGgufVariantIdentity(variant.quant),
    quant: variant.quant,
    label: ggufVariantDisplayLabel(variant),
    fit: classifyGgufVariantFit(variant, resources),
    lookupTableBytes: ggufVariantLookupTableBytes(variant),
    downloaded: Boolean(variant.downloaded),
    partial: Boolean(variant.partial),
    downloadSizeLabel: ggufVariantTransferLabel(variant),
    footprint: ggufVariantFootprint(variant, companionBytesByKey),
  }));
}

// The identifier uses llama.cpp's repo:quant syntax so it pastes into `-hf`.
export function QuantOptionsMenu({
  repoId,
  quant,
  label,
  downloaded,
  canDelete,
  onDelete,
  showPin = true,
  buttonClassName,
  iconClassName,
}: {
  repoId: string;
  quant?: string;
  label: string;
  downloaded: boolean;
  canDelete: boolean;
  onDelete: (quant?: string) => void;
  showPin?: boolean;
  buttonClassName?: string;
  iconClassName?: string;
}) {
  const pinnedKeys = usePinnedModelsStore((s) => s.pinned);
  const togglePinned = usePinnedModelsStore((s) => s.togglePinned);
  const pinned = pinnedKeys.includes(pinKey(repoId, quant));
  const deviceType = usePlatformStore((s) => s.deviceType);
  const revealLabel =
    deviceType === "mac" ? "Reveal in Finder" : "Reveal in Folder";
  const handleCopyPath = useCallback(async () => {
    try {
      const { path } = await getCachedModelPath(repoId, quant);
      if (await copyToClipboard(path)) {
        toast.success("Copied path");
      } else {
        toast.error("Failed to copy");
      }
    } catch (err) {
      toast.error(
        err instanceof Error ? err.message : "Failed to resolve model path",
      );
    }
  }, [repoId, quant]);
  const handleCopyId = useCallback(async () => {
    const id = quant ? `${repoId}:${quant}` : repoId;
    if (await copyToClipboard(id)) {
      toast.success("Copied identifier");
    } else {
      toast.error("Failed to copy");
    }
  }, [repoId, quant]);

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild={true}>
        <button
          type="button"
          onClick={(e) => e.stopPropagation()}
          aria-label={`More options for ${label}`}
          className={cn(
            "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full",
            "text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
            "data-[state=open]:bg-muted data-[state=open]:text-foreground",
            buttonClassName,
          )}
        >
          <HugeiconsIcon
            icon={MoreVerticalIcon}
            strokeWidth={1.75}
            className={cn("size-3.5", iconClassName)}
          />
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        side="bottom"
        align="end"
        sideOffset={2}
        className="unsloth-plus-menu menu-flat-destructive w-48"
      >
        {showPin && downloaded && (
          <DropdownMenuItem
            onSelect={(e) => {
              e.stopPropagation();
              togglePinned(repoId, quant);
            }}
          >
            <HugeiconsIcon
              icon={pinned ? PinOffIcon : PinIcon}
              strokeWidth={1.75}
              className="size-icon"
            />
            <span>{pinned ? "Unpin" : "Pin"}</span>
          </DropdownMenuItem>
        )}
        {downloaded && (
          <DropdownMenuItem
            onSelect={(e) => {
              e.stopPropagation();
              revealCachedModel(repoId, quant).catch((err) => {
                toast.error(
                  err instanceof Error
                    ? err.message
                    : "Failed to open file manager",
                );
              });
            }}
          >
            <HugeiconsIcon
              icon={Folder01Icon}
              strokeWidth={1.75}
              className="size-icon"
            />
            <span>{revealLabel}</span>
          </DropdownMenuItem>
        )}
        <DropdownMenuItem
          onSelect={(e) => {
            e.stopPropagation();
            void handleCopyId();
          }}
        >
          <HugeiconsIcon
            icon={Copy01Icon}
            strokeWidth={1.75}
            className="size-icon"
          />
          <span>Copy identifier</span>
        </DropdownMenuItem>
        {downloaded && (
          <DropdownMenuItem
            onSelect={(e) => {
              e.stopPropagation();
              void handleCopyPath();
            }}
          >
            <HugeiconsIcon
              icon={Copy01Icon}
              strokeWidth={1.75}
              className="size-icon"
            />
            <span>Copy path</span>
          </DropdownMenuItem>
        )}
        {canDelete && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              variant="destructive"
              onSelect={(e) => {
                e.stopPropagation();
                onDelete(quant);
              }}
            >
              <HugeiconsIcon
                icon={TrashIcon}
                strokeWidth={1.75}
                className="size-icon"
              />
              <span>Delete</span>
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

const GgufVariantMenuRow = memo(function GgufVariantMenuRow({
  repoId,
  item,
  selected,
  mutationBlocked,
  liveActive,
  showFitInfo,
  unifiedBudget,
  onSelect,
  onDelete,
}: {
  repoId: string;
  item: GgufVariantMenuItem;
  selected: boolean;
  mutationBlocked: boolean;
  liveActive: boolean;
  showFitInfo: boolean;
  unifiedBudget: boolean;
  onSelect: (quant: string) => void;
  onDelete: (quant: string) => void;
}) {
  const selectVariant = useCallback(() => {
    onSelect(item.quant);
  }, [item.quant, onSelect]);
  const handleKeyDown = useCallback<KeyboardEventHandler<HTMLDivElement>>(
    (e) => {
      if (e.target !== e.currentTarget) return;
      if (e.key === "Enter" || e.key === " ") {
        e.preventDefault();
        selectVariant();
      }
    },
    [selectVariant],
  );
  const canDelete =
    (item.downloaded || item.partial) && !mutationBlocked && !liveActive;

  return (
    <div
      role="button"
      tabIndex={0}
      aria-pressed={selected}
      onClick={selectVariant}
      onKeyDown={handleKeyDown}
      className={cn(
        "group relative mx-2 flex cursor-pointer items-center gap-2 rounded-md px-2.5 py-2 text-left transition-colors",
        selected
          ? // Dark: --accent, the app's one selection colour.
            "bg-[color-mix(in_oklab,var(--foreground)_calc(7%*var(--contrast-wash-gain,1)),transparent)] dark:bg-accent"
          : // Dark hover is --accent held back so it stays under the selected row.
            "hover:bg-[color-mix(in_oklab,var(--foreground)_calc(5%*var(--contrast-wash-gain,1)),transparent)] dark:hover:bg-[color-mix(in_srgb,var(--accent)_55%,transparent)]",
      )}
    >
      {/* Status (On device / Partial) sits beside the quant on the
          left so the model's identity reads as one unit; only the size pins
          right. No per-row "GGUF" tag: every row here is a GGUF quant and the
          trigger already labels it, so repeating it only stole the room the
          quant label needs (it would otherwise truncate to "q…"). */}
      <span className="flex min-w-0 flex-1 items-center gap-2">
        <QuantBadge
          quant={item.label}
          fit={item.fit}
          lookupTableBytes={item.lookupTableBytes}
          showFit={showFitInfo}
          unifiedBudget={unifiedBudget}
          variant="menu"
          tooltipMode="lazy"
        />
        {awaitsCompanions(item.downloaded, item.footprint) ? (
          <CompanionsPendingTag
            companionBytes={item.footprint?.companionBytes ?? 0}
          />
        ) : (
          item.downloaded && <DotTag tone="success" label="On device" />
        )}
        {!item.downloaded && item.partial && (
          <Tooltip>
            <TooltipTrigger asChild={true}>
              <span className="inline-flex">
                <DotTag
                  tone={liveActive ? "downloading" : "warning"}
                  label={liveActive ? "Downloading" : "Partial"}
                />
              </span>
            </TooltipTrigger>
            <TooltipContent side="top" sideOffset={4}>
              {liveActive
                ? "Download is running. Select it to view progress."
                : "Partial download. Select it, then use the button on the card to finish it."}
            </TooltipContent>
          </Tooltip>
        )}
      </span>
      <span className="ml-auto flex shrink-0 items-center gap-1.5">
        <span className={cn(CHIP_BASE, CHIP_DEFAULT)}>
          <GgufVariantSizeLabel
            label={item.downloadSizeLabel}
            footprint={item.footprint}
            downloaded={item.downloaded}
          />
        </span>
        {item.downloaded || item.partial ? (
          <QuantOptionsMenu
            repoId={repoId}
            quant={item.quant}
            label={item.label}
            downloaded={Boolean(item.downloaded)}
            canDelete={canDelete}
            onDelete={(q) => q && onDelete(q)}
          />
        ) : (
          <span aria-hidden={true} className="size-6 shrink-0" />
        )}
      </span>
    </div>
  );
});

export function GgufDownloadCard({
  repoId,
  isActive,
  activeQuant,
  preferredFile = null,

  preferredFileIntent = 0,
  isLoadingThisModel,
  gpuGb,
  gpuCount,
  audioCppCardGb,
  systemRamGb,
  unifiedLoadBudgetGb,
  cachePath,
  preferLocalCache = false,
  isPartial = false,
  onRun,
  runPending = false,
  onChange,
  showMemoryBar = true,
  mediaPage,
}: {
  repoId: string;
  isActive: boolean;
  activeQuant: string | null;
  preferredFile?: string | null;

  preferredFileIntent?: number;
  isLoadingThisModel: boolean;
  gpuGb?: number;
  gpuCount?: number;
  audioCppCardGb?: number;
  systemRamGb?: number;
  unifiedLoadBudgetGb?: number | null;
  cachePath?: string | null;
  preferLocalCache?: boolean;
  isPartial?: boolean;
  onRun?: (selection: HubModelRunSelection) => void;
  runPending?: boolean;
  onChange?: () => void;
  /** False for diffusion/audio/video GGUFs, which use a different planner; the llama.cpp
   *  estimator would give a confident wrong verdict. */
  showMemoryBar?: boolean;
  mediaPage?: MediaStudioPage;
}) {
  const mediaRuntime = mediaPage !== undefined;
  const hfToken = useHfTokenStore((s) => s.token);
  const online = useOnlineStatus();
  const partialsResumable = useHttpPartialsResumable();
  const localVariantPath = showMemoryBar ? null : cachePath?.trim() || null;
  const { variants, loading, error, refreshError, refresh } =
    useGgufVariantFetchState({
      repoId,
      hfToken,
      preferLocalCache,
      localPath: localVariantPath,
      includeCacheLocations: showMemoryBar,
    });
  const [selectedQuantState, setSelectedQuantState] = useState<{
    repoId: string;
    quant: string | null;
    userPicked?: boolean;
    preferredFile?: string | null;

    preferredFileIntent?: number;
  }>(() => ({ repoId, quant: null }));
  const preferredQuant = preferredFile
    ? (variants?.find((variant) =>
        ggufFilenamesMatch(variant.filename, preferredFile),
      )?.quant ?? null)
    : null;
  const selectedQuantOverride =
    selectedQuantState.repoId === repoId &&
    ggufSelectionOverrideMatchesIntent(
      preferredFile,
      preferredFileIntent,
      selectedQuantState.preferredFile,
      selectedQuantState.preferredFileIntent,
    )
      ? selectedQuantState.quant
      : preferredQuant;
  const [open, setOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
  const [updateTarget, setUpdateTarget] = useState<string | null>(null);
  const [completedVariantKeys, setCompletedVariantKeys] = useState<
    ReadonlySet<string>
  >(() => new Set<string>());

  // Use the live VRAM budget so the badge agrees with the memory bar and the loader.
  const budgetFraction = useVramBudgetFraction() ?? undefined;

  const rawSortedVariants = useMemo(() => {
    if (!variants) return null;
    return sortDownloadableGgufVariants(variants, {
      gpuGb,
      gpuCount,
      audioCppCardGb,
      systemRamGb,
      budgetFraction,
      unifiedLoadBudgetGb,
    });
  }, [
    variants,
    gpuGb,
    gpuCount,
    audioCppCardGb,
    systemRamGb,
    budgetFraction,
    unifiedLoadBudgetGb,
  ]);
  const selectLiveGgufVariantStates = useMemo(
    () => createLiveGgufVariantStatesSelector(repoId),
    [repoId],
  );
  const liveVariantStates = useDownloadManagerStore(
    selectLiveGgufVariantStates,
  );
  const selectScopedLiveFiles = useMemo(
    () => createScopedLiveGgufFilesSelector(repoId),
    [repoId],
  );
  const scopedLiveFiles = useDownloadManagerStore(selectScopedLiveFiles);
  const sortedVariants = useMemo(() => {
    if (!rawSortedVariants) return null;
    const withLive = applyLiveGgufVariantStates(
      rawSortedVariants,
      liveVariantStates,
    );
    if (completedVariantKeys.size === 0) return withLive;
    return withLive.map((v) =>
      completedVariantKeys.has(normalizeGgufVariantIdentity(v.quant))
        ? { ...v, downloaded: true, partial: false, update_available: false }
        : v,
    );
  }, [completedVariantKeys, liveVariantStates, rawSortedVariants]);
  const selectedQuant =
    (selectedQuantOverride
      ? sortedVariants?.find((v) =>
          ggufVariantsMatch(v.quant, selectedQuantOverride),
        )?.quant
      : null) ??
    sortedVariants?.[0]?.quant ??
    null;
  const selected =
    sortedVariants?.find((v) => ggufVariantsMatch(v.quant, selectedQuant)) ??
    null;
  const companionBytesByKey = useMediaCompanionBytes(
    mediaPage,
    repoId,
    variants,
    selected?.filename,
    hfToken,
  );
  const variantMenuItems = useMemo(
    () =>
      createGgufVariantMenuItems(
        sortedVariants,
        {
          gpuGb,
          gpuCount,
          audioCppCardGb,
          systemRamGb,
          budgetFraction,
          unifiedLoadBudgetGb,
        },
        companionBytesByKey,
      ),
    [
      gpuGb,
      gpuCount,
      audioCppCardGb,
      sortedVariants,
      systemRamGb,
      budgetFraction,
      unifiedLoadBudgetGb,
      companionBytesByKey,
    ],
  );

  const job = useRepoDownload({
    kind: "model",
    repoId,
    activeVariant: selectedQuant ?? undefined,
    onComplete: (variant) => {
      if (!variant) return;
      const key = normalizeGgufVariantIdentity(variant);
      setCompletedVariantKeys((prev) =>
        prev.has(key) ? prev : new Set(prev).add(key),
      );
      void refresh();
    },
  });
  const progress = job.progress;
  const cancelling = job.cancelling;

  const setExpectedBytes = job.setExpectedBytes;
  useEffect(() => {
    const controller = new AbortController();
    void downloadManager.probeAndAdopt("model", repoId, controller.signal, {
      includeVariants: true,
      fresh: true,
      onModelAdopt: (active) => {
        if (controller.signal.aborted) return;
        if (active.variant) {
          setSelectedQuantState((prev) =>
            prev.repoId === repoId && prev.userPicked
              ? prev
              : { repoId, quant: active.variant },
          );
        }
      },
    });
    return () => {
      controller.abort();
    };
  }, [repoId]);

  useEffect(() => {
    if (!variants || !progress?.variant) return;
    const knownVariant = variants.find((variant) =>
      ggufVariantsMatch(variant.quant, progress.variant),
    );
    if (!knownVariant) return;
    const expectedBytes =
      knownVariant.download_size_bytes ?? knownVariant.size_bytes ?? 0;
    if (expectedBytes > progress.expectedBytes) {
      setExpectedBytes(expectedBytes, progress.variant);
    }
  }, [variants, progress?.variant, progress?.expectedBytes, setExpectedBytes]);

  useEffect(() => {
    setCompletedVariantKeys(new Set<string>());
  }, [repoId]);

  useEffect(() => {
    if (loading || error || refreshError || !variants) return;
    setCompletedVariantKeys((prev) =>
      prev.size === 0 ? prev : new Set<string>(),
    );
  }, [loading, error, refreshError, variants]);

  const assets = useRequiredAssetsDownload({
    repoId,
    filename: selected?.filename,
    runtime: selected ? mediaPage : undefined,
    modelLabel: `${repoId} · ${selectedQuant ?? ""}`,
  });
  const selectedLiveState = selectedQuant
    ? liveVariantStates.get(normalizeGgufVariantIdentity(selectedQuant))
    : undefined;
  const selectedPresentation = pendingDrafterPresentation(selected);
  const downloadingThisVariant =
    progress !== null && ggufVariantsMatch(progress.variant, selectedQuant);
  const selectedScopedLive =
    !downloadingThisVariant && isScopedLiveVariant(selected, scopedLiveFiles);
  const selectedLiveActive =
    activeDownloadState(selectedLiveState?.state) || selectedScopedLive;
  const ctaDisabled = isLoadingThisModel || !selected;
  const selectedIsActive =
    isActive && activeQuant && ggufVariantsMatch(selected?.quant, activeQuant);
  // Media fit is the diffusion planner's question; no verdict beats a wrong one.
  const showFitInfo = !mediaRuntime && (Boolean(gpuGb) || Boolean(systemRamGb));
  const selectedFit = selected
    ? classifyGgufVariantFit(selected, {
        gpuGb,
        gpuCount,
        audioCppCardGb,
        systemRamGb,
        budgetFraction,
        unifiedLoadBudgetGb,
      })
    : null;
  const selectedDownloadSizeLabel = selected
    ? ggufVariantTransferLabel(selected)
    : null;
  const selectedFootprint = selected
    ? ggufVariantFootprint(selected, companionBytesByKey)
    : null;
  const selectedAwaitsCompanions = awaitsCompanions(
    selected?.downloaded,
    selectedFootprint,
  );
  const updateAvailable =
    selected?.downloaded === true && selected.update_available === true;
  const selectedVariantKey = selectedQuant
    ? normalizeGgufVariantIdentity(selectedQuant)
    : null;
  const activeVariantKey = activeQuant
    ? normalizeGgufVariantIdentity(activeQuant)
    : null;
  const handleSelectVariant = useCallback(
    (quant: string) => {
      setSelectedQuantState({
        repoId,
        quant,
        userPicked: true,
        preferredFile,

        preferredFileIntent,
      });
      setOpen(false);
    },
    [preferredFile, preferredFileIntent, repoId],
  );
  const handleDeleteVariant = useCallback((quant: string) => {
    setDeleteTarget(quant);
  }, []);
  const downloadAction = useDownloadCardState({
    job,
    variant: selectedQuant,
    expectedBytes: selected?.download_size_bytes ?? selected?.size_bytes ?? 0,
    presentation: selectedPresentation,
    downloading: downloadingThisVariant,
    cancelling,
    disabled: cancelling
      ? true
      : downloadingThisVariant
        ? false
        : ctaDisabled || selectedScopedLive,
    isPartial: Boolean(selected?.partial),
    partialTransport: selected?.partial_transport ?? null,
    partialResumable: selected?.partial_resumable === true,
    partialsResumable,
  });
  const selectedLabel = selected ? ggufVariantDisplayLabel(selected) : null;
  const deleteTargetVariant =
    deleteTarget && sortedVariants
      ? sortedVariants.find((v) => ggufVariantsMatch(v.quant, deleteTarget))
      : null;
  const deleteTargetLabel = deleteTargetVariant
    ? ggufVariantDisplayLabel(deleteTargetVariant)
    : deleteTarget;
  const deleteImpact = useDeleteImpact(
    deleteTarget !== null,
    repoId,
    deleteTarget,
    deleteTargetVariant?.cache_ref ?? deleteTargetVariant?.cache_path ?? cachePath ?? undefined,
  );
  const { deleting, runDelete } = useDeleteConfirmAction({
    action: async () => {
      if (!deleteTarget) return;
      await deleteCachedModel(
        repoId,
        deleteTarget,
        hfToken || undefined,
        // Redaction clears the path but keeps the ref, which pins the delete to this row.
        deleteTargetVariant?.cache_ref ??
          deleteTargetVariant?.cache_path ??
          cachePath ??
          undefined,
      );
    },
    successMessage: () =>
      `Deleted ${repoId} ${deleteTargetLabel ?? deleteTarget}`,
    errorToast: (err) => ({
      title: err instanceof Error ? err.message : "Failed to delete",
    }),
    onSuccess: () => {
      onChange?.();
    },
    onSettled: () => {
      setDeleteTarget(null);
    },
  });
  const updateTargetVariant =
    updateTarget && sortedVariants
      ? sortedVariants.find((v) => ggufVariantsMatch(v.quant, updateTarget))
      : null;
  const updateTargetLabel = updateTargetVariant
    ? ggufVariantDisplayLabel(updateTargetVariant)
    : updateTarget;
  // Run as a managed download so it gets normal progress and cancel. Only changed blobs are
  // pulled, so the cached version stays runnable until the new one lands.
  const handleConfirmUpdate = useCallback(() => {
    if (!updateTarget) return;
    const variant = updateTarget;
    const expectedBytes =
      updateTargetVariant?.download_size_bytes ??
      updateTargetVariant?.size_bytes ??
      0;
    const presentation = pendingDrafterPresentation(updateTargetVariant);
    setUpdateTarget(null);
    void downloadManager.requestStart({
      kind: "model",
      repoId,
      variant,
      expectedBytes,
      ...(presentation ? { presentation } : {}),
    });
  }, [updateTarget, updateTargetVariant, repoId]);
  const hubPlan = useHubDownloadPlan(repoId, selected?.filename);
  const variantListUnavailable = !sortedVariants || sortedVariants.length === 0;
  const showVariantLoadingState = loading && variantListUnavailable;
  const showUpdateAction = !hubPlan &&
    selected?.downloaded === true &&
    online &&
    updateAvailable &&
    !selectedIsActive &&
    !isLoadingThisModel &&
    !runPending &&
    !cancelling &&
    !downloadAction.starting &&
    !downloadingThisVariant;
  const showDownloadAction = !hubPlan && (
    !selected?.downloaded ||
    downloadingThisVariant ||
    cancelling ||
    downloadAction.starting);
  const showRunAction = !hubPlan &&
    Boolean(onRun) &&
    selected?.downloaded === true &&
    selected.partial !== true &&
    !downloadingThisVariant &&
    !cancelling &&
    !downloadAction.starting &&
    !isLoadingThisModel;

  // Keep progress visible when the variant list is unavailable, so remounts do not hide it.
  if (progress && variantListUnavailable) {
    return (
      <GgufDownloadingFallbackCard
        job={job}
        progress={progress}
        cancelling={cancelling}
      />
    );
  }

  if (showVariantLoadingState) {
    return (
      <GgufDownloadStatusCard
        job={job}
        loading={true}
        message="Loading available quantizations…"
      />
    );
  }

  if (variantListUnavailable) {
    if (isPartial) {
      return (
        <GgufDownloadStatusCard
          job={job}
          tone="muted"
          partial={true}
          message="Partial download present. Couldn't load quantizations."
          actionLabel="Reload"
          onAction={() => void refresh()}
        />
      );
    }
    return (
      <GgufDownloadStatusCard
        job={job}
        tone="danger"
        message={error ?? "No GGUF quantizations found in this repository."}
      />
    );
  }

  return (
    <div className="flex w-full flex-col gap-2">
      <DownloadCard
        footer={hubPlan ? <HubPlanProgress plan={hubPlan} /> : undefined}
        job={job}
        progress={downloadingThisVariant ? progress : null}
        dialogs={
          <>
            <DeleteConfirmDialog
              open={deleteTarget !== null}
              onOpenChange={(o) => {
                if (!o && !deleting) setDeleteTarget(null);
              }}
              title="Delete quantization?"
              deleting={deleting}
              blocked={(deleteImpact?.blocked_by.length ?? 0) > 0}
              onConfirm={() => void runDelete()}
              description={
                <>
                  This will remove{" "}
                  <span className="font-medium text-foreground">
                    {repoId} ({deleteTargetLabel})
                  </span>{" "}
                  from disk. You can re-download it later.
                  <DeleteImpactSummary impact={deleteImpact} />
                </>
              }
            />
            <UpdateConfirmDialog
              open={updateTarget !== null}
              onOpenChange={(o) => {
                if (!o) setUpdateTarget(null);
              }}
              title="Update quantization?"
              updating={false}
              onConfirm={handleConfirmUpdate}
              description={
                <>
                  This will re-download the latest version of{" "}
                  <span className="font-medium text-foreground">
                    {repoId} ({updateTargetLabel})
                  </span>{" "}
                  from Hugging Face.
                </>
              }
            />
          </>
        }
      >
        <Popover
          open={runPending ? false : open}
          onOpenChange={(nextOpen) => {
            if (!runPending) setOpen(nextOpen);
          }}
        >
          <PopoverTrigger asChild={true}>
            <button
              type="button"
              disabled={runPending}
              onClick={(e) => {
                e.preventDefault();
                setOpen((o) => !o);
              }}
              className="hub-menu-trigger flex h-9 min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-full px-3 text-left transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_calc(4%*var(--contrast-wash-gain,1)),transparent)] data-[state=open]:bg-[color-mix(in_oklab,var(--foreground)_calc(6%*var(--contrast-wash-gain,1)),transparent)] disabled:cursor-wait disabled:opacity-60 disabled:hover:bg-transparent dark:hover:bg-[color-mix(in_srgb,var(--accent)_55%,transparent)] dark:data-[state=open]:bg-accent dark:disabled:hover:bg-transparent"
            >
              <span className="flex min-w-0 items-center gap-2 overflow-hidden text-ui-12 text-muted-foreground max-[360px]:gap-1">
                {selected ? (
                  <QuantBadge
                    quant={selectedLabel ?? selected.quant}
                    fit={selectedFit ?? "oom"}
                    lookupTableBytes={ggufVariantLookupTableBytes(selected)}
                    showFit={showFitInfo}
                    unifiedBudget={unifiedLoadBudgetGb != null}
                  />
                ) : (
                  <span className="text-ui-12p5 text-muted-foreground">
                    Select quantization
                  </span>
                )}
                {selectedAwaitsCompanions ? (
                  <CompanionsPendingTag
                    companionBytes={selectedFootprint?.companionBytes ?? 0}
                    compact={true}
                  />
                ) : (
                  selected?.downloaded && (
                    // Dot only on phones.
                    <DotTag
                      tone="success"
                      label="On device"
                      className="max-sm:border-0 max-sm:px-0"
                      labelClassName="max-sm:sr-only"
                    />
                  )
                )}
                {selected && !selected.downloaded && selected.partial && (
                  <Tooltip>
                    <TooltipTrigger asChild={true}>
                      <span className="inline-flex">
                        <DotTag
                          tone={selectedLiveActive ? "downloading" : "warning"}
                          label={selectedLiveActive ? "Downloading" : "Partial"}
                        />
                      </span>
                    </TooltipTrigger>
                    <TooltipContent side="top" sideOffset={4}>
                      {selectedScopedLive
                        ? "Download is running. Progress is in the downloads panel."
                        : selectedLiveActive
                          ? "Download is running. Use the button on the right to stop it."
                          : downloadAction.partialHint}
                    </TooltipContent>
                  </Tooltip>
                )}
                <DotTag tone="gguf" label="GGUF" className="max-sm:hidden" />
                {selected &&
                  selectedDownloadSizeLabel &&
                  (!selected.downloaded || selectedFootprint) && (
                    <span className="shrink-0 tabular-nums">
                      <GgufVariantSizeLabel
                        label={selectedDownloadSizeLabel}
                        footprint={selectedFootprint}
                        downloaded={Boolean(selected.downloaded)}
                      />
                    </span>
                  )}
              </span>
              <HugeiconsIcon
                icon={ChevronDownStandardIcon}
                className="size-3.5 shrink-0 text-muted-foreground"
              />
            </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(300px*var(--ui-space-scale,1)),calc(100vw-32px))] gap-0 overflow-hidden p-0 py-2 ring-0"
          >
            <div className="max-h-[calc(344px*var(--ui-space-scale,1))] overflow-y-auto [scrollbar-width:thin]">
              {variantMenuItems.map((item) => {
                const liveState = liveVariantStates.get(item.key);
                const liveActive =
                  activeDownloadState(liveState?.state) ||
                  isScopedLiveVariant(item, scopedLiveFiles);
                return (
                  <GgufVariantMenuRow
                    key={item.filename}
                    repoId={repoId}
                    item={item}
                    selected={item.key === selectedVariantKey}
                    mutationBlocked={
                      runPending ||
                      isLoadingThisModel ||
                      (isActive && item.key === activeVariantKey)
                    }
                    liveActive={liveActive}
                    showFitInfo={showFitInfo}
                    unifiedBudget={unifiedLoadBudgetGb != null}
                    onSelect={handleSelectVariant}
                    onDelete={handleDeleteVariant}
                  />
                );
              })}
            </div>
          </PopoverContent>
        </Popover>

        {/* Options only resolve managed HF-cache repos, so skip local paths;
            they also only apply to quants actually on disk. */}
        {selected &&
          Boolean(selected.downloaded || selected.partial) &&
          !/^([/\\~.]|[A-Za-z]:)/.test(repoId) && (
            <QuantOptionsMenu
              repoId={repoId}
              quant={selected.quant}
              label={`${repoId} ${selectedLabel}`}
              downloaded={Boolean(selected.downloaded)}
              canDelete={
                Boolean(selected.downloaded || selected.partial) &&
                !selectedIsActive &&
                !downloadingThisVariant &&
                !isLoadingThisModel &&
                !runPending
              }
              onDelete={(q) => q && handleDeleteVariant(q)}
              showPin={false}
              buttonClassName="ml-0.5 size-7"
              iconClassName="size-4"
            />
          )}

        {/* Run sets itself apart; the line only separates the download and update actions. */}
        {(showUpdateAction || showDownloadAction) && !(showRunAction && onRun && selected) && (
          <CardDivider />
        )}

        {showUpdateAction && (
          <button
            type="button"
            onClick={() => selected && setUpdateTarget(selected.quant)}
            aria-label={`Update ${repoId}`}
            className="hub-action-btn ml-1 text-amber-700 dark:text-amber-300"
          >
            <HugeiconsIcon
              icon={Refresh01Icon}
              strokeWidth={1.75}
            />
            Update
          </button>
        )}

        {showDownloadAction && (
          <button
            type="button"
            disabled={downloadAction.disabled || assets.checking}
            onClick={() => {
              if (downloadingThisVariant) {
                downloadAction.onClick();
                return;
              }
              // The default follows live free memory; pin it so the card keeps this transfer.
              if (selectedQuant) handleSelectVariant(selectedQuant);
              void assets.request(downloadAction.onClick);
            }}
            aria-label={
              selectedScopedLive ? "Downloading" : downloadAction.ariaLabel
            }
            className={cn(
              "hub-action-btn w-24",
              ctaDisabled &&
                !downloadingThisVariant &&
                !cancelling &&
                "opacity-70",
              (cancelling || downloadAction.starting) && "opacity-70",
              downloadingThisVariant &&
                !cancelling &&
                "hover:bg-rose-500/10 hover:text-rose-600 dark:hover:text-rose-400",
            )}
          >
            {cancelling ? (
              <span className="inline-flex items-center gap-2 text-muted-foreground">
                <Spinner />
                Cancelling…
              </span>
            ) : downloadingThisVariant ? (
              <span className="inline-flex items-center gap-2">
                <DownloadStopIndicator mode={downloadAction.stopMode} />
                {downloadAction.progressPercent != null
                  ? `${downloadAction.progressPercent}%`
                  : null}
              </span>
            ) : downloadAction.starting ? (
              <span className="inline-flex items-center gap-2">
                <Spinner />
                Starting…
              </span>
            ) : selectedScopedLive ? (
              <span className="inline-flex items-center gap-2 text-muted-foreground">
                <Spinner />
              </span>
            ) : (
              <>
                <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} />
                {assets.checking ? "Checking…" : downloadAction.downloadLabel}
              </>
            )}
          </button>
        )}

        {hubPlan && <span className="px-3 text-ui-12 text-muted-foreground">Downloading…</span>}
        {showRunAction && onRun && selected && (
          <ModelRunActionButton
            label={`Configure and run ${repoId} ${selectedLabel ?? selected.quant}`}
            loading={runPending}
            onClick={() =>
              onRun({
                ggufVariant: selected.quant,
                ggufFilename: selected.filename,
                expectedBytes:
                  selected.download_size_bytes &&
                  selected.download_size_bytes > 0
                    ? selected.download_size_bytes
                    : selected.size_bytes,
              })
            }
          />
        )}
      </DownloadCard>
      {assets.dialog}
      {selected?.downloaded && showMemoryBar ? (
        <ModelMemoryBarFor
          repoId={repoId}
          quant={selected.quant}
          sizeBytes={selected.size_bytes}
          lookupTableBytes={ggufVariantLookupTableBytes(selected)}
          gpuGb={gpuGb}
          showReadout={true}
          className="px-1"
        />
      ) : null}
      {refreshError && (
        <button
          type="button"
          onClick={() => void refresh()}
          className="self-start px-1 text-ui-11 text-status-warning underline-offset-2 transition-colors hover:underline"
        >
          Couldn't refresh quantizations. Retry
        </button>
      )}
    </div>
  );
}