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.

44.1 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 { useIsAccountOwner } from "@/features/auth";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { usePlatformStore } from "@/config/env";
import {
  type FineTuneFormat,
  archiveAllChatItems,
  BulkExportItems,
  bulkExportConversationsByScope,
  clearAllChats,
  countAllChats,
  DeleteChatFilesSwitch,
  downloadArchivedChatExport,
  downloadChatExport,
  exportFineTuneJsonl,
  importConversationsFromSource,
  nativeImportSource,
  fileImportSource,
  type ImportSource,
  notifyChatProjectsUpdated,
  offerToDeleteKeptSandboxes,
  useChatPreferencesStore,
  useChatRuntimeStore,
  useChatSidebarItems,
} from "@/features/chat";
import {
  LibraryStorageBar,
  STORAGE_LABELS,
  formatSize,
  refreshLibraryStorage,
  useLibraryStorage,
  useLibraryVisitStore,
} from "@/features/library";
import {
  LinkedFoldersManager,
  listKnowledgeBases,
  useRagAvailabilityStore,
} from "@/features/rag";
import { useLocale, useT } from "@/i18n";

import { isTauri } from "@/lib/api-base";
import {
  ChevronDownStandardIcon,
  ChevronLeftStandardIcon,
  ChevronRightStandardIcon,
} from "@/lib/chevron-icons";
import { isDownloadCancelled, pickNativeChatImport } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import {
  ArchiveIcon,
  Download01Icon,
  FlimSlateIcon,
  ImageIcon,
  LibrariesIcon,
} from "@hugeicons/core-free-icons";
import { AiSpeechIcon, MessageCircleIcon, TrashIcon } from "@/lib/hugeicons-derived";
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import {
  EXTERNAL_IMPORT_LABELS,
  EXTERNAL_IMPORT_SOURCES,
  type ExternalImportSource,
  type ExternalImportStatus,
  importExternalChats,
  loadExternalImportStatus,
} from "../api/external-import";
import { ArchivedChatsView } from "../components/archived-chats-dialog";
import {
  type ArchivedMediaKind,
  ArchivedMediaView,
} from "../components/archived-media-dialog";
import { DocumentsRagSection } from "../components/documents-rag-section";
import { ReembedDocumentsRow } from "../components/reembed-documents-row";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
import { UploadedFilesView } from "../components/uploaded-files-dialog";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import {
  type FineTuneAction,
  useSettingsPanelPrefsStore,
} from "../stores/settings-panel-prefs-store";
import { Tick02Icon } from "@/lib/tick-icon";

// Display order, and the guard against a persisted action this build dropped.
const FINE_TUNE_ACTIONS: FineTuneAction[] = ["export", "train", "recipes"];

function LibraryDataSection() {
  const t = useT();
  const locale = useLocale();
  const openDialog = useSettingsDialogStore((s) => s.openDialog);
  const storage = useLibraryStorage();
  const count = storage.categories.reduce((sum, entry) => sum + entry.count, 0);
  const size = (bytes: number) => formatSize(bytes, locale, t) ?? "";
  const largest = storage.categories
    .slice(0, 3)
    .map((entry) => `${t(STORAGE_LABELS[entry.category])} ${size(entry.bytes)}`)
    .join(" · ");

  let summary: string;
  if (storage.status === "loading") summary = "";
  else if (storage.status === "error") summary = t("settings.library.storageError");
  else if (storage.totalBytes === 0 && count === 0) summary = t("settings.library.storageEmpty");
  else {
    summary = [
      t("settings.library.storageUsed", { size: size(storage.totalBytes) }),
      count === 1
        ? t("settings.library.itemCountOne")
        : count > 0 && t("settings.library.itemCount", { count: count.toLocaleString() }),
      storage.hiddenBytes > 0 && t("settings.library.storageHidden", { size: size(storage.hiddenBytes) }),
    ]
      .filter(Boolean)
      .join(" · ");
  }

  return (
    <SettingsSection title={t("shell.navigation.library")}>
      <SettingsRow
        label={t("settings.library.dataStorage")}
        description={summary || "\u00a0"}
      >
        <Button
          variant="outline"
          size="sm"
          onClick={() => openDialog("library", { scrollTarget: "library-storage" })}
        >
          {t("settings.library.manageStorage")}
          <HugeiconsIcon icon={ChevronRightStandardIcon} className="size-3.5" />
        </Button>
      </SettingsRow>
      {storage.status === "ready" && (count > 0 || storage.totalBytes > 0) && (
        <div className="flex flex-col gap-2 pb-3">
          <LibraryStorageBar libraryBytes={storage.diskBytes} disk={storage.disk} />
          {largest && <p className="text-xs text-muted-foreground">{largest}</p>}
        </div>
      )}
    </SettingsSection>
  );
}

