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.

53.3 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 {
  MONITOR_DETAIL_METRICS,
  formatPower,
  formatTemperature,
  gpuTelemetryRows,
  selectedDetailMetrics,
} from "@/components/monitor-details";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Progress } from "@/components/ui/progress";
import { Switch } from "@/components/ui/switch";
import { formatBytes } from "@/features/hub";
import { FolderBrowser } from "@/features/model-picker";
import {
  openModelsDir,
  pickHuggingFaceCacheDir,
} from "@/features/native-intents";
import {
  gpuMemoryDisplay,
  hasSharedMemoryHeadroom,
  sharedMemoryAvailableGb,
} from "@/hooks/gpu-memory-display";
import {
  deviceSharedMemorySplitGb,
  gpuMemoryTotalsGb,
  gpuVramUsedIsPerDevice,
  resolveGpuVramUsedGb,
} from "@/hooks/gpu-vram";
import {
  aggregateGpuMemoryTotalGb,
  useSystemInfo,
  type GpuDevice,
  type SystemInfoResponse,
  type SystemGpuInfo,
} from "@/hooks/use-system";
import { isTauri } from "@/lib/api-base";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { openLink } from "@/lib/open-link";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import {
  type HuggingFaceCacheSettings,
  loadHuggingFaceCacheSettings,
  updateHuggingFaceCacheSettings,
} from "../api/hugging-face-cache";
import { InferenceEnginesSection } from "@/features/model-picker/components/inference-engines";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import { useIsAccountOwner } from "@/features/auth";
import {
  CacheStorageRows,
  useCacheStorage,
} from "../components/cache-storage-rows";
import { DeveloperModeSection } from "../components/developer-mode-section";
import { EngineVersionsSection } from "../components/engine-versions-section";
import { LlamaBackendSection } from "../components/llama-backend-section";
import { ModelMemorySection } from "../components/model-memory-section";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
import {
  STORAGE_COLORS,
  SettingsCard,
  SettingsCardRow,
  StorageBar,
  type StorageSegment,
  StorageOverview,
} from "../components/storage-overview";
import {
  MONITOR_REFRESH_OPTIONS_MS,
  monitorRefreshMs,
} from "@/components/monitor-refresh";
import { useMonitorOverlayStore } from "../stores/monitor-overlay-store";
import { MemoryShareBar } from "@/components/monitor-memory";
import { inferenceGpuDisjoint, poolSplit } from "@/components/monitor-share";
import { useLoadedModels } from "@/features/loaded-models/use-loaded-models";
import { holdsModelsInVram, vramCards } from "@/components/monitor-cards";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";
import { ArrowUpRight01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";

const POLL_MS = 3000;

function isFiniteNumber(value: number | null | undefined): value is number {
  return typeof value === "number" && Number.isFinite(value);
}

function clampPercent(value: number | null | undefined): number {
  if (!isFiniteNumber(value)) return 0;
  return Math.max(0, Math.min(100, value));
}

function usageIndicatorClass(percent: number): string {
  if (percent >= 90) return "bg-[#df4530] dark:bg-[#ef5b40]";
  if (percent >= 70) return "bg-amber-500";
  return "bg-control-accent";
}

function usagePillClass(percent: number | null): string {
  if (isFiniteNumber(percent) && percent >= 90) {
    return "bg-[#df4530]/10 text-[#df4530] dark:text-[#ef5b40]";
  }
  if (isFiniteNumber(percent) && percent >= 70) {
    return "bg-amber-500/10 text-amber-600 dark:text-amber-400";
  }
  return "bg-control-accent/10 text-control-accent";
}

function formatGb(value: number | null | undefined): string {
  const safe = isFiniteNumber(value) ? Math.max(0, value) : 0;
  const digits = safe >= 10 ? 1 : 2;
  return `${safe.toFixed(digits)} GB`;
}

// RAM/VRAM are binary (GiB, like nvidia-smi); disk is decimal GB.
function formatGiB(value: number | null | undefined): string {
  const safe = isFiniteNumber(value) ? Math.max(0, value) : 0;
  const digits = safe >= 10 ? 1 : 2;
  // digits is never 0, so trimming cannot eat integer digits.
  const text = safe.toFixed(digits).replace(/\.?0+$/, "");
  return `${text} GiB`;
}

function formatMb(value: number | null | undefined): string {
  const safe = isFiniteNumber(value) ? Math.max(0, value) : 0;
  return `${Math.round(safe).toLocaleString()} MB`;
}

function formatPercent(value: number | null | undefined): string {
  return `${Math.round(clampPercent(value))}%`;
}

function formatFrequency(mhz: number | null | undefined): string | null {
  if (!isFiniteNumber(mhz) || mhz <= 0) return null;
  if (mhz >= 1000) return `${(mhz / 1000).toFixed(2)} GHz`;
  return `${Math.round(mhz)} MHz`;
}

function formatUptime(seconds: number | null | undefined): string {
  if (!isFiniteNumber(seconds) || seconds <= 0) return "0m";
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  if (days > 0) return `${days}d ${hours % 24}h`;
  if (hours > 0) return `${hours}h ${minutes % 60}m`;
  return `${Math.max(1, minutes)}m`;
}

function MetricTile({
  label,
  value,
  detail,
  percent,
  showUsage = true,
  extraDetail,
  children,
}: {
  label: string;
  value: string;
  detail?: string;
  // null = unknown (e.g. Windows ROCm perf counter); show a dash, not 0%.
  percent: number | null;
  showUsage?: boolean;
  extraDetail?: string;
  children?: ReactNode;
}) {
  const percentKnown = isFiniteNumber(percent);
  const safePercent = clampPercent(percent);
  return (
    <div className="flex min-w-0 flex-col gap-3 rounded-xl border border-border/60 bg-card px-6 pt-5 pb-6 dark:border-transparent">
      <div className="flex min-w-0 flex-col gap-0.5">
        <div className="flex min-w-0 items-center justify-between gap-3">
          <span className="text-ui-12 text-muted-foreground">{label}</span>
          {showUsage && percentKnown ? (
            <span
              className={cn(
                "-my-1 shrink-0 rounded-full px-2 py-1 font-mono text-ui-12 leading-none tabular-nums",
                usagePillClass(safePercent),
              )}
            >
              {formatPercent(safePercent)}
            </span>
          ) : null}
        </div>
        <span
          title={value}
          className={cn(
            "truncate font-mono text-ui-14 font-medium leading-tight tabular-nums",
            showUsage && !percentKnown
              ? "text-muted-foreground/70"
              : "text-foreground",
          )}
        >
          {value}
        </span>
        {detail ? (
          <span
            title={detail}
            className="truncate text-ui-11 text-muted-foreground"
          >
            {detail}
          </span>
        ) : null}
        {extraDetail ? (
          <span className="whitespace-pre-line text-ui-11 text-muted-foreground">
            {extraDetail}
          </span>
        ) : null}
      </div>
      {showUsage && (
        <Progress
          value={percentKnown ? safePercent : 0}
          aria-label={label}
          className="mt-auto h-1.5 rounded-full bg-muted dark:bg-[rgb(0_0_0_/_calc(0.4*var(--contrast-wash-gain,1)))]"
          indicatorClassName={usageIndicatorClass(safePercent)}
        />
      )}
      {children ? <div className="mt-auto">{children}</div> : null}
    </div>
  );
}

function InfoRow({
  label,
  value,
  detail,
}: {
  label: string;
  value: string;
  detail?: string;
}) {
  return (
    <div className="flex min-w-0 items-center justify-between gap-4 py-2.5">
      <span className="min-w-0 truncate text-sm font-medium text-foreground">
        {label}
      </span>
      <span
        title={detail ?? value}
        className="min-w-0 max-w-[60%] truncate text-right font-mono text-xs tabular-nums text-muted-foreground"
      >
        {detail ? `${value} (${detail})` : value}
      </span>
    </div>
  );
}

function deviceOrdinal(device: GpuDevice): number | undefined {
  return device.visible_ordinal ?? device.index;
}

/** OS-enumerated GPU this PyTorch cannot open; `index` is vendor-local, NOT a pin. Kept off
 * SystemGpuInfo so fit budgets and the device picker never see an unusable card. */
interface PhysicalGpuDevice {
  vendor?: string;
  index?: number;
  name?: string | null;
  memory_total_gb?: number | null;
  source?: string;
}

/** Present only when GPUs are unusable. `reason`: "torch_cpu_build" | "torch_cuda_unavailable". */
interface GpuTorchMismatch {
  reason?: string;
  torch_version?: string | null;
  physical_count?: number;
  /** An AMD device node this account cannot open, and the command that opens it. */
  permission_hint?: string | null;
  /** The closed node fully explains a ROCm wheel, so the reinstall advice is wrong. */
  permission_hint_only?: boolean;
}

/** /api/system's `gpu.driver_warning`: a Windows AMD driver with the idle-eviction bug
 * (ROCm/TheRock#7221). "critical" when the host has more than one GPU. */
interface GpuDriverWarning {
  driver_version?: string;
  severity?: "warning" | "critical";
  link?: string;
}

type GpuPhysicalInventory = SystemGpuInfo & {
  physical_devices?: PhysicalGpuDevice[];
  mismatch?: GpuTorchMismatch | null;
  driver_warning?: GpuDriverWarning | null;
};

export function ResourcesTab() {
  const t = useT();
  const isOwner = useIsAccountOwner();
  const liveUpdates = useSettingsPanelPrefsStore((s) => s.resourcesLiveUpdates);
  const setLiveUpdates = useSettingsPanelPrefsStore(
    (s) => s.setResourcesLiveUpdates,
  );
  const dismissedDriverWarning = useSettingsPanelPrefsStore(
    (s) => s.dismissedDriverWarning,
  );
  const dismissDriverWarning = useSettingsPanelPrefsStore(
    (s) => s.dismissDriverWarning,
  );
  const {
    isOpen,
    setIsOpen,
    showDetails,
    setShowDetails,
    detailMetrics: storedDetailMetrics,
    setDetailMetric,
    refreshMs,
    setRefreshMs,
    showUnslothShare,
    setShowUnslothShare,
    showModelBreakdown,
    setShowModelBreakdown,
  } = useMonitorOverlayStore();
  const wantsModels = showUnslothShare || showModelBreakdown;
  const { polledEntries: loadedModels } = useLoadedModels(
    wantsModels,
    wantsModels,
  );
  const detailMetrics = selectedDetailMetrics(storedDetailMetrics);
  // always fetch once: the switch is persisted now, so gating the hook on it
  // would leave a session that opens with it off reading zeros forever.
  const systemInfo = useSystemInfo({
    pollMs: liveUpdates ? POLL_MS : undefined,
  });
  const storageSectionRef = useRef<HTMLElement | null>(null);
  const modelMemoryRef = useRef<HTMLElement | null>(null);
  const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
  const consumeScrollTarget = useSettingsDialogStore(
    (s) => s.consumeScrollTarget,
  );
  const openDialog = useSettingsDialogStore((s) => s.openDialog);
  const [hfCache, setHfCache] = useState<HuggingFaceCacheSettings | null>(null);
  const [hfCacheLoaded, setHfCacheLoaded] = useState(false);
  const [cacheBrowserOpen, setCacheBrowserOpen] = useState(false);
  const [cacheSaving, setCacheSaving] = useState(false);
  const cache = useCacheStorage();
  const displayedGpu = systemInfo.gpu?.available
    ? systemInfo.gpu
    : (systemInfo.inference_gpu ?? systemInfo.gpu);
  const separateInferenceGpu =
    systemInfo.gpu?.available &&
    systemInfo.inference_gpu &&
    systemInfo.inference_gpu.backend !== systemInfo.gpu.backend
      ? systemInfo.inference_gpu
      : null;
  const memoryDisplay = gpuMemoryDisplay(displayedGpu);
  const inferenceDisplay = gpuMemoryDisplay(separateInferenceGpu);
  const inferenceVramTotal = separateInferenceGpu
    ? aggregateGpuMemoryTotalGb(inferenceDisplay.usageDevices)
    : 0;
  const telemetryByOrdinal = new Map(
    displayedGpu?.available
      ? gpuTelemetryRows(
          displayedGpu.devices,
          new Set(MONITOR_DETAIL_METRICS),
        ).map((row) => [row.key, row])
      : [],
  );

  useEffect(() => {
    let cancelled = false;
    void loadHuggingFaceCacheSettings()
      .then((settings) => {
        if (cancelled) return;
        setHfCache(settings);
        setHfCacheLoaded(true);
      })
      .catch(() => {
        if (cancelled) return;
        setHfCacheLoaded(true);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    const target = scrollTarget;
    const sectionRef =
      target === "resources-caches"
        ? storageSectionRef
        : target === "resources-model-memory"
          ? modelMemoryRef
          : null;
    if (!target || !sectionRef) return;
    const frame = window.requestAnimationFrame(() => {
      sectionRef.current?.scrollIntoView({
        block: "start",
        behavior: "smooth",
      });
      consumeScrollTarget(target);
    });
    return () => window.cancelAnimationFrame(frame);
  }, [consumeScrollTarget, scrollTarget]);

  const metrics = useMemo(() => {
    const devices = displayedGpu?.devices ?? [];
    const ramTotal = systemInfo.memory?.total_gb ?? 0;
    const ramAvailable = systemInfo.memory?.available_gb ?? 0;
    const ramUsed = Math.max(0, ramTotal - ramAvailable);
    const diskTotal = systemInfo.disk?.total_gb ?? 0;
    const diskFree = systemInfo.disk?.free_gb ?? 0;
    const diskUsed = Math.max(0, diskTotal - diskFree);
    const diskPercent = diskTotal > 0 ? (diskUsed / diskTotal) * 100 : 0;
    const modelsDisk = systemInfo.models_disk ?? null;
    const modelsDiskUsed = modelsDisk
      ? Math.max(0, modelsDisk.total_gb - modelsDisk.free_gb)
      : 0;
    const modelsDiskPercent =
      modelsDisk && modelsDisk.total_gb > 0
        ? (modelsDiskUsed / modelsDisk.total_gb) * 100
        : 0;
    const display = gpuMemoryDisplay(displayedGpu);
    const usageDevices = display.usageDevices;
    const gpuMemoryTotals = gpuMemoryTotalsGb(usageDevices);
    const vramTotal = gpuMemoryTotals.total;
    // null usage is unknown; 0 would fabricate a total. The host figure can still be known.
    const perDeviceKnown = gpuVramUsedIsPerDevice(usageDevices);
    const vramUsed = resolveGpuVramUsedGb(display.usageGpu);
    const vramUsageKnown = vramUsed !== null;
    const vramFree = perDeviceKnown
      ? usageDevices.reduce(
          (sum, device) =>
            sum +
            (device.vram_free_gb ??
              Math.max(
                0,
                (device.memory_total_gb ?? 0) - (device.vram_used_gb ?? 0),
              )),
          0,
        )
      : vramUsed !== null
        ? Math.max(0, vramTotal - vramUsed)
        : null;
    const vramPercent =
      vramUsageKnown && isFiniteNumber(vramUsed) && vramTotal > 0
        ? (vramUsed / vramTotal) * 100
        : 0;

    return {
      devices,
      ramTotal,
      ramUsed,
      diskTotal,
      diskFree,
      diskUsed,
      diskPercent,
      modelsDisk,
      modelsDiskUsed,
      modelsDiskPercent,
      vramTotal,
      vramDedicated: gpuMemoryTotals.dedicated,
      vramShared: gpuMemoryTotals.shared,
      vramUsed,
      vramFree,
      vramPercent,
      vramUsageKnown,
    };
  }, [displayedGpu, systemInfo]);

  const handleCacheFolder = async () => {
    if (!hfCache) return;
    if (isTauri) {
      try {
        await openModelsDir(hfCache.cacheHome);
      } catch (error) {
        toast.error(t("settings.resources.storage.openError"), {
          description: error instanceof Error ? error.message : undefined,
        });
      }
      return;
    }
    if (await copyToClipboard(hfCache.cacheHome)) {
      toast.success(t("settings.resources.storage.copied"));
    } else {
      toast.error(t("settings.resources.storage.copyError"));
    }
  };

  const saveCacheFolder = async (path: string | null) => {
    setCacheSaving(true);
    try {
      const settings = await updateHuggingFaceCacheSettings(path);
      setHfCache(settings);
      toast.success(t("settings.resources.storage.cacheSaved"));
    } catch (error) {
      toast.error(t("settings.resources.storage.cacheSaveError"), {
        description: error instanceof Error ? error.message : undefined,
      });
    } finally {
      setCacheSaving(false);
    }
  };

  const changeCacheFolder = async () => {
    if (!isTauri) {
      setCacheBrowserOpen(true);
      return;
    }
    try {
      const path = await pickHuggingFaceCacheDir();
      if (path) await saveCacheFolder(path);
    } catch (error) {
      toast.error(t("settings.resources.storage.cachePickerError"), {
        description: error instanceof Error ? error.message : undefined,
      });
    }
  };

  const cpuCoresLabel =
    systemInfo.cpu?.logical_count && systemInfo.cpu?.physical_count
      ? t("settings.resources.liveMonitor.cpuCores", {
          logical: systemInfo.cpu.logical_count,
          physical: systemInfo.cpu.physical_count,
        })
      : t("settings.resources.environment.unknown");
  const cpuFrequencyLabel = formatFrequency(systemInfo.cpu?.frequency_mhz);
  const hasGpu =
    (displayedGpu?.available ?? false) && metrics.devices.length > 0;
  // The placeholder reads as CPU-only, so say checking or empty until the host is read.
  const hostUnread = systemInfo.status !== "ready";
  const gpuUnknown = hostUnread && !hasGpu;
  const gpuUnknownLabel =
    systemInfo.status === "unavailable"
      ? t("settings.resources.gpu.unreadable")
      : t("settings.resources.gpu.detecting");
  const hostUnreadDetail =
    systemInfo.status === "unavailable"
      ? t("settings.resources.gpu.unreadable")
      : t("common.loading");
  const backendLabel = (
    displayedGpu?.backend ??
    systemInfo.device_backend ??
    "cpu"
  ).toUpperCase();
  const modelsFolderPath = hfCache
    ? hfCache.cacheHome
    : hfCacheLoaded
      ? t("settings.resources.environment.unknown")
      : t("common.loading");
  const cacheLocationDetail = hfCache
    ? hfCache.source === "environment"
      ? t("settings.resources.storage.environmentManaged", {
          variable: hfCache.environmentVariable ?? "HF_HOME",
        })
      : [
          t("settings.resources.storage.futureDownloads"),
          hfCache.freeBytes !== null
            ? t("settings.resources.storage.locationFree", {
                free: formatBytes(hfCache.freeBytes),
              })
            : null,
        ]
          .filter(Boolean)
          .join(" · ")
    : null;
  const unknownLabel = t("settings.resources.environment.unknown");
  // Disk readings are decimal GB, as are cache sizes once divided by 1e9.
  // A models folder on another drive takes the Hugging Face caches under it (hub, Xet, ...) off the system disk.
  const modelsRoot = hfCache?.cacheHome.replace(/[\\/]+$/, "");
  const onSystemDisk = (paths: string[]) =>
    !(
      metrics.modelsDisk &&
      modelsRoot &&
      paths.some(
        (path) =>
          path === modelsRoot ||
          path.startsWith(`${modelsRoot}/`) ||
          path.startsWith(`${modelsRoot}\\`),
      )
    );
  const systemEntries = cache.entries.filter(
    (entry) =>
      !(metrics.modelsDisk && entry.key === "hf_hub") &&
      onSystemDisk(entry.paths),
  );
  const diskBytes = (entry: (typeof cache.entries)[number]) =>
    entry.systemDiskBytes ??
    (systemEntries.includes(entry) ? entry.sizeBytes : 0);
  const modelsDiskGb =
    cache.entries
      .filter((entry) => entry.key === "hf_hub")
      .reduce((sum, entry) => sum + diskBytes(entry), 0) / 1e9;
  const cachesDiskGb =
    cache.entries
      .filter((entry) => entry.key !== "hf_hub")
      .reduce((sum, entry) => sum + diskBytes(entry), 0) / 1e9;
  const otherDiskGb = Math.max(
    0,
    metrics.diskUsed - modelsDiskGb - cachesDiskGb,
  );
  const cacheValue = (diskGb: number) =>
    cache.inventory ? formatGb(diskGb) : t("common.loading");
  const storageSegments: StorageSegment[] = [
    ...(metrics.modelsDisk && modelsDiskGb === 0
      ? []
      : [
          {
            key: "models",
            label: t("settings.resources.storage.segmentModels"),
            bytes: modelsDiskGb,
            value: cacheValue(modelsDiskGb),
            color: STORAGE_COLORS.yellow,
          },
        ]),
    {
      key: "caches",
      label: t("settings.resources.storage.segmentCaches"),
      bytes: cachesDiskGb,
      value: cacheValue(cachesDiskGb),
      color: STORAGE_COLORS.purple,
    },
    {
      key: "other",
      label: t("settings.resources.storage.segmentOther"),
      bytes: otherDiskGb,
      value: formatGb(otherDiskGb),
      color: STORAGE_COLORS.other,
    },
    {
      key: "free",
      label: t("settings.resources.storage.segmentFree"),
      bytes: metrics.diskFree,
      value: formatGb(metrics.diskFree),
      color: STORAGE_COLORS.free,
    },
  ];
  const unifiedPool = metrics.vramShared > 0 && metrics.vramDedicated === 0;
  const vramCapacityLabel =
    metrics.vramShared > 0 && !unifiedPool
      ? t("settings.resources.environment.vramWithShared", {
          vram: formatGiB(metrics.vramDedicated),
          shared: formatGiB(metrics.vramShared),
        })
      : formatGiB(unifiedPool ? metrics.vramShared : metrics.vramTotal);
  const vram = vramCards(memoryDisplay.usageDevices, memoryDisplay.usageGpu);
  const discreteVram =
    hasGpu &&
    !unifiedPool &&
    !memoryDisplay.sharedOnly &&
    holdsModelsInVram(vram.cards);
  const processMb =
    systemInfo.memory?.process_tree_used_mb ?? systemInfo.memory?.process_used_mb;
  const split = poolSplit({
    entries: loadedModels,
    showShare: showUnslothShare,
    showBreakdown: showModelBreakdown,
    modelsInVram: discreteVram,
    inferenceGpuElsewhere: inferenceGpuDisjoint(
      systemInfo.gpu?.backend,
      separateInferenceGpu?.backend,
    ),
    processGb: !hostUnread && processMb !== undefined ? processMb / 1024 : null,
    ramUsedGb: metrics.ramUsed,
    ramTotalGb: metrics.ramTotal,
    vramUsedGb: vram.usedGb,
    vramTotalGb: vram.totalGb,
  });
  const ramSegments = split.ram;
  const vramSegments = split.vram;
  // The placeholder's cpu backend and empty package list are not facts about the host either.
  const hostReading = (value: string) => (hostUnread ? unknownLabel : value);
  // systemInfo.gpu, not displayedGpu: a Vulkan llama.cpp makes displayedGpu use the inference
  // inventory, hiding the training problem.
  const gpuInventory = hostUnread
    ? null
    : ((systemInfo.gpu ?? null) as GpuPhysicalInventory | null);
  const gpuMismatch = gpuInventory?.mismatch ?? null;
  const physicalDevices = gpuMismatch
    ? (gpuInventory?.physical_devices ?? [])
    : [];
  const rawDriverWarning = gpuInventory?.driver_warning ?? null;
  const driverWarning =
    rawDriverWarning?.driver_version &&
    rawDriverWarning.driver_version !== dismissedDriverWarning
      ? rawDriverWarning
      : null;
  // A CPU-only wheel is fixed by reinstalling torch, a dead runtime by the driver.
  const gpuPermissionHint = gpuMismatch?.permission_hint ?? null;
  const gpuMismatchMessage =
    gpuMismatch && !(gpuPermissionHint && gpuMismatch.permission_hint_only)
      ? t(
          gpuMismatch.reason === "torch_cpu_build"
            ? "settings.resources.gpu.mismatchCpuBuild"
            : "settings.resources.gpu.mismatchUnavailable",
          { version: gpuMismatch.torch_version ?? unknownLabel },
        )
      : null;

  return (
    <div className="settings-page">
      <header className="flex flex-wrap items-start justify-between gap-3 pe-10">
        <div className="flex min-w-0 flex-col gap-1">
          <h1 className="text-xl font-semibold font-heading">
            {t("settings.resources.title")}
          </h1>
          <p className="text-xs text-muted-foreground">
            {t("settings.resources.description")}
          </p>
        </div>
        {/* Top edge on the h1's cap top (text-xl at leading 1.4; Hellix: 0.322em). */}
        <div className="mt-[calc(var(--text-xl)*0.322)] flex min-w-0 flex-wrap items-center gap-2">
          <label className="flex h-9 shrink-0 items-center gap-2 rounded-full border border-border/60 px-3.5 text-xs font-medium text-foreground">
            <span>{t("settings.resources.liveUpdates")}</span>
            <Switch
              className="scale-[0.88]"
              aria-label={t("settings.resources.liveUpdates")}
              checked={liveUpdates}
              onCheckedChange={setLiveUpdates}
            />
          </label>
        </div>
      </header>

      <SettingsSection title={t("settings.resources.liveMonitor.title")}>
        <div className="grid gap-3 py-3 sm:grid-cols-2 sm:[&>:last-child:nth-child(odd)]:col-span-2">
          <MetricTile
            label={t("settings.resources.liveMonitor.cpu")}
            value={hostReading(cpuFrequencyLabel ?? cpuCoresLabel)}
            detail={
              hostUnread
                ? hostUnreadDetail
                : cpuFrequencyLabel
                  ? cpuCoresLabel
                  : t("settings.resources.liveMonitor.currentLoad")
            }
            percent={hostUnread ? null : (systemInfo.cpu?.usage_percent ?? 0)}
          />
          <MetricTile
            label={t("settings.resources.liveMonitor.ram")}
            value={hostReading(
              `${formatGiB(metrics.ramUsed)} / ${formatGiB(metrics.ramTotal)}`,
            )}
            detail={
              hostUnread
                ? hostUnreadDetail
                : t("settings.resources.liveMonitor.free", {
                    value: formatGiB(systemInfo.memory?.available_gb),
                  })
            }
            percent={hostUnread ? null : (systemInfo.memory?.percent_used ?? 0)}
          />
          <MetricTile
            label={t("settings.resources.liveMonitor.disk")}
            value={hostReading(
              `${formatGb(metrics.diskUsed)} / ${formatGb(metrics.diskTotal)}`,
            )}
            detail={
              hostUnread
                ? hostUnreadDetail
                : t("settings.resources.liveMonitor.free", {
                    value: formatGb(metrics.diskFree),
                  })
            }
            percent={hostUnread ? null : metrics.diskPercent}
          />
          {metrics.modelsDisk && (
            <MetricTile
              label={t("settings.resources.liveMonitor.modelsDisk")}
              value={hostReading(
                `${formatGb(metrics.modelsDiskUsed)} / ${formatGb(metrics.modelsDisk.total_gb)}`,
              )}
              detail={
                hostUnread
                  ? hostUnreadDetail
                  : t("settings.resources.liveMonitor.free", {
                      value: formatGb(metrics.modelsDisk.free_gb),
                    })
              }
              percent={hostUnread ? null : metrics.modelsDiskPercent}
            />
          )}
          <MetricTile
            label={t(
              memoryDisplay.sharedOnly || unifiedPool
                ? "settings.resources.gpu.memory"
                : "settings.resources.liveMonitor.vram",
            )}
            value={
              gpuUnknown
                ? unknownLabel
                : hasGpu
                  ? memoryDisplay.sharedOnly
                    ? t("settings.resources.gpu.estimatedAvailable", {
                        value:
                          memoryDisplay.sharedAvailableGb === null
                            ? unknownLabel
                            : formatGiB(memoryDisplay.sharedAvailableGb),
                      })
                    : metrics.vramUsageKnown
                      ? `${formatGiB(metrics.vramUsed)} / ${vramCapacityLabel}`
                      : `${unknownLabel} / ${vramCapacityLabel}`
                  : gpuMismatch
                    ? t("settings.resources.liveMonitor.gpuUnusable")
                    : t("settings.resources.liveMonitor.noGpu")
            }
            detail={
              gpuUnknown
                ? gpuUnknownLabel
                : hasGpu
                  ? memoryDisplay.sharedOnly
                    ? t("settings.resources.gpu.sharedWithSystemRam")
                    : unifiedPool && memoryDisplay.unifiedAvailableGb !== null
                      ? t("settings.resources.gpu.estimatedAvailable", {
                          value: formatGiB(memoryDisplay.unifiedAvailableGb),
                        })
                      : metrics.vramUsageKnown
                        ? t("settings.resources.liveMonitor.free", {
                            value: formatGiB(metrics.vramFree),
                          })
                        : unknownLabel
                  : gpuMismatch
                    ? t("settings.resources.liveMonitor.gpuUnusableDetail")
                    : backendLabel
            }
            showUsage={!memoryDisplay.sharedOnly}
            extraDetail={
              !memoryDisplay.sharedOnly &&
              memoryDisplay.sharedDevices.length > 0
                ? `${t("settings.resources.gpu.sharedWithSystemRam")}\n${t("settings.resources.gpu.estimatedAvailable", { value: memoryDisplay.sharedAvailableGb === null ? unknownLabel : formatGiB(memoryDisplay.sharedAvailableGb) })}`
                : unifiedPool && !memoryDisplay.sharedOnly
                  ? t("settings.resources.gpu.sharedWithSystemRam")
                  : undefined
            }
            percent={metrics.vramUsageKnown ? metrics.vramPercent : null}
          />
        </div>
        {(ramSegments || vramSegments) && (
          <div
            className="grid gap-3 pb-3 sm:grid-cols-2 sm:[&>:last-child:nth-child(odd)]:col-span-2"
            data-testid="settings-unsloth-share"
          >
            {ramSegments && (
              <MetricTile
                label={t(
                  unifiedPool
                    ? "settings.resources.liveMonitor.memory"
                    : "settings.resources.liveMonitor.ram",
                )}
                value={`${formatGiB(metrics.ramUsed)} / ${formatGiB(metrics.ramTotal)}`}
                percent={null}
                showUsage={false}
              >
                <MemoryShareBar
                  segments={ramSegments}
                  noModels={!discreteVram && split.noModels}
                />
              </MetricTile>
            )}
            {vramSegments && (
              <MetricTile
                label={t("settings.resources.liveMonitor.vram")}
                value={`${formatGiB(vram.usedGb)} / ${formatGiB(vram.totalGb)}`}
                percent={null}
                showUsage={false}
              >
                <MemoryShareBar
                  segments={vramSegments}
                  noModels={split.noModels}
                />
              </MetricTile>
            )}
          </div>
        )}
        <SettingsRow
          label={t("settings.resources.liveMonitor.unslothShare")}
          description={t("settings.resources.liveMonitor.unslothShareDescription")}
        >
          <Switch
            aria-label={t("settings.resources.liveMonitor.unslothShare")}
            checked={showUnslothShare}
            onCheckedChange={setShowUnslothShare}
          />
        </SettingsRow>
        <SettingsRow
          label={t("settings.resources.liveMonitor.modelBreakdown")}
          description={t("settings.resources.liveMonitor.modelBreakdownDescription")}
        >
          <Switch
            aria-label={t("settings.resources.liveMonitor.modelBreakdown")}
            checked={showModelBreakdown}
            onCheckedChange={setShowModelBreakdown}
          />
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title={t("settings.resources.gpu.title")}>
        {driverWarning?.driver_version ? (
          <div className="flex items-start justify-between gap-3 border-b border-border/60 py-3">
            <p
              className={cn(
                "text-sm",
                driverWarning.severity === "critical"
                  ? "text-destructive"
                  : "text-amber-600 dark:text-amber-400",
              )}
            >
              {t("settings.resources.gpu.driverIdleEvict", {
                version: driverWarning.driver_version,
              })}{" "}
              {driverWarning.link?.startsWith("https://") ? (
                <a
                  href={driverWarning.link}
                  target="_blank"
                  rel="noopener noreferrer"
                  // target="_blank" has nowhere to go in the Tauri webview.
                  onClick={(event) => {
                    if (openLink(event.currentTarget.href))
                      event.preventDefault();
                  }}
                  className="inline-flex items-center gap-0.5 font-medium underline underline-offset-2"
                >
                  {t("settings.resources.gpu.driverIdleEvictDetails")}
                  <HugeiconsIcon icon={ArrowUpRight01Icon} className="size-3" />
                </a>
              ) : null}
            </p>
            <Button
              variant="ghost"
              size="sm"
              className="h-7 shrink-0 px-2 text-xs"
              onClick={() =>
                dismissDriverWarning(driverWarning.driver_version as string)
              }
            >
              {t("settings.resources.gpu.dismissNotice")}
            </Button>
          </div>
        ) : null}
        {/* Physically present, torch-unusable cards. Their own block, above the
            device rows and visually separate from them, because nothing here is
            selectable: the rows below are what a model can be loaded onto. */}
        {gpuMismatch ? (
          <div className="flex flex-col gap-2 border-b border-border/60 py-3">
            {gpuMismatchMessage && (
              <p className="text-sm text-amber-600 dark:text-amber-400">
                {gpuMismatchMessage}
              </p>
            )}
            {gpuPermissionHint && (
              <p className="select-text text-sm text-amber-600 dark:text-amber-400">
                {gpuPermissionHint}
              </p>
            )}
            {physicalDevices.map((device, index) => (
              <div
                key={`${device.vendor ?? "gpu"}-${device.index ?? index}-${device.name ?? ""}`}
                className="flex min-w-0 items-center justify-between gap-4 text-xs text-muted-foreground opacity-70"
              >
                <span className="min-w-0 truncate">
                  {device.name ?? t("settings.resources.gpu.unknownDevice")}
                </span>
                <span className="shrink-0 font-mono tabular-nums">
                  {`${
                    isFiniteNumber(device.memory_total_gb)
                      ? formatGiB(device.memory_total_gb)
                      : unknownLabel
                  } · ${t("settings.resources.gpu.unusableDevice")}`}
                </span>
              </div>
            ))}
          </div>
        ) : null}
        {separateInferenceGpu && (
          <div className="flex items-start justify-between gap-4 border-b border-border/60 py-3 text-sm">
            <span className="text-muted-foreground">
              {t("settings.resources.gpu.ggufInference")}
            </span>
            <span className="text-right font-mono text-xs text-foreground">
              {separateInferenceGpu.backend?.toUpperCase() ?? "GPU"}
              {separateInferenceGpu.available ? (
                inferenceVramTotal ? (
                  <span className="block">
                    {t("settings.resources.gpu.vramUtilization")}:{" "}
                    {formatGiB(inferenceVramTotal)}
                  </span>
                ) : (
                  ""
                )
              ) : (
                ` · ${t("settings.resources.gpu.unavailable")}`
              )}
              {separateInferenceGpu.available &&
                inferenceDisplay.usageDevices.map((device, index) => (
                  <span
                    key={`${device.index ?? index}-${device.name ?? "gpu"}`}
                    className="block normal-case"
                  >
                    {`${
                      device.name ??
                      t("settings.resources.gpu.deviceWithIndex", {
                        index: deviceOrdinal(device) ?? index,
                      })
                    } · ${t("settings.resources.gpu.used", {
                      value: isFiniteNumber(device.vram_used_gb)
                        ? formatGiB(device.vram_used_gb)
                        : unknownLabel,
                    })}`}
                  </span>
                ))}
              {separateInferenceGpu.available &&
                inferenceDisplay.sharedDevices.length > 0 && (
                  <span className="block normal-case">
                    {t("settings.resources.gpu.sharedEstimatedAvailable", {
                      value:
                        inferenceDisplay.sharedAvailableGb === null
                          ? unknownLabel
                          : formatGiB(inferenceDisplay.sharedAvailableGb),
                    })}
                  </span>
                )}
            </span>
          </div>
        )}
        {hasGpu ? (
          metrics.devices.map((device, index) => {
            const ordinal = deviceOrdinal(device);
            // Preserve null (unknown); 0 would render a fabricated reading.
            const total = device.memory_total_gb ?? null;
            const used = device.vram_used_gb ?? null;
            const free =
              device.vram_free_gb ??
              (isFiniteNumber(total) && isFiniteNumber(used)
                ? Math.max(0, total - used)
                : null);
            const percent =
              device.vram_utilization_pct ??
              (isFiniteNumber(total) && total > 0 && isFiniteNumber(used)
                ? (used / total) * 100
                : null);
            const safePercent = clampPercent(percent);
            const usedText = isFiniteNumber(used)
              ? formatGiB(used)
              : unknownLabel;
            const freeText = isFiniteNumber(free)
              ? formatGiB(free)
              : unknownLabel;
            const totalText = isFiniteNumber(total)
              ? formatGiB(total)
              : unknownLabel;
            const percentText = isFiniteNumber(percent)
              ? formatPercent(safePercent)
              : unknownLabel;
            // Its total is mostly system RAM, so "VRAM" beside it overstates the card (#8942).
            const sharedSplit = deviceSharedMemorySplitGb(device);
            const telemetry = telemetryByOrdinal.get(`${ordinal ?? index}`);
            // Shared pool: used is every app's GPU allocation (AGX), free an available-RAM floor.
            const shared = device.shared_memory === true;
            const usedBySystem =
              shared &&
              isFiniteNumber(total) &&
              isFiniteNumber(used) &&
              isFiniteNumber(free)
                ? Math.max(0, total - used - free)
                : 0;
            const segments: StorageSegment[] = [
              {
                key: "used",
                label: t("settings.resources.gpu.segmentUsed"),
                bytes: isFiniteNumber(used) ? used : 0,
                value: usedText,
                color: "bg-neutral-500 dark:bg-neutral-300",
              },
              ...(usedBySystem > 0
                ? [
                    {
                      key: "system",
                      label: t("settings.resources.gpu.segmentSystem"),
                      bytes: usedBySystem,
                      value: formatGiB(usedBySystem),
                      color: "bg-muted-foreground/40",
                    },
                  ]
                : []),
              {
                key: "free",
                label: t(
                  shared
                    ? "settings.resources.gpu.segmentAvailable"
                    : "settings.resources.storage.segmentFree",
                ),
                bytes: isFiniteNumber(free) ? free : 0,
                value: freeText,
                color: STORAGE_COLORS.free,
              },
            ];
            const deviceLabel =
              ordinal === undefined
                ? backendLabel
                : `${t("settings.resources.gpu.deviceWithIndex", {
                    index: ordinal,
                  })}, ${backendLabel}`;
            const telemetryParts = [
              telemetry?.loadPct != null
                ? `${t("settings.resources.liveMonitor.gpuLoad")} ${formatPercent(telemetry.loadPct)}`
                : null,
              telemetry?.temperatureC != null
                ? formatTemperature(telemetry.temperatureC)
                : null,
              telemetry?.powerDrawW != null
                ? formatPower(telemetry.powerDrawW, telemetry.powerLimitW)
                : null,
            ].filter((part): part is string => Boolean(part));
            return (
              <div
                key={`${device.index ?? index}-${device.name ?? "gpu"}`}
                data-settings-label={device.name ?? undefined}
                className={cn(
                  "flex min-w-0 flex-wrap items-start justify-between gap-x-6 gap-y-3 py-6 max-[992px]:flex-col max-[992px]:items-stretch",
                  index > 0 && "border-t border-border/60",
                )}
              >
                <div className="flex min-w-0 flex-1 flex-col gap-1">
                  <p className="flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground">
                    <span className="truncate">
                      {device.name ?? t("settings.resources.gpu.unknownDevice")}
                    </span>
                    {hasSharedMemoryHeadroom(device) ? (
                      <span className="text-xs font-normal text-muted-foreground">
                        {t("settings.resources.gpu.sharedWithSystemRam")}
                      </span>
                    ) : sharedSplit ? (
                      <span
                        className={cn(
                          "shrink-0 rounded-full px-1.5 py-1 text-ui-10 leading-none font-semibold tabular-nums",
                          usagePillClass(
                            isFiniteNumber(percent) ? safePercent : null,
                          ),
                        )}
                      >
                        {percentText}
                      </span>
                    ) : (
                      <span
                        className={cn(
                          "shrink-0 rounded-full px-1.5 py-1 text-ui-10 leading-none font-semibold tabular-nums",
                          usagePillClass(
                            isFiniteNumber(percent) ? safePercent : null,
                          ),
                        )}
                      >
                        {percentText}{" "}
                        {t("settings.resources.gpu.vramUtilization")}
                      </span>
                    )}
                  </p>
                  <span className="truncate text-xs text-muted-foreground">
                    {deviceLabel}
                    {sharedSplit && !hasSharedMemoryHeadroom(device) ? (
                      <>
                        {" · "}
                        {sharedSplit.dedicated > 0
                          ? t("settings.resources.environment.vramWithShared", {
                              vram: formatGiB(sharedSplit.dedicated),
                              shared: formatGiB(sharedSplit.shared),
                            })
                          : t("settings.resources.gpu.sharedWithSystemRam")}
                      </>
                    ) : null}
                  </span>
                  <span className="text-xs text-muted-foreground">
                    {t("settings.resources.gpu.usedOf", {
                      used: usedText,
                      total: totalText,
                    })}
                  </span>
                </div>
                {/* 392px: the Model downloads control's width, so both start on one edge. */}
                <div className="flex w-[min(calc(392px*var(--ui-space-scale,1)),100%)] shrink-0 flex-col gap-2.5 pt-0.5 max-[992px]:w-full">
                  {hasSharedMemoryHeadroom(device) ? (
                    <div className="text-xs text-muted-foreground">
                      {t("settings.resources.gpu.estimatedAvailable", {
                        value:
                          sharedMemoryAvailableGb([device]) === null
                            ? unknownLabel
                            : formatGiB(device.vram_free_gb),
                      })}
                    </div>
                  ) : (
                    <StorageBar
                      segments={segments}
                      totalBytes={isFiniteNumber(total) ? total : undefined}
                      legend="inline"
                      barClassName="h-1.5 rounded-full"
                    />
                  )}
                  {telemetryParts.length > 0 ? (
                    <span className="text-ui-11 tabular-nums text-muted-foreground">
                      {telemetryParts.join(" · ")}
                    </span>
                  ) : null}
                </div>
              </div>
            );
          })
        ) : gpuMismatch ? (
          // Not "no visible GPU": the unusable cards are listed above.
          <div className="py-3 text-sm text-muted-foreground">
            {t("settings.resources.gpu.noUsableGpu")}
          </div>
        ) : (
          <div className="py-3 text-sm text-muted-foreground">
            {gpuUnknown ? gpuUnknownLabel : t("settings.resources.gpu.noGpu")}
          </div>
        )}
      </SettingsSection>

      <SettingsSection title={t("settings.resources.floatingWindow")}>
        <SettingsRow
          label={t("settings.resources.showFloatingWindow")}
          description={t("settings.resources.showFloatingWindowDescription")}
        >
          <Switch
            aria-label={t("settings.resources.showFloatingWindow")}
            checked={isOpen}
            onCheckedChange={setIsOpen}
          />
        </SettingsRow>
        <SettingsRow
          label={t("settings.resources.liveMonitor.refreshRate")}
          description={t("settings.resources.liveMonitor.refreshRateDescription")}
        >
          <Select
            value={String(monitorRefreshMs(refreshMs))}
            onValueChange={(value) => setRefreshMs(Number(value))}
          >
            <SelectTrigger
              className="w-28"
              aria-label={t("settings.resources.liveMonitor.refreshRate")}
            >
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {MONITOR_REFRESH_OPTIONS_MS.map((ms) => (
                <SelectItem key={ms} value={String(ms)}>
                  {t("settings.resources.liveMonitor.refreshEvery", {
                    seconds: ms / 1000,
                  })}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </SettingsRow>
        <SettingsRow
          label={t("settings.resources.liveMonitor.detailedView")}
          description={t(
            "settings.resources.liveMonitor.detailedViewDescription",
          )}
        >
          <Switch
            aria-label={t("settings.resources.liveMonitor.detailedView")}
            checked={showDetails}
            onCheckedChange={setShowDetails}
          />
        </SettingsRow>
        {showDetails && (
          <div className="flex flex-wrap gap-x-5 gap-y-2 pb-3">
            {MONITOR_DETAIL_METRICS.map((metric) => {
              const label = t(`settings.resources.liveMonitor.${metric}`);
              return (
                <label
                  key={metric}
                  className="flex cursor-pointer items-center gap-2 text-xs font-medium text-foreground"
                >
                  <Checkbox
                    checked={detailMetrics.has(metric)}
                    onCheckedChange={(checked) =>
                      setDetailMetric(metric, checked === true)
                    }
                    aria-label={label}
                  />
                  {label}
                </label>
              );
            })}
          </div>
        )}
      </SettingsSection>

      <ModelMemorySection ref={modelMemoryRef} />

      <LlamaBackendSection />
      <EngineVersionsSection />
      <InferenceEnginesSection />

      <SettingsSection
        ref={storageSectionRef}
        title={t("settings.resources.storage.title")}
      >
        <StorageOverview
          label={t("settings.resources.storage.systemDisk")}
          heading={t("settings.resources.storage.systemUsed", {
            used: formatGb(metrics.diskUsed),
            total: formatGb(metrics.diskTotal),
          })}
          action={
            <Button
              variant="outline"
              size="sm"
              disabled={cache.loading || cache.clearing}
              onClick={() => void cache.refresh({ refresh: true })}
            >
              {t("settings.resources.storage.refreshAction")}
            </Button>
          }
          totalBytes={metrics.diskTotal}
          segments={storageSegments}
          footer={
            metrics.modelsDisk
              ? t("settings.resources.storage.modelsDiskSummary", {
                  used: formatGb(metrics.modelsDiskUsed),
                  total: formatGb(metrics.modelsDisk.total_gb),
                  free: formatGb(metrics.modelsDisk.free_gb),
                })
              : null
          }
        />
        <SettingsCard>
          <SettingsCardRow
            label={t("settings.resources.storage.modelsFolder")}
            hint={t("settings.resources.storage.modelsFolderHint")}
            description={
              <span className="flex min-w-0 flex-col gap-0.5">
                <span
                  title={hfCache?.cacheHome}
                  className="truncate font-mono text-ui-11"
                >
                  {modelsFolderPath}
                </span>
                {cacheLocationDetail ? (
                  <span className="truncate">{cacheLocationDetail}</span>
                ) : null}
              </span>
            }
          >
            {hfCache?.isCustom ? (
              <Button
                variant="outline"
                size="sm"
                disabled={cacheSaving}
                onClick={() => void saveCacheFolder(null)}
              >
                {t("settings.resources.storage.resetAction")}
              </Button>
            ) : null}
            <Button
              variant="outline"
              size="sm"
              disabled={!hfCache}
              onClick={() => void handleCacheFolder()}
            >
              {isTauri
                ? t("settings.resources.storage.openAction")
                : t("settings.resources.storage.copyAction")}
            </Button>
            <Button
              variant="outline"
              size="sm"
              disabled={!hfCache?.editable || cacheSaving}
              onClick={() => void changeCacheFolder()}
            >
              {t("settings.resources.storage.changeAction")}
            </Button>
          </SettingsCardRow>
          <CacheStorageRows cache={cache} />
        </SettingsCard>
      </SettingsSection>

      <FolderBrowser
        open={!isTauri && cacheBrowserOpen}
        onOpenChange={setCacheBrowserOpen}
        onSelect={(path) => void saveCacheFolder(path)}
        initialPath={hfCache?.cacheHome}
        title={t("settings.resources.storage.chooseTitle")}
        confirmLabel={t("settings.resources.storage.chooseAction")}
        showModelHints={false}
      />

      {isOwner ? <DeveloperModeSection /> : null}

      <EnvironmentSection systemInfo={systemInfo} backendLabel={backendLabel} />
    </div>
  );
}

/** About renders this too, from its own system query. */
export function EnvironmentSection({
  systemInfo,
  backendLabel,
}: {
  systemInfo: SystemInfoResponse;
  backendLabel: string;
}) {
  const t = useT();
  const unknownLabel = t("settings.resources.environment.unknown");
  const hostReading = (value: string) =>
    systemInfo.status !== "ready" ? unknownLabel : value;
  return (
    <SettingsSection title={t("settings.resources.environment.title")}>
      <InfoRow
        label={t("settings.resources.environment.backend")}
        value={hostReading(backendLabel)}
      />
      <InfoRow
        label={t("settings.resources.environment.python")}
        value={systemInfo.python_version}
      />
      <InfoRow
        label={t("settings.resources.environment.torch")}
        value={hostReading(
          systemInfo.ml_packages.torch ??
            t("settings.resources.environment.notInstalled"),
        )}
      />
      <InfoRow
        label={t("settings.resources.environment.transformers")}
        value={hostReading(
          systemInfo.ml_packages.transformers ??
            t("settings.resources.environment.notInstalled"),
        )}
      />
      {systemInfo.ml_packages.mlx_lm ? (
        <InfoRow
          label={t("settings.resources.environment.mlxLm")}
          value={hostReading(systemInfo.ml_packages.mlx_lm)}
        />
      ) : null}
      {systemInfo.ml_packages.mlx_vlm ? (
        <InfoRow
          label={t("settings.resources.environment.mlxVlm")}
          value={hostReading(systemInfo.ml_packages.mlx_vlm)}
        />
      ) : null}
      <InfoRow
        label={t("settings.resources.environment.uptime")}
        value={hostReading(formatUptime(systemInfo.uptime_seconds))}
      />
      <InfoRow
        label={t("settings.resources.environment.processMemory")}
        value={hostReading(formatMb(systemInfo.memory?.process_used_mb))}
      />
    </SettingsSection>
  );
}

export function StandaloneEnvironmentSection() {
  const systemInfo = useSystemInfo();
  return (
    <EnvironmentSection
      systemInfo={systemInfo}
      backendLabel={(systemInfo.device_backend ?? "cpu").toUpperCase()}
    />
  );
}