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.

45.7 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 { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Skeleton } from "@/components/ui/skeleton";
import {
  type NativeIntent,
  consumeNativePathToken,
  useNativeFileDrop,
} from "@/features/native-intents";
import { getAuthSessionEpoch } from "@/features/auth";
import { rangeBetween } from "@/features/chat";
import { isMacPlatform, useSettingsDialogStore } from "@/features/settings";
import { type TranslationKey, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { toast } from "@/lib/toast";
import {
  Cancel01Icon,
  FlimSlateIcon,
  Download01Icon,
  ImageIcon,
  MoreHorizontalIcon,
  PencilEdit02Icon,
  Upload01Icon,
} from "@hugeicons/core-free-icons";
import { Folder01Icon, FolderClosedIcon, FolderExportIcon } from "@/lib/folder-icons";
import { ChevronRightStandardIcon } from "@/lib/chevron-icons";
import { AiSpeechIcon, MessageCircleIcon, StarPointedIcon, TestTubeOutlineIcon, TrashIcon } from "@/lib/hugeicons-derived";
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate, useRouter, useSearch } from "@tanstack/react-router";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  chatAboutItems,
  chatWithModel,
  editLibraryImage,
  downloadLibraryItem,
  downloadLibraryItems,
} from "./actions";
import { type LibraryFolder, type LibraryItem, type LibraryUploadBatch, errorMessage } from "./api";
import {
  type LibraryTypeFilter,
  fileKind,
  isDeletable,
  isFileItem,
  isModelItem,
} from "./file-kind";
import {
  type LibraryActions,
  LibraryActionsProvider,
  type LibraryTarget,
} from "./actions-context";
import { ChatsLibrary } from "./chats/chats-library";
import { useFavoriteChatMatches } from "./chats/favorites";
import { useChatFavoritesStore } from "./chats/favorites-store";
import { CardSelectionContext } from "./components/card-selection";
import { FolderGrid, ItemCard, Masonry } from "./components/library-cards";
import { ConfirmDeleteDialog, NameDialog } from "./components/library-dialogs";
import { LibraryList } from "./components/library-list";
import { LibraryPreview } from "./components/library-preview";
import { LibraryHeader } from "./components/library-header";
import {
  type LibrarySortChoice,
  LibraryToolbar,
  type NewAction,
} from "./components/library-toolbar";
import { audioWorkflowOptions, runSiblings } from "./audio-items";
import { stopLibraryAudio, stopLibraryAudioUnlessShown } from "./audio-playback";
import { EMPTY_FILTERS, type LibraryFilters, filtersActive, matchesFilters } from "./filters";
import { LIBRARY_TABS, type LibrarySearch, type LibraryTab } from "./search";
import { useLibraryStore } from "./store";
import {
  SORT_STATES,
  compareBySort,
  includedBySettings,
  lastActivity,
  nextSort,
  sortParam,
  useLibrarySettingsStore,
  useLibraryViewStore,
  useLibraryVisitStore,
} from "./settings-store";

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

type EmptyCopy = [icon: typeof Folder01Icon, title: TranslationKey, description: TranslationKey];
const EMPTY_COPY: Record<LibraryTab, EmptyCopy> = {
  suggested: [Upload01Icon, "library.empty.suggestedTitle", "library.empty.suggestedDescription"],
  favorites: [StarPointedIcon, "library.empty.favoritesTitle", "library.empty.favoritesDescription"],
  folders: [FolderClosedIcon, "library.empty.foldersTitle", "library.empty.foldersDescription"],
  images: [ImageIcon, "library.empty.imagesTitle", "library.empty.imagesDescription"],
  videos: [FlimSlateIcon, "library.empty.videosTitle", "library.empty.videosDescription"],
  audio: [AiSpeechIcon, "library.empty.audioTitle", "library.empty.audioDescription"],
  models: [TestTubeOutlineIcon, "library.empty.modelsTitle", "library.empty.modelsDescription"],
  all: [Upload01Icon, "library.empty.suggestedTitle", "library.empty.suggestedDescription"],
  chats: [MessageCircleIcon, "library.chats.empty.chatsTitle", "library.chats.empty.chatsDescription"],
};

const EMPTY_LINKS = {
  images: ["/images", "library.empty.generateImage"],
  videos: ["/video", "library.empty.generateVideo"],
  audio: ["/audio", "library.empty.generateAudio"],
  models: ["/studio", "library.empty.trainModel"],
} as const;

const KIND_TABS: Partial<Record<LibraryTab, (item: LibraryItem) => boolean>> = {
  images: (item) => fileKind(item) === "image",
  videos: (item) => fileKind(item) === "video",
  audio: (item) => fileKind(item) === "audio",
  models: isModelItem,
};

const DELETE_NOTES: Record<string, TranslationKey> = {
  upload: "library.dialog.deleteUpload",
  attachment: "library.dialog.deleteAttachment",
  image: "library.dialog.deleteImage",
  video: "library.dialog.deleteVideo",
  audio: "library.dialog.deleteAudio",
  sandbox: "library.dialog.deleteSandbox",
  model: "library.dialog.deleteModel",
};

type NameDialogState =
  | { mode: "create"; parentId: string | null; thenMove?: LibraryTarget }
  | { mode: "rename"; target: LibraryTarget };

function nameMatches(name: string, needle: string): boolean {
  return !needle || name.toLowerCase().includes(needle);
}

const BAR_PILL =
  "flex items-center gap-2 rounded-full px-3 py-2 text-sm font-medium [&_svg]:-my-2 outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50";
