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.

19.6 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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Spinner } from "@/components/ui/spinner";
import {
  LIBRARY_TABS,
  type LibraryLocation,
  type LibrarySearch,
  type LibrarySettings,
  type LibraryTab as LibraryTabId,
  type LibraryTabVisibility,
  STORAGE_LABELS,
  SUGGESTED_LIMITS,
  errorMessage,
  formatSize,
  getLibraryLocations,
  moveLibraryLocation,
  parentFolder,
  refreshLibraryStorage,
  revealLibraryLocation,
  useLibrarySettingsStore,
  useLibraryStorage,
  useLibraryViewStore,
  useLibraryVisitStore,
  useRevealLabel,
} from "@/features/library";
import { useIsAccountOwner } from "@/features/auth";
import { FolderBrowser } from "@/features/model-picker";
import { type TranslationKey, useLocale, useT } from "@/i18n";
import { notifyGalleryChanged } from "@/lib/gallery-flags";
import { toast } from "@/lib/toast";
import { useNavigate } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
import {
  STORAGE_COLORS,
  SettingsCard,
  SettingsCardRow,
  StorageOverview,
} from "../components/storage-overview";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";

type ToggleKey = {
  [K in keyof LibrarySettings]: LibrarySettings[K] extends boolean ? K : never;
}[keyof LibrarySettings];

const TAB_LABELS: Record<LibraryTabId, TranslationKey> = {
  suggested: "settings.library.suggested",
  favorites: "library.tabs.favorites",
  folders: "library.tabs.folders",
  images: STORAGE_LABELS.images,
  videos: STORAGE_LABELS.videos,
  audio: STORAGE_LABELS.audio,
  models: STORAGE_LABELS.fineTunes,
  all: "settings.library.all",
  chats: "library.tabs.chats",
};

const CHOICES: {
  [K in "cardSize" | "imageLayout" | "startTab" | "sort"]: [LibrarySettings[K], TranslationKey][];
} = {
  cardSize: [
    ["small", "settings.library.small"],
    ["medium", "settings.library.medium"],
    ["large", "settings.library.large"],
  ],
  imageLayout: [
    ["masonry", "settings.library.masonry"],
    ["square", "settings.library.square"],
  ],
  startTab: [
    ["last", "settings.library.lastVisited"],
    ...(["suggested", "favorites", "folders", "chats", "all"] as const).map((tab): [typeof tab, TranslationKey] => [tab, TAB_LABELS[tab]]),
  ],
  sort: [
    ["recent", "settings.library.recent"],
    ["oldest", "settings.library.oldest"],
    ["name", "settings.library.name"],
    ["size", "library.preview.size"],
  ],
};

const CONTENT_TABS = new Set<LibraryTabId>(["images", "videos", "audio", "models"]);

const TAB_VISIBILITY: [LibraryTabVisibility, TranslationKey][] = [
  ["auto", "settings.library.tabAuto"],
  ["always", "settings.library.tabAlways"],
  ["hidden", "settings.library.tabHidden"],
];

