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.

33.5 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 { useVllmAvailable, useVllmPlatform } from "@/features/model-picker";
import { isChatGgufTask, reconcileGgufPinsAfterDelete } from "@/features/model-picker/components/model-selector/reconcile-gguf-pins";

import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  type GgufVariantDetail,
  deleteCachedDataset,
  DELETABLE_LOCAL_SOURCES,
  deleteCachedModel,
  deleteLocalModel,
  revealLocalModel,
  formatLocalUpdated,
  listGgufVariants,
  useGgufVariantsCacheVersion,
} from "../inventory";
import {
  classifyUnslothSupport,
  formatBytes,
  formatRelativeShort,
  ggufVariantDisplayLabel,
  useHfTokenStore,
} from "@/features/hub";
import {
  ModelRowMenu,
  pinKey,
  usePinnedModelsStore,
} from "@/features/model-picker";
import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";
import { cn, formatCompact } from "@/lib/utils";
import {
  Download01Icon,
  FavouriteIcon,
  PackageIcon,
} from "@hugeicons/core-free-icons";
import type { IconSvgElement } from "@hugeicons/react";
import { HugeiconsIcon } from "@hugeicons/react";
import { useVirtualizer } from "@tanstack/react-virtual";
import {
  type FocusEvent,
  type ReactNode,
  createContext,
  memo,
  useCallback,
  useContext,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { paramLabelFromId } from "../lib/view-models";
import type {
  CachedInventoryRow,
  DiscoverRow,
  LocalInventoryRow,
} from "../types";
import { DOWNLOADING_DOT_CLASS } from "./dot-tag";
import { OwnerAvatar } from "./owner-avatar";
import { AccessGlyphs } from "./shared";

const COARSE_POINTER =
  typeof window !== "undefined" &&
  typeof window.matchMedia === "function" &&
  window.matchMedia("(pointer: coarse)").matches;

// Defer the cached-size chip until first hover/focus to keep virtualized scrolling cheap.
// Coarse pointers arm immediately; default true so out-of-row usage works.
const CatalogRowInteractiveContext = createContext(true);

function CachedSizeChip(props: {
  repoId: string;
  totalBytes: number;
  isGguf: boolean;
  isDataset?: boolean;
  cachePath?: string | null;
}) {
  const interactive = useContext(CatalogRowInteractiveContext);
  if (!interactive) {
    return (
      <StatChip icon={PackageIcon} value={formatBytes(props.totalBytes)} />
    );
  }
  return <CachedSizeChipLive {...props} />;
}

function CachedSizeChipLive({
  repoId,
  totalBytes,
  isGguf,
  isDataset = false,
  cachePath,
}: {
  repoId: string;
  totalBytes: number;
  isGguf: boolean;
  isDataset?: boolean;
  cachePath?: string | null;
}) {
  const hfToken = useHfTokenStore((s) => s.token) || undefined;
  const variantsVersion = useGgufVariantsCacheVersion(repoId);
  const fetchKey = `${repoId}::${cachePath ?? ""}::${variantsVersion}`;
  const [variantState, setVariantState] = useState<{
    key: string;
    status: "idle" | "loading" | "loaded" | "error";
    variants: GgufVariantDetail[];
  }>(() => ({
    key: fetchKey,
    status: "idle",
    variants: [],
  }));
  const fetchedForRef = useRef<string | null>(null);
  const needsVariantFetch = isGguf && !isDataset;
  const currentVariantState =
    variantState.key === fetchKey
      ? variantState
      : { key: fetchKey, status: "idle" as const, variants: [] };

  const ensureVariantsLoaded = useCallback(() => {
    if (!needsVariantFetch) return;
    if (fetchedForRef.current === fetchKey) return;
    fetchedForRef.current = fetchKey;
    setVariantState({ key: fetchKey, status: "loading", variants: [] });
    listGgufVariants(repoId, hfToken, {
      preferLocalCache: true,
      localPath: cachePath ?? null,
    })
      .then((res) => {
        if (fetchedForRef.current !== fetchKey) return;
        setVariantState({
          key: fetchKey,
          status: "loaded",
          variants: res.variants.filter((v) => v.downloaded),
        });
      })
      .catch(() => {
        if (fetchedForRef.current !== fetchKey) return;
        fetchedForRef.current = null;
        setVariantState({ key: fetchKey, status: "error", variants: [] });
      });
  }, [needsVariantFetch, fetchKey, repoId, hfToken, cachePath]);

  const trigger = (
    <span
      className="pointer-events-auto hub-modal-pe-guard"
      onClick={(e) => e.stopPropagation()}
    >
      <StatChip icon={PackageIcon} value={formatBytes(totalBytes)} />
    </span>
  );

  const rows: Array<{ label: string; size_bytes: number }> | null =
    needsVariantFetch
      ? currentVariantState.status === "loaded" &&
        currentVariantState.variants.length > 0
        ? currentVariantState.variants.map((variant) => ({
            label: ggufVariantDisplayLabel(variant),
            size_bytes: variant.size_bytes,
          }))
        : null
      : [{ label: repoId, size_bytes: totalBytes }];
  const variantMessage =
    currentVariantState.status === "loading"
      ? "Loading downloaded variants..."
      : currentVariantState.status === "error"
        ? "Couldn't load downloaded variants. Open again to retry."
        : currentVariantState.status === "loaded"
          ? "No downloaded GGUF variants found."
          : "Open to load downloaded variants.";

  return (
    <Tooltip
      onOpenChange={(open) => {
        if (open) ensureVariantsLoaded();
      }}
    >
      <TooltipTrigger asChild={true}>{trigger}</TooltipTrigger>
      <TooltipContent variant="default" side="top" sideOffset={4}>
        {rows ? (
          <ul className="flex flex-col gap-1">
            {rows.map((row) => (
              <li
                key={row.label}
                className="flex items-center gap-3 tabular-nums"
              >
                <span className="min-w-0 truncate">{row.label}</span>
                <span className="ml-auto">
                  <StatChip
                    icon={PackageIcon}
                    value={formatBytes(row.size_bytes)}
                    className="text-ui-11 text-(--tooltip-muted)"
                  />
                </span>
              </li>
            ))}
          </ul>
        ) : (
          <span className="block max-w-52 text-ui-11 leading-4 text-muted-foreground">
            {variantMessage}
          </span>
        )}
      </TooltipContent>
    </Tooltip>
  );
}

function MetaDivider() {
  return (
    <span aria-hidden="true" className="shrink-0 text-muted-foreground/35">
      ·
    </span>
  );
}

export function StatChip({
  icon,
  value,
  className,
}: {
  icon: IconSvgElement;
  value: string;
  className?: string;
}) {
  return (
    <span
      className={cn(
        "inline-flex shrink-0 items-center gap-1 whitespace-nowrap text-ui-10 font-medium leading-none tabular-nums text-muted-foreground/75",
        className,
      )}
    >
      <HugeiconsIcon
        icon={icon}
        strokeWidth={1.75}
        className="size-2.5 shrink-0"
      />
      {value}
    </span>
  );
}

function CatalogRow({
  selected,
  onClick,
  tooltip,
  label,
  children,
  variant = "flat",
}: {
  selected: boolean;
  tooltip?: ReactNode;
  onClick: () => void;
  label: string;
  children: ReactNode;
  variant?: "flat" | "card";
}) {
  const [interactive, setInteractive] = useState(COARSE_POINTER);
  const arm = useCallback(() => setInteractive(true), []);
  const rowRef = useRef<HTMLDivElement>(null);
  const refocusIndex = useRef<number | null>(null);
  const armFromFocus = (event: FocusEvent<HTMLDivElement>) => {
    if (interactive) return;
    const buttons = Array.from(event.currentTarget.querySelectorAll("button"));
    refocusIndex.current = buttons.indexOf(event.target as Element as HTMLButtonElement);
    arm();
  };
  // Arming wraps the row in a Tooltip, which remounts it and would drop keyboard focus.
  useLayoutEffect(() => {
    if (refocusIndex.current === null) return;
    rowRef.current?.querySelectorAll("button")[refocusIndex.current]?.focus();
    refocusIndex.current = null;
  }, [interactive]);
  const card = variant === "card";
  const button = (
    <div
      ref={rowRef}
      data-selected={selected || undefined}
      onPointerEnter={arm}
      onFocusCapture={armFromFocus}
      className={cn(
        "group/row relative w-full select-none overflow-hidden text-left",
        card
          ? "hub-result-row flex h-full items-center rounded-2xl px-4"
          : "catalog-row block rounded-md pl-3 pr-2.5 py-2.5",
      )}
    >
      <button
        type="button"
        aria-label={label}
        onClick={onClick}
        className={cn(
          "absolute inset-0 cursor-pointer outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-inset",
          card ? "rounded-2xl" : "rounded-md",
        )}
      />
      <CatalogRowInteractiveContext.Provider value={interactive}>
        <div
          className={cn("pointer-events-none relative", card && "z-[1] w-full")}
        >
          {children}
        </div>
      </CatalogRowInteractiveContext.Provider>
    </div>
  );
  if (!tooltip || !interactive) return button;
  return (
    <Tooltip>
      <TooltipTrigger asChild={true}>{button}</TooltipTrigger>
      <TooltipContent
        side={card ? "top" : "right"}
        align="start"
        sideOffset={card ? 6 : 8}
        className="tooltip-compact max-w-xs"
      >
        {tooltip}
      </TooltipContent>
    </Tooltip>
  );
}

export { DOWNLOADING_DOT_CLASS };

function StatusDot({
  tone,
  label,
}: {
  tone: "warning" | "danger" | "success" | "downloading" | "asset";
  label: string;
}) {
  const toneClass =
    tone === "asset"
      ? "bg-status-asset"
      : tone === "warning"
        ? "bg-status-warning"
        : tone === "danger"
          ? "bg-status-danger"
          : tone === "downloading"
            ? DOWNLOADING_DOT_CLASS
            : "bg-status-success";
  return (
    <span
      role="img"
      aria-label={label}
      className={cn("inline-block size-[calc(5px*var(--ui-space-scale,1))] shrink-0 rounded-full", toneClass)}
    />
  );
}

function PartialStatusDot({ downloading }: { downloading: boolean }) {
  return downloading ? (
    <StatusDot tone="downloading" label="Downloading" />
  ) : (
    <StatusDot tone="warning" label="Partial download" />
  );
}

function TooltipLegendRow({
  toneClass,
  children,
}: {
  toneClass: string;
  children: ReactNode;
}) {
  return (
    <div className="flex items-start gap-1.5 leading-snug">
      <span
        aria-hidden="true"
        className={cn(
          "mt-1 inline-block size-1.5 shrink-0 rounded-full",
          toneClass,
        )}
      />
      <span className="min-w-0">{children}</span>
    </div>
  );
}

export function buildRowStatusTooltip({
  isGguf,
  isAdapter,
  isAvailableOnDevice,
  isSharedAsset,
  partialRepoId,
  downloading = false,
  unsupported,
  unsupportedReason,
  resourceLabel = "model",
}: {
  isGguf?: boolean;
  isAdapter?: boolean;
  isAvailableOnDevice?: boolean;
  isSharedAsset?: boolean;
  partialRepoId?: string;
  downloading?: boolean;
  unsupported?: boolean;
  unsupportedReason?: string | null;
  resourceLabel?: "model" | "dataset";
}): ReactNode {
  const lines: ReactNode[] = [];

  if (isGguf) {
    lines.push(
      <TooltipLegendRow key="gguf" toneClass="bg-format-gguf">
        GGUF format.
      </TooltipLegendRow>,
    );
  }
  if (isAdapter) {
    lines.push(
      <TooltipLegendRow key="adapter" toneClass="bg-format-adapter">
        Adapter format.
      </TooltipLegendRow>,
    );
  }

  if (partialRepoId && downloading) {
    lines.push(
      <TooltipLegendRow key="downloading" toneClass={DOWNLOADING_DOT_CLASS}>
        Downloading <span className="font-medium">{partialRepoId}</span>.
        Progress is in the downloads panel.
      </TooltipLegendRow>,
    );
  } else if (partialRepoId) {
    lines.push(
      <TooltipLegendRow key="partial" toneClass="bg-status-warning">
        Partial download of <span className="font-medium">{partialRepoId}</span>
        . Open it to finish the download.
      </TooltipLegendRow>,
    );
  } else if (isSharedAsset) {
    lines.push(
      <TooltipLegendRow key="asset" toneClass="bg-status-asset">
        Shared assets. Supporting files used by compatible models.
      </TooltipLegendRow>,
    );
  } else if (isAvailableOnDevice) {
    lines.push(
      <TooltipLegendRow key="success" toneClass="bg-status-success">
        On device. Ready to use locally.
      </TooltipLegendRow>,
    );
  }

  if (unsupported) {
    lines.push(
      <TooltipLegendRow key="danger" toneClass="bg-status-danger">
        <span className="block">
          This {resourceLabel} may not be supported yet.
        </span>
        {unsupportedReason && (
          <span className="mt-0.5 block text-(--tooltip-muted)">
            {unsupportedReason}
          </span>
        )}
        <span className="mt-0.5 block text-(--tooltip-muted)">
          Still downloadable to your Hugging Face cache.
        </span>
      </TooltipLegendRow>,
    );
  }

  if (lines.length === 0) return null;
  return <div className="space-y-1.5">{lines}</div>;
}

export const DiscoverModelRow = memo(function DiscoverModelRow({
  row,
  selected,
  deviceType,
  isDataset,
  onSelect,
}: {
  row: DiscoverRow;
  selected: boolean;
  deviceType: string | null;
  isDataset: boolean;
  onSelect: (id: string) => void;
}) {
  const vllmAvailable = useVllmAvailable();
  const vllmPlatform = useVllmPlatform();
  const support = useMemo(
    () =>
      isDataset
        ? null
        : classifyUnslothSupport({
            modelId: row.id,
            pipelineTag: row.result.pipelineTag,
            tags: row.result.tags,
            libraryName: row.result.libraryName,
            deviceType,
            quantMethod: row.result.quantMethod,
            vllmAvailable,
            vllmPlatform,
          }),
    [isDataset, row.id, row.result, deviceType, vllmAvailable, vllmPlatform],
  );
  const unsupported = support?.status === "unsupported" && !support?.supportedIn;
  const handleClick = useCallback(() => onSelect(row.id), [onSelect, row.id]);
  const partialRepoId =
    row.isAvailableOnDevice && row.isPartialOnDevice
      ? row.result.id
      : undefined;
  const downloading = Boolean(partialRepoId && row.isDownloadingOnDevice);
  const tooltip = buildRowStatusTooltip({
    isGguf: row.result.isGguf,
    isAdapter: false,
    isAvailableOnDevice: row.isAvailableOnDevice,
    partialRepoId,
    downloading,
    unsupported,
    unsupportedReason: support?.reason ?? null,
    resourceLabel: isDataset ? "dataset" : "model",
  });
  return (
    <CatalogRow
      selected={selected}
      tooltip={tooltip}
      label={row.repo}
      onClick={handleClick}
    >
      <div className="flex items-center gap-3">
        <OwnerAvatar
          owner={row.owner}
          repoName={row.repo}
          className="size-8 rounded-sm"
          remote={false}
        />
        <div className="flex min-w-0 flex-1 flex-col gap-[calc(3px*var(--ui-space-scale,1))]">
          <div className="flex h-[calc(18px*var(--ui-space-scale,1))] min-w-0 items-center justify-between gap-2">
            <div className="flex min-w-0 items-center gap-2 pr-2">
              <p className="truncate text-ui-12 font-medium leading-ui-18 tracking-[-0.005em] text-foreground">
                {row.repo}
              </p>
              <AccessGlyphs
                gated={row.result.gated}
                isPrivate={row.result.private}
                tooltip={false}
              />
              {row.result.isGguf && (
                <span
                  role="img"
                  aria-label="GGUF"
                  className="inline-block size-[calc(5px*var(--ui-space-scale,1))] shrink-0 rounded-full bg-format-gguf"
                />
              )}
              {unsupported && (
                <StatusDot tone="danger" label="May not be supported yet" />
              )}
              {row.isAvailableOnDevice && row.isPartialOnDevice && (
                <PartialStatusDot downloading={downloading} />
              )}
              {row.isAvailableOnDevice && !row.isPartialOnDevice && (
                <StatusDot tone="success" label="On device" />
              )}
            </div>
            <div className="flex shrink-0 items-center gap-2.5">
              <StatChip
                icon={FavouriteIcon}
                value={formatCompact(row.result.likes)}
              />
              <StatChip
                icon={Download01Icon}
                value={formatCompact(row.result.downloads)}
              />
            </div>
          </div>
          <div className="flex h-[calc(16px*var(--ui-space-scale,1))] min-w-0 items-center justify-between gap-2 text-ui-11p5 leading-ui-16 text-muted-foreground/85">
            <span className="flex min-w-0 items-center gap-1">
              <span className="truncate">{row.owner}</span>
              {row.owner.toLowerCase() === "unsloth" && (
                <span
                  aria-label="Verified Unsloth"
                  className="hub-verified-badge size-3.5 shrink-0 text-verified"
                />
              )}
            </span>
            <span className="shrink-0 text-ui-10p5 tabular-nums">
              {formatRelativeShort(row.result.updatedAt)}
            </span>
          </div>
        </div>
      </div>
    </CatalogRow>
  );
});

export const InventoryRow = memo(function InventoryRow({
  row,
  selected,
  isDataset,
  dimmed,
  deviceType,
  compact = false,
  showFormatDot = true,
  onSelect,
  onChange,
}: {
  row: CachedInventoryRow | LocalInventoryRow;
  selected: boolean;
  isDataset: boolean;
  dimmed: boolean;
  deviceType: string | null;
  compact?: boolean;
  showFormatDot?: boolean;
  onSelect: (id: string) => void;
  onChange?: () => void;
}) {
  const rowModelId =
    row.kind === "cache"
      ? row.repoId
      : (row.repoId ?? row.baseModelHubId ?? row.baseModel ?? row.loadId);
  const rowTagsSignature = row.tags?.join("\u0001") ?? "";
  const vllmAvailable = useVllmAvailable();
  const vllmPlatform = useVllmPlatform();
  const unsupported = useMemo(() => {
    if (isDataset) return false;
    const classified = classifyUnslothSupport({
      modelId: rowModelId,
      pipelineTag: row.pipelineTag,
      tags: rowTagsSignature ? rowTagsSignature.split("\u0001") : undefined,
      libraryName: row.libraryName,
      quantMethod: row.quantMethod,
      deviceType,
      vllmAvailable,
      vllmPlatform,
    });
    return classified.status === "unsupported" && !classified.supportedIn;
  }, [
    isDataset,
    rowModelId,
    row.pipelineTag,
    rowTagsSignature,
    row.libraryName,
    row.quantMethod,
    deviceType,
    vllmAvailable,
    vllmPlatform,
  ]);
  const handleClick = useCallback(() => onSelect(row.id), [onSelect, row.id]);
  const title = row.kind === "cache" ? row.repo : row.title;

  const subLabel = row.owner;
  const trailing =
    row.kind === "local" && row.updatedAt
      ? formatLocalUpdated(row.updatedAt)
      : null;
  const cacheDeletableRepoId =
    row.kind === "cache"
      ? row.repoId
      : row.source === "hf_cache" && row.repoId
        ? row.repoId
        : null;
  const canDelete = cacheDeletableRepoId !== null;
  const localActionPath =
    !isDataset &&
    row.kind === "local" &&
    row.source !== "hf_cache" &&
    row.path
      ? row.path
      : null;
  const partialRepoId =
    row.partial && !row.companionPrefetch
      ? row.kind === "cache"
        ? row.repoId
        : (row.repoId ?? row.loadId)
      : undefined;
  const downloading = Boolean(partialRepoId && row.downloading);
  const tooltip = buildRowStatusTooltip({
    isGguf: showFormatDot && row.isGguf,
    isAdapter: showFormatDot && row.modelFormat === "adapter",
    isAvailableOnDevice: !row.partial,
    isSharedAsset: row.companionPrefetch,
    partialRepoId,
    downloading,
    unsupported,
    resourceLabel: isDataset ? "dataset" : "model",
  });
  const formatLabel =
    row.modelFormat === "gguf"
      ? "GGUF"
      : row.modelFormat === "adapter"
        ? "Adapter"
        : row.modelFormat === "safetensors" || row.modelFormat === "checkpoint"
          ? "Safetensors"
          : null;
  const paramLabel = useMemo(() => paramLabelFromId(title), [title]);
  const quantLabel = row.formatVariant?.trim() || null;

  const metaChips =
    !isDataset && (formatLabel || paramLabel || quantLabel) ? (
      <div className="hidden shrink-0 items-center gap-1.5 sm:flex">
        {formatLabel && <span className="hub-chip">{formatLabel}</span>}
        {paramLabel && (
          <span className="hub-chip tabular-nums">{paramLabel}</span>
        )}
        {quantLabel && (
          <span className="hub-chip font-mono text-ui-10p5 uppercase">
            {quantLabel}
          </span>
        )}
      </div>
    ) : null;

  const sourceLabel = row.kind === "local" ? row.sourceLabel : null;

  const statusMarkers = (
    <>
      {showFormatDot && row.isGguf && (
        <span
          role="img"
          aria-label="GGUF"
          className="inline-block size-[calc(5px*var(--ui-space-scale,1))] shrink-0 rounded-full bg-format-gguf"
        />
      )}
      {showFormatDot && row.modelFormat === "adapter" && (
        <span
          role="img"
          aria-label="Adapter"
          className="inline-block size-[calc(5px*var(--ui-space-scale,1))] shrink-0 rounded-full bg-format-adapter"
        />
      )}
      {partialRepoId ? (
        <PartialStatusDot downloading={downloading} />
      ) : row.companionPrefetch ? (
        <StatusDot tone="asset" label="Shared assets" />
      ) : (
        <StatusDot tone="success" label="On device" />
      )}
      {unsupported && (
        <StatusDot tone="danger" label="May not be supported yet" />
      )}
    </>
  );

  const compactMarkers =
    partialRepoId || row.companionPrefetch || unsupported ? (
      <span className="flex shrink-0 items-center gap-1">
        {partialRepoId ? (
          <PartialStatusDot downloading={downloading} />
        ) : row.companionPrefetch ? (
          <StatusDot tone="asset" label="Shared assets" />
        ) : null}
        {unsupported && (
          <StatusDot tone="danger" label="May not be supported yet" />
        )}
      </span>
    ) : null;

  const ownerLine = (
    <span className="mt-0.5 flex min-w-0 items-center gap-1 text-ui-11p5 leading-ui-15 text-muted-foreground/80">
      <span className="truncate">{subLabel}</span>
      {subLabel.toLowerCase() === "unsloth" && (
        <span
          aria-label="Verified Unsloth"
          className="hub-verified-badge size-3.5 shrink-0 text-verified"
        />
      )}
    </span>
  );

  const pinnedKeys = usePinnedModelsStore((s) => s.pinned);
  const togglePinned = usePinnedModelsStore((s) => s.togglePinned);
  const rowPinned =
    cacheDeletableRepoId != null &&
    pinnedKeys.includes(pinKey(cacheDeletableRepoId));
  const deletableRepoId = canDelete ? cacheDeletableRepoId : null;
  const deleteAction =
    deletableRepoId ? (
      <ModelRowMenu
        ariaLabel={`More options for ${deletableRepoId ?? rowModelId}`}
        buttonClassName="pointer-events-auto hub-modal-pe-guard size-6 rounded-full opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 [@media(pointer:coarse)]:opacity-100"
        pin={
          isDataset || !deletableRepoId
            ? undefined
            : {
                pinned: rowPinned,
                pinLabel: "Pin",
                unpinLabel: "Unpin",
                onToggle: () => togglePinned(deletableRepoId),
              }
        }
        cachePath={
          isDataset || !deletableRepoId ? undefined : { repoId: deletableRepoId }
        }
        del={deletableRepoId ? {
          title: isDataset ? "Delete cached dataset?" : "Delete cached model?",
          // Datasets have no companion base repo, so only models get a preview.
          impact: isDataset ? undefined : { repoId: deletableRepoId },
          description: (
            <>
              This will remove{" "}
              <span className="font-medium text-foreground">
                {deletableRepoId}
              </span>{" "}
              {isDataset
                ? "and its downloaded files"
                : row.isGguf
                  ? "and all of its downloaded quantizations"
                  : "and all of its downloaded files"}
              {row.kind === "cache" ? ` (${formatBytes(row.bytes)})` : ""} from
              disk. You can re-download it later.
            </>
          ),
          successMessage: `Deleted ${deletableRepoId}`,
          onConfirm: async () => {
            // Pass the owning cache path so only this row's copy is deleted.
            const rowCachePath =
              row.kind === "cache" ? (row.cachePath ?? undefined) : undefined;
            if (isDataset) {
              await deleteCachedDataset(deletableRepoId, rowCachePath);
            } else {
              await deleteCachedModel(
                deletableRepoId,
                undefined,
                undefined,
                rowCachePath,
              );
              if (row.isGguf && isChatGgufTask(row.pipelineTag)) {
                await reconcileGgufPinsAfterDelete(
                  deletableRepoId,
                  useHfTokenStore.getState().token || undefined,
                );
              } else {
                usePinnedModelsStore.getState().unpinRepo(deletableRepoId);
              }
            }
          },
          onDeleted: onChange,
        } : undefined}
      />
    ) : localActionPath && row.kind === "local" ? (
      <ModelRowMenu
        ariaLabel={`More options for ${rowModelId}`}
        buttonClassName="pointer-events-auto hub-modal-pe-guard size-6 rounded-full opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 [@media(pointer:coarse)]:opacity-100"
        onReveal={() => revealLocalModel(localActionPath, row.loadId)}
        del={
          DELETABLE_LOCAL_SOURCES.has(row.source)
            ? {
                title: "Delete local model?",
                description: (
                  <>
                    This will permanently remove{" "}
                    <span className="font-medium text-foreground">{title}</span>{" "}
                    from{" "}
                    <span className="break-all font-mono text-xs">
                      {localActionPath}
                    </span>
                    .
                  </>
                ),
                successMessage: `Deleted ${title}`,
                onConfirm: () => deleteLocalModel(localActionPath, row.loadId),
                onDeleted: onChange,
              }
            : undefined
        }
      />
    ) : null;

  if (compact) {
    return (
      <CatalogRow
        variant="flat"
        selected={selected}
        tooltip={tooltip}
        label={title}
        onClick={handleClick}
      >
        <div
          className={cn(
            "flex w-full items-center gap-2.5 transition-opacity",
            dimmed && "opacity-25 group-hover/row:opacity-60",
          )}
        >
          <OwnerAvatar
            owner={row.owner}
            repoName={title}
            className="size-8 shrink-0 rounded-sm text-ui-12"
            remote={false}
          />
          <div className="min-w-0 flex-1">
            <div className="flex min-w-0 items-center gap-1.5">
              <span className="truncate text-ui-12p5 font-semibold leading-ui-16 text-foreground">
                {title}
              </span>
              {compactMarkers}
            </div>
            <span className="mt-0.5 flex min-w-0 items-center gap-1.5 text-ui-10p5 leading-ui-14 text-muted-foreground/75">
              <span className="flex min-w-0 items-center gap-1">
                <span className="truncate">{subLabel}</span>
                {subLabel.toLowerCase() === "unsloth" && (
                  <span
                    aria-label="Verified Unsloth"
                    className="hub-verified-badge size-3 shrink-0 text-verified"
                  />
                )}
              </span>
              {formatLabel && (
                <>
                  <MetaDivider />
                  <span className="shrink-0">{formatLabel}</span>
                </>
              )}
              {paramLabel && (
                <>
                  <MetaDivider />
                  <span className="shrink-0 tabular-nums">{paramLabel}</span>
                </>
              )}
            </span>
          </div>
          <div className="flex shrink-0 items-center gap-2 text-ui-10p5 tabular-nums text-muted-foreground/70">
            {row.kind === "cache" ? (
              <CachedSizeChip
                repoId={row.repoId}
                totalBytes={row.bytes}
                isGguf={row.isGguf}
                isDataset={isDataset}
                cachePath={row.cachePath}
              />
            ) : trailing ? (
              <span>{trailing}</span>
            ) : null}
            {deleteAction}
          </div>
        </div>
      </CatalogRow>
    );
  }

  return (
    <CatalogRow
      variant="card"
      selected={selected}
      tooltip={tooltip}
      label={title}
      onClick={handleClick}
    >
      <div
        className={cn(
          "flex w-full items-center gap-3 transition-opacity",
          dimmed && "opacity-25 group-hover/row:opacity-60",
        )}
      >
        <div className="flex min-w-0 flex-1 items-center gap-3">
          <OwnerAvatar
            owner={row.owner}
            repoName={title}
            className="size-9 rounded-md"
            remote={false}
          />
          <div className="min-w-0 flex-1">
            <div className="flex min-w-0 items-center gap-1.5">
              <span className="truncate text-ui-13p5 font-semibold leading-ui-17 text-foreground">
                {title}
              </span>
              {statusMarkers}
            </div>
            {ownerLine}
          </div>
        </div>

        {metaChips}

        <div className="flex w-[calc(96px*var(--ui-space-scale,1))] shrink-0 items-center justify-end text-right">
          {row.kind === "cache" ? (
            <CachedSizeChip
              repoId={row.repoId}
              totalBytes={row.bytes}
              isGguf={row.isGguf}
              isDataset={isDataset}
              cachePath={row.cachePath}
            />
          ) : trailing ? (
            <span className="truncate text-ui-11p5 tabular-nums text-muted-foreground/70">
              {trailing}
            </span>
          ) : sourceLabel ? (
            <span className="truncate text-ui-11p5 text-muted-foreground/55">
              {sourceLabel}
            </span>
          ) : null}
        </div>

        <div className="flex w-9 shrink-0 items-center justify-end">
          {deleteAction}
        </div>
      </div>
    </CatalogRow>
  );
});

export const CATALOG_ROW_HEIGHT_PX = 57;
export const CATALOG_COLUMN_GAP_PX = 12;

export function VirtualRows<T>({
  items,
  scrollElement,
  getKey,
  renderRow,
  scrollMargin = 0,
  columns = 1,
  rowHeight = CATALOG_ROW_HEIGHT_PX,
  cellHeight = rowHeight,
  columnGap = CATALOG_COLUMN_GAP_PX,
}: {
  items: readonly T[];
  scrollElement: HTMLDivElement | null;
  getKey: (item: T, index: number) => string;
  renderRow: (item: T) => ReactNode;
  scrollMargin?: number;
  columns?: number;
  rowHeight?: number;
  cellHeight?: number;
  columnGap?: number;
}) {
  const lanes = Math.max(1, columns);
  const rowCount = Math.ceil(items.length / lanes);
  // Slots scale with the UI font size or tall rows overlap the next absolutely positioned one.
  const scale = useUiSpaceScale();
  const slotHeight = Math.round(rowHeight * scale);
  const slotCellHeight = Math.round(cellHeight * scale);
  const laneGap = Math.round(columnGap * scale);
  // eslint-disable-next-line react-hooks/incompatible-library
  const virtualizer = useVirtualizer({
    count: rowCount,
    getScrollElement: () => scrollElement,
    estimateSize: () => slotHeight,
    overscan: 10,
    scrollMargin,
    getItemKey: (rowIndex) => {
      const item = items[rowIndex * lanes];
      return item ? getKey(item, rowIndex * lanes) : `row-${rowIndex}`;
    },
  });

  // Sizes are cached from estimateSize, so a new scale has to invalidate them.
  useEffect(() => {
    virtualizer.measure();
  }, [virtualizer, slotHeight]);

  return (
    <ul
      style={{
        height: virtualizer.getTotalSize(),
        position: "relative",
        width: "100%",
        overflowAnchor: "none",
      }}
    >
      {virtualizer.getVirtualItems().map((virtualRow) => {
        const startIndex = virtualRow.index * lanes;
        return (
          <li
            key={virtualRow.key}
            data-index={virtualRow.index}
            style={{
              position: "absolute",
              top: 0,
              left: 0,
              width: "100%",
              transform: `translateY(${virtualRow.start - scrollMargin}px)`,
              // Fixed height, no measureElement: per-row measurement causes visible jumps.
              height: `${slotHeight}px`,
              contain: "layout",
            }}
          >
            <div
              style={{
                display: "grid",
                gridTemplateColumns: `repeat(${lanes}, minmax(0, 1fr))`,
                columnGap: `${laneGap}px`,
                height: `${slotCellHeight}px`,
              }}
            >
              {Array.from({ length: lanes }, (_, lane) => {
                const item = items[startIndex + lane];
                if (item === undefined) {
                  return <div key={`empty-${lane}`} />;
                }
                return (
                  <div
                    key={getKey(item, startIndex + lane)}
                    className="min-w-0"
                  >
                    {renderRow(item)}
                  </div>
                );
              })}
            </div>
          </li>
        );
      })}
    </ul>
  );
}