const SUBPAGE_FOR_SHELF = {
  chats: "archived",
  images: "archived-images",
  videos: "archived-videos",
  audio: "archived-audio",
} as const;

export function DataTab({ searchEntry }: { searchEntry?: string }) {
  const t = useT();
  const isOwner = useIsAccountOwner();
  const navigate = useNavigate();
  const archivedRequested = useSettingsDialogStore((s) => s.archivedRequested);
  const consumeArchivedChatsRequest = useSettingsDialogStore(
    (s) => s.consumeArchivedChatsRequest,
  );
  const [confirmOpen, setConfirmOpen] = useState(false);
  // Preselected from the preference but can be turned off for this one clear.
  const [deleteFilesOnClear, setDeleteFilesOnClear] = useState(false);
  const [archiveConfirmOpen, setArchiveConfirmOpen] = useState(false);
  const [subpage, setSubpage] = useState<
    | "main"
    | "archived"
    | "archived-images"
    | "archived-videos"
    | "archived-audio"
    | "files"
  >(
    searchEntry
      ? "main"
      : archivedRequested ? SUBPAGE_FOR_SHELF[archivedRequested] : "main",
  );
  const [count, setCount] = useState<number | null>(null);
  const [exporting, setExporting] = useState(false);
  const [archivedExporting, setArchivedExporting] = useState(false);
  const { archivedItems } = useChatSidebarItems({
    requireMessages: false,
    enabled: subpage === "archived",
  });
  const [clearing, setClearing] = useState(false);
  const [archiving, setArchiving] = useState(false);
  // A source's row appears only once its probe reports conversations.
  const [externalStatus, setExternalStatus] = useState<
    Partial<Record<ExternalImportSource, ExternalImportStatus>>
  >({});
  const [externalImporting, setExternalImporting] =
    useState<ExternalImportSource | null>(null);
  const [fineTuneExporting, setFineTuneExporting] = useState(false);
  const [openingRecipe, setOpeningRecipe] = useState(false);
  const [loadingTraining, setLoadingTraining] = useState(false);
  // Hosts that cannot train redirect /studio, so a Train-tab load would strand the user.
  const trainUnavailable = usePlatformStore(
    (s) => s.isTrainUnavailable() && !s.capabilitiesUnknown(),
  );
  const ragUnavailable = useRagAvailabilityStore((s) => s.isUnavailable());
  const ragAvailabilityUnknown = useRagAvailabilityStore((s) =>
    s.availabilityUnknown(),
  );
  const storedFineTuneAction = useSettingsPanelPrefsStore(
    (s) => s.fineTuneAction,
  );
  const setFineTuneAction = useSettingsPanelPrefsStore(
    (s) => s.setFineTuneAction,
  );
  const restoredAction = FINE_TUNE_ACTIONS.includes(storedFineTuneAction)
    ? storedFineTuneAction
    : "export";
  // derived, not corrected: a stored "train" returns when Train becomes available.
  const fineTuneAction =
    trainUnavailable && restoredAction === "train" ? "export" : restoredAction;
  const fineTuneFormat: FineTuneFormat = "openai";
  // Search needs the main-page anchors even when a subpage is open.
  useEffect(() => {
    const next = searchEntry
      ? "main"
      : archivedRequested
        ? SUBPAGE_FOR_SHELF[archivedRequested]
        : null;
    if (!next) return;
    let cancelled = false;
    queueMicrotask(() => {
      if (cancelled) return;
      setSubpage(next);
      consumeArchivedChatsRequest();
    });
    return () => {
      cancelled = true;
    };
  }, [archivedRequested, searchEntry, consumeArchivedChatsRequest]);

  useEffect(() => {
    if (!ragAvailabilityUnknown) return;
    let cancelled = false;
    let retryTimer: number | undefined;
    let retryDelayMs = 1_000;

    const probeAvailability = async () => {
      try {
        await listKnowledgeBases();
      } catch {
        if (cancelled) return;
        retryTimer = window.setTimeout(() => {
          retryDelayMs = Math.min(retryDelayMs * 2, 30_000);
          void probeAvailability();
        }, retryDelayMs);
      }
    };

    void probeAvailability();
    return () => {
      cancelled = true;
      if (retryTimer !== undefined) window.clearTimeout(retryTimer);
    };
  }, [ragAvailabilityUnknown]);

  const confirmDeleteChats = useChatPreferencesStore(
    (state) => state.confirmDeleteChats,
  );
  const alwaysDeleteChatFiles = useChatPreferencesStore(
    (state) => state.alwaysDeleteChatFiles,
  );
  const setAlwaysDeleteChatFiles = useChatPreferencesStore(
    (state) => state.setAlwaysDeleteChatFiles,
  );
  const setConfirmDeleteChats = useChatPreferencesStore(
    (state) => state.setConfirmDeleteChats,
  );

  const storeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
  // Compare panes only live in the search params, as in ArchivedChatsView.
  const openChatId = useRouterState({
    select: (s) => {
      if (!s.location.pathname.startsWith("/chat")) return undefined;
      const search = s.location.search as Record<string, string | undefined>;
      return search.thread ?? search.compare ?? storeThreadId ?? undefined;
    },
  });

  useEffect(() => {
    if (subpage !== "main") return;
    let cancelled = false;
    void countAllChats().then(
      (next) => {
        if (!cancelled) setCount(next);
      },
      (error: unknown) => {
        if (cancelled) return;
        toast.error(t("common.error"), {
          description: error instanceof Error ? error.message : String(error),
        });
      },
    );
    return () => {
      cancelled = true;
    };
  }, [subpage, t]);

  const refreshExternalStatus = (source: ExternalImportSource) =>
    loadExternalImportStatus(source)
      .catch(() => null)
      .then((status) =>
        setExternalStatus((prev) => ({
          ...prev,
          [source]: status?.available ? status : undefined,
        })),
      );

  useEffect(() => {
    for (const source of EXTERNAL_IMPORT_SOURCES) {
      void refreshExternalStatus(source);
    }
  }, []);

  const handleExport = async () => {
    setExporting(true);
    try {
      await downloadChatExport();
    } catch (error) {
      if (!isDownloadCancelled(error)) {
        toast.error(t("settings.data.exportFailed"), {
          description: error instanceof Error ? error.message : String(error),
        });
      }
    } finally {
      setExporting(false);
    }
  };

  const handleExportArchived = async () => {
    setArchivedExporting(true);
    try {
      const exported = await downloadArchivedChatExport();
      toast.success(
        exported === 0
          ? t("settings.data.noArchivedChatsToExport")
          : exported === 1
            ? t("settings.data.exportedOneArchivedChat")
            : t("settings.data.exportedArchivedChatCount", { count: exported }),
      );
    } catch (error) {
      if (!isDownloadCancelled(error)) {
        toast.error(t("settings.data.failedToExportArchivedChats"), {
          description: error instanceof Error ? error.message : undefined,
        });
      }
    } finally {
      setArchivedExporting(false);
    }
  };

  const importInputRef = useRef<HTMLInputElement>(null);
  const [importing, setImporting] = useState(false);
  const handleImport = async (source: ImportSource) => {
    setImporting(true);
    const toastId = toast.loading(
      t("settings.chat.importingChats", { count: 0, percent: 0 }),
    );
    try {
      const { imported, failed } = await importConversationsFromSource(
        source,
        // No destination picker here, so a backup keeps its own projects.
        undefined,
        {
          onProgress: ({ imported: done, bytesRead, totalBytes }) => {
            const percent = totalBytes
              ? Math.min(100, Math.round((bytesRead / totalBytes) * 100))
              : 0;
            toast.loading(
              t("settings.chat.importingChats", { count: done, percent }),
              { id: toastId },
            );
          },
        },
      );
      if (imported === 0 && failed === 0) {
        toast.info(t("settings.chat.importNoConversations"), { id: toastId });
        return;
      }
      if (imported === 0) {
        toast.error(t("settings.chat.importFailed"), {
          id: toastId,
          description: t("settings.chat.importedChatCountPartial", { count: 0, failed }),
        });
        return;
      }
      toast.success(
        failed > 0
          ? t("settings.chat.importedChatCountPartial", { count: imported, failed })
          : imported === 1
            ? t("settings.chat.importedOneChat")
            : t("settings.chat.importedChatCount", { count: imported }),
        { id: toastId },
      );
    } catch (error) {
      toast.error(t("settings.chat.importFailed"), {
        id: toastId,
        description: error instanceof Error ? error.message : undefined,
      });
    } finally {
      setImporting(false);
      // Chats saved before a failed read still changed the count.
      setCount(await countAllChats().catch(() => count));
    }
  };

  const handleImportClick = async () => {
    if (!isTauri) {
      importInputRef.current?.click();
      return;
    }
    try {
      const selected = await pickNativeChatImport();
      if (!selected) {
        return;
      }
      await handleImport(nativeImportSource(selected));
    } catch (error) {
      toast.error(t("settings.chat.importFailed"), {
        description: error instanceof Error ? error.message : String(error),
      });
    }
  };

  const handleExternalImport = async (source: ExternalImportSource) => {
    setExternalImporting(source);
    try {
      const result = await importExternalChats(source);
      notifyChatProjectsUpdated();
      setCount(await countAllChats().catch(() => count));
      await refreshExternalStatus(source);
      const vars = { source: EXTERNAL_IMPORT_LABELS[source] };
      if (result.warnings.length > 0) {
        toast.warning(t("settings.chat.importedSourcePartial", vars), {
          description: result.warnings.join("\n"),
        });
      } else if (result.newChats === 0) {
        toast.success(
          result.messages > 0
            ? t("settings.chat.sourceUpdated", { ...vars, count: result.messages })
            : t("settings.chat.sourceUpToDate", vars),
        );
      } else {
        toast.success(
          result.newChats === 1
            ? t("settings.chat.importedSourceOneChat", vars)
            : t("settings.chat.importedSourceChatCount", {
                ...vars,
                count: result.newChats,
              }),
        );
      }
    } catch (error) {
      toast.error(t("settings.chat.importFailed"), {
        description: error instanceof Error ? error.message : String(error),
      });
    } finally {
      setExternalImporting(null);
    }
  };

  const handleArchiveAll = async () => {
    setArchiving(true);
    try {
      const archived = await archiveAllChatItems(openChatId, (view) => {
        navigate({ to: "/chat", search: { new: view.newThreadNonce } });
      });
      setArchiveConfirmOpen(false);
      toast.success(
        archived === 0
          ? t("settings.data.noChatsToArchive")
          : archived === 1
            ? t("settings.data.archivedOneChat")
            : t("settings.data.archivedChatCount", { count: archived }),
      );
    } catch (error) {
      toast.error(t("settings.data.failedToArchiveChats"), {
        description: error instanceof Error ? error.message : undefined,
      });
    } finally {
      setArchiving(false);
    }
  };

  const handleFineTuneExport = async () => {
    setFineTuneExporting(true);
    try {
      await exportFineTuneJsonl(fineTuneFormat);
    } catch (error) {
      if (!isDownloadCancelled(error)) {
        toast.error(t("settings.data.fineTuneExportFailed"), {
          description: error instanceof Error ? error.message : undefined,
        });
      }
    } finally {
      setFineTuneExporting(false);
    }
  };

  const handleOpenInRecipes = async () => {
    setOpeningRecipe(true);
    try {
      const { createFineTuneRecipeFromChats } = await import(
        "../components/finetune-recipe"
      );
      const recipeId = await createFineTuneRecipeFromChats(fineTuneFormat);
      if (!recipeId) return;
      useSettingsDialogStore.getState().closeDialog();
      void navigate({ to: "/data-recipes/$recipeId", params: { recipeId } });
    } catch (error) {
      toast.error(t("settings.data.fineTuneRecipeFailed"), {
        description: error instanceof Error ? error.message : undefined,
      });
    } finally {
      setOpeningRecipe(false);
    }
  };

  const handleUseInTraining = async () => {
    setLoadingTraining(true);
    try {
      // Deferred so Recipe Studio stays out of the startup bundle; the training store is eager anyway.
      const { loadFineTuneDatasetInTrainTab } = await import(
        "../components/finetune-recipe"
      );
      const loaded = await loadFineTuneDatasetInTrainTab(fineTuneFormat);
      if (!loaded) return;
      useSettingsDialogStore.getState().closeDialog();
      void navigate({ to: "/studio" });
    } catch (error) {
      toast.error(t("settings.data.fineTuneTrainFailed"), {
        description: error instanceof Error ? error.message : undefined,
      });
    } finally {
      setLoadingTraining(false);
    }
  };

  const fineTuneActionLabels = {
    train: t("settings.data.fineTuneTrainAction"),
    recipes: t("settings.data.fineTuneOpenRecipesAction"),
    export: t("settings.data.fineTuneExportAction"),
  } as const;
  const fineTuneBusy = loadingTraining || openingRecipe || fineTuneExporting;
  const runFineTuneAction = () => {
    if (fineTuneAction === "train") {
      if (trainUnavailable) return;
      void handleUseInTraining();
    } else if (fineTuneAction === "recipes") void handleOpenInRecipes();
    else void handleFineTuneExport();
  };

  const openClearConfirmation = (deleteFiles?: boolean) => {
    setDeleteFilesOnClear(deleteFiles ?? alwaysDeleteChatFiles);
    setConfirmOpen(true);
  };

  const handleClear = async () => {
    setClearing(true);
    try {
      const result = await clearAllChats({
        deleteFiles: deleteFilesOnClear,
      });
      refreshLibraryStorage();
      const clearedCount = result.deletedThreadIds.length;
      // After a clear there is no row left to reach a kept sandbox from.
      offerToDeleteKeptSandboxes(result.sandboxesKept);
      const hasFailedStore =
        result.backend === "failed" || result.legacy === "failed";
      if (!hasFailedStore && result.failedThreadIds.length === 0) {
        setCount(0);
        setConfirmOpen(false);
        toast.success(
          clearedCount === 0
            ? t("settings.chat.clearedAllChats")
            : clearedCount === 1
              ? t("settings.chat.clearedOneChat")
              : t("settings.chat.clearedChatCount", { count: clearedCount }),
        );
        return;
      }

      const fallbackRemaining =
        result.failedThreadIds.length > 0
          ? result.failedThreadIds.length
          : (count ?? 0);
      const remaining = await countAllChats().catch(() => fallbackRemaining);
      setCount(remaining);
      setConfirmOpen(false);
      toast.warning(t("settings.chat.someChatsCouldNotBeCleared"), {
        description:
          result.failedThreadIds.length > 0
            ? clearedCount === 1 && result.failedThreadIds.length === 1
              ? t("settings.chat.oneChatClearedRemainOne")
              : clearedCount === 1
                ? t("settings.chat.oneChatClearedRemain", {
                    remainingCount: result.failedThreadIds.length,
                  })
                : result.failedThreadIds.length === 1
                  ? t("settings.chat.chatsClearedRemainOne", { clearedCount })
                  : t("settings.chat.chatsClearedRemain", {
                      clearedCount,
                      remainingCount: result.failedThreadIds.length,
                    })
            : remaining === 1
              ? t("settings.chat.storageClearFailedOne")
              : t("settings.chat.storageClearFailed", { count: remaining }),
      });
    } catch (error) {
      const remaining = await countAllChats().catch(() => count);
      setCount(remaining);
      toast.error(t("settings.chat.failedToClearChats"), {
        description: error instanceof Error ? error.message : undefined,
      });
    } finally {
      setClearing(false);
    }
  };

  if (subpage === "archived") {
    return (
      <div className="settings-page">
        <header className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setSubpage("main")}
            aria-label={t("settings.data.backToData")}
            className="settings-back-button inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
          >
            <HugeiconsIcon icon={ChevronLeftStandardIcon} className="size-4 rtl:rotate-180" />
          </button>
          <h1 className="text-xl font-semibold font-heading">
            {t("settings.data.title")}
          </h1>
        </header>
        <div className="flex items-start justify-between gap-4">
          <div className="flex flex-col gap-1">
            <h2 className="settings-heading text-sm font-semibold">
              {t("settings.data.archivedChats")}
            </h2>
            <p className="text-xs text-muted-foreground">
              {t("settings.data.archivedChatsDescription")}
            </p>
          </div>
          {archivedItems.length > 0 && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild={true}>
                <Button
                  variant="outline"
                  size="sm"
                  className="mt-[var(--ui-title-cap-inset)] shrink-0"
                  disabled={archivedExporting}
                >
                  {archivedExporting ? (
                    <Spinner className="size-4" />
                  ) : (
                    <HugeiconsIcon
                      icon={Download01Icon}
                      strokeWidth={1.75}
                      className="size-4"
                    />
                  )}
                  {archivedExporting
                    ? t("settings.data.exportingArchivedChats")
                    : t("settings.data.exportArchivedChats")}
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-56">
                <BulkExportItems
                  combinedLead={
                    <DropdownMenuItem onSelect={() => void handleExportArchived()}>
                      JSON
                    </DropdownMenuItem>
                  }
                  onExport={(fmt, merged) =>
                    void bulkExportConversationsByScope("archived", fmt, merged)
                  }
                />
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>
        <ArchivedChatsView />
      </div>
    );
  }

  if (
    subpage === "archived-images" ||
    subpage === "archived-videos" ||
    subpage === "archived-audio"
  ) {
    const kind: ArchivedMediaKind =
      subpage === "archived-images"
        ? "images"
        : subpage === "archived-videos"
          ? "videos"
          : "audio";
    const heading = {
      images: t("settings.data.archivedImages"),
      videos: t("settings.data.archivedVideos"),
      audio: t("settings.data.archivedAudio"),
    }[kind];
    const description = {
      images: t("settings.data.archivedImagesDescription"),
      videos: t("settings.data.archivedVideosDescription"),
      audio: t("settings.data.archivedAudioDescription"),
    }[kind];
    return (
      <div className="settings-page">
        <header className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setSubpage("main")}
            aria-label={t("settings.data.backToData")}
            className="settings-back-button inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
          >
            <HugeiconsIcon icon={ChevronLeftStandardIcon} className="size-4 rtl:rotate-180" />
          </button>
          <h1 className="text-xl font-semibold font-heading">
            {t("settings.data.title")}
          </h1>
        </header>
        <div className="flex flex-col gap-1">
          <h2 className="settings-heading text-sm font-semibold">{heading}</h2>
          <p className="text-xs text-muted-foreground">{description}</p>
        </div>
        {/* Keyed by kind: switching shelves on an already-mounted tab otherwise keeps the
            instance, and a showMore still awaiting the old shelf appends its rows to the new one,
            which then drives restore and delete through the wrong media API. */}
        <ArchivedMediaView key={subpage} kind={kind} />
      </div>
    );
  }

  if (subpage === "files") {
    return (
      <div className="settings-page">
        <header className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setSubpage("main")}
            aria-label={t("settings.data.backToData")}
            className="settings-back-button inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
          >
            <HugeiconsIcon icon={ChevronLeftStandardIcon} className="size-4 rtl:rotate-180" />
          </button>
          <h1 className="text-xl font-semibold font-heading">
            {t("settings.data.title")}
          </h1>
        </header>
        <div className="flex flex-col gap-1">
          <h2 className="settings-heading text-sm font-semibold">
            {t("settings.data.uploadedFiles")}
          </h2>
          <p className="text-xs text-muted-foreground">
            {t("settings.data.uploadedFilesDescription")}
          </p>
        </div>
        <UploadedFilesView />
      </div>
    );
  }

  return (
    <div className="settings-page">
      <header className="flex flex-col gap-1">
        <h1 className="text-xl font-semibold font-heading">
          {t("settings.data.title")}
        </h1>
        <p className="text-xs text-muted-foreground">
          {t("settings.data.description")}
        </p>
      </header>

      <SettingsSection title={t("settings.data.manageFiles.label")} hideHeading>
        <SettingsRow
          label={t("settings.data.manageFiles.label")}
          description={t("settings.data.manageFiles.description")}
        >
          <Button
            variant="outline"
            onClick={() => {
              useSettingsDialogStore.getState().closeDialog();
              // Already on All, the view would keep its search and filters.
              useLibraryVisitStore.getState().restart();
              void navigate({ to: "/library", search: { show: "all" } });
            }}
          >
            <HugeiconsIcon icon={LibrariesIcon} strokeWidth={1.75} className="size-4" />
            {t("settings.data.manageFiles.action")}
          </Button>
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title={t("settings.data.chatsSection")}>
        <div
          data-settings-label={t("settings.data.archives")}
          className="py-3"
        >
          <p className="mb-2 text-sm font-medium">
            {t("settings.data.archives")}
          </p>
          <div className="grid grid-cols-2 gap-2 lg:grid-cols-4">
            {([
              ["archived", "archivedChats", "settings.data.archiveChatsLabel", MessageCircleIcon],
              [
                "archived-images",
                "archivedImages",
                "shell.navigation.images",
                ImageIcon,
              ],
              [
                "archived-videos",
                "archivedVideos",
                "settings.data.archiveVideosLabel",
                FlimSlateIcon,
              ],
              [
                "archived-audio",
                "archivedAudio",
                "shell.navigation.audio",
                AiSpeechIcon,
              ],
            ] as const).map(([page, label, shortLabel, icon]) => (
              <button
                key={page}
                type="button"
                data-settings-label={t(`settings.data.${label}`)}
                aria-label={t(`settings.data.${label}`)}
                onClick={() => setSubpage(page)}
                className="btn-fill flex min-w-0 items-center justify-between gap-2 rounded-full px-3 py-2 text-sm transition-colors [&_svg]:-my-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                <span className="flex min-w-0 items-center gap-2">
                  <HugeiconsIcon
                    icon={icon}
                    aria-hidden={true}
                    className="size-4 shrink-0 text-muted-foreground"
                  />
                  <span className="truncate">
                    {t(shortLabel)}
                  </span>
                </span>
                <HugeiconsIcon
                  icon={ChevronRightStandardIcon}
                  className="size-3.5 shrink-0 text-muted-foreground"
                />
              </button>
            ))}
          </div>
        </div>
        <SettingsRow
          label={t("settings.data.archiveAllChats")}
          description={t("settings.data.archiveAllChatsDescription")}
        >
          <Button
            variant="outline"
            size="sm"
            onClick={() => setArchiveConfirmOpen(true)}
          >
            <HugeiconsIcon icon={ArchiveIcon} data-icon="inline-start" />
            {t("settings.data.archiveAllAction")}
          </Button>
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title={t("settings.data.transferSection")}>
        <SettingsRow
          label={t("settings.chat.importChats")}
          description={t("settings.chat.importChatsDescription")}
        >
          <Button
            variant="outline"
            size="sm"
            onClick={() => void handleImportClick()}
            // A second import would interleave streams and, on desktop, retire the running handle.
            disabled={importing}
          >
            {importing && <Spinner className="size-3.5 mr-1.5" />}
            {t("settings.chat.importChatsAction")}
          </Button>
          <input
            ref={importInputRef}
            type="file"
            accept=".json,.jsonl,.ndjson,.csv,.md,.markdown"
            className="hidden"
            onChange={(e) => {
              const file = e.target.files?.[0];
              e.target.value = "";
              if (file) void handleImport(fileImportSource(file));
            }}
          />
        </SettingsRow>
        {EXTERNAL_IMPORT_SOURCES.map((source) =>
          externalStatus[source] ? (
            <SettingsRow
              key={source}
              label={t("settings.chat.importFromSource", {
                source: EXTERNAL_IMPORT_LABELS[source],
              })}
              description={t("settings.chat.importFromSourceDescription", {
                source: EXTERNAL_IMPORT_LABELS[source],
              })}
            >
              <Button
                variant="outline"
                size="sm"
                onClick={() => void handleExternalImport(source)}
                disabled={externalImporting !== null}
              >
                {externalImporting === source && (
                  <Spinner className="size-3.5 mr-1.5" />
                )}
                {externalImporting === source
                  ? t("settings.chat.importingAction")
                  : t("settings.chat.importChatsAction")}
              </Button>
            </SettingsRow>
          ) : null,
        )}
        <SettingsRow
          label={t("settings.chat.exportHistory")}
          description={t("settings.chat.exportHistoryDescription")}
        >
          <DropdownMenu>
            <DropdownMenuTrigger asChild={true}>
              <Button
                variant="outline"
                size="sm"
                disabled={exporting || count === 0}
              >
                {exporting
                  ? t("settings.chat.exportingAction")
                  : t("settings.chat.exportAction")}
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-56">
              <BulkExportItems
                combinedLead={
                  <DropdownMenuItem onSelect={() => void handleExport()}>
                    JSON
                  </DropdownMenuItem>
                }
                onExport={(fmt, merged) =>
                  void bulkExportConversationsByScope("history", fmt, merged)
                }
              />
            </DropdownMenuContent>
          </DropdownMenu>
        </SettingsRow>
        <SettingsRow
          label={t("settings.chat.exportConversations")}
          description={t("settings.data.exportFormatsSummary")}
          hint={t("settings.chat.exportConversationsDescription")}
        >
          <DropdownMenu>
            <DropdownMenuTrigger asChild={true}>
              <Button variant="outline" size="sm" disabled={count === 0}>
                {t("settings.chat.exportConversationsAction")}
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-56">
              {(
                [
                  { scope: "recents", label: "exportScopeRecents" },
                  { scope: "all", label: "exportScopeAll" },
                ] as const
              ).map(({ scope, label }) => (
                <DropdownMenuSub key={scope}>
                  <DropdownMenuSubTrigger>
                    <HugeiconsIcon
                      icon={Download01Icon}
                      className="size-3.5 mr-1"
                    />
                    {t(`settings.chat.${label}`)}
                  </DropdownMenuSubTrigger>
                  <DropdownMenuSubContent className="w-56">
                    <BulkExportItems
                      onExport={(fmt, merged) =>
                        void bulkExportConversationsByScope(scope, fmt, merged)
                      }
                    />
                  </DropdownMenuSubContent>
                </DropdownMenuSub>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
        </SettingsRow>
        <SettingsRow
          label={t("settings.data.fineTuneExport")}
          description={t("settings.data.trainingSummary")}
          hint={t("settings.data.fineTuneExportDescription")}
        >
          <div className="flex items-center gap-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild={true}>
                <Button
                  variant="picker"
                  size="sm"
                  disabled={count === 0}
                  className="w-44 justify-between"
                >
                  <span className="truncate">
                    {fineTuneActionLabels[fineTuneAction]}
                  </span>
                  <HugeiconsIcon
                    icon={ChevronDownStandardIcon}
                    className="size-3.5 shrink-0"
                  />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-56">
                {FINE_TUNE_ACTIONS.map((action) => (
                  <DropdownMenuItem
                    key={action}
                    disabled={action === "train" && trainUnavailable}
                    onSelect={() => setFineTuneAction(action)}
                  >
                    <span className="flex-1">
                      {fineTuneActionLabels[action]}
                    </span>
                    {fineTuneAction === action ? (
                      <HugeiconsIcon icon={Tick02Icon} className="size-4" />
                    ) : null}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
            <Button
              size="icon-sm"
              onClick={runFineTuneAction}
              disabled={fineTuneBusy || count === 0}
              aria-label={t("settings.data.fineTuneRunAction")}
              title={`${t("settings.data.fineTuneRunAction")}: ${fineTuneActionLabels[fineTuneAction]}`}
              className="shrink-0 rounded-full"
            >
              {fineTuneBusy ? (
                <Spinner className="size-4" />
              ) : (
                <HugeiconsIcon
                  icon={ChevronRightStandardIcon}
                  strokeWidth={2.5}
                  className="size-4"
                />
              )}
            </Button>
          </div>
        </SettingsRow>
      </SettingsSection>

      <SettingsSection title={t("settings.data.deletionSection")}>
        <SettingsRow
          label={t("settings.data.confirmBeforeDeleting")}
          description={t("settings.data.confirmDeletionSummary")}
        >
          <Switch
            aria-label={t("settings.data.confirmBeforeDeleting")}
            checked={confirmDeleteChats}
            onCheckedChange={setConfirmDeleteChats}
          />
        </SettingsRow>
        <SettingsRow
          label={t("settings.data.sandboxFiles")}
          description={t("settings.data.sandboxFilesDescription")}
        >
          <Select
            value={alwaysDeleteChatFiles ? "delete" : "keep"}
            onValueChange={(value) => setAlwaysDeleteChatFiles(value === "delete")}
          >
            <SelectTrigger
              size="sm"
              aria-label={t("settings.data.sandboxFiles")}
            >
              <SelectValue />
            </SelectTrigger>
            <SelectContent align="end">
              <SelectItem value="keep">
                {t("settings.data.keepSandboxFiles")}
              </SelectItem>
              <SelectItem value="delete">
                {t("settings.data.deleteSandboxFiles")}
              </SelectItem>
            </SelectContent>
          </Select>
        </SettingsRow>
        <p className="pb-3 text-xs leading-relaxed text-muted-foreground">
          {t("settings.data.projectFilesKept")}
        </p>
        <div className="border-t border-border/60">
          <SettingsRow
            label={t("settings.chat.clearAllChats")}
            description={
              count === null
                ? t("settings.chat.clearAllChatsDescription")
                : count === 0
                  ? t("settings.chat.noChatsToClear")
                  : count === 1
                    ? t("settings.chat.clearOneChatDescription")
                    : t("settings.chat.clearChatCountDescription", { count })
            }
          >
            <DropdownMenu>
              <DropdownMenuTrigger asChild={true}>
                <Button
                  variant="destructive"
                  size="sm"
                  disabled={count === null || count === 0 || clearing}
                  className="text-destructive hover:text-destructive aria-expanded:text-destructive hover:border-destructive/60"
                >
                  <HugeiconsIcon icon={TrashIcon} className="size-3.5" />
                  {t("settings.data.deleteAllAction")}
                  <HugeiconsIcon icon={ChevronDownStandardIcon} className="size-3.5" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-64">
                <DropdownMenuItem
                  variant="destructive"
                  onSelect={() => openClearConfirmation(false)}
                >
                  {t("settings.data.deleteChatsOnly")}
                </DropdownMenuItem>
                <DropdownMenuItem
                  variant="destructive"
                  onSelect={() => openClearConfirmation(true)}
                >
                  {t("settings.data.deleteChatsAndSandboxes")}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </SettingsRow>
        </div>
      </SettingsSection>

      <LibraryDataSection />

      <SettingsSection title={t("settings.data.filesSection")}>
        <SettingsRow
          label={t("settings.data.uploadedFiles")}
          description={t("settings.data.uploadedFilesDescription")}
        >
          <Button
            variant="outline"
            size="sm"
            onClick={() => setSubpage("files")}
          >
            {t("settings.data.manageAction")}
          </Button>
        </SettingsRow>
        {!ragAvailabilityUnknown && !ragUnavailable ? (
          <div className="py-3">
            <LinkedFoldersManager />
          </div>
        ) : null}
        {/* The owner sees it beside the embedding model below. */}
        {!isOwner ? <ReembedDocumentsRow /> : null}
      </SettingsSection>

      {isOwner ? <DocumentsRagSection /> : null}

      <Dialog open={archiveConfirmOpen} onOpenChange={setArchiveConfirmOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t("settings.data.archiveAllChatsTitle")}</DialogTitle>
            <DialogDescription>
              {t("settings.data.archiveAllChatsConfirmDescription")}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setArchiveConfirmOpen(false)}
            >
              {t("common.cancel")}
            </Button>
            <Button onClick={handleArchiveAll} disabled={archiving}>
              {archiving
                ? t("settings.data.archivingAction")
                : t("settings.data.archiveAllAction")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={confirmOpen}
        onOpenChange={(open) => {
          if (!clearing) setConfirmOpen(open);
        }}
      >
        <DialogContent className="max-w-md" showCloseButton={!clearing}>
          <DialogHeader>
            <DialogTitle>
              {count === 1
                ? t("settings.chat.clearOneChatTitle")
                : t("settings.chat.clearChatsTitle", { count: count ?? 0 })}
            </DialogTitle>
            <DialogDescription>
              {t("settings.chat.clearChatsConfirmDescription")}
            </DialogDescription>
          </DialogHeader>
          <fieldset disabled={clearing} className="min-w-0 disabled:opacity-50">
            <DeleteChatFilesSwitch
              id="clear-chats-delete-files"
              label={t("settings.data.deleteSandboxFiles")}
              checked={deleteFilesOnClear}
              onCheckedChange={setDeleteFilesOnClear}
              description={t("settings.data.deleteSandboxFilesDescription")}
            />
          </fieldset>
          <DialogFooter>
            <Button
              variant="outline"
              disabled={clearing}
              onClick={() => setConfirmOpen(false)}
            >
              {t("common.cancel")}
            </Button>
            <Button
              variant="destructive"
              onClick={handleClear}
              disabled={clearing}
            >
              {clearing
                ? t("settings.chat.clearingAction")
                : count === 1
                  ? t("settings.chat.clearOneChatAction")
                  : t("settings.chat.clearChatCountAction", {
                      count: count ?? 0,
                    })}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}