function ChoiceSelect({
  label,
  value,
  options,
  onChange,
}: {
  label: string;
  value: string;
  options: [string, string][];
  onChange: (value: string) => void;
}) {
  return (
    <Select value={value} onValueChange={onChange}>
      <SelectTrigger size="sm" className="w-48" aria-label={label}>
        <SelectValue />
      </SelectTrigger>
      <SelectContent align="end">
        {options.map(([option, text]) => (
          <SelectItem key={option} value={option}>
            {text}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

const CATEGORY_COLORS: Record<string, string> = {
  files: STORAGE_COLORS.yellow,
  images: STORAGE_COLORS.purple,
  videos: STORAGE_COLORS.orange,
  audio: STORAGE_COLORS.green,
  fineTunes: STORAGE_COLORS.blue,
};

function StorageSection() {
  const t = useT();
  const locale = useLocale();
  const navigate = useNavigate();
  const closeDialog = useSettingsDialogStore((s) => s.closeDialog);
  const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
  const consumeScrollTarget = useSettingsDialogStore((s) => s.consumeScrollTarget);
  const sectionRef = useRef<HTMLElement | null>(null);
  const setView = useLibraryViewStore((s) => s.setView);
  const restartLibrary = useLibraryVisitStore((s) => s.restart);
  const storage = useLibraryStorage();
  const size = (bytes: number) => formatSize(bytes, locale, t) ?? "";

  useEffect(() => {
    if (scrollTarget !== "library-storage") return;
    const frame = window.requestAnimationFrame(() => {
      sectionRef.current?.scrollIntoView({ block: "start", behavior: "smooth" });
      consumeScrollTarget("library-storage");
    });
    return () => window.cancelAnimationFrame(frame);
  }, [consumeScrollTarget, scrollTarget]);

  const open = (link: LibrarySearch) => {
    closeDialog();
    setView("list");
    // Already on that tab, the view would keep its filters and show less than counted.
    restartLibrary();
    void navigate({ to: "/library", search: link });
  };

  return (
    <SettingsSection
      ref={sectionRef}
      title={t("settings.library.storageSection")}
      description={t("settings.library.storageDescription")}
    >
      {storage.status === "loading" ? (
        <Spinner className="my-4 size-5 text-muted-foreground" />
      ) : storage.status === "error" ? (
        <p className="py-3 text-sm text-muted-foreground">{t("settings.library.storageError")}</p>
      ) : (
        <>
          <StorageOverview
            heading={t("settings.library.storageUsed", { size: size(storage.totalBytes) })}
            action={
              <Button variant="outline" size="sm" onClick={refreshLibraryStorage}>
                {t("settings.library.storageRefresh")}
              </Button>
            }
            segments={[
              ...storage.categories.map((entry) => ({
                key: entry.category,
                label: t(STORAGE_LABELS[entry.category]),
                bytes: entry.bytes,
                value: size(entry.bytes),
                color: CATEGORY_COLORS[entry.category],
              })),
              ...(storage.hiddenBytes > 0
                ? [
                    {
                      key: "hidden",
                      label: t("settings.library.storageHiddenLabel"),
                      bytes: storage.hiddenBytes,
                      value: size(storage.hiddenBytes),
                      color: STORAGE_COLORS.other,
                    },
                  ]
                : []),
            ]}
            footer={
              storage.disk && storage.disk.totalBytes > 0
                ? t("settings.library.storageDisk", {
                    free: size(storage.disk.freeBytes),
                    total: size(storage.disk.totalBytes),
                  })
                : null
            }
          />
          {storage.categories.length === 0 && storage.hiddenBytes === 0 && (
            <p className="pb-3 text-sm text-muted-foreground">{t("settings.library.storageEmpty")}</p>
          )}
          {storage.categories.length > 0 && (
            <SettingsCard>
              {storage.categories.map((entry) => (
                <SettingsCardRow
                  key={entry.category}
                  label={t(STORAGE_LABELS[entry.category])}
                  description={`${size(entry.bytes)} · ${
                    entry.count === 1
                      ? t("settings.library.itemCountOne")
                      : t("settings.library.itemCount", { count: entry.count.toLocaleString() })
                  }`}
                >
                  <Button variant="outline" size="sm" onClick={() => open(entry.link)}>
                    {t("settings.library.storageOpen")}
                  </Button>
                </SettingsCardRow>
              ))}
            </SettingsCard>
          )}
          {storage.hiddenBytes > 0 && (
            <p className="py-2 text-xs text-muted-foreground">
              {t("settings.library.storageHidden", { size: size(storage.hiddenBytes) })}
            </p>
          )}
        </>
      )}
    </SettingsSection>
  );
}

function LocationsSection() {
  const t = useT();
  const locale = useLocale();
  const revealLabel = useRevealLabel();
  const owner = useIsAccountOwner();
  const [locations, setLocations] = useState<LibraryLocation[] | null>(null);
  const [moving, setMoving] = useState(false);
  const [picking, setPicking] = useState<LibraryLocation | null>(null);
  const [resettingAway, setResettingAway] = useState<LibraryLocation | null>(null);
  useEffect(() => {
    let cancelled = false;
    void getLibraryLocations()
      .catch((): LibraryLocation[] => [])
      .then((next) => !cancelled && setLocations(next));
    return () => {
      cancelled = true;
    };
  }, []);
  const nameOf = (location: LibraryLocation) => t(STORAGE_LABELS[location.key]);
  const manyDisks = new Set(locations?.map((location) => location.device).filter(Boolean)).size > 1;

  async function move(location: LibraryLocation, path: string | null) {
    const name = nameOf(location);
    setMoving(true);
    const id = toast.loading(t("settings.library.locationMoving", { name }));
    try {
      const result = await moveLibraryLocation(location.key, path);
      setLocations(result.locations);
      refreshLibraryStorage();
      if (location.key === "images" || location.key === "videos" || location.key === "audio") {
        notifyGalleryChanged(location.key);
      }
      void import("@/features/library/store").then(({ useLibraryStore }) => {
        const library = useLibraryStore.getState();
        if (library.status !== "idle") void library.refresh();
      });
      toast.success(t("settings.library.locationMoved", { name }), {
        id,
        description: result.leftBehind
          ? t("settings.library.locationLeftBehind", { path: result.leftBehind })
          : undefined,
      });
    } catch (error) {
      toast.error(t("settings.library.locationMoveFailed", { name }), { id, description: errorMessage(error) });
    } finally {
      setMoving(false);
    }
  }

  return (
    <SettingsSection
      title={t("settings.library.locationsSection")}
      description={t("settings.library.locationsDescription")}
    >
      {locations === null ? (
        <Spinner className="my-4 size-5 text-muted-foreground" />
      ) : (
        locations.map((location) => (
          <SettingsRow
            key={location.key}
            label={nameOf(location)}
            description={
              <>
                <span className="block truncate font-mono text-ui-11" title={location.path}>
                  {location.path}
                </span>
                {location.available === false ? (
                  <span className="block text-xs text-destructive">
                    {t("settings.library.locationUnavailable")}
                  </span>
                ) : (
                  manyDisks &&
                  location.disk && (
                    <span className="block text-xs">
                      {t("settings.library.locationFree", {
                        free: formatSize(location.disk.freeBytes, locale, t) ?? "",
                      })}
                    </span>
                  )
                )}
              </>
            }
          >
            <div className="flex shrink-0 items-center gap-2">
              {owner && location.movable && location.custom && (
                <Button
                  variant="outline"
                  size="sm"
                  disabled={moving}
                  onClick={() =>
                    location.available === false
                      ? setResettingAway(location)
                      : void move(location, null)
                  }
                >
                  {t("settings.library.locationReset")}
                </Button>
              )}
              {owner && location.movable && (
                <Button
                  variant="outline"
                  size="sm"
                  disabled={moving}
                  onClick={() => setPicking(location)}
                >
                  {t("settings.resources.storage.changeAction")}
                </Button>
              )}
              {revealLabel && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() =>
                    void revealLibraryLocation(location.key).catch((error: unknown) =>
                      toast.error(t("settings.library.revealFailed"), { description: errorMessage(error) }),
                    )
                  }
                >
                  {revealLabel}
                </Button>
              )}
            </div>
          </SettingsRow>
        ))
      )}
      <FolderBrowser
        open={picking !== null}
        onOpenChange={(next) => !next && setPicking(null)}
        onSelect={(path) => {
          if (picking) void move(picking, path);
        }}
        initialPath={picking ? parentFolder(picking.path) : undefined}
        title={picking ? t("settings.library.locationMoveTitle", { name: nameOf(picking) }) : ""}
        description={t("settings.library.locationMoveDescription")}
        confirmLabel={t("settings.library.locationMoveAction")}
        showModelHints={false}
      />
      <AlertDialog
        open={resettingAway !== null}
        onOpenChange={(open) => !open && setResettingAway(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="break-words">
              {t("settings.library.locationResetUnavailableTitle", {
                name: resettingAway ? nameOf(resettingAway) : "",
              })}
            </AlertDialogTitle>
            <AlertDialogDescription className="break-words">
              {t("settings.library.locationResetUnavailableDescription", {
                path: resettingAway?.path ?? "",
              })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                if (resettingAway) void move(resettingAway, null);
                setResettingAway(null);
              }}
            >
              {t("settings.library.locationReset")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </SettingsSection>
  );
}

export function LibraryTab() {
  const t = useT();
  const settings = useLibrarySettingsStore();

  const choice = <K extends keyof typeof CHOICES>(key: K, labelKey: TranslationKey, descriptionKey: TranslationKey) => (
    <SettingsRow label={t(labelKey)} description={t(descriptionKey)}>
      <ChoiceSelect
        label={t(labelKey)}
        value={settings[key]}
        options={CHOICES[key].map(([option, text]) => [option, t(text)])}
        onChange={(value) => settings.set({ [key]: value } as Partial<LibrarySettings>)}
      />
    </SettingsRow>
  );

  const toggle = (key: ToggleKey, labelKey: TranslationKey, descriptionKey: TranslationKey) => (
    <SettingsRow label={t(labelKey)} description={t(descriptionKey)}>
      <Switch
        aria-label={t(labelKey)}
        checked={settings[key]}
        onCheckedChange={(checked) => settings.set({ [key]: checked })}
      />
    </SettingsRow>
  );

  return (
    <div className="settings-page">
      <header className="flex flex-col gap-1">
        <h1 className="text-xl font-semibold font-heading">{t("shell.navigation.library")}</h1>
      </header>

      <StorageSection />

      <SettingsSection title={t("settings.library.layoutSection")}>
        {choice("cardSize", "settings.library.cardSize", "settings.library.cardSizeDescription")}
        {choice("imageLayout", "settings.library.imageLayout", "settings.library.imageLayoutDescription")}
        {toggle("showCardDates", "settings.library.showCardDates", "settings.library.showCardDatesDescription")}
      </SettingsSection>

      <SettingsSection title={t("settings.library.downloadsSection")}>
        {toggle("imageInfoStamp", "settings.library.imageInfoStamp", "settings.library.imageInfoStampDescription")}
      </SettingsSection>

      <SettingsSection title={t("settings.library.browsingSection")}>
        {choice("startTab", "settings.library.startTab", "settings.library.startTabDescription")}
        {choice("sort", "settings.library.sort", "settings.library.sortDescription")}
        <SettingsRow
          label={t("settings.library.suggestedLimit")}
          description={t("settings.library.suggestedLimitDescription")}
        >
          <ChoiceSelect
            label={t("settings.library.suggestedLimit")}
            value={String(settings.suggestedLimit)}
            options={SUGGESTED_LIMITS.map((limit) => [String(limit), String(limit)])}
            onChange={(value) => settings.set({ suggestedLimit: Number(value) })}
          />
        </SettingsRow>
      </SettingsSection>

      <SettingsSection
        title={t("settings.library.tabsSection")}
        description={t("settings.library.tabsDescription")}
      >
        {LIBRARY_TABS.map((tab) => {
          const label = t(TAB_LABELS[tab]);
          const visibility = settings.tabs[tab] ?? "always";
          const setVisibility = (next: LibraryTabVisibility) =>
            settings.set({ tabs: { ...settings.tabs, [tab]: next } });
          return (
            <SettingsRow key={tab} label={label}>
              {CONTENT_TABS.has(tab) ? (
                <ChoiceSelect
                  label={label}
                  value={visibility}
                  options={TAB_VISIBILITY.map(([option, text]) => [option, t(text)])}
                  onChange={(value) => setVisibility(value as LibraryTabVisibility)}
                />
              ) : (
                <Switch
                  aria-label={label}
                  checked={visibility !== "hidden"}
                  onCheckedChange={(checked) => setVisibility(checked ? "always" : "hidden")}
                />
              )}
            </SettingsRow>
          );
        })}
      </SettingsSection>

      <SettingsSection
        title={t("settings.library.contentSection")}
        description={t("settings.library.contentDescription")}
      >
        {toggle("showChatAttachments", "settings.library.showChatAttachments", "settings.library.showChatAttachmentsDescription")}
        {toggle("showChatToolFiles", "settings.library.showChatToolFiles", "settings.library.showChatToolFilesDescription")}
        {toggle("showGeneratedMedia", "settings.library.showGeneratedMedia", "settings.library.showGeneratedMediaDescription")}
        {toggle("showFineTunes", "settings.library.categoryFineTunes", "settings.library.showFineTunesDescription")}
      </SettingsSection>

      <SettingsSection title={t("settings.library.deletingSection")}>
        {toggle("confirmDelete", "settings.library.confirmDelete", "settings.library.confirmDeleteDescription")}
        <SettingsRow
          label={t("settings.library.reset")}
          description={t("settings.library.resetDescription")}
          destructive={true}
        >
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              settings.reset();
              toast.success(t("settings.library.resetDone"));
            }}
          >
            {t("settings.library.resetButton")}
          </Button>
        </SettingsRow>
      </SettingsSection>

      <LocationsSection />
    </div>
  );
}