const BAR_ROUND =
  "flex size-9 items-center justify-center rounded-full outline-none transition-colors hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring";

function EmptyState({
  icon,
  title,
  description,
  action,
}: {
  icon: typeof Folder01Icon;
  title: string;
  description: string;
  action?: ReactNode;
}) {
  return (
    <div className="mx-auto mt-16 flex max-w-md flex-col items-center gap-2 text-center">
      <HugeiconsIcon icon={icon} strokeWidth={1.5} className="mb-2 size-7" />
      <h2 className="font-medium text-ui-21 text-foreground">{title}</h2>
      <p className="text-ui-15 text-muted-foreground">{description}</p>
      {action && <div className="mt-3">{action}</div>}
    </div>
  );
}

function SectionHeading({ children }: { children: ReactNode }) {
  return <h2 className="mb-4 mt-8 font-medium text-ui-18 text-foreground">{children}</h2>;
}

function LoadingGrid() {
  return (
    <div className="mt-6 grid grid-cols-2 gap-5 sm:grid-cols-3 lg:grid-cols-5">
      {Array.from({ length: 10 }, (_, index) => (
        <Skeleton key={index} className="aspect-square rounded-2xl" />
      ))}
    </div>
  );
}

const FILE_TYPES: LibraryTypeFilter[] = ["documents", "spreadsheets", "presentations", "pdfs"];

export function LibraryPage() {
  const search = useSearch({ from: "/library" });
  const refresh = useLibraryStore((s) => s.refresh);
  const visit = useLibraryVisitStore((s) => s.visit);

  useEffect(() => {
    void refresh();
    const onFocus = () => void refresh();
    window.addEventListener("focus", onFocus);
    return () => window.removeEventListener("focus", onFocus);
  }, [refresh]);

  return (
    <LibraryView
      key={`${visit}:${search.show ?? ""}:${search.folder ?? ""}:${search.filter ?? ""}`}
      search={search}
    />
  );
}

function LibraryView({ search }: { search: LibrarySearch }) {
  const t = useT();
  const navigate = useNavigate();
  const { items: allItems, folders, status, error, refresh, patchItem, removeItem, upload, addFolder, patchFolder, removeFolder, markOpened } =
    useLibraryStore();
  const settings = useLibrarySettingsStore();
  const items = useMemo(
    () => allItems.filter((item) => includedBySettings(item.id, settings)),
    [allItems, settings],
  );
  const view = useLibraryViewStore((s) => s.view);
  const setView = useLibraryViewStore((s) => s.setView);
  const openSettings = useSettingsDialogStore((s) => s.openDialog);
  useEffect(() => stopLibraryAudio, []);

  const [query, setQuery] = useState("");
  const [chosenFilters, setFilters] = useState<LibraryFilters>(() =>
    search.filter === "files" ? { ...EMPTY_FILTERS, types: new Set(FILE_TYPES) } : EMPTY_FILTERS,
  );
  const [selection, setSelectionState] = useState<Set<string>>(new Set());
  // The entry last clicked, which a shift click ranges from. A key rather than an index: the
  // listing can re-sort between clicks.
  const selectionAnchor = useRef<string | null>(null);
  // Select all and clearing drop the anchor, so a shift click never reaches back past them.
  const setSelection = useCallback((next: Set<string>) => {
    selectionAnchor.current = null;
    setSelectionState(next);
  }, []);
  const [nameDialog, setNameDialog] = useState<NameDialogState | null>(null);
  const [pendingDelete, setPendingDelete] = useState<LibraryTarget[] | null>(null);
  const fileInput = useRef<HTMLInputElement>(null);

  const loaded = status === "ready";
  // "auto" tabs count as shown until the listing lands, so the start tab is not swapped mid-load.
  const tabVisible = (entry: LibraryTab) => {
    const visibility = settings.tabs[entry] ?? "always";
    if (visibility === "hidden" || (entry === "models" && !settings.showFineTunes)) return false;
    return visibility === "always" || !loaded || items.some(KIND_TABS[entry] ?? (() => true));
  };
  const [preferred] = useState(() =>
    settings.startTab === "last" ? settings.lastTab : settings.startTab,
  );
  // Decided once on load so the tab does not jump when a file lands later.
  const [emptyOnLoad, setEmptyOnLoad] = useState<boolean | null>(null);
  if (emptyOnLoad === null && loaded) setEmptyOnLoad(items.length === 0 && folders.length === 0);
  const hasStarredChats = useChatFavoritesStore(
    (s) => s.chatIds.length + s.projectIds.length + s.sectionIds.length > 0,
  );
  const nothingButChats =
    emptyOnLoad === true &&
    tabVisible("chats") &&
    !(preferred === "favorites" && hasStarredChats);
  const tab: LibraryTab =
    search.show ??
    (nothingButChats
      ? "chats"
      : tabVisible(preferred)
        ? preferred
        : (LIBRARY_TABS.find(tabVisible) ?? "all"));
  const sort = SORT_STATES[search.sort ?? settings.sort];
  const folderId = search.folder ?? null;
  const folderById = useMemo(() => new Map(folders.map((f) => [f.id, f])), [folders]);
  const currentFolder = folderId ? (folderById.get(folderId) ?? null) : null;

  const go = useCallback(
    (next: LibrarySearch, replace = false) =>
      void navigate({ to: "/library", search: next, replace }),
    [navigate],
  );

  const gridSortValue = (search.sort ? SORT_STATES[search.sort].key : "default") as LibrarySortChoice;
  const gridSort = {
    value: gridSortValue,
    activity: tab === "suggested" && !folderId,
    showSize: Boolean(folderId) || tab !== "folders",
    desc: sort.desc,
    onDirectionChange: (desc: boolean) =>
      desc !== sort.desc && go({ ...search, sort: sortParam({ key: sort.key, desc }) }, true),
    onChange: (choice: LibrarySortChoice) =>
      choice !== gridSortValue &&
      go(
        {
          ...search,
          sort:
            choice === "default"
              ? undefined
              : sortParam({ key: choice, desc: choice !== "name" }),
        },
        true,
      ),
  };

  const [parentOfOpen, setParentOfOpen] = useState<string | null>(null);
  if (currentFolder && currentFolder.parentId !== parentOfOpen) {
    setParentOfOpen(currentFolder.parentId);
  }
  const folderGone = status === "ready" && folderId !== null && currentFolder === null;
  useEffect(() => {
    if (!folderGone) return;
    const parent = parentOfOpen && folderById.has(parentOfOpen) ? parentOfOpen : undefined;
    go({ folder: parent, show: "folders" }, true);
  }, [folderGone, parentOfOpen, folderById, go]);


  const counts = useMemo(() => {
    const map = new Map<string, number>();
    const bump = (id: string | null) => id && map.set(id, (map.get(id) ?? 0) + 1);
    for (const item of items) bump(item.folderId);
    for (const folder of folders) bump(folder.parentId);
    return map;
  }, [items, folders]);

  const needle = query.trim().toLowerCase();
  const favoriteChats = useFavoriteChatMatches(query, tab === "favorites" && !folderId);

  const kindFilter = folderId ? undefined : KIND_TABS[tab];
  const filterMode = folderId || tab === "folders" ? "none" : kindFilter ? "source" : "all";
  const filters = filterMode === "none" ? EMPTY_FILTERS : chosenFilters;
  const workflowOptions = useMemo(
    () => (tab === "audio" && !folderId ? audioWorkflowOptions(items) : []),
    [tab, folderId, items],
  );

  const shownTabs = LIBRARY_TABS.filter((entry) => entry === tab || tabVisible(entry));

  const setLibrarySettings = settings.set;
  useEffect(() => {
    if (!folderId) setLibrarySettings({ lastTab: tab });
  }, [tab, folderId, setLibrarySettings]);
  const visibleItems = useMemo(() => {
    let pool = items;
    if (folderId) pool = pool.filter((item) => item.folderId === folderId);
    else if (tab === "favorites") pool = pool.filter((item) => item.favorite);
    else if (kindFilter) pool = pool.filter(kindFilter);
    else if (tab === "folders") pool = [];
    pool = pool.filter(
      (item) => nameMatches(item.name, needle) && matchesFilters(item, filters, !kindFilter),
    );
    if (tab === "suggested" && !folderId) {
      const byActivity = [...pool].sort((a, b) => lastActivity(b) - lastActivity(a));
      pool = needle || filtersActive(filters) ? byActivity : byActivity.slice(0, settings.suggestedLimit);
      if (sort.key === "modified") return sort.desc ? pool : pool.reverse();
    }
    return [...pool].sort(compareBySort(sort));
  }, [items, folderId, tab, needle, filters, kindFilter, settings.suggestedLimit, sort]);

  // Only grid cards can pause a clip: stop it once its card is gone or the list view replaces them.
  useEffect(() => {
    if (view !== "grid") stopLibraryAudio();
    else stopLibraryAudioUnlessShown(new Set(visibleItems.map((item) => item.id)));
  }, [view, visibleItems]);

  const visibleFolders = useMemo(() => {
    const showsFolders = folderId || tab === "folders" || tab === "all";
    if (!showsFolders || (filtersActive(filters) && tab !== "folders")) return [];
    return folders
      .filter((folder) => folder.parentId === folderId)
      .filter((folder) => nameMatches(folder.name, needle))
      .sort(compareBySort(sort.key === "size" ? { key: "name", desc: false } : sort));
  }, [folders, folderId, tab, needle, filters, sort]);

  // Folders then items, the order both views show them in: grid's masonry deals cards across
  // columns row by row, so this is also left to right, top to bottom there.
  const orderedKeys = useMemo(
    () => [
      ...visibleFolders.map((folder) => `folder:${folder.id}`),
      ...visibleItems.map((item) => `item:${item.id}`),
    ],
    [visibleFolders, visibleItems],
  );
  // A search, filter or Content setting that hides a selected entry deselects it, so bulk actions
  // only ever act on what is on screen and clearing the filter never brings a selection back.
  const visibleKeys = useMemo(() => new Set(orderedKeys), [orderedKeys]);
  if ([...selection].some((key) => !visibleKeys.has(key))) {
    setSelectionState(new Set([...selection].filter((key) => visibleKeys.has(key))));
  }
  // A hidden anchor goes too: else clearing the search brings it back, and the next shift click
  // reaches from an entry the selection already lost.
  useEffect(() => {
    if (selectionAnchor.current && !visibleKeys.has(selectionAnchor.current)) {
      selectionAnchor.current = null;
    }
  }, [visibleKeys]);

  const previewItem = search.item ? (items.find((item) => item.id === search.item) ?? null) : null;
  const previewId = previewItem?.id ?? null;
  useEffect(() => {
    if (previewId) markOpened(previewId);
  }, [previewId, markOpened]);

  const router = useRouter();
  const pushedPreview = useRef<string | null>(null);
  const [closingPreview, setClosingPreview] = useState<string | null>(null);
  if (!search.item && closingPreview !== null) setClosingPreview(null);
  useEffect(() => {
    if (!search.item) pushedPreview.current = null;
  }, [search.item]);
  const openPreview = (id: string) => {
    pushedPreview.current = id;
    go({ ...search, item: id });
  };
  // Another clip of the same run, in place of this one: Back still closes the preview.
  const switchPreview = (id: string) => {
    if (pushedPreview.current === search.item) pushedPreview.current = id;
    go({ ...search, item: id }, true);
  };
  const previewRun = useMemo(
    () => (previewItem ? runSiblings(items, previewItem) : []),
    [items, previewItem],
  );
  const closePreview = () => {
    if (!search.item) return;
    setClosingPreview(search.item);
    if (pushedPreview.current === search.item) {
      pushedPreview.current = null;
      router.history.back();
    } else {
      go({ ...search, item: undefined }, true);
    }
  };

  const missingItem =
    search.item && status === "ready" && !previewItem && closingPreview !== search.item
      ? search.item
      : null;
  useEffect(() => {
    if (!missingItem) return;
    let cancelled = false;
    void refresh().then(() => {
      if (cancelled) return;
      if (useLibraryStore.getState().items.some((item) => item.id === missingItem)) return;
      toast(t("library.toast.missingItem"));
      void navigate({
        to: "/library",
        search: (prev) => ({ ...prev, item: undefined }),
        replace: true,
      });
    });
    return () => {
      cancelled = true;
    };
  }, [missingItem, refresh, navigate, t]);


  const fail = (message: string) => (err: unknown) =>
    toast.error(message, { description: errorMessage(err) });

  const filesInFolder = (id: string) => {
    const inside = new Set([id]);
    for (let grew = true; grew; ) {
      grew = false;
      for (const folder of folders) {
        if (folder.parentId && inside.has(folder.parentId) && !inside.has(folder.id)) {
          inside.add(folder.id);
          grew = true;
        }
      }
    }
    return items.filter(
      (item) => item.folderId !== null && inside.has(item.folderId) && isFileItem(item),
    );
  };

  const chatAbout = (item: LibraryItem) =>
    void (item.model ? chatWithModel(navigate, item) : chatAboutItems(navigate, [item]));

  const moveAll = async (targets: LibraryTarget[], destination: string | null) => {
    const folder = destination
      ? (folderById.get(destination)?.name ?? t("library.toast.folderFallback"))
      : null;
    const results = await Promise.allSettled(
      targets.map((target) =>
        target.kind === "item"
          ? patchItem(target.item.id, { folderId: destination })
          : patchFolder(target.folder.id, { parentId: destination }),
      ),
    );
    const failed = results.find((result) => result.status === "rejected");
    if (failed) fail(t("library.toast.moveFailed"))(failed.reason);
    else if (folder === null) toast.success(t("library.toast.movedToLibrary"));
    else toast.success(t("library.toast.movedToFolder", { folder }));
  };

  const actions: LibraryActions = {
    folders,
    openItem: (item) => openPreview(item.id),
    openFolder: (id) => go({ folder: id }),
    chatAbout: (target) =>
      target.kind === "item"
        ? chatAbout(target.item)
        : void chatAboutItems(navigate, filesInFolder(target.folder.id)),
    editImage: (item) => void editLibraryImage(navigate, item),
    toggleFavorite: (item) =>
      void patchItem(item.id, { favorite: !item.favorite }).catch(fail(t("library.toast.favoritesFailed"))),
    download: (item) => void downloadLibraryItem(item),
    rename: (target) => setNameDialog({ mode: "rename", target }),
    moveTo: (target, destination) => void moveAll([target], destination),
    moveToNewFolder: (target) =>
      setNameDialog({ mode: "create", parentId: folderId, thenMove: target }),
    remove: (target) => requestDelete([target]),
  };

  async function uploadBatch(batch: LibraryUploadBatch, count: number, label: string) {
    if (count === 0) return;
    const id = toast.loading(
      count === 1
        ? t("library.toast.uploadingOne", { name: label })
        : t("library.toast.uploadingMany", { count }),
    );
    try {
      await upload(batch, folderId);
      toast.success(
        count === 1 ? t("library.toast.uploadedOne") : t("library.toast.uploadedMany", { count }),
        { id },
      );
    } catch (err) {
      toast.error(t("library.toast.uploadFailed"), { id, description: errorMessage(err) });
    }
  }

  const uploadFiles = (files: File[]) =>
    uploadBatch({ files }, files.length, files[0]?.name ?? "");

  async function uploadNativeDrops(intents: NativeIntent[]) {
    // The grants belong to the signed-in account; another who signs in must not upload them.
    const sessionEpoch = getAuthSessionEpoch();
    try {
      const leases = await Promise.all(
        intents.map((intent) => consumeNativePathToken(intent.path.token, "attach")),
      );
      await uploadBatch(
        { nativePathLeases: leases.map((lease) => lease.nativePathLease), sessionEpoch },
        leases.length,
        leases[0]?.displayLabel ?? "",
      );
    } catch (err) {
      fail(t("library.toast.readDropsFailed"))(err);
    }
  }

  const { ref: dropRef, dragging, dragHandlers } = useNativeFileDrop({
    onFiles: uploadFiles,
    onNativeIntents: uploadNativeDrops,
  });

  async function createNote() {
    try {
      const note = new File([""], `${t("library.create.untitledNote")}.md`, {
        type: "text/markdown",
      });
      const [id] = await upload({ files: [note] }, folderId);
      if (id) openPreview(id);
    } catch (err) {
      fail(t("library.toast.createNoteFailed"))(err);
    }
  }

  function handleNew(action: NewAction) {
    switch (action) {
      case "note":
        void createNote();
        break;
      case "image":
        void navigate({ to: "/images" });
        break;
      case "video":
        void navigate({ to: "/video" });
        break;
      case "audio":
        void navigate({ to: "/audio", search: { task: "text-to-speech" } });
        break;
      case "model":
        void navigate({ to: "/studio" });
        break;
      case "folder":
        setNameDialog({ mode: "create", parentId: folderId });
        break;
      case "upload":
        fileInput.current?.click();
        break;
    }
  }

  async function submitName(name: string) {
    if (!nameDialog) return;
    try {
      if (nameDialog.mode === "rename") {
        const { target } = nameDialog;
        if (target.kind === "item") await patchItem(target.item.id, { name });
        else await patchFolder(target.folder.id, { name });
        return;
      }
      const folder = await addFolder(name, nameDialog.parentId);
      if (nameDialog.thenMove) await moveAll([nameDialog.thenMove], folder.id);
    } catch (err) {
      const renaming = nameDialog.mode === "rename";
      fail(t(renaming ? "library.toast.renameFailed" : "library.toast.createFolderFailed"))(err);
      throw err;
    }
  }

  const requestDelete = (targets: LibraryTarget[]) =>
    settings.confirmDelete ? setPendingDelete(targets) : void confirmDelete(targets);

  async function confirmDelete(targets: LibraryTarget[]) {
    setPendingDelete(null);
    setSelection(new Set());
    if (targets.some((t) => t.kind === "item" && t.item.id === search.item)) closePreview();
    const results = await Promise.allSettled(
      targets.map((target) =>
        target.kind === "item"
          ? removeItem(target.item.id, target.item.fingerprint)
          : removeFolder(target.folder.id),
      ),
    );
    const failed = results.find((result) => result.status === "rejected");
    if (failed) fail(t("library.toast.deleteFailed"))(failed.reason);
    if (folderId && targets.some((t) => t.kind === "folder" && t.folder.id === folderId)) {
      go({ folder: currentFolder?.parentId ?? undefined, show: "folders" }, true);
    }
  }

  const deleteCopy = (targets: LibraryTarget[]) => {
    if (targets.length > 1) {
      return {
        title: t("library.dialog.deleteManyTitle", { count: targets.length }),
        description: t("library.dialog.deleteManyDescription"),
      };
    }
    const target = targets[0]!;
    if (target.kind === "folder") {
      const parent = target.folder.parentId ? folderById.get(target.folder.parentId) : null;
      return {
        title: t("library.dialog.deleteTitle", { name: target.folder.name }),
        description: parent
          ? t("library.dialog.deleteFolderIntoParent", { folder: parent.name })
          : t("library.dialog.deleteFolderIntoLibrary"),
      };
    }
    const source = target.item.id.split(":", 1)[0]!;
    return {
      title: t("library.dialog.deleteTitle", { name: target.item.name }),
      description: t(DELETE_NOTES[source] ?? "library.dialog.deleteUpload"),
    };
  };

  // A shift click sets the whole range to the clicked entry's new state, as in Chats.
  const toggleSelected = (key: string, range = false) => {
    const anchor = selectionAnchor.current;
    const keys = range && anchor ? rangeBetween(orderedKeys, anchor, key) : [key];
    const on = !selection.has(key);
    const next = new Set(selection);
    for (const each of keys) {
      if (on) next.add(each);
      else next.delete(each);
    }
    setSelectionState(next);
    selectionAnchor.current = next.size > 0 ? key : null;
  };
  const selectAll = () => setSelection(new Set(orderedKeys));
  const selectionBar = useRef<HTMLDivElement>(null);

  const cardSelection = { selection, toggle: toggleSelected };

  // Chats return their own view below, which has its own select all and Escape.
  const showsChats = tab === "chats" && !folderId;
  const selecting = selection.size > 0;
  // Cmd/Ctrl+A selects everything shown and Escape clears it, outside text fields. Both stand down
  // while a menu or dialog (the preview among them) is open, since the selection is behind it.
  // Passive on Escape, as Chats is: a menu closing on it has already prevented the default.
  useEffect(() => {
    if (showsChats || (!selecting && orderedKeys.length === 0)) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.defaultPrevented) return;
      const target = event.target;
      if (target instanceof HTMLElement && target.closest("input, textarea, select, [contenteditable]")) {
        return;
      }
      if (document.querySelector('[role="menu"], [role="dialog"], [role="alertdialog"]')) return;
      const mod = isMacPlatform() ? event.metaKey : event.ctrlKey;
      // By the letter typed, or by the key's position on a layout that types no Latin letter.
      const isA = /^[a-z]$/i.test(event.key) ? event.key.toLowerCase() === "a" : event.code === "KeyA";
      if (mod && !event.altKey && !event.shiftKey && isA) {
        if (orderedKeys.length === 0) return;
        event.preventDefault();
        setSelection(new Set(orderedKeys));
      } else if (event.key === "Escape" && selecting) {
        if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
        setSelection(new Set());
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [showsChats, selecting, orderedKeys, setSelection]);

  const selectedTargets = (): LibraryTarget[] => {
    const out: LibraryTarget[] = [];
    for (const folder of visibleFolders)
      if (selection.has(`folder:${folder.id}`)) out.push({ kind: "folder", folder });
    for (const item of visibleItems)
      if (selection.has(`item:${item.id}`)) out.push({ kind: "item", item });
    return out;
  };

  const bulkDestinations = () =>
    folders.filter((folder) => {
      for (let at: LibraryFolder | undefined = folder; at; at = at.parentId ? folderById.get(at.parentId) : undefined)
        if (selection.has(`folder:${at.id}`)) return false;
      return true;
    });


  const breadcrumb: LibraryFolder[] = [];
  for (let at = currentFolder; at; at = at.parentId ? (folderById.get(at.parentId) ?? null) : null) {
    breadcrumb.unshift(at);
    if (breadcrumb.length > 32) break;
  }

  const title = folderId ? (
    <nav className="flex min-w-0 items-center gap-2 text-[calc(1.6875rem*var(--ui-font-scale,1))] font-semibold tracking-[-0.028em]" aria-label={t("library.breadcrumb")}>
      <button
        type="button"
        onClick={() => go({ show: "folders" })}
        className="shrink-0 text-muted-foreground transition-colors hover:text-foreground"
      >
        {t("shell.navigation.library")}
      </button>
      {breadcrumb.map((folder, index) => (
        <span key={folder.id} className="flex min-w-0 items-center gap-2">
          <HugeiconsIcon icon={ChevronRightStandardIcon} strokeWidth={2} className="size-5 shrink-0 text-muted-foreground" />
          {index === breadcrumb.length - 1 ? (
            <span className="truncate text-foreground">{folder.name}</span>
          ) : (
            <button
              type="button"
              onClick={() => go({ folder: folder.id })}
              className="truncate text-muted-foreground transition-colors hover:text-foreground"
            >
              {folder.name}
            </button>
          )}
        </span>
      ))}
    </nav>
  ) : (
    // truncate clips at the padding box, which the y overhangs; the margins give it back.
    <h1 className="-my-[0.15em] min-w-0 truncate py-[0.15em] pr-[0.08em] text-[calc(1.6875rem*var(--ui-font-scale,1))] font-semibold leading-[1.04] tracking-[-0.028em] text-foreground">
      {t("shell.navigation.library")}
    </h1>
  );


  const uploadButton = (
    <Button variant="muted" className="rounded-full" onClick={() => fileInput.current?.click()}>
      {t("library.empty.uploadFiles")}
    </Button>
  );

  function renderCards() {
    const itemsGrid = visibleItems.length > 0 && (
      <Masonry
        items={visibleItems}
        getKey={(item) => item.id}
        render={(item) => <ItemCard item={item} />}
      />
    );
    if (folderId || tab === "all") {
      const sectioned = !folderId;
      return (
        <>
          {visibleFolders.length > 0 && (
            <>
              {sectioned && <SectionHeading>{t("library.tabs.folders")}</SectionHeading>}
              <div className={cn(!sectioned && "mt-6")}>
                <FolderGrid folders={visibleFolders} counts={counts} />
              </div>
            </>
          )}
          {visibleItems.length > 0 && (
            <>
              {sectioned ? (
                <SectionHeading>{t("library.sections.items")}</SectionHeading>
              ) : (
                <div className="mt-6" />
              )}
              {itemsGrid}
            </>
          )}
        </>
      );
    }
    if (tab === "folders") {
      return (
        <div className="mt-6">
          <FolderGrid folders={visibleFolders} counts={counts} />
        </div>
      );
    }
    return <div className="mt-6">{itemsGrid}</div>;
  }

  function emptyAction(): ReactNode {
    if (tab === "favorites") return undefined;
    if (tab === "folders") {
      return (
        <Button
          variant="muted"
          className="rounded-full"
          onClick={() => setNameDialog({ mode: "create", parentId: null })}
        >
          {t("library.empty.createFolder")}
        </Button>
      );
    }
    if (!(tab in EMPTY_LINKS)) return uploadButton;
    const [to, label] = EMPTY_LINKS[tab as keyof typeof EMPTY_LINKS];
    const generate = (
      <Button variant="muted" className="rounded-full" onClick={() => void navigate({ to })}>
        {t(label)}
      </Button>
    );
    if (tab === "images" || tab === "videos") {
      return (
        <div className="flex flex-wrap items-center justify-center gap-2">
          {uploadButton}
          {generate}
        </div>
      );
    }
    return generate;
  }

  function renderFavorites() {
    return (
      <ChatsLibrary
        search={{}}
        embedded={{
          query,
          view,
          render: (entries) =>
            view === "list" ? (
              <div className="mt-6">
                <LibraryList
                  folders={[]}
                  items={visibleItems}
                  counts={counts}
                  selection={selection}
                  onSelectionChange={setSelection}
                  onToggle={toggleSelected}
                  sort={sort}
                  onSortChange={(key) => go({ ...search, sort: sortParam(nextSort(sort, key)) }, true)}
                  activity={false}
                  leading={entries.rows}
                  favoriteMarks={false}
                />
              </div>
            ) : (
              <div className="mt-6">
                <CardSelectionContext.Provider value={cardSelection}>
                  <Masonry
                    items={[
                      ...entries.cards,
                      ...visibleItems.map((item) => ({ key: item.id, node: <ItemCard item={item} /> })),
                    ]}
                    getKey={(entry) => entry.key}
                    render={(entry) => entry.node}
                  />
                </CardSelectionContext.Provider>
              </div>
            ),
        }}
      />
    );
  }

  function renderBody() {
    if (status === "loading" || status === "idle") return <LoadingGrid />;
    if (status === "error") {
      return (
        <EmptyState
          icon={Folder01Icon}
          title={t("library.empty.loadErrorTitle")}
          description={error ?? t("library.empty.loadErrorFallback")}
          action={
            <Button variant="muted" className="rounded-full" onClick={() => void refresh()}>
              {t("library.empty.tryAgain")}
            </Button>
          }
        />
      );
    }
    const empty = visibleItems.length === 0 && visibleFolders.length === 0;
    const narrowed = Boolean(needle) || filtersActive(filters);
    if (favoriteChats > 0) return renderFavorites();
    if (empty && narrowed) {
      return (
        <EmptyState
          icon={Folder01Icon}
          title={t("library.empty.noMatchesTitle")}
          description={t("library.empty.noMatchesDescription")}
        />
      );
    }
    if (empty && folderId) {
      return (
        <div className="mt-6 flex min-h-[calc(420px*var(--ui-space-scale,1))] flex-col items-center justify-center gap-5 rounded-2xl border border-dashed border-border bg-muted/50">
          <HugeiconsIcon icon={Upload01Icon} strokeWidth={1.5} className="size-8" />
          {uploadButton}
          <p className="text-sm text-muted-foreground">{t("library.empty.dropHere")}</p>
        </div>
      );
    }
    if (empty) {
      const [emptyIcon, emptyTitle, emptyDescription] = EMPTY_COPY[tab];
      return (
        <EmptyState
          icon={emptyIcon}
          title={t(emptyTitle)}
          description={t(emptyDescription)}
          action={emptyAction()}
        />
      );
    }
    if (view === "list") {
      return (
        <div className="mt-6">
          <LibraryList
            folders={visibleFolders}
            items={visibleItems}
            counts={counts}
            selection={selection}
            onSelectionChange={setSelection}
            onToggle={toggleSelected}
            sort={sort}
            onSortChange={(key) => go({ ...search, sort: sortParam(nextSort(sort, key)) }, true)}
            activity={tab === "suggested" && !folderId}
            favoriteMarks={tab !== "favorites"}
          />
        </div>
      );
    }
    return (
      <CardSelectionContext.Provider value={cardSelection}>{renderCards()}</CardSelectionContext.Provider>
    );
  }

  const nameDialogProps =
    nameDialog?.mode === "rename"
      ? {
          title: t(
            nameDialog.target.kind === "folder"
              ? "library.dialog.renameFolder"
              : "library.dialog.renameFile",
          ),
          submitLabel: t("common.rename"),
          initialValue:
            nameDialog.target.kind === "item" ? nameDialog.target.item.name : nameDialog.target.folder.name,
        }
      : {
          title: t("library.menu.newFolder"),
          submitLabel: t("library.dialog.create"),
          initialValue: "",
        };

  const selectedCount = selection.size;
  const selectedFiles = () => {
    const out = new Map<string, LibraryItem>();
    for (const target of selectedTargets()) {
      const files =
        target.kind === "item"
          ? [target.item].filter(isFileItem)
          : filesInFolder(target.folder.id);
      for (const file of files) out.set(file.id, file);
    }
    return [...out.values()];
  };
  const selectedModel = () => {
    const targets = selectedTargets();
    const only = targets.length === 1 ? targets[0] : undefined;
    return only?.kind === "item" && isModelItem(only.item) ? only.item : null;
  };
  const bulkChat = () => {
    const model = selectedModel();
    if (model) chatAbout(model);
    else void chatAboutItems(navigate, selectedFiles());
    setSelection(new Set());
  };
  const bulkDownload = () => {
    const files = selectedFiles();
    setSelection(new Set());
    void downloadLibraryItems(files);
  };
  const bulkMove = (destination: string | null) => {
    void moveAll(selectedTargets(), destination);
    setSelection(new Set());
  };
  const deletableSelection = () =>
    selectedTargets().filter((t) => t.kind === "folder" || isDeletable(t.item));
  const deleteText = pendingDelete ? deleteCopy(pendingDelete) : null;

  const headerTabs = {
    items: shownTabs.map((key) => ({ key, label: t(TAB_LABELS[key]) })),
    active: tab,
    onChange: (next: string) => go({ show: next as LibraryTab }),
  };

  if (tab === "chats" && !folderId) {
    return <ChatsLibrary search={search} title={title} tabs={headerTabs} />;
  }

  return (
    <LibraryActionsProvider value={actions}>
      <main
        ref={dropRef}
        {...dragHandlers}
        className="relative mx-auto w-full max-w-[calc(1560px*var(--ui-space-scale,1))] px-6 pb-24 pt-8 font-heading sm:px-10"
      >
        <input
          ref={fileInput}
          type="file"
          multiple
          hidden
          onChange={(event) => {
            void uploadFiles([...(event.target.files ?? [])]);
            event.target.value = "";
          }}
        />
        <LibraryHeader
          title={title}
          controls={
            <LibraryToolbar
              filters={filters}
              onFiltersChange={setFilters}
              filterMode={filterMode}
              workflows={workflowOptions}
              view={view}
              onViewChange={setView}
              sort={view === "grid" && (folderId || tab !== "favorites") ? gridSort : undefined}
              search={query}
              onSearchChange={setQuery}
              searchPlaceholder={t(folderId ? "library.searchFolder" : "library.searchLibrary")}
              onNew={handleNew}
              onSettings={() => openSettings("library")}
            />
          }
          tabs={folderId ? null : headerTabs}
        />
        <div className="pl-3">{renderBody()}</div>

        {dragging && (
          <div className="pointer-events-none fixed inset-0 z-40 flex items-center justify-center bg-background/70 backdrop-blur-sm">
            <div className="flex flex-col items-center gap-3 rounded-2xl border-2 border-dashed border-muted-foreground px-16 py-12">
              <HugeiconsIcon icon={Upload01Icon} strokeWidth={1.5} className="size-8" />
              <p className="font-medium text-lg">
                {currentFolder
                  ? t("library.dropToUploadInto", { folder: currentFolder.name })
                  : t("library.dropToUpload")}
              </p>
            </div>
          </div>
        )}

        {selectedCount > 0 && (
          // Sized to its pills, and scrolls sideways rather than squashing them in a narrow window.
          <div
            ref={selectionBar}
            role="toolbar"
            aria-label={t("library.selection.countOfTotal", { count: selectedCount, total: orderedKeys.length })}
            tabIndex={-1}
            className="fixed bottom-8 left-1/2 z-30 flex w-max max-w-[calc(100vw-2rem)] -translate-x-1/2 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden [&>*]:shrink-0 items-center gap-2 rounded-full bg-sidebar py-2 pl-6 pr-2 text-sidebar-foreground shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] outline-none focus-visible:ring-2 focus-visible:ring-ring dark:shadow-[0_8px_28px_-6px_var(--background)]"
          >
            <span className="mr-4 flex items-center whitespace-nowrap text-sm font-medium">
              <span aria-live="polite">
                {t("library.selection.countOfTotal", { count: selectedCount, total: orderedKeys.length })}
              </span>
              {selectedCount < orderedKeys.length && (
                <>
                  <span aria-hidden className="mx-2 text-muted-foreground">
                    ·
                  </span>
                  <button
                    type="button"
                    // The link goes once everything is selected, so focus moves to the bar first.
                    onClick={() => {
                      selectAll();
                      selectionBar.current?.focus();
                    }}
                    className="rounded-full underline decoration-muted-foreground underline-offset-[3px] outline-none transition-colors hover:decoration-current focus-visible:ring-2 focus-visible:ring-ring"
                  >
                    {t("library.selection.selectAll")}
                  </button>
                </>
              )}
            </span>
            <button
              type="button"
              disabled={selectedModel() === null && selectedFiles().length === 0}
              onClick={bulkChat}
              className={cn(BAR_PILL, "bg-action text-background transition-opacity hover:opacity-85")}
            >
              <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-4" />
              {t("library.selection.startChat")}
            </button>
            <button
              type="button"
              disabled={selectedFiles().length === 0}
              onClick={bulkDownload}
              className={cn(
                BAR_PILL,
                "btn-fill transition-colors ",
              )}
            >
              <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-4" />
              {t("library.menu.download")}
            </button>
            <button
              type="button"
              disabled={deletableSelection().length === 0}
              onClick={() => requestDelete(deletableSelection())}
              className={cn(
                BAR_PILL,
                "bg-destructive/10 text-destructive transition-colors hover:bg-destructive/15",
              )}
            >
              <HugeiconsIcon icon={TrashIcon} strokeWidth={1.75} className="size-4" />
              {t("common.delete")}
            </button>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button
                  type="button"
                  aria-label={t("library.menu.moreActions")}
                  className={cn(BAR_ROUND, "data-[state=open]:bg-sidebar-accent")}
                >
                  <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-5" />
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="center" side="top" className="library-menu w-48">
                <DropdownMenuSub>
                  <DropdownMenuSubTrigger className="gap-2.5">
                    <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />
                    {t("library.selection.move")}
                  </DropdownMenuSubTrigger>
                  <DropdownMenuSubContent className="library-menu max-h-[min(--spacing(80),var(--radix-dropdown-menu-content-available-height))] w-56">
                    <DropdownMenuItem onSelect={() => bulkMove(null)}>
                      <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
                      {t("library.menu.noFolder")}
                    </DropdownMenuItem>
                    {bulkDestinations().map((folder) => (
                      <DropdownMenuItem key={folder.id} onSelect={() => bulkMove(folder.id)}>
                        <HugeiconsIcon icon={FolderClosedIcon} strokeWidth={1.75} className="size-icon" />
                        <span className="truncate">{folder.name}</span>
                      </DropdownMenuItem>
                    ))}
                  </DropdownMenuSubContent>
                </DropdownMenuSub>
              </DropdownMenuContent>
            </DropdownMenu>
            <button
              type="button"
              aria-label={t("library.selection.clear")}
              onClick={() => setSelection(new Set())}
              className={BAR_ROUND}
            >
              <HugeiconsIcon icon={Cancel01Icon} strokeWidth={1.75} className="size-5" />
            </button>
          </div>
        )}
      </main>

      <NameDialog
        open={nameDialog !== null}
        {...nameDialogProps}
        onSubmit={submitName}
        onOpenChange={(open) => !open && setNameDialog(null)}
      />
      <ConfirmDeleteDialog
        open={pendingDelete !== null}
        title={deleteText?.title ?? ""}
        description={deleteText?.description ?? ""}
        confirmLabel={t("common.delete")}
        onConfirm={() => pendingDelete && void confirmDelete(pendingDelete)}
        onOpenChange={(open) => !open && setPendingDelete(null)}
      />
      <LibraryPreview
        item={previewItem}
        onOpenChange={(open) => !open && closePreview()}
        onChat={chatAbout}
        onDownload={(item) => void downloadLibraryItem(item)}
        onToggleFavorite={actions.toggleFavorite}
        onDelete={(item) => actions.remove({ kind: "item", item })}
        onSaved={() => void refresh()}
        run={previewRun}
        onOpenItem={switchPreview}
        onDownloadRun={(run) => void downloadLibraryItems(run)}
      />
    </LibraryActionsProvider>
  );
}