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.

studio: organize data settings and make archives searchable (#10974)

Michael Han0ab40feeb4cc
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index b187a1da738..6f4f93eb3cf 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -26,6 +26,7 @@ on:
- 'tests/studio/probe_dismiss_guard.py'
- 'tests/studio/playwright_nonmodal_menus.py'
- 'tests/studio/playwright_settings_tabs.py'
+ - 'tests/studio/playwright_data_settings.py'
- 'tests/studio/playwright_keyboard_shortcuts.py'
- 'tests/studio/playwright_find_in_page.py'
- 'tests/studio/playwright_tool_activity.py'
@@ -461,6 +462,10 @@ jobs:
working-directory: ${{ github.workspace }}
run: python3 tests/studio/playwright_settings_tabs.py
+ - name: Data settings deletion choices
+ working-directory: ${{ github.workspace }}
+ run: python3 tests/studio/playwright_data_settings.py
+
# A listener is not a pure function: what a chord does to a focused button, to a
# text field, on auto-repeat, or under AltGr is only answerable in a browser, and
# the node suite pins those through source text. Chromium here because that is what
@@ -526,6 +531,7 @@ jobs:
logs/playwright-*
logs/settings_tabs_report.json
logs/settings_tabs_blocked_report.json
+ logs/data_settings*
logs/nonmodal_menus_report.json
logs/pw/
retention-days: 3
@@ -620,11 +626,24 @@ jobs:
timeout-minutes: 3
run: python tests/studio/playwright_composer_icons.py chromium firefox
+ - name: Data settings deletion choices in Chromium
+ working-directory: ${{ github.workspace }}
+ run: python tests/studio/playwright_data_settings.py
+
+ - name: Data settings deletion choices in Firefox
+ working-directory: ${{ github.workspace }}
+ env:
+ PW_ENGINE: firefox
+ PW_OUT: logs/data_settings_firefox_report.json
+ run: python tests/studio/playwright_data_settings.py
+
- name: Upload alignment failure artifacts
if: failure()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-composer-icons
- path: logs/playwright-composer-icons
+ path: |
+ logs/playwright-composer-icons
+ logs/data_settings*
retention-days: 1
if-no-files-found: ignore
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index bf272febbc7..d5cdbcb77fc 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -48,7 +48,8 @@ export const BUDGET = {
// days. rawBytes stays put at 64.7 KB spare so both halves come up for one re-measure
// together instead of each dragging main red on its own.
transferBytes: 1_690_000,
- rawBytes: 5_500_000,
+ // Library locale messages: 5,499,994 to 5,502,720 raw bytes, still 85 eager chunks.
+ rawBytes: 5_510_000,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/features/chat/components/delete-chat-files-switch.tsx b/studio/frontend/src/features/chat/components/delete-chat-files-switch.tsx
index 48f815b7677..d9ca43f4fb4 100644
--- a/studio/frontend/src/features/chat/components/delete-chat-files-switch.tsx
+++ b/studio/frontend/src/features/chat/components/delete-chat-files-switch.tsx
@@ -12,15 +12,17 @@ export function DeleteChatFilesSwitch({
checked,
onCheckedChange,
description,
+ label: labelOverride,
}: {
id: string;
checked: boolean;
onCheckedChange: (next: boolean) => void;
/** For a delete covering more than one chat, which reads differently. */
description?: string;
+ label?: string;
}) {
const t = useT();
- const label = t("shell.selection.deleteFilesLabel");
+ const label = labelOverride ?? t("shell.selection.deleteFilesLabel");
return (
<div className="flex items-start justify-between gap-4 rounded-md border border-border/60 bg-muted/35 px-3 py-2.5">
<label htmlFor={id} className="min-w-0 space-y-1">
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 4576cf842af..726606f9908 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -258,6 +258,7 @@ export {
getStoredChatThread,
isThreadIncognito,
listStoredChatMessages,
+ listStoredChatProjects,
listStoredChatThreads,
markThreadIncognito,
} from "./utils/chat-history-storage";
diff --git a/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx b/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx
index e6a1a6e25c8..5bf6e30fe3b 100644
--- a/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx
+++ b/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx
@@ -11,41 +11,66 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
import {
type SidebarItem,
+ type ProjectRecord,
+ listStoredChatProjects,
DeleteChatFilesSwitch,
deleteChatItem,
unarchiveChatItem,
useChatPreferencesStore,
+ useChatProjects,
useChatRuntimeStore,
useChatSidebarItems,
} from "@/features/chat";
+import { translate, useLocale, useT } from "@/i18n";
import { toast } from "@/lib/toast";
-import { ArchiveRestoreIcon, Delete02Icon } from "@hugeicons/core-free-icons";
+import { Delete02Icon, Message01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { Button } from "@/components/ui/button";
import { useNavigate, useRouterState } from "@tanstack/react-router";
-import { useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+import { useLibraryProjectLabels } from "./use-library-project-labels";
+import {
+ DEFAULT_LIBRARY_FILTERS,
+ filterLibraryItems,
+ type LibraryFilters,
+} from "./data-library";
+import {
+ ChatLibraryGroups,
+ LibraryRow,
+ LibraryToolbar,
+} from "./data-library-controls";
-/** Archived chats shown per page; "Show more" reveals the next page. */
const ARCHIVED_PAGE_SIZE = 20;
-function formatCreatedAt(ms: number): string {
- return new Date(ms).toLocaleDateString(undefined, {
- year: "numeric",
- month: "long",
- day: "numeric",
- });
-}
-
export function ArchivedChatsView() {
+ const t = useT();
+ const locale = useLocale();
+ const labels = useLibraryProjectLabels();
const { archivedItems } = useChatSidebarItems({ requireMessages: false });
+ const { projects: activeProjects } = useChatProjects();
+ const [projects, setProjects] = useState<ProjectRecord[]>(activeProjects);
+ useEffect(() => {
+ let cancelled = false;
+ void listStoredChatProjects({ includeArchived: true })
+ .then((all) => {
+ if (!cancelled) setProjects(all);
+ })
+ .catch((error) => {
+ if (!cancelled)
+ toast.error(translate("settings.data.library.projectsFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [activeProjects]);
const navigate = useNavigate();
const closeSettings = useSettingsDialogStore((s) => s.closeDialog);
const storeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
- // Open chat id from the route. Compare panes do not write the store, so the
- // pair id only lives in the search params; mirror how the sidebar reads it.
const openChatId = useRouterState({
select: (s) => {
if (!s.location.pathname.startsWith("/chat")) return undefined;
@@ -59,180 +84,278 @@ export function ArchivedChatsView() {
const alwaysDeleteChatFiles = useChatPreferencesStore(
(s) => s.alwaysDeleteChatFiles,
);
- const [confirmingDelete, setConfirmingDelete] = useState<SidebarItem | null>(
- null,
- );
- // Preselected from the preference, so the dialog shows what is about to
- // happen and can still be turned off for this one chat.
+ const [confirmingDelete, setConfirmingDelete] = useState<SidebarItem[]>([]);
const [deleteFilesOnDelete, setDeleteFilesOnDelete] = useState(false);
- // Pagination: the view remounts with its settings tab, so plain state
- // restarts from the first page on each visit.
const [visibleCount, setVisibleCount] = useState(ARCHIVED_PAGE_SIZE);
+ const [filters, setFilters] = useState(DEFAULT_LIBRARY_FILTERS);
+ const [removed, setRemoved] = useState<ReadonlySet<string>>(new Set());
+ const [busy, setBusy] = useState(false);
+ const running = useRef(false);
+ const projectNames = useMemo(
+ () => new Map(projects.map((p) => [p.id, p.name])),
+ [projects],
+ );
+ const filtered = useMemo(
+ () =>
+ filterLibraryItems(
+ archivedItems.filter((item) => !removed.has(item.id)),
+ filters,
+ projectNames,
+ labels,
+ locale,
+ ),
+ [archivedItems, removed, filters, projectNames, labels, locale],
+ );
+ const narrowed =
+ filters.query.trim() !== "" ||
+ filters.type !== "all" ||
+ filters.project !== "all";
+
+ function changeFilters(next: LibraryFilters) {
+ setFilters(next);
+ setVisibleCount(ARCHIVED_PAGE_SIZE);
+ }
- // Open an archived chat: leave it archived, just navigate to it.
function openChat(item: SidebarItem) {
+ const project = item.projectId ? { project: item.projectId } : {};
navigate({
to: "/chat",
search:
- item.type === "single" ? { thread: item.id } : { compare: item.id },
+ item.type === "single"
+ ? { thread: item.id, ...project }
+ : { compare: item.id, ...project },
});
closeSettings();
}
- async function handleUnarchive(item: SidebarItem) {
- try {
- await unarchiveChatItem(item);
- toast.success("Chat unarchived");
- } catch (err) {
- toast.error("Failed to unarchive chat", {
- description: err instanceof Error ? err.message : undefined,
- });
- }
+ async function handleDelete(item: SidebarItem, deleteFiles: boolean) {
+ await deleteChatItem(
+ item,
+ openChatId,
+ (view) => {
+ navigate({
+ to: "/chat",
+ search: item.projectId
+ ? { project: item.projectId }
+ : { new: view.newThreadNonce },
+ });
+ },
+ { deleteFiles },
+ );
}
- async function handleDelete(item: SidebarItem, deleteFiles: boolean) {
+ async function run(
+ items: SidebarItem[],
+ action: "delete" | "restore",
+ deleteFiles = false,
+ ) {
+ if (running.current || items.length === 0) return;
+ running.current = true;
+ setBusy(true);
+ let completed = 0;
try {
- // Pass the open chat id (single or compare) so deleting it resets nav.
- await deleteChatItem(
- item,
- openChatId,
- (view) => {
- navigate({
- to: "/chat",
- search: item.projectId
- ? { project: item.projectId }
- : { new: view.newThreadNonce },
- });
- },
- { deleteFiles },
+ for (const item of items) {
+ if (action === "delete") await handleDelete(item, deleteFiles);
+ else await unarchiveChatItem(item);
+ setRemoved((previous) => new Set([...previous, item.id]));
+ completed += 1;
+ }
+ toast.success(
+ t(
+ action === "delete"
+ ? "settings.data.library.deletedChats"
+ : "settings.data.library.restoredChats",
+ { count: completed },
+ ),
);
- toast.success("Chat deleted");
} catch (err) {
- toast.error("Failed to delete chat", {
- description: err instanceof Error ? err.message : undefined,
- });
+ toast.error(
+ t(
+ action === "delete"
+ ? "settings.data.library.deleteFailed"
+ : "settings.data.library.restoreFailed",
+ ),
+ {
+ description: err instanceof Error ? err.message : undefined,
+ },
+ );
+ } finally {
+ running.current = false;
+ setBusy(false);
}
}
- function requestDelete(item: SidebarItem) {
- if (confirmDeleteChats) {
+ function requestDelete(items: SidebarItem[], bulk = false) {
+ if (running.current) return;
+ if (bulk || confirmDeleteChats) {
setDeleteFilesOnDelete(alwaysDeleteChatFiles);
- setConfirmingDelete(item);
- return;
- }
- // No confirmation to preselect, so the preference is the answer.
- void handleDelete(item, alwaysDeleteChatFiles);
+ setConfirmingDelete([...items]);
+ } else void run(items, "delete", alwaysDeleteChatFiles);
}
return (
<div className="flex flex-col gap-4">
- {archivedItems.length === 0 ? (
+ <LibraryToolbar
+ filters={filters}
+ onChange={changeFilters}
+ placeholder={t("settings.data.library.searchArchivedChats")}
+ projects={projectNames}
+ disabled={busy}
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <span role="status" className="flex-1 text-xs text-muted-foreground">
+ {t(
+ filtered.length === 1
+ ? "settings.data.library.oneChat"
+ : "settings.data.library.chatCount",
+ { count: filtered.length },
+ )}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={busy || filtered.length === 0}
+ onClick={() => void run([...filtered], "restore")}
+ >
+ {narrowed
+ ? t("settings.data.library.unarchiveResults")
+ : t("settings.data.library.unarchiveAll")}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ disabled={busy || filtered.length === 0}
+ onClick={() => requestDelete(filtered, true)}
+ >
+ <HugeiconsIcon icon={Delete02Icon} className="mr-1.5 size-4" />
+ {narrowed
+ ? t("settings.data.library.deleteResults")
+ : t("settings.data.deleteAllAction")}
+ </Button>
+ </div>
+ {filtered.length === 0 ? (
<p className="py-8 text-center text-sm text-muted-foreground">
- No archived chats.
+ {narrowed
+ ? t("settings.data.library.noArchivedMatches")
+ : t("settings.data.library.noArchivedChats")}
</p>
) : (
- <div>
- <div className="flex items-center gap-4 border-b border-border/60 px-1 pb-2 text-xs font-semibold text-foreground">
- <span className="flex-1">Name</span>
- <span className="w-32 shrink-0">Date created</span>
- <span className="w-16 shrink-0" />
- </div>
- {archivedItems.slice(0, visibleCount).map((item) => (
- <div
- key={item.id}
- className="group flex items-center gap-4 border-b border-border/40 px-1 py-2.5 text-sm last:border-0"
- >
- <button
- type="button"
- onClick={() => openChat(item)}
- className="min-w-0 flex-1 truncate text-left text-primary hover:underline"
- title={item.title}
- >
- {item.title}
- </button>
- <span className="w-32 shrink-0 text-muted-foreground tabular-nums">
- {formatCreatedAt(item.createdAt)}
- </span>
- <span className="flex w-16 shrink-0 items-center justify-end gap-1">
- <button
- type="button"
- onClick={() => void handleUnarchive(item)}
- aria-label="Unarchive chat"
- title="Unarchive"
- className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
- >
- <HugeiconsIcon
- icon={ArchiveRestoreIcon}
- strokeWidth={1.75}
- className="size-4"
- />
- </button>
- <button
- type="button"
- onClick={() => requestDelete(item)}
- aria-label="Delete chat"
- title="Delete"
- className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
- >
- <HugeiconsIcon
- icon={Delete02Icon}
- strokeWidth={1.75}
- className="size-4"
- />
- </button>
- </span>
- </div>
- ))}
- {archivedItems.length > visibleCount ? (
- <div className="flex justify-center pt-3">
- <Button
- variant="outline"
- size="sm"
- onClick={() =>
- setVisibleCount(visibleCount + ARCHIVED_PAGE_SIZE)
- }
- >
- Show more ({archivedItems.length - visibleCount})
- </Button>
- </div>
- ) : null}
+ <ChatLibraryGroups
+ items={filtered.slice(0, visibleCount)}
+ projects={projectNames}
+ >
+ {(item) => (
+ <LibraryRow
+ title={item.title}
+ date={
+ filters.sort === "updated" ? item.updatedAt : item.createdAt
+ }
+ onOpen={() => openChat(item)}
+ leading={
+ <HugeiconsIcon
+ icon={Message01Icon}
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ }
+ actions={
+ <>
+ <Button
+ variant="ghost"
+ size="icon"
+ disabled={busy}
+ onClick={() => requestDelete([item])}
+ aria-label={t("settings.data.library.deleteItem", {
+ title: item.title,
+ })}
+ title={t("shell.dialog.deleteChat.title")}
+ className="text-muted-foreground hover:text-destructive"
+ >
+ <HugeiconsIcon icon={Delete02Icon} className="size-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={busy}
+ onClick={() => void run([item], "restore")}
+ aria-label={t("settings.data.library.unarchiveItem", {
+ title: item.title,
+ })}
+ className="rounded-xl bg-muted/60 hover:bg-muted"
+ >
+ {t("settings.data.library.unarchive")}
+ </Button>
+ </>
+ }
+ />
+ )}
+ </ChatLibraryGroups>
+ )}
+ {filtered.length > visibleCount && (
+ <div className="flex justify-center">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ setVisibleCount((count) => count + ARCHIVED_PAGE_SIZE)
+ }
+ >
+ {t("settings.voice.recents.showMore", {
+ count: filtered.length - visibleCount,
+ })}
+ </Button>
</div>
)}
-
<AlertDialog
- open={confirmingDelete !== null}
- onOpenChange={(o) => {
- if (!o) setConfirmingDelete(null);
+ open={confirmingDelete.length > 0}
+ onOpenChange={(open) => {
+ if (!open && !busy) setConfirmingDelete([]);
}}
>
- <AlertDialogContent>
+ <AlertDialogContent
+ onEscapeKeyDown={(event) => {
+ if (busy) event.preventDefault();
+ }}
+ >
<AlertDialogHeader>
- <AlertDialogTitle>Delete chat</AlertDialogTitle>
+ <AlertDialogTitle>
+ {confirmingDelete.length === 1
+ ? t("shell.dialog.deleteChat.title")
+ : t("settings.data.library.deleteArchivedTitle", {
+ count: confirmingDelete.length,
+ })}
+ </AlertDialogTitle>
<AlertDialogDescription>
- Delete{" "}
- <span className="font-medium text-foreground">
- &quot;{confirmingDelete?.title}&quot;
- </span>
- ? This cannot be undone.
+ {confirmingDelete.length === 1 && (
+ <>{confirmingDelete[0]?.title}. </>
+ )}
+ {t("settings.data.library.deleteArchivedWarning", {
+ count: confirmingDelete.length,
+ })}
</AlertDialogDescription>
</AlertDialogHeader>
- <DeleteChatFilesSwitch
- id="archived-chat-delete-files"
- checked={deleteFilesOnDelete}
- onCheckedChange={setDeleteFilesOnDelete}
- />
+ <fieldset disabled={busy}>
+ <DeleteChatFilesSwitch
+ id="archived-chat-delete-files"
+ checked={deleteFilesOnDelete}
+ onCheckedChange={setDeleteFilesOnDelete}
+ />
+ </fieldset>
<AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogCancel disabled={busy}>
+ {t("common.cancel")}
+ </AlertDialogCancel>
<AlertDialogAction
variant="destructive"
- onClick={() => {
- const item = confirmingDelete;
- const deleteFiles = deleteFilesOnDelete;
- setConfirmingDelete(null);
- if (item) void handleDelete(item, deleteFiles);
+ disabled={busy}
+ onClick={(event) => {
+ event.preventDefault();
+ void run(confirmingDelete, "delete", deleteFilesOnDelete).then(
+ () => setConfirmingDelete([]),
+ );
}}
>
- Delete
+ {busy ? t("settings.data.library.deleting") : t("common.delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
diff --git a/studio/frontend/src/features/settings/components/archived-media-dialog.tsx b/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
index d0a01e677a6..9d172ad565f 100644
--- a/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
+++ b/studio/frontend/src/features/settings/components/archived-media-dialog.tsx
@@ -2,14 +2,31 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import {
- ArchiveRestoreIcon,
AudioWave01Icon,
Delete02Icon,
+ Image03Icon,
+ FlimSlateIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import {
+ DEFAULT_LIBRARY_FILTERS,
+ filterLibraryItems,
+ type LibraryFilters,
+} from "./data-library";
+import { LibraryRow, LibraryToolbar } from "./data-library-controls";
import { Spinner } from "@/components/ui/spinner";
import {
deleteAudioClip,
@@ -31,10 +48,12 @@ import {
import { videoThumbnailQueue } from "@/features/video/thumbnail-request-queue";
import { BlobUrlCache } from "@/lib/blob-url-cache";
import { notifyGalleryChanged } from "@/lib/gallery-flags";
+import { translate, useLocale, useT } from "@/i18n";
import { toast } from "@/lib/toast";
/** Archived items shown per page; "Show more" pulls the next page. Matches ArchivedChatsView. */
const ARCHIVED_PAGE_SIZE = 20;
+const SEARCH_PAGE_SIZE = 200;
// Blob budget for archived thumbnails. Far smaller than the gallery strip's 192 MB: these are 40px
// rows in a settings list, and only the loaded pages are ever on screen.
@@ -47,18 +66,12 @@ const THUMB_RETRY_DELAY_MS = 750;
export type ArchivedMediaKind = "images" | "videos" | "audio";
-const NOUN: Record<ArchivedMediaKind, string> = {
- images: "image",
- videos: "video",
- audio: "clip",
-};
-
/** The shape both galleries share, once flattened for this list. */
interface ArchivedRow {
id: string;
- prompt: string;
+ title: string;
/** Epoch ms, so images (epoch seconds) and videos (ISO 8601) render the same way. */
- createdAtMs: number;
+ createdAt: number;
/** Relative, auth-protected URL of the underlying file. */
url: string;
}
@@ -74,25 +87,16 @@ interface ArchivedPage {
nextAudioCursor: AudioCursor | null;
}
-function formatCreatedAt(ms: number): string {
- if (!Number.isFinite(ms)) return "";
- return new Date(ms).toLocaleDateString(undefined, {
- year: "numeric",
- month: "long",
- day: "numeric",
- });
-}
-
/**
* The archived shelf for one media gallery, modelled on ArchivedChatsView: rows with restore and
* delete, revealed a page at a time. Unlike chats there is nothing readable to identify a result
* by, so each row carries a thumbnail alongside its prompt.
*/
export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
+ const t = useT();
+ const locale = useLocale();
const isImages = kind === "images";
const isAudio = kind === "audio";
- const noun = NOUN[kind];
- const Noun = noun[0].toUpperCase() + noun.slice(1);
const [rows, setRows] = useState<ArchivedRow[]>([]);
// `showMore` reads the row count and the drop count from refs, not state: both can change while
// its request is in flight, and a stale closure is exactly what makes it skip a row. The ref is
@@ -110,6 +114,41 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
setRows(next);
}, []);
const [hasMore, setHasMore] = useState(false);
+ const [filters, setFilters] = useState<LibraryFilters>({
+ ...DEFAULT_LIBRARY_FILTERS,
+ sort: "default",
+ });
+ const [visibleCount, setVisibleCount] = useState(ARCHIVED_PAGE_SIZE);
+ const [paging, setPaging] = useState(false);
+ const [pageError, setPageError] = useState(false);
+ const [bulkIntent, setBulkIntent] = useState<"delete" | "restore" | null>(
+ null,
+ );
+ const [confirming, setConfirming] = useState<{
+ rows: ArchivedRow[];
+ action: "delete" | "restore";
+ } | null>(null);
+ const [busy, setBusy] = useState(false);
+ const running = useRef(false);
+ const filtered = useMemo(
+ () => filterLibraryItems(rows, filters, undefined, undefined, locale),
+ [rows, filters, locale],
+ );
+ const displayed = useMemo(
+ () => filtered.slice(0, visibleCount),
+ [filtered, visibleCount],
+ );
+ const scanAll =
+ filters.query.trim() !== "" ||
+ filters.sort !== "default" ||
+ bulkIntent !== null;
+
+ function changeFilters(next: LibraryFilters) {
+ setFilters(next);
+ setVisibleCount(ARCHIVED_PAGE_SIZE);
+ setPageError(false);
+ setBulkIntent(null);
+ }
const [loading, setLoading] = useState(true);
const [thumbs, setThumbs] = useState<Record<string, string>>({});
// Archived images and video posters are object URLs, so "Show more" a few times would otherwise
@@ -121,14 +160,18 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
const [visible, setVisible] = useState<ReadonlySet<string>>(new Set());
const loadPage = useCallback(
- async (offset: number, before: AudioCursor | null = null): Promise<ArchivedPage> => {
+ async (
+ offset: number,
+ before: AudioCursor | null = null,
+ pageSize = ARCHIVED_PAGE_SIZE,
+ ): Promise<ArchivedPage> => {
if (isImages) {
- const page = await getGallery(offset, ARCHIVED_PAGE_SIZE, true);
+ const page = await getGallery(offset, pageSize, true);
return {
rows: page.images.map((i) => ({
id: i.id,
- prompt: i.prompt,
- createdAtMs: i.created_at * 1000,
+ title: i.prompt,
+ createdAt: i.created_at * 1000,
url: i.url,
})),
hasMore: page.has_more,
@@ -136,12 +179,12 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
};
}
if (isAudio) {
- const page = await listAudioGallery(0, ARCHIVED_PAGE_SIZE, before, true);
+ const page = await listAudioGallery(0, pageSize, before, true);
return {
rows: page.audio.map((a) => ({
id: a.id,
- prompt: a.prompt,
- createdAtMs: Date.parse(a.created_at),
+ title: a.prompt,
+ createdAt: Date.parse(a.created_at),
url: a.url,
})),
hasMore: page.has_more,
@@ -151,12 +194,12 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
: null,
};
}
- const page = await getVideoGallery(offset, ARCHIVED_PAGE_SIZE, true);
+ const page = await getVideoGallery(offset, pageSize, true);
return {
rows: page.videos.map((v) => ({
id: v.id,
- prompt: v.prompt,
- createdAtMs: Date.parse(v.created_at),
+ title: v.prompt,
+ createdAt: Date.parse(v.created_at),
url: v.url,
})),
hasMore: page.has_more,
@@ -178,7 +221,9 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
setHasMore(page.hasMore);
} catch (err) {
if (!cancelled) {
- toast.error(`Failed to load archived ${kind}`, {
+ setPageError(true);
+ setHasMore(true);
+ toast.error(translate("settings.data.library.loadFailed"), {
description: err instanceof Error ? err.message : undefined,
});
}
@@ -202,12 +247,19 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
useEffect(() => {
const root = listRef.current;
if (!root) return;
+ setVisible((previous) =>
+ new Set(
+ displayed.filter((row) => previous.has(row.id)).map((row) => row.id),
+ ),
+ );
+ let observing = true;
if (typeof IntersectionObserver === "undefined") {
- setVisible(new Set(rows.map((r) => r.id)));
+ setVisible(new Set(displayed.map((r) => r.id)));
return;
}
const io = new IntersectionObserver(
(entries) => {
+ if (!observing) return;
setVisible((prev) => {
const next = new Set(prev);
for (const entry of entries) {
@@ -222,9 +274,13 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
// A little margin so a row is fetched just before it scrolls into view.
{ rootMargin: "200px 0px" },
);
- for (const el of root.querySelectorAll("[data-archived-id]")) io.observe(el);
- return () => io.disconnect();
- }, [rows]);
+ for (const el of root.querySelectorAll("[data-archived-id]"))
+ io.observe(el);
+ return () => {
+ observing = false;
+ io.disconnect();
+ };
+ }, [displayed, loading]);
// Thumbnails for VISIBLE rows that do not have one yet. `requested` is a ref, not state, so a
// landing thumbnail cannot re-enter this effect and refetch the rest.
@@ -282,10 +338,15 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
if (isImages || kind === "videos") {
const { url, bytes } = isImages
? await fetchGalleryObjectUrl(row.url)
- : await videoThumbnailQueue.run(() => fetchGalleryVideoThumbnail(row.id));
+ : await videoThumbnailQueue.run(() =>
+ fetchGalleryVideoThumbnail(row.id),
+ );
// Dropped from the list, or the dialog closed: there is no row left to show it on,
// and caching it after the unmount sweep would leak the blob.
- if (!alive.current || !rowsRef.current.some((r) => r.id === row.id)) {
+ if (
+ !alive.current ||
+ !rowsRef.current.some((r) => r.id === row.id)
+ ) {
URL.revokeObjectURL(url);
requested.current.delete(row.id);
return;
@@ -332,7 +393,7 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
// Drop a row, then top the page back up if that emptied it while more remain, so the list never
// dead-ends with rows still unreachable behind a hidden "Show more".
const dropRow = useCallback(
- (id: string, backToGallery: boolean) => {
+ (id: string) => {
putRows(rowsRef.current.filter((r) => r.id !== id));
// Every drop shifts the rows behind it up by one, so an offset taken before this point is
// now short. `showMore` uses the counter to notice and re-page instead of skipping a row.
@@ -354,13 +415,8 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
delete next[id];
return next;
});
- // The page that owns this gallery is mounted persistently and only loads on mount, so a
- // restore has to be announced or the strip stays stale until a reload. A delete does not:
- // the item was archived, so it was never on that strip, and refetching would only cost the
- // user the pages they had scrolled to.
- if (backToGallery) notifyGalleryChanged(kind);
},
- [kind, putRows],
+ [putRows],
);
async function handleRestore(row: ArchivedRow) {
@@ -372,14 +428,15 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
if (isImages) await setGalleryImageFlags(row.id, { archived: false });
else if (isAudio) await setAudioClipFlags(row.id, { archived: false });
else await setGalleryVideoFlags(row.id, { archived: false });
- dropRow(row.id, true);
+ dropRow(row.id);
pendingMutations.current -= 1;
- toast.success(`${Noun} restored`);
+ return true;
} catch (err) {
pendingMutations.current -= 1;
- toast.error(`Failed to restore ${noun}`, {
+ toast.error(t("settings.data.library.restoreFailed"), {
description: err instanceof Error ? err.message : undefined,
});
+ return false;
}
}
@@ -392,39 +449,100 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
if (isImages) await deleteGalleryImage(row.id);
else if (isAudio) await deleteAudioClip(row.id);
else await deleteGalleryVideo(row.id);
- dropRow(row.id, false);
+ dropRow(row.id);
pendingMutations.current -= 1;
- toast.success(`${Noun} deleted`);
+ return true;
} catch (err) {
pendingMutations.current -= 1;
- toast.error(`Failed to delete ${noun}`, {
+ toast.error(t("settings.data.library.deleteFailed"), {
description: err instanceof Error ? err.message : undefined,
});
+ return false;
}
}
- async function showMore() {
- if (loadingMore.current) return;
+ const showMore = useCallback(async () => {
+ if (loadingMore.current || running.current) return;
loadingMore.current = true;
+ setPaging(true);
+ setPageError(false);
try {
- // Images and videos page by offset over a shelf the user can shorten; audio uses its stable
- // cursor. The same retry fence keeps locally mutated responses off every shelf.
for (let attempt = 0; attempt < 4; attempt += 1) {
const before = mutations.current;
- const page = await loadPage(rowsRef.current.length, audioCursor.current);
- if (mutations.current !== before || pendingMutations.current > 0) continue;
+ const page = await loadPage(
+ rowsRef.current.length,
+ audioCursor.current,
+ scanAll ? SEARCH_PAGE_SIZE : ARCHIVED_PAGE_SIZE,
+ );
+ if (!alive.current) return;
+ if (mutations.current !== before || pendingMutations.current > 0)
+ continue;
const seen = new Set(rowsRef.current.map((r) => r.id));
- putRows([...rowsRef.current, ...page.rows.filter((r) => !seen.has(r.id))]);
+ const added = page.rows.filter((r) => !seen.has(r.id));
+ if (page.hasMore && added.length === 0)
+ throw new Error(t("settings.data.library.pageStalled"));
+ putRows([...rowsRef.current, ...added]);
audioCursor.current = page.nextAudioCursor;
setHasMore(page.hasMore);
return;
}
+ throw new Error(t("settings.data.library.pageChanged"));
} catch (err) {
- toast.error(`Failed to load more archived ${kind}`, {
+ if (!alive.current) return;
+ setPageError(true);
+ toast.error(t("settings.data.library.loadMoreFailed"), {
description: err instanceof Error ? err.message : undefined,
});
} finally {
loadingMore.current = false;
+ if (alive.current) setPaging(false);
+ }
+ }, [t, loadPage, putRows, scanAll]);
+
+ useEffect(() => {
+ if (!scanAll || loading || paging || pageError || busy || !hasMore) return;
+ const timer = setTimeout(
+ () => void showMore(),
+ rows.length <= ARCHIVED_PAGE_SIZE ? 250 : 0,
+ );
+ return () => clearTimeout(timer);
+ }, [
+ scanAll,
+ loading,
+ paging,
+ pageError,
+ busy,
+ hasMore,
+ showMore,
+ rows.length,
+ ]);
+
+ useEffect(() => {
+ if (!bulkIntent || hasMore || loading || paging || pageError) return;
+ setConfirming({ rows: [...filtered], action: bulkIntent });
+ setBulkIntent(null);
+ }, [bulkIntent, hasMore, loading, paging, pageError, filtered]);
+
+ async function run(targets: ArchivedRow[], action: "delete" | "restore") {
+ if (running.current) return;
+ running.current = true;
+ setBusy(true);
+ let restored = false;
+ try {
+ for (const row of targets) {
+ const succeeded =
+ action === "delete"
+ ? await handleDelete(row)
+ : await handleRestore(row);
+ if (!succeeded) break;
+ if (action === "restore") restored = true;
+ }
+ } finally {
+ // refresh the persistent gallery once, including after a partially successful batch.
+ if (restored) notifyGalleryChanged(kind);
+ running.current = false;
+ setBusy(false);
+ setConfirming(null);
}
}
@@ -436,77 +554,214 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {
);
}
- // Only a genuinely empty shelf ends here. Emptying the LOADED page while more remain keeps the
- // list rendered so "Show more" survives, else the rest become unreachable without reopening.
- if (rows.length === 0 && !hasMore) {
- return (
- <p className="py-8 text-center text-sm text-muted-foreground">
- No archived {kind}.
- </p>
- );
- }
-
return (
<div className="flex flex-col gap-4">
- <div ref={listRef}>
- <div className="flex items-center gap-4 border-b border-border/60 px-1 pb-2 text-xs font-semibold text-foreground">
- <span className="w-10 shrink-0" />
- <span className="flex-1">Prompt</span>
- <span className="w-32 shrink-0">Date created</span>
- <span className="w-16 shrink-0" />
- </div>
- {rows.map((row) => (
- <div
- key={row.id}
- data-archived-id={row.id}
- className="group flex items-center gap-4 border-b border-border/40 px-1 py-2.5 text-sm last:border-0"
- >
- <span className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-md bg-muted/40">
- {isAudio ? (
- <HugeiconsIcon
- icon={AudioWave01Icon}
- className="size-4 text-muted-foreground"
- />
- ) : thumbs[row.id] ? (
- <img src={thumbs[row.id]} alt="" className="size-full object-cover" />
- ) : null}
- </span>
- <span className="min-w-0 flex-1 truncate" title={row.prompt}>
- {row.prompt}
- </span>
- <span className="w-32 shrink-0 text-muted-foreground tabular-nums">
- {formatCreatedAt(row.createdAtMs)}
- </span>
- <span className="flex w-16 shrink-0 items-center justify-end gap-1">
- <button
- type="button"
- onClick={() => void handleRestore(row)}
- aria-label={`Restore ${noun}`}
- title="Restore"
- className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
- >
- <HugeiconsIcon icon={ArchiveRestoreIcon} strokeWidth={1.75} className="size-4" />
- </button>
- <button
- type="button"
- onClick={() => void handleDelete(row)}
- aria-label={`Delete ${noun}`}
- title="Delete"
- className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
- >
- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-4" />
- </button>
- </span>
- </div>
- ))}
- {hasMore ? (
- <div className="flex justify-center pt-3">
- <Button variant="outline" size="sm" onClick={() => void showMore()}>
- Show more
+ <LibraryToolbar
+ filters={filters}
+ onChange={changeFilters}
+ placeholder={t(
+ isImages
+ ? "settings.data.library.searchImages"
+ : isAudio
+ ? "settings.data.library.searchAudio"
+ : "settings.data.library.searchVideos",
+ )}
+ disabled={busy || bulkIntent !== null}
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <span role="status" className="flex-1 text-xs text-muted-foreground">
+ {pageError
+ ? t("settings.data.library.incompleteSearch")
+ : scanAll && hasMore
+ ? t("settings.data.library.searchingRemaining", {
+ count: rows.length,
+ })
+ : t("settings.data.library.itemCount", {
+ count: `${filtered.length}${hasMore ? "+" : ""}`,
+ })}
+ </span>
+ {bulkIntent ? (
+ <Button variant="ghost" size="sm" onClick={() => setBulkIntent(null)}>
+ {t("common.cancel")}
+ </Button>
+ ) : (
+ <>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={busy || (rows.length === 0 && !hasMore)}
+ onClick={() => setBulkIntent("restore")}
+ >
+ {filters.query.trim()
+ ? t("settings.data.library.unarchiveResults")
+ : t("settings.data.library.unarchiveAll")}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={busy || (rows.length === 0 && !hasMore)}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ onClick={() => setBulkIntent("delete")}
+ >
+ <HugeiconsIcon icon={Delete02Icon} className="mr-1.5 size-4" />
+ {filters.query.trim()
+ ? t("settings.data.library.deleteResults")
+ : t("settings.data.deleteAllAction")}
</Button>
+ </>
+ )}
+ </div>
+ <div
+ ref={listRef}
+ className="divide-y divide-border/50 rounded-2xl border border-border/60 px-3 sm:px-4"
+ >
+ {displayed.map((row) => (
+ <div key={row.id} data-archived-id={row.id}>
+ <LibraryRow
+ title={row.title}
+ date={row.createdAt}
+ leading={
+ <span className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted/40">
+ {!isAudio && thumbs[row.id] ? (
+ <img
+ src={thumbs[row.id]}
+ alt=""
+ className="size-full object-cover"
+ />
+ ) : (
+ <HugeiconsIcon
+ icon={
+ isAudio
+ ? AudioWave01Icon
+ : isImages
+ ? Image03Icon
+ : FlimSlateIcon
+ }
+ className="size-5 text-muted-foreground"
+ />
+ )}
+ </span>
+ }
+ actions={
+ <>
+ <Button
+ variant="ghost"
+ size="icon"
+ disabled={busy || bulkIntent !== null}
+ aria-label={t("settings.data.library.deleteItem", {
+ title: row.title,
+ })}
+ title={t("common.delete")}
+ className="text-muted-foreground hover:text-destructive"
+ onClick={() =>
+ setConfirming({ rows: [row], action: "delete" })
+ }
+ >
+ <HugeiconsIcon icon={Delete02Icon} className="size-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={busy || bulkIntent !== null}
+ aria-label={t("settings.data.library.unarchiveItem", {
+ title: row.title,
+ })}
+ className="rounded-xl bg-muted/60 hover:bg-muted"
+ onClick={() => void run([row], "restore")}
+ >
+ {t("settings.data.library.unarchive")}
+ </Button>
+ </>
+ }
+ />
</div>
- ) : null}
+ ))}
+ {displayed.length === 0 && (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ {hasMore
+ ? t("settings.data.library.noLoadedMatches")
+ : filters.query.trim()
+ ? t("settings.data.library.noMediaMatches")
+ : t("settings.data.library.noMedia")}
+ </p>
+ )}
</div>
+ {hasMore || filtered.length > visibleCount ? (
+ <div className="flex justify-center">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={paging || busy}
+ onClick={() => {
+ if (pageError) void showMore();
+ else if (filtered.length > visibleCount)
+ setVisibleCount((count) => count + ARCHIVED_PAGE_SIZE);
+ else
+ void showMore().then(() =>
+ setVisibleCount((count) => count + ARCHIVED_PAGE_SIZE),
+ );
+ }}
+ >
+ {paging
+ ? t("common.loading")
+ : pageError
+ ? t("picker.retry")
+ : t("shell.navigation.showMore")}
+ </Button>
+ </div>
+ ) : null}
+ <AlertDialog
+ open={confirming !== null}
+ onOpenChange={(open) => {
+ if (!open && !busy) setConfirming(null);
+ }}
+ >
+ <AlertDialogContent
+ onEscapeKeyDown={(event) => {
+ if (busy) event.preventDefault();
+ }}
+ >
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(
+ confirming?.action === "delete"
+ ? "settings.data.library.deleteItemsTitle"
+ : "settings.data.library.unarchiveItemsTitle",
+ { count: confirming?.rows.length ?? 0 },
+ )}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {confirming?.rows.length === 1
+ ? `"${confirming.rows[0].title}". `
+ : ""}
+ {confirming?.action === "delete"
+ ? t("settings.data.library.deleteFilesWarning")
+ : t("settings.data.library.restoreWarning")}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={busy}>
+ {t("common.cancel")}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ disabled={busy || !confirming?.rows.length}
+ variant={
+ confirming?.action === "delete" ? "destructive" : "default"
+ }
+ onClick={(event) => {
+ event.preventDefault();
+ if (confirming) void run(confirming.rows, confirming.action);
+ }}
+ >
+ {busy
+ ? t("settings.data.library.working")
+ : confirming?.action === "delete"
+ ? t("common.delete")
+ : t("settings.data.library.unarchive")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
);
}
diff --git a/studio/frontend/src/features/settings/components/data-library-controls.tsx b/studio/frontend/src/features/settings/components/data-library-controls.tsx
new file mode 100644
index 00000000000..0ec2f24ad8f
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/data-library-controls.tsx
@@ -0,0 +1,299 @@
+// 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 { useMemo, useState, type ReactNode } from "react";
+import { useLocale, useT, type TranslationKey } from "@/i18n";
+import { useLibraryProjectLabels } from "./use-library-project-labels";
+import { Folder01Icon, Search01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Command,
+ CommandEmpty,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
+import {
+ type LibraryFilters,
+ type LibraryItem,
+ type LibrarySort,
+ formatLibraryDate,
+ groupLibraryItems,
+} from "./data-library";
+
+const SORT_LABELS: Record<LibrarySort, TranslationKey> = {
+ default: "settings.data.library.defaultSort",
+ updated: "settings.data.library.updated",
+ created: "settings.data.library.created",
+ oldest: "settings.data.library.oldest",
+ alphabetical: "settings.data.library.alphabetical",
+};
+const TYPE_LABELS: Record<string, TranslationKey> = {
+ all: "settings.data.library.allChats",
+ single: "settings.data.library.singleChats",
+ compare: "settings.data.library.compareChats",
+};
+
+export function LibraryToolbar({
+ filters,
+ onChange,
+ placeholder,
+ projects,
+ disabled = false,
+}: {
+ filters: LibraryFilters;
+ onChange: (filters: LibraryFilters) => void;
+ placeholder: string;
+ projects?: ReadonlyMap<string, string>;
+ disabled?: boolean;
+}) {
+ const t = useT();
+ const locale = useLocale();
+ const compare = useMemo(() => new Intl.Collator(locale).compare, [locale]);
+ const [projectOpen, setProjectOpen] = useState(false);
+ const projectLabel =
+ filters.project === "all"
+ ? t("settings.data.library.allProjects")
+ : filters.project === "none"
+ ? t("settings.data.library.noProject")
+ : (projects?.get(filters.project.slice(8)) ??
+ t("settings.data.library.unavailableProject"));
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative min-w-48 flex-1">
+ <HugeiconsIcon
+ icon={Search01Icon}
+ className="pointer-events-none absolute start-3 top-3 size-4 text-muted-foreground"
+ />
+ <Input
+ type="search"
+ value={filters.query}
+ onChange={(event) =>
+ onChange({ ...filters, query: event.target.value })
+ }
+ disabled={disabled}
+ placeholder={placeholder}
+ aria-label={placeholder}
+ className="h-10 rounded-full ps-9"
+ />
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <Button
+ variant="outline"
+ disabled={disabled}
+ className="h-10 gap-2 rounded-xl"
+ aria-label={t("settings.data.library.filterSort")}
+ >
+ {projects
+ ? t(TYPE_LABELS[filters.type])
+ : filters.sort === "default"
+ ? t("settings.data.library.sort")
+ : t(SORT_LABELS[filters.sort])}
+ <HugeiconsIcon
+ icon={ChevronDownStandardIcon}
+ className="size-4 text-muted-foreground"
+ />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-52">
+ {projects && (
+ <>
+ <DropdownMenuLabel>
+ {t("settings.data.library.type")}
+ </DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={filters.type}
+ onValueChange={(type) => onChange({ ...filters, type })}
+ >
+ {Object.entries(TYPE_LABELS).map(([value, label]) => (
+ <DropdownMenuRadioItem key={value} value={value}>
+ {t(label)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ <DropdownMenuLabel>
+ {t("settings.data.library.sortBy")}
+ </DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={filters.sort}
+ onValueChange={(sort) =>
+ onChange({ ...filters, sort: sort as LibrarySort })
+ }
+ >
+ {Object.entries(SORT_LABELS)
+ .filter(([value]) =>
+ projects ? value !== "default" : value !== "updated",
+ )
+ .map(([value, label]) => (
+ <DropdownMenuRadioItem key={value} value={value}>
+ {t(label)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {projects && (
+ <Popover open={projectOpen} onOpenChange={setProjectOpen}>
+ <PopoverTrigger asChild={true}>
+ <Button
+ variant="outline"
+ disabled={disabled}
+ className="h-10 max-w-full gap-2 rounded-xl"
+ aria-label={t("settings.data.library.filterProject")}
+ >
+ <HugeiconsIcon icon={Folder01Icon} className="size-4 shrink-0" />
+ <span className="max-w-40 truncate">{projectLabel}</span>
+ <HugeiconsIcon
+ icon={ChevronDownStandardIcon}
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-64 p-1">
+ <Command>
+ <CommandInput
+ placeholder={t("settings.data.library.searchProjects")}
+ aria-label={t("settings.data.library.searchProjects")}
+ />
+ <CommandList>
+ <CommandEmpty>
+ {t("settings.data.library.noProjects")}
+ </CommandEmpty>
+ {[
+ ["all", t("settings.data.library.allProjects")],
+ ["none", t("settings.data.library.noProject")],
+ ...[...projects]
+ .sort((a, b) => compare(a[1], b[1]))
+ .map(([id, name]) => [`project:${id}`, name]),
+ ].map(([value, label]) => (
+ <CommandItem
+ key={value}
+ value={value}
+ keywords={[label]}
+ onSelect={() => {
+ onChange({ ...filters, project: value });
+ setProjectOpen(false);
+ }}
+ >
+ {label}
+ </CommandItem>
+ ))}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ );
+}
+
+export function LibraryRow({
+ title,
+ date,
+ leading,
+ actions,
+ onOpen,
+}: {
+ title: string;
+ date: number;
+ leading?: ReactNode;
+ actions?: ReactNode;
+ onOpen?: () => void;
+}) {
+ const t = useT();
+ const locale = useLocale();
+ return (
+ <div className="flex min-w-0 items-center gap-3 py-3.5 text-sm">
+ {leading}
+ <div className="min-w-0 flex-1">
+ {onOpen ? (
+ <button
+ type="button"
+ onClick={onOpen}
+ title={title}
+ className="block max-w-full truncate text-start font-medium hover:underline"
+ >
+ {title || t("settings.data.library.untitled")}
+ </button>
+ ) : (
+ <p title={title} className="truncate font-medium">
+ {title || t("settings.data.library.untitled")}
+ </p>
+ )}
+ <p className="mt-1 text-xs text-muted-foreground">
+ {formatLibraryDate(date, locale)}
+ </p>
+ </div>
+ {actions && (
+ <div className="flex shrink-0 items-center gap-1">{actions}</div>
+ )}
+ </div>
+ );
+}
+
+export function ChatLibraryGroups<T extends LibraryItem>({
+ items,
+ projects,
+ children,
+}: {
+ items: readonly T[];
+ projects: ReadonlyMap<string, string>;
+ children: (item: T) => ReactNode;
+}) {
+ const t = useT();
+ const labels = useLibraryProjectLabels();
+ return (
+ <div className="space-y-5">
+ {groupLibraryItems(items, projects, labels).map((group) => (
+ <section key={group.id} className="space-y-2">
+ <div className="flex items-center gap-2 px-1 text-sm">
+ <HugeiconsIcon
+ icon={Folder01Icon}
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ <h3
+ className="min-w-0 flex-1 truncate font-medium"
+ title={group.name}
+ >
+ {group.name}
+ </h3>
+ <span className="text-xs text-muted-foreground">
+ {t(
+ group.items.length === 1
+ ? "settings.data.library.oneChat"
+ : "settings.data.library.chatCount",
+ { count: group.items.length },
+ )}
+ </span>
+ </div>
+ <div className="divide-y divide-border/50 rounded-2xl border border-border/60 px-3 sm:px-4">
+ {group.items.map((item) => (
+ <div key={item.id}>{children(item)}</div>
+ ))}
+ </div>
+ </section>
+ ))}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/settings/components/data-library.ts b/studio/frontend/src/features/settings/components/data-library.ts
new file mode 100644
index 00000000000..ee974c326b9
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/data-library.ts
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type LibrarySort =
+ | "default"
+ | "updated"
+ | "created"
+ | "oldest"
+ | "alphabetical";
+export interface LibraryFilters {
+ query: string;
+ type: string;
+ project: string;
+ sort: LibrarySort;
+}
+export const DEFAULT_LIBRARY_FILTERS: LibraryFilters = {
+ query: "",
+ type: "all",
+ project: "all",
+ sort: "updated",
+};
+export interface LibraryItem {
+ id: string;
+ title: string;
+ createdAt: number;
+ updatedAt?: number;
+ type?: string;
+ projectId?: string | null;
+}
+
+export interface LibraryProjectLabels {
+ noProject: string;
+ unavailableProject: string;
+}
+
+function searchable(value: string): string {
+ return value.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase();
+}
+
+export function filterLibraryItems<T extends LibraryItem>(
+ items: readonly T[],
+ filters: LibraryFilters,
+ projects: ReadonlyMap<string, string> = new Map(),
+ labels?: LibraryProjectLabels,
+ locale?: string,
+): T[] {
+ const terms = searchable(filters.query).trim().split(/\s+/).filter(Boolean);
+ const timestamp = (item: T) => {
+ const value =
+ filters.sort === "updated"
+ ? (item.updatedAt ?? item.createdAt)
+ : item.createdAt;
+ return Number.isFinite(value) ? value : 0;
+ };
+ const matching = items.filter((item) => {
+ if (filters.type !== "all" && item.type !== filters.type) return false;
+ if (filters.project === "none" && item.projectId) return false;
+ if (
+ filters.project.startsWith("project:") &&
+ item.projectId !== filters.project.slice(8)
+ )
+ return false;
+ const project = item.projectId
+ ? (projects.get(item.projectId) ?? labels?.unavailableProject ?? "")
+ : (labels?.noProject ?? "");
+ const haystack = searchable(`${item.title} ${project}`);
+ return terms.every((term) => haystack.includes(term));
+ });
+ if (filters.sort === "default") return matching;
+ const compare = new Intl.Collator(locale).compare;
+ return matching.sort((a, b) => {
+ const byTitle = compare(a.title, b.title);
+ if (filters.sort === "alphabetical") return byTitle || compare(a.id, b.id);
+ const byTime =
+ (timestamp(b) - timestamp(a)) * (filters.sort === "oldest" ? -1 : 1);
+ return byTime || byTitle || compare(a.id, b.id);
+ });
+}
+
+export function groupLibraryItems<T extends LibraryItem>(
+ items: readonly T[],
+ projects: ReadonlyMap<string, string>,
+ labels: LibraryProjectLabels,
+) {
+ const groups = new Map<string, { id: string; name: string; items: T[] }>();
+ for (const item of items) {
+ const id = item.projectId ?? "";
+ let group = groups.get(id);
+ if (!group) {
+ group = {
+ id,
+ name: id
+ ? (projects.get(id) ?? labels.unavailableProject)
+ : labels.noProject,
+ items: [],
+ };
+ groups.set(id, group);
+ }
+ group.items.push(item);
+ }
+ return [...groups.values()];
+}
+
+export function formatLibraryDate(ms: number, locale?: string): string {
+ const date = new Date(ms);
+ return Number.isFinite(date.getTime())
+ ? date.toLocaleString(locale, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ })
+ : "";
+}
diff --git a/studio/frontend/src/features/settings/components/dictation-dictionary-view.tsx b/studio/frontend/src/features/settings/components/dictation-dictionary-view.tsx
index b6d375987fd..8f1db7fbf1e 100644
--- a/studio/frontend/src/features/settings/components/dictation-dictionary-view.tsx
+++ b/studio/frontend/src/features/settings/components/dictation-dictionary-view.tsx
@@ -46,9 +46,9 @@ export function DictationDictionaryView({ onBack }: { onBack: () => void }) {
type="button"
onClick={onBack}
aria-label={t("settings.voice.dictionary.backToVoice")}
- className="inline-flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ className="settings-back-button inline-flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
- <ChevronLeftIcon className="size-4" />
+ <ChevronLeftIcon className="size-4 rtl:rotate-180" />
</button>
<h1 className="font-heading text-xl font-semibold">
{t("settings.voice.title")}
diff --git a/studio/frontend/src/features/settings/components/manage-chats-view.tsx b/studio/frontend/src/features/settings/components/manage-chats-view.tsx
index c4e1cf6f556..570d6985e11 100644
--- a/studio/frontend/src/features/settings/components/manage-chats-view.tsx
+++ b/studio/frontend/src/features/settings/components/manage-chats-view.tsx
@@ -38,6 +38,7 @@ import {
usePinnedChatsStore,
} from "@/features/chat";
import { isDownloadCancelled } from "@/lib/native-files";
+import { useLocale, useT } from "@/i18n";
import { toast } from "@/lib/toast";
import {
Archive02Icon,
@@ -45,27 +46,39 @@ import {
Download01Icon,
Folder01Icon,
PinIcon,
+ Message01Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate, useRouterState } from "@tanstack/react-router";
-import { useRef, useState } from "react";
+import { useMemo, useRef, useState } from "react";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
-const MANAGE_PAGE_SIZE = 20;
-
-function formatCreatedAt(ms: number): string {
- return new Date(ms).toLocaleDateString(undefined, {
- year: "numeric",
- month: "long",
- day: "numeric",
- });
-}
+import { useLibraryProjectLabels } from "./use-library-project-labels";
+import {
+ DEFAULT_LIBRARY_FILTERS,
+ filterLibraryItems,
+ groupLibraryItems,
+ type LibraryFilters,
+} from "./data-library";
+import {
+ ChatLibraryGroups,
+ LibraryRow,
+ LibraryToolbar,
+} from "./data-library-controls";
-function chatCount(n: number): string {
- return n === 1 ? "1 chat" : `${n} chats`;
-}
+const MANAGE_PAGE_SIZE = 20;
export function ManageChatsView() {
+ const t = useT();
+ const locale = useLocale();
+ const labels = useLibraryProjectLabels();
+ const chatCount = (count: number) =>
+ t(
+ count === 1
+ ? "settings.data.library.oneChat"
+ : "settings.data.library.chatCount",
+ { count },
+ );
const { items } = useChatSidebarItems({ requireMessages: false });
const { projects } = useChatProjects();
const navigate = useNavigate();
@@ -91,17 +104,40 @@ export function ManageChatsView() {
const [busy, setBusy] = useState(false);
const lastToggledId = useRef<string | null>(null);
- const visible = items.slice(0, visibleCount);
+ const [filters, setFilters] = useState(DEFAULT_LIBRARY_FILTERS);
+ const projectNames = useMemo(
+ () => new Map(projects.map((p) => [p.id, p.name])),
+ [projects],
+ );
+ const filtered = useMemo(
+ () => filterLibraryItems(items, filters, projectNames, labels, locale),
+ [items, filters, projectNames, labels, locale],
+ );
+ const visible = groupLibraryItems(
+ filtered.slice(0, visibleCount),
+ projectNames,
+ labels,
+ ).flatMap((group) => group.items);
const selectedItems = items.filter((item) => selectedIds.has(item.id));
+
+ function changeFilters(next: LibraryFilters) {
+ setFilters(next);
+ setSelectedIds(new Set());
+ lastToggledId.current = null;
+ setVisibleCount(MANAGE_PAGE_SIZE);
+ }
const selectedCount = selectedItems.length;
+ const visibleSelectedCount = visible.filter((item) =>
+ selectedIds.has(item.id),
+ ).length;
const allVisibleSelected =
- visible.length > 0 && visible.every((item) => selectedIds.has(item.id));
+ visible.length > 0 && visibleSelectedCount === visible.length;
const allSelectedPinned =
selectedCount > 0 &&
selectedItems.every((item) => pinnedIds.includes(item.id));
- const projectNames = new Map(projects.map((p) => [p.id, p.name]));
function toggleRow(index: number, shiftKey: boolean) {
+ if (busy) return;
const rowId = visible[index].id;
const target = !selectedIds.has(rowId);
const anchorId = lastToggledId.current;
@@ -127,9 +163,15 @@ export function ManageChatsView() {
}
function toggleAllVisible() {
- setSelectedIds(
- allVisibleSelected ? new Set() : new Set(visible.map((item) => item.id)),
- );
+ if (busy) return;
+ setSelectedIds((previous) => {
+ const next = new Set(previous);
+ for (const item of visible) {
+ if (allVisibleSelected) next.delete(item.id);
+ else next.add(item.id);
+ }
+ return next;
+ });
lastToggledId.current = null;
}
@@ -173,8 +215,13 @@ export function ManageChatsView() {
const handleArchive = () =>
run(
() => archiveChatItems(selectedItems, openChatId, resetView),
- `Archived ${chatCount(selectedCount)}`,
- "Failed to archive chats",
+ t(
+ selectedCount === 1
+ ? "settings.data.archivedOneChat"
+ : "settings.data.archivedChatCount",
+ { count: selectedCount },
+ ),
+ t("settings.data.failedToArchiveChats"),
);
const handleDelete = () =>
@@ -185,8 +232,8 @@ export function ManageChatsView() {
deleteChatItems(selectedItems, openChatId, resetView, {
deleteFiles: alwaysDeleteChatFiles,
}),
- `Deleted ${chatCount(selectedCount)}`,
- "Failed to delete chats",
+ t("settings.data.library.deletedChats", { count: selectedCount }),
+ t("settings.data.library.deleteFailed"),
);
const handleMove = (projectId: string | null) =>
@@ -197,16 +244,26 @@ export function ManageChatsView() {
);
},
projectId
- ? `Moved ${chatCount(selectedCount)} to ${projectNames.get(projectId) ?? "project"}`
- : `Moved ${chatCount(selectedCount)} to Recents`,
- "Failed to move chats",
+ ? t("settings.data.library.movedChatsToProject", {
+ count: selectedCount,
+ project: projectNames.get(projectId) ?? labels.unavailableProject,
+ })
+ : t("settings.data.library.movedChatsToRecents", {
+ count: selectedCount,
+ }),
+ t("settings.data.library.moveFailed"),
);
function handleTogglePin() {
const ids = selectedItems.map((item) => item.id);
setPinned(ids, !allSelectedPinned);
toast.success(
- `${allSelectedPinned ? "Unpinned" : "Pinned"} ${chatCount(ids.length)}`,
+ t(
+ allSelectedPinned
+ ? "settings.data.library.unpinnedChats"
+ : "settings.data.library.pinnedChats",
+ { count: ids.length },
+ ),
);
setSelectedIds(new Set());
}
@@ -223,194 +280,212 @@ export function ManageChatsView() {
await exportBulkConversationsSeparate(threadIds, format, basename);
}
} catch (error) {
- if (!isDownloadCancelled(error)) toast.error("Export failed.");
+ if (!isDownloadCancelled(error))
+ toast.error(t("settings.data.exportFailed"));
}
}
- if (items.length === 0) {
- return (
- <p className="py-8 text-center text-sm text-muted-foreground">
- No chats.
- </p>
- );
- }
-
const actionsDisabled = busy || selectedCount === 0;
return (
<div className="flex flex-col gap-4">
+ <LibraryToolbar
+ filters={filters}
+ onChange={changeFilters}
+ placeholder={t("settings.data.library.searchChats")}
+ projects={projectNames}
+ disabled={busy}
+ />
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-1 items-center gap-3 px-1">
<Checkbox
checked={
allVisibleSelected
? true
- : selectedCount > 0
+ : visibleSelectedCount > 0
? "indeterminate"
: false
}
+ disabled={busy || visible.length === 0}
onCheckedChange={toggleAllVisible}
- aria-label="Select all visible chats"
- title="Select all visible"
+ aria-label={t("settings.data.library.selectAll")}
+ title={t("settings.data.library.selectAll")}
/>
<span className="text-xs text-muted-foreground">
{selectedCount > 0
- ? `${chatCount(selectedCount)} selected`
- : chatCount(items.length)}
+ ? t("settings.data.library.selectedChats", {
+ count: selectedCount,
+ })
+ : chatCount(filtered.length)}
</span>
</div>
- <DropdownMenu>
- <DropdownMenuTrigger asChild={true}>
- <Button variant="outline" size="sm" disabled={actionsDisabled}>
+ {selectedCount > 0 && (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <Button variant="outline" size="sm" disabled={actionsDisabled}>
+ <HugeiconsIcon
+ icon={Folder01Icon}
+ strokeWidth={1.75}
+ className="size-3.5 mr-1.5"
+ />
+ {t("settings.data.library.move")}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-52">
+ <DropdownMenuItem
+ disabled={selectedItems.every((item) => !item.projectId)}
+ onSelect={() => void handleMove(null)}
+ >
+ {t("shell.navigation.recents")}
+ </DropdownMenuItem>
+ {projects.map((project) => (
+ <DropdownMenuItem
+ key={project.id}
+ onSelect={() => void handleMove(project.id)}
+ >
+ <HugeiconsIcon
+ icon={Folder01Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ <span className="truncate">{project.name}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={actionsDisabled}
+ onClick={handleTogglePin}
+ >
<HugeiconsIcon
- icon={Folder01Icon}
+ icon={PinIcon}
strokeWidth={1.75}
className="size-3.5 mr-1.5"
/>
- Move
+ {allSelectedPinned
+ ? t("settings.data.library.unpin")
+ : t("settings.data.library.pin")}
</Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-52">
- <DropdownMenuItem
- disabled={selectedItems.every((item) => !item.projectId)}
- onSelect={() => void handleMove(null)}
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={actionsDisabled}
+ onClick={() => void handleArchive()}
>
- Recents
- </DropdownMenuItem>
- {projects.map((project) => (
- <DropdownMenuItem
- key={project.id}
- onSelect={() => void handleMove(project.id)}
- >
- <HugeiconsIcon
- icon={Folder01Icon}
- strokeWidth={1.75}
- className="size-4"
- />
- <span className="truncate">{project.name}</span>
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- <Button
- variant="outline"
- size="sm"
- disabled={actionsDisabled}
- onClick={handleTogglePin}
- >
- <HugeiconsIcon
- icon={PinIcon}
- strokeWidth={1.75}
- className="size-3.5 mr-1.5"
- />
- {allSelectedPinned ? "Unpin" : "Pin"}
- </Button>
- <Button
- variant="outline"
- size="sm"
- disabled={actionsDisabled}
- onClick={() => void handleArchive()}
- >
- <HugeiconsIcon
- icon={Archive02Icon}
- strokeWidth={1.75}
- className="size-3.5 mr-1.5"
- />
- Archive
- </Button>
- <DropdownMenu>
- <DropdownMenuTrigger asChild={true}>
- <Button variant="outline" size="sm" disabled={actionsDisabled}>
<HugeiconsIcon
- icon={Download01Icon}
+ icon={Archive02Icon}
strokeWidth={1.75}
className="size-3.5 mr-1.5"
/>
- Export
+ {t("settings.data.library.archive")}
</Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-56">
- {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
- <DropdownMenuItem
- key={`m-${fmt}`}
- onSelect={() => void handleExport(fmt, true)}
- >
- {label} (combined)
- </DropdownMenuItem>
- ))}
- <DropdownMenuSeparator />
- {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
- <DropdownMenuItem
- key={`s-${fmt}`}
- onSelect={() => void handleExport(fmt, false)}
- >
- {label} (per chat)
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- <Button
- variant="outline"
- size="sm"
- disabled={actionsDisabled}
- onClick={() => setConfirmingDelete(true)}
- className="text-destructive hover:text-destructive hover:border-destructive/60"
- >
- <HugeiconsIcon
- icon={Delete02Icon}
- strokeWidth={1.75}
- className="size-3.5 mr-1.5"
- />
- Delete
- </Button>
- </div>
-
- <div>
- <div className="flex items-center gap-4 border-b border-border/60 px-1 pb-2 text-xs font-semibold text-foreground">
- <span className="w-4 shrink-0" />
- <span className="flex-1">Name</span>
- <span className="w-28 shrink-0">Project</span>
- <span className="w-32 shrink-0">Date created</span>
- </div>
- {visible.map((item, index) => (
- <div
- key={item.id}
- className="group flex items-center gap-4 border-b border-border/40 px-1 py-2.5 text-sm last:border-0 hover:bg-muted/40"
- >
- <Checkbox
- checked={selectedIds.has(item.id)}
- onClick={(e) => toggleRow(index, e.shiftKey)}
- aria-label={`Select "${item.title}"`}
- />
- <button
- type="button"
- onClick={() => openChat(item)}
- className="min-w-0 flex-1 truncate text-left hover:underline"
- title={item.title}
- >
- {item.title}
- </button>
- <span className="w-28 shrink-0 truncate text-muted-foreground">
- {item.projectId ? (projectNames.get(item.projectId) ?? "") : ""}
- </span>
- <span className="w-32 shrink-0 text-muted-foreground tabular-nums">
- {formatCreatedAt(item.createdAt)}
- </span>
- </div>
- ))}
- {items.length > visibleCount ? (
- <div className="flex justify-center pt-3">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <Button variant="outline" size="sm" disabled={actionsDisabled}>
+ <HugeiconsIcon
+ icon={Download01Icon}
+ strokeWidth={1.75}
+ className="size-3.5 mr-1.5"
+ />
+ {t("common.export")}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-56">
+ {COMBINED_EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
+ <DropdownMenuItem
+ key={`m-${fmt}`}
+ onSelect={() => void handleExport(fmt, true)}
+ >
+ {label} {t("settings.chat.exportCombinedSuffix")}
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator />
+ {EXPORT_FORMATS_LIST.map(({ fmt, label }) => (
+ <DropdownMenuItem
+ key={`s-${fmt}`}
+ onSelect={() => void handleExport(fmt, false)}
+ >
+ {label} {t("settings.chat.exportPerChatSuffix")}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
<Button
variant="outline"
size="sm"
- onClick={() => setVisibleCount(visibleCount + MANAGE_PAGE_SIZE)}
+ disabled={actionsDisabled}
+ onClick={() => setConfirmingDelete(true)}
+ className="text-destructive hover:text-destructive hover:border-destructive/60"
>
- Show more ({items.length - visibleCount})
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ strokeWidth={1.75}
+ className="size-3.5 mr-1.5"
+ />
+ {t("common.delete")}
</Button>
- </div>
- ) : null}
+ </>
+ )}
</div>
+ {filtered.length === 0 ? (
+ <p
+ role="status"
+ className="py-8 text-center text-sm text-muted-foreground"
+ >
+ {t("settings.data.library.noChats")}
+ </p>
+ ) : (
+ <ChatLibraryGroups items={visible} projects={projectNames}>
+ {(item) => (
+ <LibraryRow
+ title={item.title}
+ date={
+ filters.sort === "updated" ? item.updatedAt : item.createdAt
+ }
+ onOpen={() => openChat(item)}
+ leading={
+ <>
+ <Checkbox
+ checked={selectedIds.has(item.id)}
+ disabled={busy}
+ onClick={(event) =>
+ toggleRow(
+ visible.findIndex((row) => row.id === item.id),
+ event.shiftKey,
+ )
+ }
+ aria-label={t("settings.data.library.selectItem", {
+ title: item.title,
+ })}
+ />
+ <HugeiconsIcon
+ icon={Message01Icon}
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ </>
+ }
+ />
+ )}
+ </ChatLibraryGroups>
+ )}
+ {filtered.length > visibleCount && (
+ <div className="flex justify-center">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setVisibleCount((count) => count + MANAGE_PAGE_SIZE)}
+ >
+ {t("settings.voice.recents.showMore", {
+ count: filtered.length - visibleCount,
+ })}
+ </Button>
+ </div>
+ )}
+
<AlertDialog
open={confirmingDelete}
onOpenChange={(o) => {
@@ -420,18 +495,18 @@ export function ManageChatsView() {
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
- Delete {chatCount(selectedCount)}
+ {t("settings.data.library.deleteChatsTitle", {
+ count: selectedCount,
+ })}
</AlertDialogTitle>
<AlertDialogDescription>
- Delete the{" "}
- {selectedCount === 1
- ? "selected chat"
- : `${selectedCount} selected chats`}
- ? This cannot be undone.
+ {t("settings.data.library.deleteChatsWarning", {
+ count: selectedCount,
+ })}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={() => {
@@ -439,7 +514,7 @@ export function ManageChatsView() {
void handleDelete();
}}
>
- Delete
+ {t("common.delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
diff --git a/studio/frontend/src/features/settings/components/recent-dictations-view.tsx b/studio/frontend/src/features/settings/components/recent-dictations-view.tsx
index 7dde8046282..999227261d1 100644
--- a/studio/frontend/src/features/settings/components/recent-dictations-view.tsx
+++ b/studio/frontend/src/features/settings/components/recent-dictations-view.tsx
@@ -206,9 +206,9 @@ export function RecentDictationsView({
? t("settings.voice.recents.backToRecents")
: t("settings.voice.recents.backToVoice")
}
- className="inline-flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ className="settings-back-button inline-flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
- <ChevronLeftIcon className="size-4" />
+ <ChevronLeftIcon className="size-4 rtl:rotate-180" />
</button>
<h1 className="font-heading text-xl font-semibold">
{t("settings.voice.title")}
diff --git a/studio/frontend/src/features/settings/components/use-library-project-labels.ts b/studio/frontend/src/features/settings/components/use-library-project-labels.ts
new file mode 100644
index 00000000000..cd1307a7fe3
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/use-library-project-labels.ts
@@ -0,0 +1,16 @@
+// 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 { useMemo } from "react";
+import { useT } from "@/i18n";
+
+export function useLibraryProjectLabels() {
+ const t = useT();
+ return useMemo(
+ () => ({
+ noProject: t("settings.data.library.noProject"),
+ unavailableProject: t("settings.data.library.unavailableProject"),
+ }),
+ [t],
+ );
+}
diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsx
index 670cf937c75..fe64a69ae8c 100644
--- a/studio/frontend/src/features/settings/settings-dialog.tsx
+++ b/studio/frontend/src/features/settings/settings-dialog.tsx
@@ -56,6 +56,11 @@ import {
type SettingsTab,
useSettingsDialogStore,
} from "./stores/settings-dialog-store";
+
+interface SettingsPanelProps {
+ searchEntry?: string;
+}
+
// Statically imported, every panel ran before first paint even though the dialog
// starts closed. Load each on first view instead; this map also drives the prefetch.
const TAB_LOADERS = {
@@ -91,12 +96,14 @@ const TAB_LOADERS = {
import("./tabs/debugging-tab").then((m) => ({ default: m.DebuggingTab })),
about: () =>
import("./tabs/about-tab").then((m) => ({ default: m.AboutTab })),
-} satisfies Record<SettingsTab, () => Promise<{ default: FC }>>;
+} satisfies Record<SettingsTab, () => Promise<{ default: FC<SettingsPanelProps> }>>;
-function lazyTabs<T extends Record<string, () => Promise<{ default: FC }>>>(
+function lazyTabs<
+ T extends Record<string, () => Promise<{ default: FC<SettingsPanelProps> }>>,
+>(
loaders: T,
-): Record<keyof T, ComponentType> {
- const out = {} as Record<keyof T, ComponentType>;
+): Record<keyof T, ComponentType<SettingsPanelProps>> {
+ const out = {} as Record<keyof T, ComponentType<SettingsPanelProps>>;
for (const id of Object.keys(loaders) as (keyof T)[]) {
out[id] = lazy(loaders[id]);
}
@@ -250,11 +257,6 @@ const SETTINGS_SEARCH_INDEX = createSettingsSearchIndex({
clientPlatform.includes("linux")),
});
-function renderTab(tab: SettingsTab) {
- const Tab = LAZY_TABS[tab];
- return <Tab />;
-}
-
export function SettingsDialog() {
const t = useT();
const isOwner = useIsAccountOwner();
@@ -271,6 +273,7 @@ export function SettingsDialog() {
// the highlight lag the click. Render the panel from a deferred value so the nav updates first.
const deferredTab = useDeferredValue(activeTab);
const panelTab = resolveSettingsTab(deferredTab, isOwner);
+ const Tab = LAZY_TABS[panelTab];
const [query, setQuery] = useState("");
// Once opened, pull the other panels in on idle so a tab click never waits on the
@@ -617,7 +620,7 @@ export function SettingsDialog() {
<button
type="button"
onClick={closeDialog}
- className="absolute top-3 right-3 z-10 flex size-[30px] items-center justify-center rounded-[10px] text-[#383835] dark:text-[#c7c7c4] transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ className="absolute top-3 end-3 z-10 flex size-[30px] items-center justify-center rounded-[10px] text-[#383835] dark:text-[#c7c7c4] transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
aria-label={t("settings.dialog.closeAriaLabel")}
>
<HugeiconsIcon icon={Cancel01Icon} className="size-4" />
@@ -640,7 +643,13 @@ export function SettingsDialog() {
</div>
}
>
- {renderTab(panelTab)}
+ <Tab
+ searchEntry={
+ pendingScroll?.tab === panelTab
+ ? pendingScroll.entry
+ : undefined
+ }
+ />
</Suspense>
</SettingsPanelBoundary>
</div>
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 7e2907b8d02..d1084e177d9 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -119,7 +119,12 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.data.archivedChats",
"settings.data.archiveAllChats",
"settings.data.confirmBeforeDeleting",
- "settings.data.alwaysDeleteFiles",
+ "settings.data.sandboxFiles",
+ "settings.data.deletionSection",
+ "settings.data.archives",
+ "settings.data.archivedImages",
+ "settings.data.archivedVideos",
+ "settings.data.archivedAudio",
"settings.data.uploadedFiles",
"settings.chat.exportHistory",
"settings.chat.exportConversations",
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index a99536e33d9..47d38be83d4 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -21,6 +21,13 @@ import {
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";
@@ -61,8 +68,12 @@ import { isDownloadCancelled, pickNativeChatImport } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import {
Archive02Icon,
+ AudioWave01Icon,
Delete02Icon,
Download01Icon,
+ FlimSlateIcon,
+ Image03Icon,
+ Message01Icon,
Tick02Icon,
Upload01Icon,
} from "@hugeicons/core-free-icons";
@@ -99,7 +110,7 @@ const SUBPAGE_FOR_SHELF = {
audio: "archived-audio",
} as const;
-export function DataTab() {
+export function DataTab({ searchEntry }: { searchEntry?: string }) {
const t = useT();
const isOwner = useIsAccountOwner();
const navigate = useNavigate();
@@ -121,12 +132,19 @@ export function DataTab() {
| "archived-videos"
| "archived-audio"
| "files"
- >(archivedRequested ? SUBPAGE_FOR_SHELF[archivedRequested] : "main");
+ >(
+ 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);
// Gates the archived subpage Export button.
- const { archivedItems } = useChatSidebarItems({ requireMessages: false });
+ const { archivedItems } = useChatSidebarItems({
+ requireMessages: false,
+ enabled: subpage === "archived",
+ });
const [clearing, setClearing] = useState(false);
const [archiving, setArchiving] = useState(false);
const [fineTuneExporting, setFineTuneExporting] = useState(false);
@@ -153,20 +171,24 @@ export function DataTab() {
chatOnly && restoredAction === "train" ? "export" : restoredAction;
// Chat Completions (OpenAI messages) is the only export format we ship.
const fineTuneFormat: FineTuneFormat = "openai";
- // Requests can arrive after Data is already mounted (for example from the
- // archive-all toast), so always switch before consuming the flag.
+ // Search needs the main-page anchors even when a subpage is already open.
useEffect(() => {
- if (!archivedRequested) return;
+ const next = searchEntry
+ ? "main"
+ : archivedRequested
+ ? SUBPAGE_FOR_SHELF[archivedRequested]
+ : null;
+ if (!next) return;
let cancelled = false;
queueMicrotask(() => {
if (cancelled) return;
- setSubpage(SUBPAGE_FOR_SHELF[archivedRequested]);
+ setSubpage(next);
consumeArchivedChatsRequest();
});
return () => {
cancelled = true;
};
- }, [archivedRequested, consumeArchivedChatsRequest]);
+ }, [archivedRequested, searchEntry, consumeArchivedChatsRequest]);
useEffect(() => {
if (!ragAvailabilityUnknown) return;
@@ -218,8 +240,23 @@ export function DataTab() {
});
useEffect(() => {
- void countAllChats().then(setCount);
- }, []);
+ 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 handleExport = async () => {
setExporting(true);
@@ -427,6 +464,11 @@ export function DataTab() {
else void handleFineTuneExport();
};
+ const openClearConfirmation = (deleteFiles?: boolean) => {
+ setDeleteFilesOnClear(deleteFiles ?? alwaysDeleteChatFiles);
+ setConfirmOpen(true);
+ };
+
const handleClear = async () => {
setClearing(true);
try {
@@ -497,9 +539,9 @@ export function DataTab() {
type="button"
onClick={() => setSubpage("main")}
aria-label={t("settings.data.backToData")}
- className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ 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"
>
- <ChevronLeftIcon className="size-4" />
+ <ChevronLeftIcon className="size-4 rtl:rotate-180" />
</button>
<h1 className="text-xl font-semibold font-heading">
{t("settings.data.title")}
@@ -526,9 +568,9 @@ export function DataTab() {
type="button"
onClick={() => setSubpage("main")}
aria-label={t("settings.data.backToData")}
- className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ 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"
>
- <ChevronLeftIcon className="size-4" />
+ <ChevronLeftIcon className="size-4 rtl:rotate-180" />
</button>
<h1 className="text-xl font-semibold font-heading">
{t("settings.data.title")}
@@ -599,9 +641,9 @@ export function DataTab() {
type="button"
onClick={() => setSubpage("main")}
aria-label={t("settings.data.backToData")}
- className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ 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"
>
- <ChevronLeftIcon className="size-4" />
+ <ChevronLeftIcon className="size-4 rtl:rotate-180" />
</button>
<h1 className="text-xl font-semibold font-heading">
{t("settings.data.title")}
@@ -627,9 +669,9 @@ export function DataTab() {
type="button"
onClick={() => setSubpage("main")}
aria-label={t("settings.data.backToData")}
- className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ 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"
>
- <ChevronLeftIcon className="size-4" />
+ <ChevronLeftIcon className="size-4 rtl:rotate-180" />
</button>
<h1 className="text-xl font-semibold font-heading">
{t("settings.data.title")}
@@ -659,69 +701,7 @@ export function DataTab() {
</p>
</header>
- <div className="flex flex-col divide-y divide-border/60">
- <SettingsRow
- alignTop={true}
- label={t("settings.data.fineTuneExport")}
- description={t("settings.data.fineTuneExportDescription")}
- >
- <div className="flex items-center gap-2">
- <DropdownMenu>
- <DropdownMenuTrigger asChild={true}>
- {/* Fixed width so switching actions never resizes the row. */}
- <Button
- variant="outline"
- 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" && chatOnly}
- 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 title={t("settings.data.chatsSection")}>
<SettingsRow
label={t("settings.data.manageChats")}
description={t("settings.data.manageChatsDescription")}
@@ -734,59 +714,61 @@ export function DataTab() {
{t("settings.data.manageAction")}
</Button>
</SettingsRow>
-
- <SettingsRow
- label={t("settings.data.archivedChats")}
- description={t("settings.data.archivedChatsDescription")}
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setSubpage("archived")}
- >
- {t("settings.data.manageAction")}
- </Button>
- </SettingsRow>
-
- <SettingsRow
- label={t("settings.data.archivedImages")}
- description={t("settings.data.archivedImagesDescription")}
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setSubpage("archived-images")}
- >
- {t("settings.data.manageAction")}
- </Button>
- </SettingsRow>
-
- <SettingsRow
- label={t("settings.data.archivedVideos")}
- description={t("settings.data.archivedVideosDescription")}
- >
- <Button
- variant="outline"
- size="sm"
- onClick={() => setSubpage("archived-videos")}
- >
- {t("settings.data.manageAction")}
- </Button>
- </SettingsRow>
-
- <SettingsRow
- label={t("settings.data.archivedAudio")}
- description={t("settings.data.archivedAudioDescription")}
+ <div
+ data-settings-label={t("settings.data.archives")}
+ className="py-3"
>
- <Button
- variant="outline"
- size="sm"
- onClick={() => setSubpage("archived-audio")}
- >
- {t("settings.data.manageAction")}
- </Button>
- </SettingsRow>
-
+ <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", Message01Icon],
+ [
+ "archived-images",
+ "archivedImages",
+ "shell.navigation.images",
+ Image03Icon,
+ ],
+ [
+ "archived-videos",
+ "archivedVideos",
+ "settings.data.archiveVideosLabel",
+ FlimSlateIcon,
+ ],
+ [
+ "archived-audio",
+ "archivedAudio",
+ "shell.navigation.audio",
+ AudioWave01Icon,
+ ],
+ ] 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="flex min-w-0 items-center justify-between gap-2 rounded-xl border border-border/60 px-3 py-2.5 text-sm transition-colors hover:bg-muted 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")}
@@ -800,27 +782,40 @@ export function DataTab() {
{t("settings.data.archiveAllAction")}
</Button>
</SettingsRow>
+ </SettingsSection>
+ <SettingsSection title={t("settings.data.transferSection")}>
<SettingsRow
- label={t("settings.data.confirmBeforeDeleting")}
- description={t("settings.data.confirmBeforeDeletingDescription")}
- >
- <Switch
- checked={confirmDeleteChats}
- onCheckedChange={setConfirmDeleteChats}
- />
- </SettingsRow>
-
- <SettingsRow
- label={t("settings.data.alwaysDeleteFiles")}
- description={t("settings.data.alwaysDeleteFilesDescription")}
+ label={t("settings.chat.importChats")}
+ description={t("settings.chat.importChatsDescription")}
>
- <Switch
- checked={alwaysDeleteChatFiles}
- onCheckedChange={setAlwaysDeleteChatFiles}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void handleImportClick()}
+ // A second pick mid-import would interleave two streams into one
+ // history, and on desktop it retires the running import's handle.
+ disabled={importing}
+ >
+ {importing ? (
+ <Spinner className="size-3.5 mr-1.5" />
+ ) : (
+ <HugeiconsIcon icon={Upload01Icon} className="size-3.5 mr-1.5" />
+ )}
+ {t("settings.chat.importChatsAction")}
+ </Button>
+ <input
+ ref={importInputRef}
+ type="file"
+ accept=".json,.jsonl,.ndjson,.csv"
+ className="hidden"
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (file) void handleImport(fileImportSource(file));
+ }}
/>
</SettingsRow>
-
<SettingsRow
label={t("settings.chat.exportHistory")}
description={t("settings.chat.exportHistoryDescription")}
@@ -837,10 +832,10 @@ export function DataTab() {
: t("settings.chat.exportAction")}
</Button>
</SettingsRow>
-
<SettingsRow
label={t("settings.chat.exportConversations")}
- description={t("settings.chat.exportConversationsDescription")}
+ description={t("settings.data.exportFormatsSummary")}
+ hint={t("settings.chat.exportConversationsDescription")}
>
<DropdownMenu>
<DropdownMenuTrigger asChild={true}>
@@ -895,69 +890,151 @@ export function DataTab() {
</DropdownMenuContent>
</DropdownMenu>
</SettingsRow>
-
<SettingsRow
- destructive={true}
- // divide-y already draws the row separator; drop the extra border.
- className="border-t-0 mt-0 pt-3"
- 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 })
- }
+ label={t("settings.data.fineTuneExport")}
+ description={t("settings.data.trainingSummary")}
+ hint={t("settings.data.fineTuneExportDescription")}
>
- <Button
- variant="outline"
- size="sm"
- onClick={() => {
- setDeleteFilesOnClear(alwaysDeleteChatFiles);
- setConfirmOpen(true);
- }}
- disabled={count === 0}
- className="text-destructive hover:text-destructive hover:border-destructive/60"
- >
- <HugeiconsIcon icon={Delete02Icon} className="size-3.5 mr-1.5" />
- {t("settings.chat.clearChatsAction")}
- </Button>
+ <div className="flex items-center gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ {/* Fixed width so switching actions never resizes the row. */}
+ <Button
+ variant="outline"
+ 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" && chatOnly}
+ 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.chat.importChats")}
- description={t("settings.chat.importChatsDescription")}
+ label={t("settings.data.confirmBeforeDeleting")}
+ description={t("settings.data.confirmDeletionSummary")}
>
- <Button
- variant="outline"
- size="sm"
- onClick={() => void handleImportClick()}
- // A second pick mid-import would interleave two streams into one
- // history, and on desktop it retires the running import's handle.
- disabled={importing}
- >
- {importing ? (
- <Spinner className="size-3.5 mr-1.5" />
- ) : (
- <HugeiconsIcon icon={Upload01Icon} className="size-3.5 mr-1.5" />
- )}
- {t("settings.chat.importChatsAction")}
- </Button>
- <input
- ref={importInputRef}
- type="file"
- accept=".json,.jsonl,.ndjson,.csv"
- className="hidden"
- onChange={(e) => {
- const file = e.target.files?.[0];
- e.target.value = "";
- if (file) void handleImport(fileImportSource(file));
- }}
+ <Switch
+ aria-label={t("settings.data.confirmBeforeDeleting")}
+ checked={confirmDeleteChats}
+ onCheckedChange={setConfirmDeleteChats}
/>
</SettingsRow>
- </div>
+ <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="outline"
+ size="sm"
+ disabled={count === null || count === 0 || clearing}
+ className="text-destructive hover:text-destructive aria-expanded:text-destructive hover:border-destructive/60"
+ >
+ <HugeiconsIcon icon={Delete02Icon} 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>
<SettingsSection title={t("settings.data.filesSection")}>
<SettingsRow
@@ -1006,8 +1083,13 @@ export function DataTab() {
</DialogContent>
</Dialog>
- <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
- <DialogContent className="max-w-md">
+ <Dialog
+ open={confirmOpen}
+ onOpenChange={(open) => {
+ if (!clearing) setConfirmOpen(open);
+ }}
+ >
+ <DialogContent className="max-w-md" showCloseButton={!clearing}>
<DialogHeader>
<DialogTitle>
{count === 1
@@ -1018,15 +1100,21 @@ export function DataTab() {
{t("settings.chat.clearChatsConfirmDescription")}
</DialogDescription>
</DialogHeader>
- <DeleteChatFilesSwitch
- id="clear-chats-delete-files"
- checked={deleteFilesOnClear}
- onCheckedChange={setDeleteFilesOnClear}
- // Every chat at once, so the per-chat wording does not fit.
- description={t("shell.selection.deleteFilesDescription")}
- />
+ <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" onClick={() => setConfirmOpen(false)}>
+ <Button
+ variant="outline"
+ disabled={clearing}
+ onClick={() => setConfirmOpen(false)}
+ >
{t("common.cancel")}
</Button>
<Button
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 48c9a0604e5..1d9bfd66353 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1521,7 +1521,7 @@ export const ar = {
exportPerChatSuffix: "(لكل محادثة)",
importChats: "استيراد المحادثات",
importChatsDescription:
- "استيراد ملف تصدير من Open WebUI أو JSONL أو NDJSON أو CSV إلى الأخيرة.",
+ "استيراد ملفات JSON أو JSONL أو NDJSON أو CSV إلى الأخيرة.",
importChatsAction: "استيراد",
importNoConversations: "لم يُعثر على محادثات في الملف.",
importedOneChat: "تم استيراد محادثة واحدة إلى العناصر الأخيرة.",
@@ -1567,6 +1567,80 @@ export const ar = {
failedToClearChats: "فشل مسح المحادثات",
},
data: {
+ library: {
+ defaultSort: "الافتراضي",
+ updated: "التحديث",
+ created: "الإنشاء",
+ oldest: "الأقدم أولاً",
+ alphabetical: "أبجديًا",
+ allChats: "كل المحادثات",
+ singleChats: "محادثات فردية",
+ compareChats: "محادثات المقارنة",
+ allProjects: "كل المشاريع",
+ noProject: "بلا مشروع",
+ unavailableProject: "المشروع غير متاح",
+ filterSort: "التصفية والترتيب",
+ sort: "الترتيب",
+ type: "النوع",
+ sortBy: "الترتيب حسب",
+ filterProject: "التصفية حسب المشروع",
+ searchProjects: "البحث في المشاريع",
+ noProjects: "لم يتم العثور على مشاريع.",
+ untitled: "بلا عنوان",
+ oneChat: "محادثة واحدة",
+ chatCount: "عدد المحادثات: {count}",
+ searchChats: "البحث في المحادثات أو المشاريع",
+ searchArchivedChats: "البحث في المحادثات المؤرشفة أو المشاريع",
+ searchImages: "البحث في الصور المؤرشفة",
+ searchVideos: "البحث في الفيديوهات المؤرشفة",
+ searchAudio: "البحث في المقاطع الصوتية المؤرشفة",
+ unarchive: "إلغاء الأرشفة",
+ unarchiveAll: "إلغاء أرشفة الكل",
+ unarchiveResults: "إلغاء أرشفة النتائج",
+ deleteResults: "حذف النتائج",
+ noChats: "لا توجد محادثات تطابق بحثك.",
+ noArchivedChats: "لا توجد محادثات مؤرشفة.",
+ noArchivedMatches: "لا توجد محادثات مؤرشفة تطابق بحثك.",
+ noMedia: "لا توجد عناصر مؤرشفة.",
+ noMediaMatches: "لا توجد عناصر مؤرشفة تطابق بحثك.",
+ itemCount: "عدد العناصر: {count}",
+ incompleteSearch: "البحث غير مكتمل. أعد محاولة تحميل العناصر المتبقية.",
+ searchingRemaining: "جارٍ البحث في العناصر المتبقية (تم تحميل {count})...",
+ noLoadedMatches: "لا توجد نتائج مطابقة في العناصر المحملة حتى الآن.",
+ deleteItem: "حذف: {title}",
+ unarchiveItem: "إلغاء الأرشفة: {title}",
+ deleteItemsTitle: "حذف العناصر المؤرشفة ({count})",
+ unarchiveItemsTitle: "إلغاء أرشفة العناصر ({count})",
+ deleteFilesWarning: "سيتم حذف هذه الملفات نهائيًا. لا يمكن التراجع عن هذا الإجراء.",
+ restoreWarning: "ستعود هذه العناصر إلى المعرض.",
+ working: "جارٍ التنفيذ...",
+ loadFailed: "تعذر تحميل العناصر المؤرشفة",
+ loadMoreFailed: "تعذر تحميل المزيد من العناصر المؤرشفة",
+ restoreFailed: "تعذر إلغاء أرشفة العناصر المحددة",
+ deleteFailed: "تعذر حذف العناصر المحددة",
+ projectsFailed: "تعذر تحميل المشاريع المؤرشفة",
+ pageStalled: "لم تتقدم صفحة الأرشيف. حاول مرة أخرى.",
+ pageChanged: "تغير الأرشيف أثناء التحميل. حاول مرة أخرى.",
+ selectAll: "تحديد كل المحادثات الظاهرة",
+ selectItem: "تحديد «{title}»",
+ selectedChats: "المحادثات المحددة: {count}",
+ move: "نقل",
+ pin: "تثبيت",
+ unpin: "إلغاء التثبيت",
+ archive: "أرشفة",
+ deletedChats: "المحادثات المحذوفة: {count}",
+ restoredChats: "المحادثات الملغاة أرشفتها: {count}",
+ pinnedChats: "المحادثات المثبتة: {count}",
+ unpinnedChats: "المحادثات الملغى تثبيتها: {count}",
+ movedChatsToProject: "المحادثات المنقولة إلى {project}: {count}",
+ movedChatsToRecents: "المحادثات المنقولة إلى الأخيرة: {count}",
+ moveFailed: "تعذر نقل المحادثات",
+ deleteChatsTitle: "حذف المحادثات ({count})",
+ deleteChatsWarning: "هل تريد حذف المحادثات المحددة ({count})؟ لا يمكن التراجع عن هذا الإجراء.",
+ deleteArchivedTitle: "حذف المحادثات المؤرشفة ({count})",
+ deleteArchivedWarning: "هل تريد حذف المحادثات المؤرشفة المحددة ({count})؟ لا يمكن التراجع عن هذا الإجراء.",
+ deleting: "جارٍ الحذف...",
+ },
title: "البيانات",
backToData: "العودة إلى البيانات",
exportFailed: "تعذّر تصدير المحادثات",
@@ -1609,6 +1683,27 @@ export const ar = {
alwaysDeleteFiles: "حذف الملفات دائمًا",
alwaysDeleteFilesDescription:
"حذف المحادثة يزيل أيضًا مجلد بيئة العزل الخاص بها من القرص. أما الملفات التي كتبتها داخل مشروع فتبقى في مساحة عمل ذلك المشروع.",
+ chatsSection: "المحادثات والأرشيف",
+ transferSection: "الاستيراد والتصدير",
+ deletionSection: "الحذف",
+ archives: "الأرشيف",
+ archiveChatsLabel: "المحادثات",
+ archiveVideosLabel: "الفيديو",
+ exportFormatsSummary:
+ "تصدير المحادثات الأخيرة ومحادثات المشاريع بالتنسيق المفضل لديك.",
+ trainingSummary: "تحويل محادثاتك إلى مجموعة بيانات للضبط الدقيق.",
+ confirmDeletionSummary: "طلب التأكيد قبل حذف المحادثات الفردية.",
+ sandboxFiles: "ملفات بيئة المحادثة المعزولة",
+ sandboxFilesDescription: "الإجراء الافتراضي عند حذف محادثة.",
+ keepSandboxFiles: "الاحتفاظ بملفات البيئة المعزولة",
+ deleteSandboxFiles: "حذف ملفات البيئة المعزولة",
+ projectFilesKept:
+ "البيئات المعزولة هي مجلدات تُنشأ لكل محادثة. تُحفظ الملفات الموجودة في مساحات عمل المشاريع.",
+ deleteAllAction: "حذف الكل",
+ deleteChatsOnly: "حذف المحادثات فقط…",
+ deleteChatsAndSandboxes: "حذف المحادثات والبيئات المعزولة…",
+ deleteSandboxFilesDescription:
+ "حذف مجلد البيئة المعزولة لكل محادثة والملفات الموجودة فيه أيضًا. تُحفظ الملفات الموجودة في مساحات عمل المشاريع.",
filesSection: "الملفات",
uploadedFiles: "الملفات المرفوعة",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 45354fc9aa6..a6396eeb61f 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1562,7 +1562,7 @@ export const de = {
exportPerChatSuffix: "(pro Chat)",
importChats: "Chats importieren",
importChatsDescription:
- "Einen Open-WebUI-, JSONL-, NDJSON- oder CSV-Export in Zuletzt importieren.",
+ "JSON-, JSONL-, NDJSON- oder CSV-Dateien in Zuletzt importieren.",
importChatsAction: "Importieren",
importNoConversations: "Keine Konversationen in der Datei gefunden.",
importedOneChat: "1 Konversation in „Zuletzt verwendet“ importiert.",
@@ -1609,6 +1609,80 @@ export const de = {
failedToClearChats: "Chats konnten nicht gelöscht werden",
},
data: {
+ library: {
+ defaultSort: "Standard",
+ updated: "Aktualisiert",
+ created: "Erstellt",
+ oldest: "Älteste zuerst",
+ alphabetical: "Alphabetisch",
+ allChats: "Alle Chats",
+ singleChats: "Einzelchats",
+ compareChats: "Vergleichschats",
+ allProjects: "Alle Projekte",
+ noProject: "Kein Projekt",
+ unavailableProject: "Projekt nicht verfügbar",
+ filterSort: "Filtern und sortieren",
+ sort: "Sortieren",
+ type: "Typ",
+ sortBy: "Sortieren nach",
+ filterProject: "Nach Projekt filtern",
+ searchProjects: "Projekte suchen",
+ noProjects: "Keine Projekte gefunden.",
+ untitled: "Ohne Titel",
+ oneChat: "1 Chat",
+ chatCount: "{count} Chats",
+ searchChats: "Chats oder Projekte suchen",
+ searchArchivedChats: "Archivierte Chats oder Projekte suchen",
+ searchImages: "Archivierte Bilder suchen",
+ searchVideos: "Archivierte Videos suchen",
+ searchAudio: "Archivierte Audiodateien suchen",
+ unarchive: "Aus Archiv wiederherstellen",
+ unarchiveAll: "Alle wiederherstellen",
+ unarchiveResults: "Ergebnisse wiederherstellen",
+ deleteResults: "Ergebnisse löschen",
+ noChats: "Keine Chats entsprechen deiner Suche.",
+ noArchivedChats: "Keine archivierten Chats.",
+ noArchivedMatches: "Keine archivierten Chats entsprechen deiner Suche.",
+ noMedia: "Keine archivierten Einträge.",
+ noMediaMatches: "Keine archivierten Einträge entsprechen deiner Suche.",
+ itemCount: "Einträge: {count}",
+ incompleteSearch: "Die Suche ist unvollständig. Lade die übrigen Einträge erneut.",
+ searchingRemaining: "Übrige Einträge werden durchsucht ({count} geladen)...",
+ noLoadedMatches: "Keine Treffer in den bisher geladenen Einträgen.",
+ deleteItem: "Löschen: {title}",
+ unarchiveItem: "Aus Archiv wiederherstellen: {title}",
+ deleteItemsTitle: "Archivierte Einträge löschen ({count})",
+ unarchiveItemsTitle: "Einträge wiederherstellen ({count})",
+ deleteFilesWarning: "Diese Dateien werden dauerhaft gelöscht. Dies kann nicht rückgängig gemacht werden.",
+ restoreWarning: "Diese Einträge werden wieder in der Galerie angezeigt.",
+ working: "Wird bearbeitet...",
+ loadFailed: "Archivierte Einträge konnten nicht geladen werden",
+ loadMoreFailed: "Weitere archivierte Einträge konnten nicht geladen werden",
+ restoreFailed: "Ausgewählte Einträge konnten nicht wiederhergestellt werden",
+ deleteFailed: "Ausgewählte Einträge konnten nicht gelöscht werden",
+ projectsFailed: "Archivierte Projekte konnten nicht geladen werden",
+ pageStalled: "Die Archivseite wurde nicht weitergeladen. Versuche es erneut.",
+ pageChanged: "Das Archiv hat sich während des Ladens geändert. Versuche es erneut.",
+ selectAll: "Alle sichtbaren Chats auswählen",
+ selectItem: "„{title}“ auswählen",
+ selectedChats: "Ausgewählte Chats: {count}",
+ move: "Verschieben",
+ pin: "Anheften",
+ unpin: "Loslösen",
+ archive: "Archivieren",
+ deletedChats: "Gelöschte Chats: {count}",
+ restoredChats: "Wiederhergestellte Chats: {count}",
+ pinnedChats: "Angeheftete Chats: {count}",
+ unpinnedChats: "Losgelöste Chats: {count}",
+ movedChatsToProject: "Nach {project} verschobene Chats: {count}",
+ movedChatsToRecents: "Nach Zuletzt verwendet verschobene Chats: {count}",
+ moveFailed: "Chats konnten nicht verschoben werden",
+ deleteChatsTitle: "Chats löschen ({count})",
+ deleteChatsWarning: "Ausgewählte Chats löschen ({count})? Dies kann nicht rückgängig gemacht werden.",
+ deleteArchivedTitle: "{count} archivierte Chats löschen",
+ deleteArchivedWarning: "Ausgewählte archivierte Chats löschen ({count})? Dies kann nicht rückgängig gemacht werden.",
+ deleting: "Wird gelöscht...",
+ },
title: "Daten",
backToData: "Zurück zu Daten",
exportFailed: "Chats konnten nicht exportiert werden",
@@ -1653,6 +1727,27 @@ export const de = {
alwaysDeleteFiles: "Dateien immer löschen",
alwaysDeleteFilesDescription:
"Beim Löschen eines Chats wird auch dessen eigener Sandbox-Ordner von der Festplatte entfernt. Dateien, die er in einem Projekt erstellt hat, bleiben im Arbeitsbereich dieses Projekts.",
+ chatsSection: "Chats und Archive",
+ transferSection: "Import und Export",
+ deletionSection: "Löschen",
+ archives: "Archive",
+ archiveChatsLabel: "Chats",
+ archiveVideosLabel: "Videos",
+ exportFormatsSummary:
+ "Exportiere Chats aus Zuletzt und Projekten im gewünschten Format.",
+ trainingSummary: "Erstelle aus deinen Chats einen Datensatz für das Fine-Tuning.",
+ confirmDeletionSummary: "Vor dem Löschen einzelner Chats nachfragen.",
+ sandboxFiles: "Sandbox-Dateien der Chats",
+ sandboxFilesDescription: "Standardaktion beim Löschen eines Chats.",
+ keepSandboxFiles: "Sandbox-Dateien behalten",
+ deleteSandboxFiles: "Sandbox-Dateien löschen",
+ projectFilesKept:
+ "Sandboxen sind Ordner für einzelne Chats. Dateien in Projektarbeitsbereichen bleiben erhalten.",
+ deleteAllAction: "Alle löschen",
+ deleteChatsOnly: "Nur Chats löschen…",
+ deleteChatsAndSandboxes: "Chats und Sandboxen löschen…",
+ deleteSandboxFilesDescription:
+ "Auch den Sandbox-Ordner jedes Chats samt Dateien löschen. Dateien in Projektarbeitsbereichen bleiben erhalten.",
filesSection: "Dateien",
uploadedFiles: "Hochgeladene Dateien",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index af11423983b..a156c44b208 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1514,7 +1514,7 @@ export const en = {
exportPerChatSuffix: "(per chat)",
importChats: "Import chats",
importChatsDescription:
- "Import an Open WebUI, JSONL, NDJSON, or CSV export into Recents.",
+ "Import JSON, JSONL, NDJSON, or CSV files into Recents.",
importChatsAction: "Import",
importNoConversations: "No conversations found in file.",
importedOneChat: "Imported 1 conversation to Recents.",
@@ -1558,6 +1558,80 @@ export const en = {
failedToClearChats: "Failed to clear chats",
},
data: {
+ library: {
+ defaultSort: "Default",
+ updated: "Updated",
+ created: "Created",
+ oldest: "Oldest first",
+ alphabetical: "Alphabetical",
+ allChats: "All chats",
+ singleChats: "Single chats",
+ compareChats: "Compare chats",
+ allProjects: "All projects",
+ noProject: "No project",
+ unavailableProject: "Unavailable project",
+ filterSort: "Filter and sort",
+ sort: "Sort",
+ type: "Type",
+ sortBy: "Sort by",
+ filterProject: "Filter by project",
+ searchProjects: "Search projects",
+ noProjects: "No projects found.",
+ untitled: "Untitled",
+ oneChat: "1 chat",
+ chatCount: "{count} chats",
+ searchChats: "Search chats or projects",
+ searchArchivedChats: "Search archived chats or projects",
+ searchImages: "Search archived images",
+ searchVideos: "Search archived videos",
+ searchAudio: "Search archived audio",
+ unarchive: "Unarchive",
+ unarchiveAll: "Unarchive all",
+ unarchiveResults: "Unarchive results",
+ deleteResults: "Delete results",
+ noChats: "No chats match your search.",
+ noArchivedChats: "No archived chats.",
+ noArchivedMatches: "No archived chats match your search.",
+ noMedia: "No archived items.",
+ noMediaMatches: "No archived items match your search.",
+ itemCount: "Items: {count}",
+ incompleteSearch: "Search is incomplete. Retry loading the remaining items.",
+ searchingRemaining: "Searching remaining items ({count} loaded)...",
+ noLoadedMatches: "No matches in the items loaded so far.",
+ deleteItem: "Delete: {title}",
+ unarchiveItem: "Unarchive: {title}",
+ deleteItemsTitle: "Delete archived items ({count})",
+ unarchiveItemsTitle: "Unarchive items ({count})",
+ deleteFilesWarning: "These files will be permanently deleted. This cannot be undone.",
+ restoreWarning: "These items will return to the gallery.",
+ working: "Working...",
+ loadFailed: "Failed to load archived items",
+ loadMoreFailed: "Failed to load more archived items",
+ restoreFailed: "Failed to unarchive selected items",
+ deleteFailed: "Failed to delete selected items",
+ projectsFailed: "Failed to load archived projects",
+ pageStalled: "The archive page did not advance. Try again.",
+ pageChanged: "The archive changed while loading. Try again.",
+ selectAll: "Select all visible chats",
+ selectItem: "Select \"{title}\"",
+ selectedChats: "Selected chats: {count}",
+ move: "Move",
+ pin: "Pin",
+ unpin: "Unpin",
+ archive: "Archive",
+ deletedChats: "Chats deleted: {count}",
+ restoredChats: "Chats unarchived: {count}",
+ pinnedChats: "Chats pinned: {count}",
+ unpinnedChats: "Chats unpinned: {count}",
+ movedChatsToProject: "Chats moved to {project}: {count}",
+ movedChatsToRecents: "Chats moved to Recents: {count}",
+ moveFailed: "Failed to move chats",
+ deleteChatsTitle: "Delete chats ({count})",
+ deleteChatsWarning: "Delete the selected chats ({count})? This cannot be undone.",
+ deleteArchivedTitle: "Delete {count} archived chats",
+ deleteArchivedWarning: "Delete the selected archived chats ({count})? This cannot be undone.",
+ deleting: "Deleting...",
+ },
title: "Data",
backToData: "Back to Data",
exportFailed: "Could not export chats",
@@ -1600,6 +1674,24 @@ export const en = {
alwaysDeleteFiles: "Always delete files",
alwaysDeleteFilesDescription:
"Deleting a chat also removes its own sandbox folder from disk. Files it wrote inside a project stay in that project workspace.",
+ chatsSection: "Chats & archives",
+ transferSection: "Import & export",
+ deletionSection: "Deletion",
+ archives: "Archives",
+ archiveChatsLabel: "Chats",
+ archiveVideosLabel: "Videos",
+ exportFormatsSummary: "Export Recents and project chats in your preferred format.",
+ trainingSummary: "Turn your chats into a fine-tuning dataset.",
+ confirmDeletionSummary: "Ask before deleting individual chats.",
+ sandboxFiles: "Chat sandbox files",
+ sandboxFilesDescription: "Default action when deleting a chat.",
+ keepSandboxFiles: "Keep sandbox files",
+ deleteSandboxFiles: "Delete sandbox files",
+ projectFilesKept: "Sandboxes are folders created for individual chats. Files saved in project workspaces are kept.",
+ deleteAllAction: "Delete all",
+ deleteChatsOnly: "Delete chats only…",
+ deleteChatsAndSandboxes: "Delete chats and sandboxes…",
+ deleteSandboxFilesDescription: "Also delete each chat's sandbox folder and the files inside it. Files in project workspaces are kept.",
filesSection: "Files",
uploadedFiles: "Uploaded files",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 14596851b1c..d5d620aaf5e 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1553,7 +1553,7 @@ export const es = {
exportPerChatSuffix: "(por chat)",
importChats: "Importar chats",
importChatsDescription:
- "Importa una exportación de Open WebUI, JSONL, NDJSON o CSV a Recientes.",
+ "Importa archivos JSON, JSONL, NDJSON o CSV a Recientes.",
importChatsAction: "Importar",
importNoConversations: "No se encontraron conversaciones en el archivo.",
importedOneChat: "Se importó 1 conversación a Recientes.",
@@ -1599,6 +1599,80 @@ export const es = {
failedToClearChats: "No se pudieron borrar los chats",
},
data: {
+ library: {
+ defaultSort: "Predeterminado",
+ updated: "Actualización",
+ created: "Creación",
+ oldest: "Más antiguos primero",
+ alphabetical: "Orden alfabético",
+ allChats: "Todos los chats",
+ singleChats: "Chats individuales",
+ compareChats: "Chats de comparación",
+ allProjects: "Todos los proyectos",
+ noProject: "Sin proyecto",
+ unavailableProject: "Proyecto no disponible",
+ filterSort: "Filtrar y ordenar",
+ sort: "Ordenar",
+ type: "Tipo",
+ sortBy: "Ordenar por",
+ filterProject: "Filtrar por proyecto",
+ searchProjects: "Buscar proyectos",
+ noProjects: "No se encontraron proyectos.",
+ untitled: "Sin título",
+ oneChat: "1 chat",
+ chatCount: "{count} chats",
+ searchChats: "Buscar chats o proyectos",
+ searchArchivedChats: "Buscar chats archivados o proyectos",
+ searchImages: "Buscar imágenes archivadas",
+ searchVideos: "Buscar vídeos archivados",
+ searchAudio: "Buscar audio archivado",
+ unarchive: "Desarchivar",
+ unarchiveAll: "Desarchivar todo",
+ unarchiveResults: "Desarchivar resultados",
+ deleteResults: "Eliminar resultados",
+ noChats: "Ningún chat coincide con tu búsqueda.",
+ noArchivedChats: "No hay chats archivados.",
+ noArchivedMatches: "Ningún chat archivado coincide con tu búsqueda.",
+ noMedia: "No hay elementos archivados.",
+ noMediaMatches: "Ningún elemento archivado coincide con tu búsqueda.",
+ itemCount: "Elementos: {count}",
+ incompleteSearch: "La búsqueda está incompleta. Reintenta cargar los elementos restantes.",
+ searchingRemaining: "Buscando los elementos restantes ({count} cargados)...",
+ noLoadedMatches: "No hay coincidencias entre los elementos cargados hasta ahora.",
+ deleteItem: "Eliminar: {title}",
+ unarchiveItem: "Desarchivar: {title}",
+ deleteItemsTitle: "Eliminar elementos archivados ({count})",
+ unarchiveItemsTitle: "Desarchivar elementos ({count})",
+ deleteFilesWarning: "Estos archivos se eliminarán permanentemente. Esta acción no se puede deshacer.",
+ restoreWarning: "Estos elementos volverán a la galería.",
+ working: "Procesando...",
+ loadFailed: "No se pudieron cargar los elementos archivados",
+ loadMoreFailed: "No se pudieron cargar más elementos archivados",
+ restoreFailed: "No se pudieron desarchivar los elementos seleccionados",
+ deleteFailed: "No se pudieron eliminar los elementos seleccionados",
+ projectsFailed: "No se pudieron cargar los proyectos archivados",
+ pageStalled: "La página del archivo no avanzó. Inténtalo de nuevo.",
+ pageChanged: "El archivo cambió durante la carga. Inténtalo de nuevo.",
+ selectAll: "Seleccionar todos los chats visibles",
+ selectItem: "Seleccionar \"{title}\"",
+ selectedChats: "Chats seleccionados: {count}",
+ move: "Mover",
+ pin: "Fijar",
+ unpin: "Desfijar",
+ archive: "Archivar",
+ deletedChats: "Chats eliminados: {count}",
+ restoredChats: "Chats desarchivados: {count}",
+ pinnedChats: "Chats fijados: {count}",
+ unpinnedChats: "Chats desfijados: {count}",
+ movedChatsToProject: "Chats movidos a {project}: {count}",
+ movedChatsToRecents: "Chats movidos a Recientes: {count}",
+ moveFailed: "No se pudieron mover los chats",
+ deleteChatsTitle: "Eliminar chats ({count})",
+ deleteChatsWarning: "¿Eliminar los chats seleccionados ({count})? Esta acción no se puede deshacer.",
+ deleteArchivedTitle: "Eliminar {count} chats archivados",
+ deleteArchivedWarning: "¿Eliminar los chats archivados seleccionados ({count})? Esta acción no se puede deshacer.",
+ deleting: "Eliminando...",
+ },
title: "Datos",
backToData: "Volver a Datos",
exportFailed: "No se pudieron exportar los chats",
@@ -1643,6 +1717,27 @@ export const es = {
alwaysDeleteFiles: "Eliminar siempre los archivos",
alwaysDeleteFilesDescription:
"Al eliminar un chat también se quita del disco su carpeta de entorno aislado. Los archivos que haya escrito dentro de un proyecto permanecen en el espacio de trabajo de ese proyecto.",
+ chatsSection: "Chats y archivos",
+ transferSection: "Importar y exportar",
+ deletionSection: "Eliminación",
+ archives: "Archivos",
+ archiveChatsLabel: "Chats",
+ archiveVideosLabel: "Vídeos",
+ exportFormatsSummary:
+ "Exporta los chats de Recientes y proyectos en el formato que prefieras.",
+ trainingSummary: "Convierte tus chats en un conjunto de datos para ajuste fino.",
+ confirmDeletionSummary: "Pedir confirmación antes de eliminar chats individuales.",
+ sandboxFiles: "Archivos del entorno aislado",
+ sandboxFilesDescription: "Acción predeterminada al eliminar un chat.",
+ keepSandboxFiles: "Conservar archivos del entorno",
+ deleteSandboxFiles: "Eliminar archivos del entorno",
+ projectFilesKept:
+ "Los entornos aislados son carpetas creadas para cada chat. Se conservan los archivos guardados en los espacios de trabajo de los proyectos.",
+ deleteAllAction: "Eliminar todo",
+ deleteChatsOnly: "Eliminar solo los chats…",
+ deleteChatsAndSandboxes: "Eliminar chats y entornos aislados…",
+ deleteSandboxFilesDescription:
+ "Elimina también la carpeta del entorno aislado de cada chat y sus archivos. Se conservan los archivos de los espacios de trabajo de los proyectos.",
filesSection: "Archivos",
uploadedFiles: "Archivos subidos",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 1e540f31445..3a29b0ab554 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1559,7 +1559,7 @@ export const fr = {
exportPerChatSuffix: "(par discussion)",
importChats: "Importer des discussions",
importChatsDescription:
- "Importez un export Open WebUI, JSONL, NDJSON ou CSV dans Récents.",
+ "Importez des fichiers JSON, JSONL, NDJSON ou CSV dans Récents.",
importChatsAction: "Importer",
importNoConversations: "Aucune conversation trouvée dans le fichier.",
importedOneChat: "1 conversation importée dans Récents.",
@@ -1607,6 +1607,80 @@ export const fr = {
failedToClearChats: "Échec de l'effacement des discussions",
},
data: {
+ library: {
+ defaultSort: "Par défaut",
+ updated: "Modification",
+ created: "Création",
+ oldest: "Les plus anciens d’abord",
+ alphabetical: "Ordre alphabétique",
+ allChats: "Toutes les discussions",
+ singleChats: "Discussions simples",
+ compareChats: "Discussions comparatives",
+ allProjects: "Tous les projets",
+ noProject: "Sans projet",
+ unavailableProject: "Projet indisponible",
+ filterSort: "Filtrer et trier",
+ sort: "Trier",
+ type: "Type",
+ sortBy: "Trier par",
+ filterProject: "Filtrer par projet",
+ searchProjects: "Rechercher des projets",
+ noProjects: "Aucun projet trouvé.",
+ untitled: "Sans titre",
+ oneChat: "1 discussion",
+ chatCount: "{count} discussions",
+ searchChats: "Rechercher des discussions ou des projets",
+ searchArchivedChats: "Rechercher des discussions archivées ou des projets",
+ searchImages: "Rechercher des images archivées",
+ searchVideos: "Rechercher des vidéos archivées",
+ searchAudio: "Rechercher des fichiers audio archivés",
+ unarchive: "Désarchiver",
+ unarchiveAll: "Tout désarchiver",
+ unarchiveResults: "Désarchiver les résultats",
+ deleteResults: "Supprimer les résultats",
+ noChats: "Aucune discussion ne correspond à votre recherche.",
+ noArchivedChats: "Aucune discussion archivée.",
+ noArchivedMatches: "Aucune discussion archivée ne correspond à votre recherche.",
+ noMedia: "Aucun élément archivé.",
+ noMediaMatches: "Aucun élément archivé ne correspond à votre recherche.",
+ itemCount: "Éléments : {count}",
+ incompleteSearch: "La recherche est incomplète. Réessayez de charger les éléments restants.",
+ searchingRemaining: "Recherche des éléments restants ({count} chargés)...",
+ noLoadedMatches: "Aucune correspondance parmi les éléments déjà chargés.",
+ deleteItem: "Supprimer : {title}",
+ unarchiveItem: "Désarchiver : {title}",
+ deleteItemsTitle: "Supprimer les éléments archivés ({count})",
+ unarchiveItemsTitle: "Désarchiver les éléments ({count})",
+ deleteFilesWarning: "Ces fichiers seront supprimés définitivement. Cette action est irréversible.",
+ restoreWarning: "Ces éléments seront replacés dans la galerie.",
+ working: "Traitement en cours...",
+ loadFailed: "Impossible de charger les éléments archivés",
+ loadMoreFailed: "Impossible de charger davantage d’éléments archivés",
+ restoreFailed: "Impossible de désarchiver les éléments sélectionnés",
+ deleteFailed: "Impossible de supprimer les éléments sélectionnés",
+ projectsFailed: "Impossible de charger les projets archivés",
+ pageStalled: "La page des archives n’a pas avancé. Réessayez.",
+ pageChanged: "Les archives ont changé pendant le chargement. Réessayez.",
+ selectAll: "Sélectionner toutes les discussions visibles",
+ selectItem: "Sélectionner « {title} »",
+ selectedChats: "Discussions sélectionnées : {count}",
+ move: "Déplacer",
+ pin: "Épingler",
+ unpin: "Désépingler",
+ archive: "Archiver",
+ deletedChats: "Discussions supprimées : {count}",
+ restoredChats: "Discussions désarchivées : {count}",
+ pinnedChats: "Discussions épinglées : {count}",
+ unpinnedChats: "Discussions désépinglées : {count}",
+ movedChatsToProject: "Discussions déplacées vers {project} : {count}",
+ movedChatsToRecents: "Discussions déplacées vers Récentes : {count}",
+ moveFailed: "Impossible de déplacer les discussions",
+ deleteChatsTitle: "Supprimer les discussions ({count})",
+ deleteChatsWarning: "Supprimer les discussions sélectionnées ({count}) ? Cette action est irréversible.",
+ deleteArchivedTitle: "Supprimer {count} discussions archivées",
+ deleteArchivedWarning: "Supprimer les discussions archivées sélectionnées ({count}) ? Cette action est irréversible.",
+ deleting: "Suppression...",
+ },
title: "Données",
backToData: "Retour aux données",
exportFailed: "Impossible d’exporter les chats",
@@ -1651,6 +1725,29 @@ export const fr = {
alwaysDeleteFiles: "Toujours supprimer les fichiers",
alwaysDeleteFilesDescription:
"La suppression d'une discussion retire aussi son dossier bac à sable du disque. Les fichiers écrits dans un projet restent dans l'espace de travail de ce projet.",
+ chatsSection: "Discussions et archives",
+ transferSection: "Importation et exportation",
+ deletionSection: "Suppression",
+ archives: "Archives",
+ archiveChatsLabel: "Discussions",
+ archiveVideosLabel: "Vidéos",
+ exportFormatsSummary:
+ "Exportez les discussions de Récents et des projets dans le format de votre choix.",
+ trainingSummary:
+ "Transformez vos discussions en jeu de données pour le réglage fin.",
+ confirmDeletionSummary: "Demander confirmation avant de supprimer une discussion.",
+ sandboxFiles: "Fichiers du bac à sable",
+ sandboxFilesDescription:
+ "Action par défaut lors de la suppression d’une discussion.",
+ keepSandboxFiles: "Conserver les fichiers du bac à sable",
+ deleteSandboxFiles: "Supprimer les fichiers du bac à sable",
+ projectFilesKept:
+ "Les bacs à sable sont des dossiers créés pour chaque discussion. Les fichiers enregistrés dans les espaces de travail des projets sont conservés.",
+ deleteAllAction: "Tout supprimer",
+ deleteChatsOnly: "Supprimer uniquement les discussions…",
+ deleteChatsAndSandboxes: "Supprimer les discussions et les bacs à sable…",
+ deleteSandboxFilesDescription:
+ "Supprime aussi le dossier du bac à sable de chaque discussion et son contenu. Les fichiers des espaces de travail des projets sont conservés.",
filesSection: "Fichiers",
uploadedFiles: "Fichiers importés",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index a147636f098..6d10aa1e0ee 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1527,7 +1527,7 @@ export const hi = {
exportPerChatSuffix: "(प्रति चैट)",
importChats: "चैट इंपोर्ट करें",
importChatsDescription:
- "Open WebUI, JSONL, NDJSON या CSV एक्सपोर्ट को Recents में इंपोर्ट करें।",
+ "JSON, JSONL, NDJSON या CSV फ़ाइलों को Recents में इंपोर्ट करें।",
importChatsAction: "इंपोर्ट करें",
importNoConversations: "फ़ाइल में कोई वार्तालाप नहीं मिला।",
importedOneChat: "1 वार्तालाप हाल के सेक्शन में इंपोर्ट किया गया।",
@@ -1572,6 +1572,80 @@ export const hi = {
failedToClearChats: "चैट साफ़ करने में विफल",
},
data: {
+ library: {
+ defaultSort: "डिफ़ॉल्ट",
+ updated: "अपडेट का समय",
+ created: "बनाने का समय",
+ oldest: "सबसे पुराने पहले",
+ alphabetical: "वर्णानुक्रम",
+ allChats: "सभी चैट",
+ singleChats: "एकल चैट",
+ compareChats: "तुलना चैट",
+ allProjects: "सभी प्रोजेक्ट",
+ noProject: "कोई प्रोजेक्ट नहीं",
+ unavailableProject: "प्रोजेक्ट उपलब्ध नहीं है",
+ filterSort: "फ़िल्टर और क्रम",
+ sort: "क्रमबद्ध करें",
+ type: "प्रकार",
+ sortBy: "इसके अनुसार क्रमबद्ध करें",
+ filterProject: "प्रोजेक्ट के अनुसार फ़िल्टर करें",
+ searchProjects: "प्रोजेक्ट खोजें",
+ noProjects: "कोई प्रोजेक्ट नहीं मिला।",
+ untitled: "बिना शीर्षक",
+ oneChat: "1 चैट",
+ chatCount: "{count} चैट",
+ searchChats: "चैट या प्रोजेक्ट खोजें",
+ searchArchivedChats: "संग्रहीत चैट या प्रोजेक्ट खोजें",
+ searchImages: "संग्रहीत चित्र खोजें",
+ searchVideos: "संग्रहीत वीडियो खोजें",
+ searchAudio: "संग्रहीत ऑडियो खोजें",
+ unarchive: "संग्रह से निकालें",
+ unarchiveAll: "सभी को संग्रह से निकालें",
+ unarchiveResults: "परिणामों को संग्रह से निकालें",
+ deleteResults: "परिणाम मिटाएँ",
+ noChats: "आपकी खोज से मेल खाती कोई चैट नहीं है।",
+ noArchivedChats: "कोई संग्रहीत चैट नहीं है।",
+ noArchivedMatches: "आपकी खोज से मेल खाती कोई संग्रहीत चैट नहीं है।",
+ noMedia: "कोई संग्रहीत आइटम नहीं है।",
+ noMediaMatches: "आपकी खोज से मेल खाता कोई संग्रहीत आइटम नहीं है।",
+ itemCount: "आइटम: {count}",
+ incompleteSearch: "खोज अधूरी है। बाकी आइटम लोड करने का फिर से प्रयास करें।",
+ searchingRemaining: "बाकी आइटम खोजे जा रहे हैं ({count} लोड हो चुके हैं)...",
+ noLoadedMatches: "अब तक लोड किए गए आइटम में कोई मेल नहीं मिला।",
+ deleteItem: "मिटाएँ: {title}",
+ unarchiveItem: "संग्रह से निकालें: {title}",
+ deleteItemsTitle: "संग्रहीत आइटम मिटाएँ ({count})",
+ unarchiveItemsTitle: "आइटम को संग्रह से निकालें ({count})",
+ deleteFilesWarning: "ये फ़ाइलें स्थायी रूप से मिटा दी जाएँगी। इसे पूर्ववत नहीं किया जा सकता।",
+ restoreWarning: "ये आइटम गैलरी में वापस आ जाएँगे।",
+ working: "प्रक्रिया जारी है...",
+ loadFailed: "संग्रहीत आइटम लोड नहीं हो सके",
+ loadMoreFailed: "और संग्रहीत आइटम लोड नहीं हो सके",
+ restoreFailed: "चुने गए आइटम को संग्रह से नहीं निकाला जा सका",
+ deleteFailed: "चुने गए आइटम मिटाए नहीं जा सके",
+ projectsFailed: "संग्रहीत प्रोजेक्ट लोड नहीं हो सके",
+ pageStalled: "संग्रह का अगला पृष्ठ लोड नहीं हुआ। फिर से प्रयास करें।",
+ pageChanged: "लोड करते समय संग्रह बदल गया। फिर से प्रयास करें।",
+ selectAll: "दिख रही सभी चैट चुनें",
+ selectItem: "\"{title}\" चुनें",
+ selectedChats: "चुनी गई चैट: {count}",
+ move: "स्थानांतरित करें",
+ pin: "पिन करें",
+ unpin: "अनपिन करें",
+ archive: "संग्रहीत करें",
+ deletedChats: "मिटाई गई चैट: {count}",
+ restoredChats: "संग्रह से निकाली गई चैट: {count}",
+ pinnedChats: "पिन की गई चैट: {count}",
+ unpinnedChats: "अनपिन की गई चैट: {count}",
+ movedChatsToProject: "{project} में स्थानांतरित चैट: {count}",
+ movedChatsToRecents: "हाल के में स्थानांतरित चैट: {count}",
+ moveFailed: "चैट स्थानांतरित नहीं हो सकीं",
+ deleteChatsTitle: "चैट मिटाएँ ({count})",
+ deleteChatsWarning: "चुनी गई चैट ({count}) मिटाएँ? इसे पूर्ववत नहीं किया जा सकता।",
+ deleteArchivedTitle: "{count} संग्रहीत चैट मिटाएँ",
+ deleteArchivedWarning: "चुनी गई संग्रहीत चैट ({count}) मिटाएँ? इसे पूर्ववत नहीं किया जा सकता।",
+ deleting: "मिटाया जा रहा है...",
+ },
title: "डेटा",
backToData: "डेटा पर वापस जाएँ",
exportFailed: "चैट एक्सपोर्ट नहीं की जा सकीं",
@@ -1615,6 +1689,27 @@ export const hi = {
alwaysDeleteFiles: "फ़ाइलें हमेशा हटाएँ",
alwaysDeleteFilesDescription:
"चैट हटाने पर उसका अपना सैंडबॉक्स फ़ोल्डर भी डिस्क से हट जाता है। किसी प्रोजेक्ट के अंदर लिखी गई फ़ाइलें उस प्रोजेक्ट के कार्यक्षेत्र में बनी रहती हैं।",
+ chatsSection: "चैट और संग्रह",
+ transferSection: "इंपोर्ट और एक्सपोर्ट",
+ deletionSection: "हटाना",
+ archives: "संग्रह",
+ archiveChatsLabel: "चैट",
+ archiveVideosLabel: "वीडियो",
+ exportFormatsSummary:
+ "Recents और प्रोजेक्ट की चैट को अपने पसंदीदा फ़ॉर्मैट में एक्सपोर्ट करें।",
+ trainingSummary: "अपनी चैट से फ़ाइन-ट्यूनिंग के लिए डेटासेट बनाएँ।",
+ confirmDeletionSummary: "अलग-अलग चैट हटाने से पहले पुष्टि माँगें।",
+ sandboxFiles: "चैट की सैंडबॉक्स फ़ाइलें",
+ sandboxFilesDescription: "चैट हटाते समय डिफ़ॉल्ट कार्रवाई।",
+ keepSandboxFiles: "सैंडबॉक्स फ़ाइलें रखें",
+ deleteSandboxFiles: "सैंडबॉक्स फ़ाइलें हटाएँ",
+ projectFilesKept:
+ "सैंडबॉक्स अलग-अलग चैट के लिए बनाए गए फ़ोल्डर हैं। प्रोजेक्ट के कार्यक्षेत्रों में सहेजी गई फ़ाइलें रखी जाती हैं।",
+ deleteAllAction: "सभी हटाएँ",
+ deleteChatsOnly: "केवल चैट हटाएँ…",
+ deleteChatsAndSandboxes: "चैट और सैंडबॉक्स हटाएँ…",
+ deleteSandboxFilesDescription:
+ "हर चैट का सैंडबॉक्स फ़ोल्डर और उसके अंदर की फ़ाइलें भी हटाएँ। प्रोजेक्ट के कार्यक्षेत्रों की फ़ाइलें रखी जाती हैं।",
filesSection: "फ़ाइलें",
uploadedFiles: "अपलोड की गई फ़ाइलें",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 239b6725f3c..4a88d9b8d20 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1526,7 +1526,7 @@ export const it = {
exportPerChatSuffix: "(uno per chat)",
importChats: "Importa chat",
importChatsDescription:
- "Importa un export Open WebUI, JSONL, NDJSON o CSV in Recenti.",
+ "Importa file JSON, JSONL, NDJSON o CSV in Recenti.",
importChatsAction: "Importa",
importNoConversations: "Nessuna conversazione trovata nel file.",
importedOneChat: "1 conversazione importata nei Recenti.",
@@ -1572,6 +1572,80 @@ export const it = {
failedToClearChats: "Cancellazione delle chat non riuscita",
},
data: {
+ library: {
+ defaultSort: "Predefinito",
+ updated: "Aggiornamento",
+ created: "Creazione",
+ oldest: "Meno recenti prima",
+ alphabetical: "Ordine alfabetico",
+ allChats: "Tutte le chat",
+ singleChats: "Chat singole",
+ compareChats: "Chat di confronto",
+ allProjects: "Tutti i progetti",
+ noProject: "Nessun progetto",
+ unavailableProject: "Progetto non disponibile",
+ filterSort: "Filtra e ordina",
+ sort: "Ordina",
+ type: "Tipo",
+ sortBy: "Ordina per",
+ filterProject: "Filtra per progetto",
+ searchProjects: "Cerca progetti",
+ noProjects: "Nessun progetto trovato.",
+ untitled: "Senza titolo",
+ oneChat: "1 chat",
+ chatCount: "{count} chat",
+ searchChats: "Cerca chat o progetti",
+ searchArchivedChats: "Cerca chat archiviate o progetti",
+ searchImages: "Cerca immagini archiviate",
+ searchVideos: "Cerca video archiviati",
+ searchAudio: "Cerca audio archiviati",
+ unarchive: "Ripristina",
+ unarchiveAll: "Ripristina tutto",
+ unarchiveResults: "Ripristina risultati",
+ deleteResults: "Elimina risultati",
+ noChats: "Nessuna chat corrisponde alla ricerca.",
+ noArchivedChats: "Nessuna chat archiviata.",
+ noArchivedMatches: "Nessuna chat archiviata corrisponde alla ricerca.",
+ noMedia: "Nessun elemento archiviato.",
+ noMediaMatches: "Nessun elemento archiviato corrisponde alla ricerca.",
+ itemCount: "Elementi: {count}",
+ incompleteSearch: "La ricerca è incompleta. Riprova a caricare gli elementi rimanenti.",
+ searchingRemaining: "Ricerca degli elementi rimanenti ({count} caricati)...",
+ noLoadedMatches: "Nessuna corrispondenza tra gli elementi caricati finora.",
+ deleteItem: "Elimina: {title}",
+ unarchiveItem: "Ripristina: {title}",
+ deleteItemsTitle: "Elimina elementi archiviati ({count})",
+ unarchiveItemsTitle: "Ripristina elementi ({count})",
+ deleteFilesWarning: "Questi file verranno eliminati definitivamente. L'azione non può essere annullata.",
+ restoreWarning: "Questi elementi torneranno nella galleria.",
+ working: "Elaborazione...",
+ loadFailed: "Impossibile caricare gli elementi archiviati",
+ loadMoreFailed: "Impossibile caricare altri elementi archiviati",
+ restoreFailed: "Impossibile ripristinare gli elementi selezionati",
+ deleteFailed: "Impossibile eliminare gli elementi selezionati",
+ projectsFailed: "Impossibile caricare i progetti archiviati",
+ pageStalled: "La pagina dell'archivio non è avanzata. Riprova.",
+ pageChanged: "L'archivio è cambiato durante il caricamento. Riprova.",
+ selectAll: "Seleziona tutte le chat visibili",
+ selectItem: "Seleziona \"{title}\"",
+ selectedChats: "Chat selezionate: {count}",
+ move: "Sposta",
+ pin: "Fissa",
+ unpin: "Rimuovi dai fissati",
+ archive: "Archivia",
+ deletedChats: "Chat eliminate: {count}",
+ restoredChats: "Chat ripristinate: {count}",
+ pinnedChats: "Chat fissate: {count}",
+ unpinnedChats: "Chat rimosse dai fissati: {count}",
+ movedChatsToProject: "Chat spostate in {project}: {count}",
+ movedChatsToRecents: "Chat spostate in Recenti: {count}",
+ moveFailed: "Impossibile spostare le chat",
+ deleteChatsTitle: "Elimina chat ({count})",
+ deleteChatsWarning: "Eliminare le chat selezionate ({count})? L'azione non può essere annullata.",
+ deleteArchivedTitle: "Elimina {count} chat archiviate",
+ deleteArchivedWarning: "Eliminare le chat archiviate selezionate ({count})? L'azione non può essere annullata.",
+ deleting: "Eliminazione...",
+ },
title: "Dati",
backToData: "Torna a Dati",
exportFailed: "Impossibile esportare le chat",
@@ -1616,6 +1690,27 @@ export const it = {
alwaysDeleteFiles: "Elimina sempre i file",
alwaysDeleteFilesDescription:
"L'eliminazione di una chat rimuove dal disco anche la sua cartella sandbox. I file scritti dentro un progetto restano nello spazio di lavoro di quel progetto.",
+ chatsSection: "Chat e archivi",
+ transferSection: "Importazione ed esportazione",
+ deletionSection: "Eliminazione",
+ archives: "Archivi",
+ archiveChatsLabel: "Chat",
+ archiveVideosLabel: "Video",
+ exportFormatsSummary:
+ "Esporta le chat di Recenti e dei progetti nel formato che preferisci.",
+ trainingSummary: "Trasforma le chat in un dataset per il fine-tuning.",
+ confirmDeletionSummary: "Chiedi conferma prima di eliminare le singole chat.",
+ sandboxFiles: "File della sandbox delle chat",
+ sandboxFilesDescription: "Azione predefinita quando elimini una chat.",
+ keepSandboxFiles: "Conserva i file della sandbox",
+ deleteSandboxFiles: "Elimina i file della sandbox",
+ projectFilesKept:
+ "Le sandbox sono cartelle create per le singole chat. I file salvati negli spazi di lavoro dei progetti vengono conservati.",
+ deleteAllAction: "Elimina tutto",
+ deleteChatsOnly: "Elimina solo le chat…",
+ deleteChatsAndSandboxes: "Elimina chat e sandbox…",
+ deleteSandboxFilesDescription:
+ "Elimina anche la cartella sandbox di ogni chat e i file al suo interno. I file negli spazi di lavoro dei progetti vengono conservati.",
filesSection: "File",
uploadedFiles: "File caricati",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index ce95332aa72..483fdc2a013 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1506,7 +1506,7 @@ export const ja = {
exportCombinedSuffix: "(一括)",
exportPerChatSuffix: "(チャットごと)",
importChats: "チャットをインポート",
- importChatsDescription: "Open WebUI、JSONL、NDJSON、または CSV のエクスポートファイルを履歴にインポートします。",
+ importChatsDescription: "JSON、JSONL、NDJSON、または CSV ファイルを履歴にインポートします。",
importChatsAction: "インポート",
importNoConversations: "ファイル内に会話が見つかりませんでした。",
importedOneChat: "1 件の会話を履歴にインポートしました。",
@@ -1542,6 +1542,80 @@ export const ja = {
failedToClearChats: "チャットの消去に失敗しました",
},
data: {
+ library: {
+ defaultSort: "既定",
+ updated: "更新日時",
+ created: "作成日時",
+ oldest: "古い順",
+ alphabetical: "名前順",
+ allChats: "すべてのチャット",
+ singleChats: "単一チャット",
+ compareChats: "比較チャット",
+ allProjects: "すべてのプロジェクト",
+ noProject: "プロジェクトなし",
+ unavailableProject: "利用できないプロジェクト",
+ filterSort: "絞り込みと並べ替え",
+ sort: "並べ替え",
+ type: "種類",
+ sortBy: "並べ替え基準",
+ filterProject: "プロジェクトで絞り込む",
+ searchProjects: "プロジェクトを検索",
+ noProjects: "プロジェクトが見つかりません。",
+ untitled: "無題",
+ oneChat: "1 件のチャット",
+ chatCount: "{count} 件のチャット",
+ searchChats: "チャットまたはプロジェクトを検索",
+ searchArchivedChats: "アーカイブ済みチャットまたはプロジェクトを検索",
+ searchImages: "アーカイブ済み画像を検索",
+ searchVideos: "アーカイブ済み動画を検索",
+ searchAudio: "アーカイブ済み音声を検索",
+ unarchive: "アーカイブ解除",
+ unarchiveAll: "すべてアーカイブ解除",
+ unarchiveResults: "検索結果のアーカイブを解除",
+ deleteResults: "検索結果を削除",
+ noChats: "検索に一致するチャットはありません。",
+ noArchivedChats: "アーカイブ済みチャットはありません。",
+ noArchivedMatches: "検索に一致するアーカイブ済みチャットはありません。",
+ noMedia: "アーカイブ済み項目はありません。",
+ noMediaMatches: "検索に一致するアーカイブ済み項目はありません。",
+ itemCount: "項目数:{count}",
+ incompleteSearch: "検索が完了していません。残りの項目の読み込みを再試行してください。",
+ searchingRemaining: "残りの項目を検索中({count} 件読み込み済み)...",
+ noLoadedMatches: "読み込み済みの項目に一致するものはありません。",
+ deleteItem: "削除:{title}",
+ unarchiveItem: "アーカイブ解除:{title}",
+ deleteItemsTitle: "アーカイブ済み項目を削除({count} 件)",
+ unarchiveItemsTitle: "項目のアーカイブを解除({count} 件)",
+ deleteFilesWarning: "これらのファイルは完全に削除されます。この操作は取り消せません。",
+ restoreWarning: "これらの項目はギャラリーに戻ります。",
+ working: "処理中...",
+ loadFailed: "アーカイブ済み項目を読み込めませんでした",
+ loadMoreFailed: "追加のアーカイブ済み項目を読み込めませんでした",
+ restoreFailed: "選択した項目のアーカイブを解除できませんでした",
+ deleteFailed: "選択した項目を削除できませんでした",
+ projectsFailed: "アーカイブ済みプロジェクトを読み込めませんでした",
+ pageStalled: "アーカイブの次のページに進めませんでした。再試行してください。",
+ pageChanged: "読み込み中にアーカイブが変更されました。再試行してください。",
+ selectAll: "表示中のすべてのチャットを選択",
+ selectItem: "「{title}」を選択",
+ selectedChats: "{count} 件のチャットを選択中",
+ move: "移動",
+ pin: "固定",
+ unpin: "固定解除",
+ archive: "アーカイブ",
+ deletedChats: "削除したチャット:{count} 件",
+ restoredChats: "アーカイブ解除したチャット:{count} 件",
+ pinnedChats: "固定したチャット:{count} 件",
+ unpinnedChats: "固定解除したチャット:{count} 件",
+ movedChatsToProject: "{project} に移動したチャット:{count} 件",
+ movedChatsToRecents: "最近のチャットに移動したチャット:{count} 件",
+ moveFailed: "チャットを移動できませんでした",
+ deleteChatsTitle: "チャットを削除({count} 件)",
+ deleteChatsWarning: "選択した {count} 件のチャットを削除しますか?この操作は取り消せません。",
+ deleteArchivedTitle: "アーカイブ済みチャットを {count} 件削除",
+ deleteArchivedWarning: "選択した {count} 件のアーカイブ済みチャットを削除しますか?この操作は取り消せません。",
+ deleting: "削除中...",
+ },
title: "データ",
backToData: "データに戻る",
exportFailed: "チャットをエクスポートできませんでした",
@@ -1586,6 +1660,25 @@ export const ja = {
alwaysDeleteFiles: "常にファイルを削除",
alwaysDeleteFilesDescription:
"チャットを削除すると、そのチャット専用のサンドボックスフォルダーもディスクから削除されます。プロジェクト内で作成したファイルは、そのプロジェクトのワークスペースに残ります。",
+ chatsSection: "チャットとアーカイブ",
+ transferSection: "インポートとエクスポート",
+ deletionSection: "削除",
+ archives: "アーカイブ",
+ archiveChatsLabel: "チャット",
+ archiveVideosLabel: "動画",
+ exportFormatsSummary: "履歴とプロジェクトのチャットをお好みの形式でエクスポートします。",
+ trainingSummary: "チャットからファインチューニング用のデータセットを作成します。",
+ confirmDeletionSummary: "個別のチャットを削除する前に確認します。",
+ sandboxFiles: "チャットのサンドボックスファイル",
+ sandboxFilesDescription: "チャット削除時の既定の動作です。",
+ keepSandboxFiles: "サンドボックスファイルを保持",
+ deleteSandboxFiles: "サンドボックスファイルを削除",
+ projectFilesKept: "サンドボックスは個々のチャット用に作成されたフォルダーです。プロジェクトのワークスペースに保存されたファイルは保持されます。",
+ deleteAllAction: "すべて削除",
+ deleteChatsOnly: "チャットのみ削除…",
+ deleteChatsAndSandboxes: "チャットとサンドボックスを削除…",
+ deleteSandboxFilesDescription:
+ "各チャットのサンドボックスフォルダーとその中のファイルも削除します。プロジェクトのワークスペース内のファイルは保持されます。",
filesSection: "ファイル",
uploadedFiles: "アップロード済みファイル",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 1dd7182f114..4211f372ea1 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1519,7 +1519,7 @@ export const ko = {
exportPerChatSuffix: "(채팅별)",
importChats: "채팅 가져오기",
importChatsDescription:
- "Open WebUI, JSONL, NDJSON 또는 CSV 내보내기 파일을 최근 항목으로 가져옵니다.",
+ "JSON, JSONL, NDJSON 또는 CSV 파일을 최근 항목으로 가져옵니다.",
importChatsAction: "가져오기",
importNoConversations: "파일에서 대화를 찾을 수 없습니다.",
importedOneChat: "1개의 대화를 최근 항목으로 가져왔습니다.",
@@ -1564,6 +1564,80 @@ export const ko = {
failedToClearChats: "채팅 지우기에 실패했습니다",
},
data: {
+ library: {
+ defaultSort: "기본값",
+ updated: "수정일",
+ created: "생성일",
+ oldest: "오래된 순",
+ alphabetical: "가나다순",
+ allChats: "모든 채팅",
+ singleChats: "단일 채팅",
+ compareChats: "비교 채팅",
+ allProjects: "모든 프로젝트",
+ noProject: "프로젝트 없음",
+ unavailableProject: "사용할 수 없는 프로젝트",
+ filterSort: "필터 및 정렬",
+ sort: "정렬",
+ type: "유형",
+ sortBy: "정렬 기준",
+ filterProject: "프로젝트별 필터",
+ searchProjects: "프로젝트 검색",
+ noProjects: "프로젝트를 찾을 수 없습니다.",
+ untitled: "제목 없음",
+ oneChat: "채팅 1개",
+ chatCount: "채팅 {count}개",
+ searchChats: "채팅 또는 프로젝트 검색",
+ searchArchivedChats: "보관된 채팅 또는 프로젝트 검색",
+ searchImages: "보관된 이미지 검색",
+ searchVideos: "보관된 동영상 검색",
+ searchAudio: "보관된 오디오 검색",
+ unarchive: "보관 해제",
+ unarchiveAll: "모두 보관 해제",
+ unarchiveResults: "검색 결과 보관 해제",
+ deleteResults: "검색 결과 삭제",
+ noChats: "검색과 일치하는 채팅이 없습니다.",
+ noArchivedChats: "보관된 채팅이 없습니다.",
+ noArchivedMatches: "검색과 일치하는 보관된 채팅이 없습니다.",
+ noMedia: "보관된 항목이 없습니다.",
+ noMediaMatches: "검색과 일치하는 보관된 항목이 없습니다.",
+ itemCount: "항목: {count}개",
+ incompleteSearch: "검색이 완료되지 않았습니다. 나머지 항목을 다시 불러오세요.",
+ searchingRemaining: "나머지 항목 검색 중 ({count}개 불러옴)...",
+ noLoadedMatches: "현재 불러온 항목에 일치하는 결과가 없습니다.",
+ deleteItem: "삭제: {title}",
+ unarchiveItem: "보관 해제: {title}",
+ deleteItemsTitle: "보관된 항목 삭제 ({count}개)",
+ unarchiveItemsTitle: "항목 보관 해제 ({count}개)",
+ deleteFilesWarning: "이 파일들은 영구적으로 삭제됩니다. 이 작업은 취소할 수 없습니다.",
+ restoreWarning: "이 항목들은 갤러리로 돌아갑니다.",
+ working: "처리 중...",
+ loadFailed: "보관된 항목을 불러오지 못했습니다",
+ loadMoreFailed: "보관된 항목을 더 불러오지 못했습니다",
+ restoreFailed: "선택한 항목의 보관을 해제하지 못했습니다",
+ deleteFailed: "선택한 항목을 삭제하지 못했습니다",
+ projectsFailed: "보관된 프로젝트를 불러오지 못했습니다",
+ pageStalled: "보관 목록의 다음 페이지로 이동하지 못했습니다. 다시 시도하세요.",
+ pageChanged: "불러오는 동안 보관 목록이 변경되었습니다. 다시 시도하세요.",
+ selectAll: "표시된 모든 채팅 선택",
+ selectItem: "\"{title}\" 선택",
+ selectedChats: "선택한 채팅: {count}개",
+ move: "이동",
+ pin: "고정",
+ unpin: "고정 해제",
+ archive: "보관",
+ deletedChats: "삭제한 채팅: {count}개",
+ restoredChats: "보관 해제한 채팅: {count}개",
+ pinnedChats: "고정한 채팅: {count}개",
+ unpinnedChats: "고정 해제한 채팅: {count}개",
+ movedChatsToProject: "{project}(으)로 이동한 채팅: {count}개",
+ movedChatsToRecents: "최근 항목으로 이동한 채팅: {count}개",
+ moveFailed: "채팅을 이동하지 못했습니다",
+ deleteChatsTitle: "채팅 삭제 ({count}개)",
+ deleteChatsWarning: "선택한 채팅 {count}개를 삭제할까요? 이 작업은 취소할 수 없습니다.",
+ deleteArchivedTitle: "보관된 채팅 {count}개 삭제",
+ deleteArchivedWarning: "선택한 보관된 채팅 {count}개를 삭제할까요? 이 작업은 취소할 수 없습니다.",
+ deleting: "삭제 중...",
+ },
title: "데이터",
backToData: "데이터로 돌아가기",
exportFailed: "채팅을 내보내지 못했습니다",
@@ -1606,6 +1680,25 @@ export const ko = {
alwaysDeleteFiles: "항상 파일 삭제",
alwaysDeleteFilesDescription:
"채팅을 삭제하면 해당 채팅 전용 샌드박스 폴더도 디스크에서 삭제됩니다. 프로젝트 안에서 만든 파일은 해당 프로젝트 작업 공간에 남습니다.",
+ chatsSection: "채팅 및 보관함",
+ transferSection: "가져오기 및 내보내기",
+ deletionSection: "삭제",
+ archives: "보관함",
+ archiveChatsLabel: "채팅",
+ archiveVideosLabel: "동영상",
+ exportFormatsSummary: "최근 항목과 프로젝트의 채팅을 원하는 형식으로 내보냅니다.",
+ trainingSummary: "채팅을 미세 조정용 데이터셋으로 만듭니다.",
+ confirmDeletionSummary: "개별 채팅을 삭제하기 전에 확인합니다.",
+ sandboxFiles: "채팅 샌드박스 파일",
+ sandboxFilesDescription: "채팅 삭제 시 기본 동작입니다.",
+ keepSandboxFiles: "샌드박스 파일 유지",
+ deleteSandboxFiles: "샌드박스 파일 삭제",
+ projectFilesKept: "샌드박스는 개별 채팅을 위해 만든 폴더입니다. 프로젝트 작업 공간에 저장된 파일은 유지됩니다.",
+ deleteAllAction: "모두 삭제",
+ deleteChatsOnly: "채팅만 삭제…",
+ deleteChatsAndSandboxes: "채팅 및 샌드박스 삭제…",
+ deleteSandboxFilesDescription:
+ "각 채팅의 샌드박스 폴더와 그 안의 파일도 삭제합니다. 프로젝트 작업 공간의 파일은 유지됩니다.",
filesSection: "파일",
uploadedFiles: "업로드한 파일",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 4dcfcfb325a..630194cc4a1 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1541,7 +1541,7 @@ export const ptBR = {
exportPerChatSuffix: "(por chat)",
importChats: "Importar chats",
importChatsDescription:
- "Importe um export do Open WebUI, JSONL, NDJSON ou CSV para Recentes.",
+ "Importe arquivos JSON, JSONL, NDJSON ou CSV para Recentes.",
importChatsAction: "Importar",
importNoConversations: "Nenhuma conversa encontrada no arquivo.",
importedOneChat: "1 conversa foi importada para Recentes.",
@@ -1585,6 +1585,80 @@ export const ptBR = {
failedToClearChats: "Falha ao limpar os chats",
},
data: {
+ library: {
+ defaultSort: "Padrão",
+ updated: "Atualização",
+ created: "Criação",
+ oldest: "Mais antigos primeiro",
+ alphabetical: "Ordem alfabética",
+ allChats: "Todos os chats",
+ singleChats: "Chats individuais",
+ compareChats: "Chats de comparação",
+ allProjects: "Todos os projetos",
+ noProject: "Sem projeto",
+ unavailableProject: "Projeto indisponível",
+ filterSort: "Filtrar e ordenar",
+ sort: "Ordenar",
+ type: "Tipo",
+ sortBy: "Ordenar por",
+ filterProject: "Filtrar por projeto",
+ searchProjects: "Buscar projetos",
+ noProjects: "Nenhum projeto encontrado.",
+ untitled: "Sem título",
+ oneChat: "1 chat",
+ chatCount: "{count} chats",
+ searchChats: "Buscar chats ou projetos",
+ searchArchivedChats: "Buscar chats arquivados ou projetos",
+ searchImages: "Buscar imagens arquivadas",
+ searchVideos: "Buscar vídeos arquivados",
+ searchAudio: "Buscar áudios arquivados",
+ unarchive: "Desarquivar",
+ unarchiveAll: "Desarquivar tudo",
+ unarchiveResults: "Desarquivar resultados",
+ deleteResults: "Excluir resultados",
+ noChats: "Nenhum chat corresponde à sua busca.",
+ noArchivedChats: "Nenhum chat arquivado.",
+ noArchivedMatches: "Nenhum chat arquivado corresponde à sua busca.",
+ noMedia: "Nenhum item arquivado.",
+ noMediaMatches: "Nenhum item arquivado corresponde à sua busca.",
+ itemCount: "Itens: {count}",
+ incompleteSearch: "A busca está incompleta. Tente carregar os itens restantes novamente.",
+ searchingRemaining: "Buscando os itens restantes ({count} carregados)...",
+ noLoadedMatches: "Nenhuma correspondência nos itens carregados até agora.",
+ deleteItem: "Excluir: {title}",
+ unarchiveItem: "Desarquivar: {title}",
+ deleteItemsTitle: "Excluir itens arquivados ({count})",
+ unarchiveItemsTitle: "Desarquivar itens ({count})",
+ deleteFilesWarning: "Estes arquivos serão excluídos permanentemente. Isso não pode ser desfeito.",
+ restoreWarning: "Estes itens voltarão para a galeria.",
+ working: "Processando...",
+ loadFailed: "Não foi possível carregar os itens arquivados",
+ loadMoreFailed: "Não foi possível carregar mais itens arquivados",
+ restoreFailed: "Não foi possível desarquivar os itens selecionados",
+ deleteFailed: "Não foi possível excluir os itens selecionados",
+ projectsFailed: "Não foi possível carregar os projetos arquivados",
+ pageStalled: "A página do arquivo não avançou. Tente novamente.",
+ pageChanged: "O arquivo mudou durante o carregamento. Tente novamente.",
+ selectAll: "Selecionar todos os chats visíveis",
+ selectItem: "Selecionar \"{title}\"",
+ selectedChats: "Chats selecionados: {count}",
+ move: "Mover",
+ pin: "Fixar",
+ unpin: "Desafixar",
+ archive: "Arquivar",
+ deletedChats: "Chats excluídos: {count}",
+ restoredChats: "Chats desarquivados: {count}",
+ pinnedChats: "Chats fixados: {count}",
+ unpinnedChats: "Chats desafixados: {count}",
+ movedChatsToProject: "Chats movidos para {project}: {count}",
+ movedChatsToRecents: "Chats movidos para Recentes: {count}",
+ moveFailed: "Não foi possível mover os chats",
+ deleteChatsTitle: "Excluir chats ({count})",
+ deleteChatsWarning: "Excluir os chats selecionados ({count})? Isso não pode ser desfeito.",
+ deleteArchivedTitle: "Excluir {count} chats arquivados",
+ deleteArchivedWarning: "Excluir os chats arquivados selecionados ({count})? Isso não pode ser desfeito.",
+ deleting: "Excluindo...",
+ },
title: "Dados",
backToData: "Voltar para Dados",
exportFailed: "Não foi possível exportar os chats",
@@ -1627,6 +1701,27 @@ export const ptBR = {
alwaysDeleteFiles: "Sempre excluir os arquivos",
alwaysDeleteFilesDescription:
"Excluir uma conversa também remove do disco a pasta de sandbox dela. Os arquivos escritos dentro de um projeto permanecem no espaço de trabalho desse projeto.",
+ chatsSection: "Chats e arquivos",
+ transferSection: "Importação e exportação",
+ deletionSection: "Exclusão",
+ archives: "Arquivos",
+ archiveChatsLabel: "Chats",
+ archiveVideosLabel: "Vídeos",
+ exportFormatsSummary:
+ "Exporte os chats de Recentes e dos projetos no formato que preferir.",
+ trainingSummary: "Transforme seus chats em um conjunto de dados para ajuste fino.",
+ confirmDeletionSummary: "Pedir confirmação antes de excluir chats individuais.",
+ sandboxFiles: "Arquivos da sandbox dos chats",
+ sandboxFilesDescription: "Ação padrão ao excluir um chat.",
+ keepSandboxFiles: "Manter arquivos da sandbox",
+ deleteSandboxFiles: "Excluir arquivos da sandbox",
+ projectFilesKept:
+ "Sandboxes são pastas criadas para cada chat. Os arquivos salvos nos espaços de trabalho dos projetos são mantidos.",
+ deleteAllAction: "Excluir tudo",
+ deleteChatsOnly: "Excluir apenas os chats…",
+ deleteChatsAndSandboxes: "Excluir chats e sandboxes…",
+ deleteSandboxFilesDescription:
+ "Exclui também a pasta da sandbox de cada chat e os arquivos nela. Os arquivos nos espaços de trabalho dos projetos são mantidos.",
filesSection: "Arquivos",
uploadedFiles: "Arquivos enviados",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index d535dc47ecd..c464e8fde54 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1537,7 +1537,7 @@ export const ru = {
exportPerChatSuffix: "(по чатам)",
importChats: "Импортировать чаты",
importChatsDescription:
- "Импортируйте экспорт Open WebUI, JSONL, NDJSON или CSV в Недавние.",
+ "Импортируйте файлы JSON, JSONL, NDJSON или CSV в Недавние.",
importChatsAction: "Импорт",
importNoConversations: "В файле не найдено диалогов.",
importedOneChat: "Импортирован 1 диалог в «Недавние».",
@@ -1581,6 +1581,80 @@ export const ru = {
failedToClearChats: "Не удалось очистить чаты",
},
data: {
+ library: {
+ defaultSort: "По умолчанию",
+ updated: "По обновлению",
+ created: "По созданию",
+ oldest: "Сначала старые",
+ alphabetical: "По алфавиту",
+ allChats: "Все чаты",
+ singleChats: "Одиночные чаты",
+ compareChats: "Чаты сравнения",
+ allProjects: "Все проекты",
+ noProject: "Без проекта",
+ unavailableProject: "Проект недоступен",
+ filterSort: "Фильтры и сортировка",
+ sort: "Сортировка",
+ type: "Тип",
+ sortBy: "Сортировать по",
+ filterProject: "Фильтр по проекту",
+ searchProjects: "Поиск проектов",
+ noProjects: "Проекты не найдены.",
+ untitled: "Без названия",
+ oneChat: "1 чат",
+ chatCount: "Чатов: {count}",
+ searchChats: "Поиск чатов или проектов",
+ searchArchivedChats: "Поиск архивных чатов или проектов",
+ searchImages: "Поиск архивных изображений",
+ searchVideos: "Поиск архивных видео",
+ searchAudio: "Поиск архивного аудио",
+ unarchive: "Разархивировать",
+ unarchiveAll: "Разархивировать всё",
+ unarchiveResults: "Разархивировать результаты",
+ deleteResults: "Удалить результаты",
+ noChats: "Нет чатов, соответствующих запросу.",
+ noArchivedChats: "Нет архивных чатов.",
+ noArchivedMatches: "Нет архивных чатов, соответствующих запросу.",
+ noMedia: "Нет архивных элементов.",
+ noMediaMatches: "Нет архивных элементов, соответствующих запросу.",
+ itemCount: "Элементов: {count}",
+ incompleteSearch: "Поиск не завершён. Повторите загрузку оставшихся элементов.",
+ searchingRemaining: "Поиск оставшихся элементов (загружено: {count})...",
+ noLoadedMatches: "Среди загруженных элементов совпадений нет.",
+ deleteItem: "Удалить: {title}",
+ unarchiveItem: "Разархивировать: {title}",
+ deleteItemsTitle: "Удалить архивные элементы ({count})",
+ unarchiveItemsTitle: "Разархивировать элементы ({count})",
+ deleteFilesWarning: "Эти файлы будут удалены навсегда. Это действие нельзя отменить.",
+ restoreWarning: "Эти элементы вернутся в галерею.",
+ working: "Обработка...",
+ loadFailed: "Не удалось загрузить архивные элементы",
+ loadMoreFailed: "Не удалось загрузить другие архивные элементы",
+ restoreFailed: "Не удалось разархивировать выбранные элементы",
+ deleteFailed: "Не удалось удалить выбранные элементы",
+ projectsFailed: "Не удалось загрузить архивные проекты",
+ pageStalled: "Следующая страница архива не загружена. Повторите попытку.",
+ pageChanged: "Архив изменился во время загрузки. Повторите попытку.",
+ selectAll: "Выбрать все видимые чаты",
+ selectItem: "Выбрать «{title}»",
+ selectedChats: "Выбрано чатов: {count}",
+ move: "Переместить",
+ pin: "Закрепить",
+ unpin: "Открепить",
+ archive: "Архивировать",
+ deletedChats: "Удалено чатов: {count}",
+ restoredChats: "Разархивировано чатов: {count}",
+ pinnedChats: "Закреплено чатов: {count}",
+ unpinnedChats: "Откреплено чатов: {count}",
+ movedChatsToProject: "Перемещено чатов в {project}: {count}",
+ movedChatsToRecents: "Перемещено чатов в недавние: {count}",
+ moveFailed: "Не удалось переместить чаты",
+ deleteChatsTitle: "Удалить чаты ({count})",
+ deleteChatsWarning: "Удалить выбранные чаты ({count})? Это действие нельзя отменить.",
+ deleteArchivedTitle: "Удалить архивные чаты ({count})",
+ deleteArchivedWarning: "Удалить выбранные архивные чаты ({count})? Это действие нельзя отменить.",
+ deleting: "Удаление...",
+ },
title: "Данные",
backToData: "Вернуться к данным",
exportFailed: "Не удалось экспортировать чаты",
@@ -1624,6 +1698,27 @@ export const ru = {
alwaysDeleteFiles: "Всегда удалять файлы",
alwaysDeleteFilesDescription:
"При удалении чата с диска удаляется и его собственная папка песочницы. Файлы, созданные внутри проекта, остаются в рабочей папке этого проекта.",
+ chatsSection: "Чаты и архивы",
+ transferSection: "Импорт и экспорт",
+ deletionSection: "Удаление",
+ archives: "Архивы",
+ archiveChatsLabel: "Чаты",
+ archiveVideosLabel: "Видео",
+ exportFormatsSummary: "Экспортируйте чаты из Недавних и проектов в нужном формате.",
+ trainingSummary: "Создайте из чатов набор данных для дообучения.",
+ confirmDeletionSummary:
+ "Запрашивать подтверждение перед удалением отдельных чатов.",
+ sandboxFiles: "Файлы песочниц чатов",
+ sandboxFilesDescription: "Действие по умолчанию при удалении чата.",
+ keepSandboxFiles: "Сохранять файлы песочниц",
+ deleteSandboxFiles: "Удалять файлы песочниц",
+ projectFilesKept:
+ "Песочницы представляют собой папки, созданные для отдельных чатов. Файлы в рабочих пространствах проектов сохраняются.",
+ deleteAllAction: "Удалить всё",
+ deleteChatsOnly: "Удалить только чаты…",
+ deleteChatsAndSandboxes: "Удалить чаты и песочницы…",
+ deleteSandboxFilesDescription:
+ "Также удалить папку песочницы каждого чата и файлы в ней. Файлы в рабочих пространствах проектов сохраняются.",
filesSection: "Файлы",
uploadedFiles: "Загруженные файлы",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 4488959018b..53527b7a464 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1489,7 +1489,7 @@ export const zhCN = {
exportPerChatSuffix: "(每个对话)",
importChats: "导入对话",
importChatsDescription:
- "将 Open WebUI、JSONL、NDJSON 或 CSV 导出文件导入到最近对话。",
+ "将 JSON、JSONL、NDJSON 或 CSV 文件导入到最近对话。",
importChatsAction: "导入",
importNoConversations: "文件中未找到对话。",
importedOneChat: "已导入 1 个对话到最近对话。",
@@ -1531,6 +1531,80 @@ export const zhCN = {
failedToClearChats: "清除聊天失败",
},
data: {
+ library: {
+ defaultSort: "默认",
+ updated: "更新时间",
+ created: "创建时间",
+ oldest: "最早优先",
+ alphabetical: "按字母排序",
+ allChats: "所有聊天",
+ singleChats: "单模型聊天",
+ compareChats: "对比聊天",
+ allProjects: "所有项目",
+ noProject: "无项目",
+ unavailableProject: "项目不可用",
+ filterSort: "筛选和排序",
+ sort: "排序",
+ type: "类型",
+ sortBy: "排序依据",
+ filterProject: "按项目筛选",
+ searchProjects: "搜索项目",
+ noProjects: "未找到项目。",
+ untitled: "无标题",
+ oneChat: "1 个聊天",
+ chatCount: "{count} 个聊天",
+ searchChats: "搜索聊天或项目",
+ searchArchivedChats: "搜索已归档的聊天或项目",
+ searchImages: "搜索已归档的图片",
+ searchVideos: "搜索已归档的视频",
+ searchAudio: "搜索已归档的音频",
+ unarchive: "取消归档",
+ unarchiveAll: "全部取消归档",
+ unarchiveResults: "取消归档搜索结果",
+ deleteResults: "删除搜索结果",
+ noChats: "没有与搜索匹配的聊天。",
+ noArchivedChats: "没有已归档的聊天。",
+ noArchivedMatches: "没有与搜索匹配的已归档聊天。",
+ noMedia: "没有已归档的条目。",
+ noMediaMatches: "没有与搜索匹配的已归档条目。",
+ itemCount: "条目数:{count}",
+ incompleteSearch: "搜索尚未完成。请重试加载剩余条目。",
+ searchingRemaining: "正在搜索剩余条目(已加载 {count} 项)...",
+ noLoadedMatches: "目前已加载的条目中没有匹配结果。",
+ deleteItem: "删除:{title}",
+ unarchiveItem: "取消归档:{title}",
+ deleteItemsTitle: "删除已归档条目({count} 项)",
+ unarchiveItemsTitle: "取消归档条目({count} 项)",
+ deleteFilesWarning: "这些文件将被永久删除,此操作无法撤销。",
+ restoreWarning: "这些条目将返回到媒体库。",
+ working: "正在处理...",
+ loadFailed: "无法加载已归档条目",
+ loadMoreFailed: "无法加载更多已归档条目",
+ restoreFailed: "无法取消归档所选条目",
+ deleteFailed: "无法删除所选条目",
+ projectsFailed: "无法加载已归档的项目列表",
+ pageStalled: "归档列表未加载下一页,请重试。",
+ pageChanged: "加载期间归档内容已发生变化,请重试。",
+ selectAll: "选择所有可见聊天",
+ selectItem: "选择“{title}”",
+ selectedChats: "已选择 {count} 个聊天",
+ move: "移动",
+ pin: "置顶",
+ unpin: "取消置顶",
+ archive: "归档",
+ deletedChats: "已删除 {count} 个聊天",
+ restoredChats: "已取消归档 {count} 个聊天",
+ pinnedChats: "已置顶 {count} 个聊天",
+ unpinnedChats: "已取消置顶 {count} 个聊天",
+ movedChatsToProject: "已将 {count} 个聊天移至 {project}",
+ movedChatsToRecents: "已将 {count} 个聊天移至最近使用",
+ moveFailed: "无法移动聊天",
+ deleteChatsTitle: "删除聊天({count} 个)",
+ deleteChatsWarning: "删除所选的 {count} 个聊天?此操作无法撤销。",
+ deleteArchivedTitle: "删除 {count} 个已归档聊天",
+ deleteArchivedWarning: "删除所选的 {count} 个已归档聊天?此操作无法撤销。",
+ deleting: "正在删除...",
+ },
title: "数据",
backToData: "返回数据",
exportFailed: "无法导出聊天",
@@ -1570,6 +1644,24 @@ export const zhCN = {
alwaysDeleteFiles: "始终删除文件",
alwaysDeleteFilesDescription:
"删除对话时,同时从磁盘中删除它自己的沙盒文件夹。它在项目内写入的文件仍保留在该项目的工作区中。",
+ chatsSection: "对话与归档",
+ transferSection: "导入与导出",
+ deletionSection: "删除",
+ archives: "归档",
+ archiveChatsLabel: "对话",
+ archiveVideosLabel: "视频",
+ exportFormatsSummary: "以所需格式导出最近对话和项目中的对话。",
+ trainingSummary: "将对话转换为微调数据集。",
+ confirmDeletionSummary: "删除单个对话前询问确认。",
+ sandboxFiles: "对话沙盒文件",
+ sandboxFilesDescription: "删除对话时的默认操作。",
+ keepSandboxFiles: "保留沙盒文件",
+ deleteSandboxFiles: "删除沙盒文件",
+ projectFilesKept: "沙盒是为单个对话创建的文件夹。保存在项目工作区中的文件会被保留。",
+ deleteAllAction: "全部删除",
+ deleteChatsOnly: "仅删除对话…",
+ deleteChatsAndSandboxes: "删除对话和沙盒…",
+ deleteSandboxFilesDescription: "同时删除每个对话的沙盒文件夹及其中的文件。项目工作区中的文件会被保留。",
filesSection: "文件",
uploadedFiles: "上传的文件",
uploadedFilesDescription: "查看和管理上传到聊天、项目和知识库的文件。",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 6e025f6f4f1..333a84c81cc 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -3773,3 +3773,10 @@ html[data-chat-font] .aui-root {
background-color: #2c2c2c;
box-shadow: 0 4px 20px 6px var(--background);
}
+
+@layer components {
+ /* Align the arrow with page content while retaining its hit area. */
+ .settings-back-button {
+ margin-inline-start: -0.75rem;
+ }
+}
diff --git a/studio/frontend/tests/data-library.test.ts b/studio/frontend/tests/data-library.test.ts
new file mode 100644
index 00000000000..8d75b3e0f02
--- /dev/null
+++ b/studio/frontend/tests/data-library.test.ts
@@ -0,0 +1,258 @@
+// 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 assert from "node:assert/strict";
+import test from "node:test";
+import {
+ DEFAULT_LIBRARY_FILTERS,
+ filterLibraryItems,
+ formatLibraryDate,
+ groupLibraryItems,
+ type LibraryItem,
+} from "../src/features/settings/components/data-library.ts";
+
+const labels = {
+ noProject: "No project",
+ unavailableProject: "Unavailable project",
+};
+const projects = new Map([
+ ["p1", "Research notes"],
+ ["p2", "Research notes"],
+]);
+const items: LibraryItem[] = [
+ {
+ id: "a",
+ title: "Café research",
+ createdAt: 10,
+ updatedAt: 40,
+ projectId: "p1",
+ type: "single",
+ },
+ {
+ id: "b",
+ title: "Beta",
+ createdAt: 30,
+ updatedAt: 10,
+ projectId: "p2",
+ type: "compare",
+ },
+ { id: "c", title: "日本語", createdAt: 20, type: "single" },
+];
+const ids = (rows: LibraryItem[]) => rows.map((row) => row.id);
+const filter = (overrides: Partial<typeof DEFAULT_LIBRARY_FILTERS>) =>
+ filterLibraryItems(
+ items,
+ { ...DEFAULT_LIBRARY_FILTERS, ...overrides },
+ projects,
+ labels,
+ );
+
+test("search matches normalized title and project terms in any order", () => {
+ for (const query of [" NOTES CAFE ", "Café Research", "cafe\u0301"])
+ assert.deepEqual(ids(filter({ query })), ["a"]);
+ assert.deepEqual(ids(filter({ query: "日本" })), ["c"]);
+ assert.deepEqual(ids(filter({ query: "No project" })), ["c"]);
+ assert.deepEqual(ids(filter({ query: "missing" })), []);
+});
+
+test("project identity stays distinct when names are duplicated", () => {
+ assert.deepEqual(ids(filter({ project: "project:p1" })), ["a"]);
+ assert.deepEqual(ids(filter({ project: "project:p2" })), ["b"]);
+ assert.deepEqual(ids(filter({ project: "none" })), ["c"]);
+ assert.deepEqual(ids(filter({ project: "project:removed" })), []);
+});
+
+test("type, project and text filters compose", () => {
+ assert.deepEqual(ids(filter({ type: "compare", query: "research" })), ["b"]);
+ assert.deepEqual(ids(filter({ type: "single", project: "project:p2" })), []);
+});
+
+test("default ordering preserves the server page order", () => {
+ assert.deepEqual(ids(filter({ sort: "default" })), ["a", "b", "c"]);
+});
+
+test("sorts use the requested timestamp with a creation fallback", () => {
+ assert.deepEqual(ids(filter({ sort: "updated" })), ["a", "c", "b"]);
+ assert.deepEqual(ids(filter({ sort: "created" })), ["b", "c", "a"]);
+ assert.deepEqual(ids(filter({ sort: "oldest" })), ["a", "c", "b"]);
+ assert.deepEqual(ids(filter({ sort: "alphabetical" })).slice(0, 2), [
+ "b",
+ "a",
+ ]);
+});
+
+test("equal timestamps and titles have a stable id tie break", () => {
+ const same = [
+ { id: "z", title: "Same", createdAt: 1 },
+ { id: "a", title: "Same", createdAt: 1 },
+ ];
+ assert.deepEqual(ids(filterLibraryItems(same, DEFAULT_LIBRARY_FILTERS)), [
+ "a",
+ "z",
+ ]);
+ assert.deepEqual(ids(same), ["z", "a"]);
+});
+
+test("legacy timestamps do not produce invalid date text or unstable ordering", () => {
+ assert.equal(formatLibraryDate(Number.NaN), "");
+ assert.equal(formatLibraryDate(Number.POSITIVE_INFINITY), "");
+ assert.equal(formatLibraryDate(1e30), "");
+ const rows = [
+ { id: "invalid", title: "Invalid", createdAt: NaN },
+ { id: "valid", title: "Valid", createdAt: 1 },
+ ];
+ assert.deepEqual(ids(filterLibraryItems(rows, DEFAULT_LIBRARY_FILTERS)), [
+ "valid",
+ "invalid",
+ ]);
+});
+
+test("groups keep project ids, sorted row order and missing projects", () => {
+ const groups = groupLibraryItems(
+ [...items, { id: "d", title: "Missing", createdAt: 1, projectId: "gone" }],
+ projects,
+ labels,
+ );
+ assert.deepEqual(
+ groups.map((group) => group.id),
+ ["p1", "p2", "", "gone"],
+ );
+ assert.equal(groups[2].name, "No project");
+ assert.equal(groups[3].name, "Unavailable project");
+ assert.deepEqual(
+ groups.flatMap((group) => ids(group.items)),
+ ["a", "b", "c", "d"],
+ );
+});
+
+test("filtering a large library reaches records after the rendered page", () => {
+ const many = Array.from({ length: 10000 }, (_, i) => ({
+ id: String(i),
+ title: `Chat ${i}`,
+ createdAt: i,
+ }));
+ assert.deepEqual(
+ ids(
+ filterLibraryItems(many, {
+ ...DEFAULT_LIBRARY_FILTERS,
+ query: "Chat 9999",
+ }),
+ ),
+ ["9999"],
+ );
+ assert.equal(many[0].id, "0");
+});
+
+test("localized project labels drive matching and grouping", () => {
+ const spanish = {
+ noProject: "Sin proyecto",
+ unavailableProject: "Proyecto no disponible",
+ };
+ const rows = [
+ ...items,
+ { id: "missing", title: "Lost", projectId: "gone", createdAt: 1 },
+ ];
+ for (const [query, expected] of [
+ ["SIN PROYECTO", "c"],
+ ["disponible proyecto", "missing"],
+ ]) {
+ assert.deepEqual(
+ ids(
+ filterLibraryItems(
+ rows,
+ { ...DEFAULT_LIBRARY_FILTERS, query },
+ projects,
+ spanish,
+ ),
+ ),
+ [expected],
+ );
+ }
+ const groups = groupLibraryItems(rows, projects, spanish);
+ assert.equal(groups[2].name, spanish.noProject);
+ assert.equal(groups[3].name, spanish.unavailableProject);
+ assert.deepEqual(
+ ids(
+ filterLibraryItems(
+ rows,
+ { ...DEFAULT_LIBRARY_FILTERS, query: "No project" },
+ projects,
+ spanish,
+ ),
+ ),
+ [],
+ );
+});
+
+test("media without project labels cannot match an invented project name", () => {
+ assert.deepEqual(
+ filterLibraryItems(items, {
+ ...DEFAULT_LIBRARY_FILTERS,
+ query: "No project",
+ }),
+ [],
+ );
+});
+
+test("dates use the requested app locale", () => {
+ const ms = 1700000000000;
+ for (const locale of ["es", "ja", "ar"]) {
+ assert.equal(
+ formatLibraryDate(ms, locale),
+ new Date(ms).toLocaleString(locale, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ }),
+ );
+ }
+});
+
+test("title ordering and timestamp ties follow the selected app locale", () => {
+ const rows = [
+ { id: "z", title: "Zebra", createdAt: 1, updatedAt: 1 },
+ { id: "a", title: "阿", createdAt: 1, updatedAt: 1 },
+ { id: "b", title: "八", createdAt: 1, updatedAt: 1 },
+ ];
+ const orders = {
+ en: ["z", "b", "a"],
+ "zh-CN": ["a", "b", "z"],
+ ja: ["z", "a", "b"],
+ };
+ for (const sort of [
+ "alphabetical",
+ "created",
+ "updated",
+ "oldest",
+ ] as const) {
+ for (const [locale, expected] of Object.entries(orders)) {
+ assert.deepEqual(
+ ids(
+ filterLibraryItems(
+ rows,
+ { ...DEFAULT_LIBRARY_FILTERS, sort },
+ undefined,
+ undefined,
+ locale,
+ ),
+ ),
+ expected,
+ );
+ }
+ }
+ assert.deepEqual(
+ ids(
+ filterLibraryItems(
+ rows,
+ { ...DEFAULT_LIBRARY_FILTERS, sort: "default" },
+ undefined,
+ undefined,
+ "zh-CN",
+ ),
+ ),
+ ["z", "a", "b"],
+ );
+ assert.deepEqual(ids(rows), ["z", "a", "b"]);
+});
diff --git a/studio/frontend/tests/find-in-page.test.ts b/studio/frontend/tests/find-in-page.test.ts
index 2adc1385016..eabb8c587c1 100644
--- a/studio/frontend/tests/find-in-page.test.ts
+++ b/studio/frontend/tests/find-in-page.test.ts
@@ -2203,19 +2203,20 @@ test("a capped search does not segment the whole index to answer its first pass"
});
test("a query that matches everywhere stops seeking the segmenter per candidate", () => {
- // `containing` seeks, which is why it replaced segmenting whole blocks, and a seek per candidate
- // undoes that: a capped search anchored near the end walks the candidates up to three times, so a
- // page of one repeated syllable asked for millions. Counted, so the assertion is not the clock.
+ // Fixed seek costs make the budget check independent of host speed.
const probe = `
let seeks = 0;
+ let scans = 0;
+ let clock = 1;
+ Object.defineProperty(performance, "now", { value: () => clock });
const Real = Intl.Segmenter;
Intl.Segmenter = class {
constructor(...args) { this.inner = new Real(...args); }
segment(input) {
const segments = this.inner.segment(input);
return {
- containing: (at) => { seeks += 1; return segments.containing(at); },
- [Symbol.iterator]: () => segments[Symbol.iterator](),
+ containing: (at) => { seeks += 1; clock += 0.01; return segments.containing(at); },
+ [Symbol.iterator]: () => { scans += 1; return segments[Symbol.iterator](); },
};
}
};
@@ -2236,10 +2237,8 @@ test("a query that matches everywhere stops seeking the segmenter per candidate"
const index = buildTextIndex(el("DIV", [el("P", nodes)]));
const found = findMatches(index, "\uac00", MAX_MATCHES, index.text.length);
if (found.length !== MAX_MATCHES) throw new Error("expected a capped search, got " + found.length);
- // One pass over the boundaries replaces the seeks, so what is left is what the budget bought
- // before it. The number is not fixed: the cap is time, and a seek into Hangul is cheap, so
- // this shape gets tens of thousands where a page of flags would get tens. 1.6M without it.
- if (seeks > 200000) throw new Error("seeks per candidate: " + seeks);
+ if (scans !== 1) throw new Error("expected one boundary scan, got " + scans);
+ if (seeks > 10000) throw new Error("seeks per candidate: " + seeks);
`;
const run = spawnSync(
process.execPath,
diff --git a/studio/frontend/tests/gallery-flags.test.ts b/studio/frontend/tests/gallery-flags.test.ts
index 5965738c631..8b138ac3c3d 100644
--- a/studio/frontend/tests/gallery-flags.test.ts
+++ b/studio/frontend/tests/gallery-flags.test.ts
@@ -482,10 +482,10 @@ test("a page fetch is refused while a shelf mutation is still pending", async ()
test("archived audio pages from the stable server cursor", () => {
assert.match(
archivedMediaSource,
- /listAudioGallery\(\s*0,\s*ARCHIVED_PAGE_SIZE,\s*before,\s*true,?\s*\)/,
+ /listAudioGallery\(\s*0,\s*pageSize,\s*before,\s*true,?\s*\)/,
);
assert.match(
archivedMediaSource,
- /const page = await loadPage\(\s*rowsRef\.current\.length,\s*audioCursor\.current,?\s*\);[\s\S]*audioCursor\.current = page\.nextAudioCursor;/,
+ /const page = await loadPage\(\s*rowsRef\.current\.length,\s*audioCursor\.current,\s*scanAll \? SEARCH_PAGE_SIZE : ARCHIVED_PAGE_SIZE,?\s*\);[\s\S]*audioCursor\.current = page\.nextAudioCursor;/,
);
});
diff --git a/studio/frontend/tests/manage-chats-bulk-selection.test.ts b/studio/frontend/tests/manage-chats-bulk-selection.test.ts
index d176883cc7c..82ada592584 100644
--- a/studio/frontend/tests/manage-chats-bulk-selection.test.ts
+++ b/studio/frontend/tests/manage-chats-bulk-selection.test.ts
@@ -6,6 +6,7 @@
import assert from "node:assert/strict";
import test from "node:test";
+import { en } from "../src/i18n/locales/en.ts";
import {
installLocalStorageFake,
@@ -104,8 +105,9 @@ test("bulk delete passes the always-delete-files preference through", async () =
test("the header checkbox says it selects the visible chats, which is what it does", async () => {
const src = await manageChatsSource();
- // Rows sit behind a "Show more", so the label must not promise the whole list.
+ // rows sit behind "show more", so the label must not promise the whole list.
assert.match(src, /onCheckedChange=\{toggleAllVisible\}/);
- assert.match(src, /aria-label="Select all visible chats"/);
+ assert.match(src, /aria-label=\{t\("settings\.data\.library\.selectAll"\)\}/);
+ assert.equal(en.settings.data.library.selectAll, "Select all visible chats");
assert.doesNotMatch(src, /aria-label="Select all chats"/);
});
diff --git a/studio/frontend/tests/video-gallery-thumbnail-load.test.ts b/studio/frontend/tests/video-gallery-thumbnail-load.test.ts
index 14afb15912e..058d458017f 100644
--- a/studio/frontend/tests/video-gallery-thumbnail-load.test.ts
+++ b/studio/frontend/tests/video-gallery-thumbnail-load.test.ts
@@ -182,7 +182,7 @@ test("archived video rows reuse still posters", () => {
assert.ok(archived.includes("fetchGalleryVideoThumbnail(row.id)"));
assert.ok(archived.includes("videoThumbnailQueue.run(() =>"));
assert.ok(!archived.includes("fetchGalleryVideoSignedUrl"));
- const row = between(archived, "{rows.map((row) => (", "{hasMore ? (");
+ const row = between(archived, "{displayed.map((row) => (", "{hasMore || filtered.length > visibleCount ? (");
assert.ok(row.includes("<img"));
assert.ok(row.includes("src={thumbs[row.id]}"));
assert.ok(!row.includes("<video"));
diff --git a/tests/studio/playwright_data_settings.py b/tests/studio/playwright_data_settings.py
new file mode 100644
index 00000000000..8475ea796f0
--- /dev/null
+++ b/tests/studio/playwright_data_settings.py
@@ -0,0 +1,1016 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Data settings against memory-only chat storage, with no backend or model.
+
+PW_ENGINE=chromium|firefox|webkit selects the browser engine.
+PW_CHANNEL=chrome|msedge optionally selects a branded Chromium browser.
+PW_PORT and PW_OUT select the local port and JSON report.
+"""
+
+import itertools
+import json
+import os
+import sys
+from pathlib import Path
+
+from playwright.sync_api import expect, sync_playwright
+
+from _playwright_robust import start_vite, stop_process, wait_for_smoke_page
+
+FIXTURE = """(() => {
+ localStorage.setItem('unsloth_chat_legacy_imported_to_studio_db', 'true');
+ const fixture = { rows: [], requests: [], hold: false, fail: false, listFail: false, media: {}, projects: [{ id: "research", name: "Research notes", createdAt: 1, updatedAt: 1 }, { id: "other", name: "Other project", createdAt: 2, updatedAt: 2 }, { id: "archived-project", name: "Old experiments", createdAt: 3, updatedAt: 3, archived: true }] };
+ window.__dataFixture = fixture;
+ window.fetch = async (input, init = {}) => {
+ const url = new URL(typeof input === 'string' ? input : input.url, location.origin);
+ const method = init.method || input?.method || 'GET';
+ const record = { path: url.pathname, query: url.search, method, done: false };
+ record.body = init.body ? JSON.parse(init.body) : null;
+ fixture.requests.push(record);
+ let body = {}, status = 200;
+ if (url.pathname === '/api/chat/threads' && method === 'DELETE') {
+ if (fixture.holdMutation) await new Promise(resolve => { fixture.releaseMutation = resolve; });
+ if (fixture.failMutation) { status = 503; body = { detail: 'Mutation unavailable' }; }
+ else { fixture.rows = fixture.rows.filter(row => !record.body.ids.includes(row.id)); body = { sandboxes_kept: [] }; }
+ } else if (url.pathname.startsWith('/api/chat/threads/') && method === 'PATCH') {
+ const row = fixture.rows.find(row => row.id === decodeURIComponent(url.pathname.split('/').pop()));
+ Object.assign(row, record.body); body = row;
+ } else if (url.pathname === '/api/chat/threads') {
+ if (fixture.listFail) { status = 503; body = { detail: 'Chat list unavailable' }; }
+ else body = { threads: fixture.rows };
+ } else if (url.pathname === '/api/chat/projects') body = { projects: fixture.projects.filter(project => url.searchParams.get('include_archived') !== 'false' || !project.archived) };
+ else if (url.pathname === '/api/chat/export') {
+ if (fixture.holdExport) await new Promise(resolve => { fixture.releaseExport = resolve; });
+ body = { threads: fixture.rows, messages: [], projects: [] };
+ }
+ else if (url.pathname === '/api/chat' && method === 'DELETE') {
+ if (fixture.hold) await new Promise(resolve => { fixture.release = resolve; });
+ if (fixture.fail) { status = 503; body = { detail: 'Deletion unavailable' }; }
+ else {
+ body = { deletedThreadIds: fixture.rows.map(row => row.id), sandboxes_kept: [] };
+ fixture.rows = [];
+ }
+ } else if (url.pathname.includes('knowledge-bases')) {
+ body = { knowledgeBases: [], ragAvailable: false };
+ } else if (url.pathname.includes('linked-folders')) body = { folders: [] };
+ else if (url.pathname.includes('gallery')) {
+ const kind = url.pathname.includes('/images/') ? 'images' : url.pathname.includes('/video/') ? 'videos' : 'audio';
+ const entries = fixture.media[kind] ?? [];
+ const suffix = url.pathname.split('/gallery')[1];
+ if (suffix && (method === 'PATCH' || method === 'DELETE')) {
+ if (fixture.holdMutation) await new Promise(resolve => { fixture.releaseMutation = resolve; });
+ if (fixture.failMutation || fixture.failMutationId === decodeURIComponent(suffix.slice(1))) { status = 503; body = { detail: 'Mutation unavailable' }; }
+ else {
+ const id = decodeURIComponent(suffix.slice(1));
+ body = entries.find(row => row.id === id) ?? {};
+ fixture.media[kind] = entries.filter(row => row.id !== id);
+ }
+ } else if (!suffix) {
+ const before = url.searchParams.get('before_id');
+ const offset = before ? entries.findIndex(row => row.id === before) + 1 : Number(url.searchParams.get('offset') ?? 0);
+ const limit = Number(url.searchParams.get('limit') ?? 20);
+ const pageRows = entries.slice(offset, offset + limit);
+ if (offset > 0 && fixture.holdPage) await new Promise(resolve => { fixture.releasePage = resolve; });
+ if (fixture.failPage && offset > 0) { status = 503; body = { detail: 'Page unavailable' }; }
+ else {
+ const last = pageRows.at(-1);
+ body = { [kind]: fixture.stallPage && offset > 0 ? [] : pageRows, has_more: fixture.stallPage && offset > 0 || offset + limit < entries.length,
+ next_before_mtime: last ? offset + pageRows.length : null, next_before_id: last?.id ?? null };
+ }
+ } else {
+ return new Response(Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aZwoAAAAASUVORK5CYII='), c => c.charCodeAt(0)), { headers: { 'Content-Type': 'image/png' } });
+ }
+ }
+ else if (url.pathname.includes('messages')) body = { messages: [] };
+ record.done = true;
+ return new Response(JSON.stringify(body), {
+ status, headers: { 'Content-Type': 'application/json' },
+ });
+ };
+})();"""
+
+
+def run(page):
+ checks = []
+
+ def reset(**options):
+ page.evaluate("window.__settingsSmoke.close()")
+ expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
+ page.evaluate(
+ """options => {
+ const f = window.__dataFixture;
+ Object.assign(f, { requests: [], hold: false, holdExport: false, fail: false, listFail: false }, options);
+ f.rows = Array.from({ length: options.count ?? 3 }, (_, i) => ({
+ id: crypto.randomUUID(), title: `Chat ${i}`, modelType: 'base', modelId: 'test',
+ createdAt: 1700000000000 + i, updatedAt: 1700000000000 + i,
+ }));
+ window.__settingsSmoke.open('data');
+ }""",
+ options,
+ )
+ page.get_by_role("combobox", name = "Chat sandbox files", exact = True).wait_for()
+ page.wait_for_function(
+ "window.__dataFixture.requests.some(r => r.path === '/api/chat/threads' && r.done)"
+ )
+
+ def deletes():
+ return page.evaluate("window.__dataFixture.requests.filter(r => r.method === 'DELETE')")
+
+ def confirm(mode):
+ page.get_by_role("button", name = "Delete all", exact = True).click()
+ label = "Delete chats and sandboxes…" if mode else "Delete chats only…"
+ page.get_by_role("menuitem", name = label, exact = True).click()
+ return page.get_by_role("dialog").last
+
+ for preference, mode, override in itertools.product([False, True], repeat = 3):
+ reset()
+ page.get_by_role("combobox", name = "Chat sandbox files", exact = True).click()
+ page.get_by_role(
+ "option",
+ name = "Delete sandbox files" if preference else "Keep sandbox files",
+ exact = True,
+ ).click()
+ dialog = confirm(mode)
+ toggle = dialog.get_by_role("switch")
+ expect(toggle).to_have_attribute("aria-checked", str(mode).lower())
+ assert not deletes(), "The menu must only open confirmation"
+ if override:
+ toggle.click()
+ dialog.get_by_role("button", name = "Clear 3 chats", exact = True).click()
+ expect(page.get_by_role("button", name = "Delete all", exact = True)).to_be_disabled()
+ requests = deletes()
+ assert len(requests) == 1
+ assert requests[0]["query"] == ("?delete_files=true" if mode != override else "")
+ checks.append(f"choice-{preference}-{mode}-{override}")
+
+ for dismissal in ["Cancel", "Close", "Escape"]:
+ reset()
+ dialog = confirm(True)
+ if dismissal == "Escape":
+ page.keyboard.press("Escape")
+ else:
+ dialog.get_by_role("button", name = dismissal, exact = True).click()
+ expect(page.locator("#clear-chats-delete-files")).to_have_count(0)
+ assert not deletes()
+ checks.append(f"dismiss-{dismissal}")
+
+ reset(hold = True)
+ dialog = confirm(True)
+ dialog.get_by_role("button", name = "Clear 3 chats", exact = True).click()
+ page.wait_for_function("typeof window.__dataFixture.release === 'function'")
+ expect(dialog.get_by_role("switch")).to_be_disabled()
+ expect(dialog.get_by_role("button", name = "Cancel", exact = True)).to_be_disabled()
+ expect(dialog.get_by_role("button", name = "Close", exact = True)).to_have_count(0)
+ page.keyboard.press("Escape")
+ expect(page.locator("#clear-chats-delete-files")).to_be_visible()
+ page.mouse.click(5, 5)
+ expect(page.locator("#clear-chats-delete-files")).to_be_visible()
+ page.evaluate("window.__dataFixture.release()")
+ expect(page.locator("#clear-chats-delete-files")).to_have_count(0)
+ assert len(deletes()) == 1
+ checks.append("pending-delete-locks-choice-and-dismissal")
+
+ reset(fail = True)
+ dialog = confirm(True)
+ dialog.get_by_role("button", name = "Clear 3 chats", exact = True).click()
+ expect(page.locator("#clear-chats-delete-files")).to_have_count(0)
+ expect(page.get_by_role("button", name = "Delete all", exact = True)).to_be_enabled()
+ assert page.evaluate("window.__dataFixture.rows.length") == 3
+ assert len(deletes()) == 2
+ checks.append("failed-delete-preserves-chats-and-reenables-action")
+
+ for count in [0, 1, 1000]:
+ reset(count = count)
+ trigger = page.get_by_role("button", name = "Delete all", exact = True)
+ if count == 0:
+ expect(trigger).to_be_disabled()
+ else:
+ dialog = confirm(False)
+ expect(dialog.get_by_role("heading")).to_contain_text(str(count))
+ dialog.get_by_role("button", name = "Cancel", exact = True).click()
+ checks.append(f"count-{count}")
+
+ reset(listFail = True)
+ expect(page.get_by_role("button", name = "Delete all", exact = True)).to_be_disabled()
+ checks.append("failed-count-cannot-open-zero-chat-confirmation")
+
+ reset()
+ for label in ["Archived chats", "Archived images", "Archived videos", "Archived audio"]:
+ button = page.get_by_role("button", name = label, exact = True)
+ expect(button.locator("svg")).to_have_count(2)
+ button.click()
+ page.get_by_role("button", name = "Back to Data", exact = True).click()
+ checks.append(f"archive-{label}")
+
+ for source, target in itertools.product(
+ [
+ "Manage chats",
+ "Uploaded files",
+ "Archived chats",
+ "Archived images",
+ "Archived videos",
+ "Archived audio",
+ ],
+ [
+ "Archived chats",
+ "Archived images",
+ "Archived videos",
+ "Archived audio",
+ "Chat sandbox files",
+ "Uploaded files",
+ ],
+ ):
+ reset()
+ if source.startswith("Archived"):
+ page.get_by_role("button", name = source, exact = True).click()
+ else:
+ page.locator(f'[data-settings-label="{source}"]').get_by_role(
+ "button", name = "Manage", exact = True
+ ).click()
+ expect(page.get_by_role("button", name = "Back to Data", exact = True)).to_be_visible()
+ page.locator("aside input").fill(target)
+ page.locator("aside").get_by_role("button", name = target, exact = True).click()
+ expect(page.locator(".settings-search-hit")).to_have_attribute(
+ "data-settings-label", target
+ )
+ expect(page.get_by_role("button", name = "Back to Data", exact = True)).to_have_count(0)
+ assert not deletes()
+ checks.append(f"search-{source}-to-{target}")
+
+ for shelf in ["chats", "images", "videos", "audio"]:
+ page.evaluate("shelf => window.__settingsSmoke.openArchived(shelf)", shelf)
+ expect(page.get_by_role("heading", name = f"Archived {shelf}", exact = True)).to_be_visible()
+ page.locator("aside input").fill("Chat sandbox files")
+ page.locator("aside").get_by_role("button", name = "Chat sandbox files", exact = True).click()
+ expect(page.locator(".settings-search-hit")).to_have_attribute(
+ "data-settings-label", "Chat sandbox files"
+ )
+ expect(page.get_by_role("button", name = "Back to Data", exact = True)).to_have_count(0)
+ checks.append(f"archive-request-after-search-{shelf}")
+
+ reset(holdExport = True)
+ export_row = page.locator('[data-settings-label="Export chat history"]')
+ export_row.get_by_role("button", name = "Export", exact = True).click()
+ page.wait_for_function("typeof window.__dataFixture.releaseExport === 'function'")
+ page.locator("aside input").fill("Chat sandbox files")
+ page.locator("aside").get_by_role("button", name = "Chat sandbox files", exact = True).click()
+ expect(page.locator(".settings-search-hit")).to_have_attribute(
+ "data-settings-label", "Chat sandbox files"
+ )
+ expect(export_row.get_by_role("button", name = "Exporting...", exact = True)).to_be_disabled()
+ with page.expect_download():
+ page.evaluate("window.__dataFixture.releaseExport()")
+ expect(export_row.get_by_role("button", name = "Export", exact = True)).to_be_enabled()
+ assert (
+ page.evaluate(
+ "window.__dataFixture.requests.filter(r => r.path === '/api/chat/export').length"
+ )
+ == 1
+ )
+ checks.append("search-preserves-in-flight-export")
+
+ checks.extend(run_libraries(page))
+ checks.extend(run_library_locales(page))
+ checks.extend(run_library_selection(page))
+ checks.extend(run_library_collation(page))
+ checks.extend(run_restore_notifications(page))
+ checks.extend(run_thumbnail_retention(page))
+
+ errors = page.evaluate("window.__settingsSmoke.errors()")
+ resize_notice = "ResizeObserver loop completed with undelivered notifications."
+ failures = [error for error in errors if error != resize_notice]
+ assert not failures, failures
+ return {"checks": checks, "browser_notices": errors}
+
+
+def run_libraries(page):
+ checks = []
+
+ def seed(shelf, **options):
+ page.evaluate("window.__settingsSmoke.close()")
+ expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
+ page.evaluate(
+ """({shelf, options}) => {
+ const f = window.__dataFixture;
+ Object.assign(f, { requests: [], holdMutation: false, failMutation: false,
+ holdPage: false, failPage: false, stallPage: false, listFail: false }, options);
+ f.rows = Array.from({ length: 32 }, (_, i) => ({
+ id: crypto.randomUUID(), title: i === 26 ? 'Café needle' : i === 0 ? 'Zulu sample' : `Chat ${String(i).padStart(2, '0')}`,
+ modelType: 'base', modelId: 'test',
+ projectId: i === 31 && shelf === 'chats' ? 'archived-project' : i % 2 === 0 || i === 1 ? 'research' : 'other',
+ archived: shelf === 'chats', createdAt: 1700000000000 + i * 86400000,
+ updatedAt: 1700000000000 + (32 - i) * 86400000,
+ }));
+ delete f.releaseMutation; delete f.releasePage;
+ const pairId = crypto.randomUUID();
+ for (const i of [1, 2]) Object.assign(f.rows[i], { pairId, title: 'Compare models' });
+ for (const kind of ['images', 'videos', 'audio']) {
+ const route = kind === 'videos' ? 'video' : kind;
+ f.media[kind] = Array.from({ length: options.mediaCount ?? 447 }, (_, i) => ({
+ id: `${kind}-${i}`, prompt: i === 26 ? 'Café needle' : `Sample ${String(i).padStart(2, '0')}`,
+ created_at: kind === 'images' ? 1700000000 - i * 86400 : new Date(1700000000000 - i * 86400000).toISOString(),
+ url: `/api/inference/${route}/gallery/${kind}-${i}/content`, archived: true,
+ }));
+ }
+ if (options.reorderDates) {
+ for (const kind of ['images', 'videos', 'audio']) f.media[kind][300].created_at = kind === 'images' ? 1900000000 : new Date(1900000000000).toISOString();
+ }
+ if (shelf === 'manage') window.__settingsSmoke.open('data');
+ else window.__settingsSmoke.openArchived(shelf);
+ }""",
+ {"shelf": shelf, "options": options},
+ )
+ if shelf == "manage":
+ page.locator('[data-settings-label="Manage chats"]').get_by_role(
+ "button", name = "Manage", exact = True
+ ).click()
+ label = "Search chats or projects"
+ else:
+ label = (
+ "Search archived chats or projects"
+ if shelf == "chats"
+ else f"Search archived {shelf}"
+ )
+ search = page.get_by_role("searchbox", name = label, exact = True)
+ search.wait_for()
+ page.evaluate("window.dispatchEvent(new Event('unsloth-chat-projects-updated'))")
+ return search
+
+ def sort(label):
+ page.get_by_role("button", name = "Filter and sort", exact = True).click()
+ page.get_by_role("menuitemradio", name = label, exact = True).click()
+
+ def mutation_requests():
+ return page.evaluate(
+ "window.__dataFixture.requests.filter(r => ['PATCH', 'DELETE'].includes(r.method))"
+ )
+
+ for shelf in ["manage", "chats"]:
+ search = seed(shelf)
+ search.fill(" RESEARCH cafe ")
+ expect(page.get_by_role("button", name = "Café needle", exact = True)).to_be_visible()
+ expect(page.get_by_role("button", name = "Zulu sample", exact = True)).to_have_count(0)
+ checks.append(f"{shelf}-search-title-and-project-across-pages-unicode")
+ search.fill("missing query")
+ expect(
+ page.get_by_text(
+ "No chats match your search."
+ if shelf == "manage"
+ else "No archived chats match your search.",
+ exact = True,
+ )
+ ).to_be_visible()
+ search.fill("")
+ page.get_by_role("button", name = "Filter by project", exact = True).click()
+ page.get_by_role("combobox", name = "Search projects", exact = True).fill("Research")
+ page.get_by_role("option", name = "Research notes", exact = True).click()
+ expect(page.get_by_role("heading", name = "Other project", exact = True)).to_have_count(0)
+ checks.append(f"{shelf}-searchable-project-filter")
+ sort("Compare chats")
+ expect(page.get_by_role("button", name = "Compare models", exact = True)).to_have_count(1)
+ expect(page.get_by_role("button", name = "Café needle", exact = True)).to_have_count(0)
+ sort("Single chats")
+ expect(page.get_by_role("button", name = "Compare models", exact = True)).to_have_count(0)
+ checks.append(f"{shelf}-type-filter-paired-chats")
+ sort("Alphabetical")
+ expect(page.locator("section").last.locator("button[title]").first).to_have_text(
+ "Café needle"
+ )
+ sort("Created")
+ expect(page.get_by_role("button", name = "Chat 30", exact = True)).to_be_visible()
+ sort("Updated")
+ expect(page.get_by_role("button", name = "Zulu sample", exact = True)).to_be_visible()
+ checks.append(f"{shelf}-sort-created-updated-alphabetical")
+ assert page.get_by_text("Date created", exact = True).count() == 0
+ title = page.get_by_role("button", name = "Zulu sample", exact = True)
+ subtitle = title.locator("..").locator("p")
+ assert subtitle.inner_text()
+ assert subtitle.bounding_box()["y"] > title.bounding_box()["y"]
+ checks.append(f"{shelf}-date-beneath-title")
+
+ search = seed("chats")
+ search.fill("Old experiments")
+ expect(page.get_by_role("button", name = "Chat 31", exact = True)).to_be_visible()
+ checks.append("archive-search-includes-archived-project-names")
+
+ search = seed("manage")
+ page.get_by_role("checkbox", name = "Select all visible chats", exact = True).click()
+ expect(page.get_by_text("Selected chats: 20", exact = True)).to_be_visible()
+ search.fill("needle")
+ expect(
+ page.get_by_role("checkbox", name = 'Select "Café needle"', exact = True)
+ ).not_to_be_checked()
+ expect(page.get_by_role("button", name = "Archive", exact = True)).to_have_count(0)
+ assert not mutation_requests()
+ checks.append("manage-filter-clears-hidden-selection")
+ page.get_by_role("checkbox", name = 'Select "Café needle"', exact = True).click()
+ page.get_by_role("button", name = "Archive", exact = True).click()
+ page.wait_for_function(
+ "window.__dataFixture.rows.find(r => r.title === 'Café needle').archived === true"
+ )
+ assert len(mutation_requests()) == 1
+ checks.append("manage-filtered-archive-scope")
+
+ search = seed("chats", holdMutation = True)
+ search.fill("Compare models")
+ page.get_by_role("button", name = "Delete results", exact = True).click()
+ dialog = page.get_by_role("alertdialog")
+ expect(dialog.get_by_role("heading")).to_have_text("Delete chat")
+ toggle = dialog.get_by_role("switch")
+ if toggle.get_attribute("aria-checked") != "true":
+ toggle.click()
+ dialog.get_by_role("button", name = "Delete", exact = True).click()
+ page.wait_for_function("typeof window.__dataFixture.releaseMutation === 'function'")
+ expect(toggle).to_be_disabled()
+ expect(dialog.get_by_role("button", name = "Cancel", exact = True)).to_be_disabled()
+ page.keyboard.press("Escape")
+ expect(dialog).to_be_visible()
+ page.evaluate("window.__dataFixture.releaseMutation()")
+ expect(dialog).to_have_count(0)
+ requests = mutation_requests()
+ assert len(requests) == 1 and len(requests[0]["body"]["ids"]) == 2
+ assert requests[0]["body"]["delete_files"] is True
+ assert page.evaluate("window.__dataFixture.rows.length") == 30
+ checks.append("archive-filtered-delete-pair-sandbox-choice-pending-lock")
+
+ for kind in ["images", "videos", "audio"]:
+ search = seed(kind)
+ search.fill("CAFE needle")
+ row = page.locator("[data-archived-id]")
+ expect(row).to_have_count(1)
+ expect(row).to_contain_text("Café needle")
+ expect(page.get_by_text("Searching remaining items", exact = False)).to_have_count(0)
+ assert (
+ page.evaluate(
+ "window.__dataFixture.requests.filter(r => r.path.endsWith('/gallery') && r.query.includes('archived=true')).length"
+ )
+ >= 3
+ )
+ assert page.get_by_text("Date created", exact = True).count() == 0
+ checks.append(f"{kind}-search-full-archive-and-compact-row")
+ search.fill("missing query")
+ expect(page.get_by_text("No archived items match your search.", exact = True)).to_be_visible()
+ search.fill("")
+ sort("Alphabetical")
+ expect(row.first).to_contain_text("Café needle")
+ sort("Oldest first")
+ expect(row.first).to_contain_text("Sample 446")
+ checks.append(f"{kind}-empty-query-reset-and-sorts")
+ search.fill("needle")
+ page.get_by_role("button", name = "Delete results", exact = True).click()
+ dialog = page.get_by_role("alertdialog")
+ expect(dialog.get_by_role("heading")).to_have_text("Delete archived items (1)")
+ dialog.get_by_role("button", name = "Cancel", exact = True).click()
+ assert not mutation_requests()
+ page.get_by_role("button", name = "Delete results", exact = True).click()
+ dialog.get_by_role("button", name = "Delete", exact = True).click()
+ expect(dialog).to_have_count(0)
+ expect(row).to_have_count(0)
+ assert len(mutation_requests()) == 1
+ assert page.evaluate("kind => window.__dataFixture.media[kind].length", kind) == 446
+ checks.append(f"{kind}-filtered-delete-confirm-cancel-scope")
+
+ search = seed(kind, failPage = True)
+ search.fill("needle")
+ expect(
+ page.get_by_text("Search is incomplete. Retry loading the remaining items.", exact = True)
+ ).to_be_visible()
+ assert page.get_by_text("No archived items match your search.", exact = True).count() == 0
+ page.evaluate("window.__dataFixture.failPage = false")
+ page.get_by_role("button", name = "Retry", exact = True).click()
+ expect(
+ page.get_by_role("button", name = "Unarchive: Café needle", exact = True)
+ ).to_be_visible()
+ checks.append(f"{kind}-failed-page-retry-retains-search")
+ page.evaluate("window.__dataFixture.holdMutation = true")
+ page.get_by_role("button", name = "Unarchive: Café needle", exact = True).click()
+ page.wait_for_function("typeof window.__dataFixture.releaseMutation === 'function'")
+ expect(
+ page.get_by_role("button", name = "Unarchive: Café needle", exact = True)
+ ).to_be_disabled()
+ page.evaluate("window.__dataFixture.releaseMutation()")
+ expect(page.locator("[data-archived-id]").filter(has_text = "Café needle")).to_have_count(0)
+ assert len(mutation_requests()) == 1
+ checks.append(f"{kind}-restore-pending-lock")
+
+ search = seed(kind, failMutation = True)
+ search.fill("needle")
+ page.get_by_role("button", name = "Delete: Café needle", exact = True).click()
+ dialog = page.get_by_role("alertdialog")
+ dialog.get_by_role("button", name = "Delete", exact = True).click()
+ expect(dialog).to_have_count(0)
+ expect(page.get_by_role("button", name = "Delete: Café needle", exact = True)).to_be_enabled()
+ assert page.evaluate("kind => window.__dataFixture.media[kind].length", kind) == 447
+ checks.append(f"{kind}-failed-delete-retains-row")
+
+ search = seed(kind, stallPage = True)
+ search.fill("needle")
+ expect(page.get_by_role("button", name = "Retry", exact = True)).to_be_visible()
+ count = page.evaluate("window.__dataFixture.requests.length")
+ page.wait_for_timeout(800)
+ assert page.evaluate("window.__dataFixture.requests.length") == count
+ checks.append(f"{kind}-stalled-page-stops-retrying")
+
+ for kind in ["images", "videos", "audio"]:
+ search = seed(kind, holdPage = True)
+ page.get_by_role("button", name = "Show more", exact = True).click()
+ page.wait_for_function("typeof window.__dataFixture.releasePage === 'function'")
+ page.get_by_role("button", name = "Unarchive: Sample 00", exact = True).click()
+ expect(page.locator("[data-archived-id]").filter(has_text = "Sample 00")).to_have_count(0)
+ page.evaluate("window.__dataFixture.holdPage = false; window.__dataFixture.releasePage()")
+ search.fill("Sample 20")
+ expect(page.locator(f'[data-archived-id="{kind}-20"]')).to_contain_text("Sample 20")
+ expect(page.get_by_text("Searching remaining items", exact = False)).to_have_count(0)
+ checks.append(f"{kind}-restore-during-pagination-keeps-boundary-item")
+
+ seed(kind, mediaCount = 23)
+ page.get_by_role("button", name = "Delete all", exact = True).click()
+ dialog = page.get_by_role("alertdialog")
+ expect(dialog.get_by_role("heading")).to_have_text("Delete archived items (23)")
+ assert not mutation_requests()
+ dialog.get_by_role("button", name = "Cancel", exact = True).click()
+ assert page.evaluate("kind => window.__dataFixture.media[kind].length", kind) == 23
+ checks.append(f"{kind}-bulk-confirmation-loads-all-pages-before-delete")
+
+ for kind in ["images", "videos", "audio"]:
+ seed(kind, reorderDates = True)
+ expect(page.locator("[data-archived-id]")).to_have_count(20)
+ sort("Created")
+ expect(page.locator("[data-archived-id]").first).to_contain_text("Sample 300")
+ expect(page.get_by_text("Searching remaining items", exact = False)).to_have_count(0)
+ expect(page.locator("[data-archived-id]")).to_have_count(20)
+ thumbnails = page.evaluate(
+ "window.__dataFixture.requests.filter(r => r.path.includes('/content')).length"
+ )
+ assert thumbnails < 60, thumbnails
+ checks.append(f"{kind}-global-date-sort-with-bounded-rows-and-thumbnails")
+
+ for width, theme in itertools.product([360, 768, 1280], ["light", "dark"]):
+ page.set_viewport_size({"width": width, "height": 1000})
+ page.evaluate(
+ "theme => document.documentElement.classList.toggle('dark', theme === 'dark')", theme
+ )
+ search = seed("chats")
+ search.fill("needle")
+ row = page.get_by_role("button", name = "Café needle", exact = True)
+ expect(row).to_be_visible()
+ assert row.bounding_box()["width"] > 10
+ assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
+ expect(
+ page.get_by_role("button", name = "Unarchive: Café needle", exact = True)
+ ).to_be_visible()
+ search.focus()
+ # macOS WebKit uses Option-Tab to include buttons in keyboard navigation.
+ key = (
+ "Alt+Tab"
+ if sys.platform == "darwin" and os.environ.get("PW_ENGINE") == "webkit"
+ else "Tab"
+ )
+ page.keyboard.press(key)
+ expect(page.get_by_role("button", name = "Filter and sort", exact = True)).to_be_focused()
+ page.keyboard.press("Enter")
+ expect(page.get_by_role("menuitemradio", name = "Updated", exact = True)).to_be_visible()
+ page.keyboard.press("Escape")
+ checks.append(f"archive-layout-keyboard-{width}-{theme}")
+ page.set_viewport_size({"width": 1280, "height": 1000})
+ return checks
+
+
+def run_library_locales(page):
+ checks = []
+ page.set_viewport_size({"width": 1280, "height": 1000})
+ page.evaluate("document.documentElement.classList.remove('dark')")
+ locales = ["en", "es", "fr", "de", "it", "pt-BR", "ru", "zh-CN", "ja", "ko", "hi", "ar"]
+ for locale in locales:
+ text = page.evaluate(
+ """async locale => {
+ const api = await import('/src/i18n/index.ts');
+ await api.setLocale(locale);
+ return {
+ ...api.messages[locale].settings.data.library,
+ manage: api.translate('settings.data.manageChats'),
+ manageAction: api.translate('settings.data.manageAction'),
+ cancel: api.translate('common.cancel'),
+ delete: api.translate('common.delete'),
+ deleteAll: api.translate('settings.data.deleteAllAction'),
+ data: api.translate('settings.data.title'),
+ back: api.translate('settings.data.backToData'),
+ archived: api.translate('settings.data.archivedChats'),
+ };
+ }""",
+ locale,
+ )
+ if locale == "es":
+ assert text["noProject"] == "Sin proyecto"
+ for shelf in ["manage", "chats", "images", "videos", "audio"]:
+ page.evaluate("window.__settingsSmoke.close()")
+ expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
+ page.evaluate(
+ """shelf => {
+ const f = window.__dataFixture;
+ Object.assign(f, {failMutation: false, holdMutation: false, failPage: false,
+ stallPage: false, holdPage: false, listFail: false, requests: []});
+ f.rows = [null, 'gone', 'research'].map((projectId, index) => ({
+ id: `locale-${index}`, title: `Sample ${index}`, modelType: 'base', modelId: 'test',
+ projectId, createdAt: 1700000000000, updatedAt: 1700000000000,
+ archived: shelf === 'chats',
+ }));
+ f.media = Object.fromEntries(['images', 'videos', 'audio'].map(kind => [kind, [{
+ id: 'locale-media', prompt: 'Sample media', url: '/unused',
+ created_at: kind === 'images' ? 1700000000 : '2023-11-14T22:13:20Z',
+ }]]));
+ if (shelf === 'manage') window.__settingsSmoke.open('data');
+ else window.__settingsSmoke.openArchived(shelf);
+ }""",
+ shelf,
+ )
+ if shelf == "manage":
+ page.locator(f'[data-settings-label="{text["manage"]}"]').get_by_role(
+ "button", name = text["manageAction"], exact = True
+ ).click()
+ placeholder = text[
+ {
+ "manage": "searchChats",
+ "chats": "searchArchivedChats",
+ "images": "searchImages",
+ "videos": "searchVideos",
+ "audio": "searchAudio",
+ }[shelf]
+ ]
+ search = page.get_by_role("searchbox", name = placeholder, exact = True)
+ expect(search).to_be_visible()
+ toolbar = page.get_by_role("button", name = text["filterSort"], exact = True)
+ toolbar.click()
+ expect(
+ page.get_by_role("menuitemradio", name = text["alphabetical"], exact = True)
+ ).to_be_visible()
+ if shelf in ["manage", "chats"]:
+ expect(
+ page.get_by_role("menuitemradio", name = text["singleChats"], exact = True)
+ ).to_be_visible()
+ page.keyboard.press("Escape")
+ if shelf in ["manage", "chats"]:
+ expect(page.get_by_role("button", name = "Sample 0", exact = True)).to_be_visible()
+ search.fill(text["noProject"])
+ expect(page.get_by_role("button", name = "Sample 0", exact = True)).to_be_visible()
+ expect(page.get_by_role("button", name = "Sample 1", exact = True)).to_have_count(0)
+ search.fill(text["unavailableProject"])
+ expect(page.get_by_role("button", name = "Sample 1", exact = True)).to_be_visible()
+ search.fill("")
+ page.get_by_role("button", name = text["filterProject"], exact = True).click()
+ page.get_by_role("combobox", name = text["searchProjects"], exact = True).fill(
+ text["noProject"]
+ )
+ page.get_by_role("option", name = text["noProject"], exact = True).click()
+ expect(
+ page.get_by_role("heading", name = text["noProject"], exact = True)
+ ).to_be_visible()
+ expect(page.get_by_role("button", name = "Sample 1", exact = True)).to_have_count(0)
+ if shelf == "manage":
+ page.get_by_role("checkbox", name = text["selectAll"], exact = True).click()
+ expect(
+ page.get_by_role("button", name = text["archive"], exact = True)
+ ).to_be_visible()
+ page.get_by_role("button", name = text["delete"], exact = True).click()
+ expect(page.get_by_role("alertdialog")).to_contain_text(
+ text["deleteChatsWarning"].replace("{count}", "1")
+ )
+ else:
+ page.get_by_role("button", name = text["deleteResults"], exact = True).click()
+ expect(page.get_by_role("alertdialog")).to_contain_text(
+ text["deleteArchivedWarning"].replace("{count}", "1")
+ )
+ else:
+ row = page.locator("[data-archived-id]")
+ expect(row).to_contain_text("Sample media")
+ expected_date = page.evaluate(
+ "locale => new Date(1700000000000).toLocaleString(locale, {year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit'})",
+ locale,
+ )
+ expect(row).to_contain_text(expected_date)
+ expect(
+ page.get_by_role(
+ "button",
+ name = text["unarchiveItem"].replace("{title}", "Sample media"),
+ exact = True,
+ )
+ ).to_be_visible()
+ page.get_by_role("button", name = text["deleteAll"], exact = True).click()
+ expect(page.get_by_role("alertdialog").get_by_role("heading")).to_have_text(
+ text["deleteItemsTitle"].replace("{count}", "1")
+ )
+ expect(page.get_by_role("alertdialog")).to_contain_text(text["deleteFilesWarning"])
+ page.get_by_role("alertdialog").get_by_role(
+ "button", name = text["cancel"], exact = True
+ ).click()
+ assert not page.evaluate(
+ "window.__dataFixture.requests.some(r => r.method === 'DELETE' || r.method === 'PATCH')"
+ )
+ search.fill("NoMatchingTitle")
+ empty_key = (
+ "noChats"
+ if shelf == "manage"
+ else "noArchivedMatches"
+ if shelf == "chats"
+ else "noMediaMatches"
+ )
+ expect(page.get_by_text(text[empty_key], exact = True)).to_be_visible()
+ if locale == "es" and shelf == "chats":
+ page.locator("aside input").fill(text["archived"])
+ page.locator("aside").get_by_role(
+ "button", name = text["archived"], exact = True
+ ).click()
+ expect(page.locator(".settings-search-hit")).to_have_attribute(
+ "data-settings-label", text["archived"]
+ )
+ expect(page.get_by_role("button", name = text["back"], exact = True)).to_have_count(0)
+ checks.append("localized-settings-search-exits-archive")
+ checks.append(f"library-locale-{locale}-{shelf}")
+ # Change locale with the archive and its query still mounted.
+ page.evaluate("async () => {await (await import('/src/i18n/index.ts')).setLocale('es');}")
+ search = page.get_by_role("searchbox", name = "Buscar audio archivado", exact = True)
+ expect(search).to_have_value("NoMatchingTitle")
+ expect(page.get_by_role("button", name = "Filtrar y ordenar", exact = True)).to_be_visible()
+ checks.append("library-locale-live-switch-retains-query")
+ page.evaluate("async () => {await (await import('/src/i18n/index.ts')).setLocale('en');}")
+ return checks
+
+
+def run_library_selection(page):
+ page.evaluate("window.__settingsSmoke.close()")
+ expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
+ page.evaluate("""() => {
+ const f = window.__dataFixture;
+ Object.assign(f, {requests: [], failMutation: false, holdMutation: false, listFail: false});
+ f.rows = Array.from({length: 32}, (_, i) => ({
+ id: `selection-${i}`, title: `Chat ${i}`, modelType: 'base', modelId: 'test',
+ createdAt: 1700000000000, updatedAt: 1700000000000 + (32-i)*1000,
+ }));
+ window.__settingsSmoke.open('data');
+ }""")
+ page.locator('[data-settings-label="Manage chats"]').get_by_role(
+ "button", name = "Manage", exact = True
+ ).click()
+ target = page.get_by_role("checkbox", name = 'Select "Chat 19"', exact = True)
+ target.click()
+ expect(page.get_by_text("Selected chats: 1", exact = True)).to_be_visible()
+ page.evaluate("""() => {
+ window.__dataFixture.rows[20].updatedAt = 1900000000000;
+ window.dispatchEvent(new Event('unsloth-chat-history-updated'));
+ }""")
+ expect(target).to_have_count(0)
+ expect(page.get_by_role("button", name = "Chat 20", exact = True)).to_be_visible()
+ expect(page.get_by_text("Selected chats: 1", exact = True)).to_be_visible()
+ checks = ["selected-chat-survives-live-page-reorder"]
+ select_all = page.get_by_role("checkbox", name = "Select all visible chats", exact = True)
+ expect(select_all).not_to_be_checked()
+ select_all.click()
+ expect(page.get_by_text("Selected chats: 21", exact = True)).to_be_visible()
+ select_all.click()
+ expect(page.get_by_text("Selected chats: 1", exact = True)).to_be_visible()
+ checks.append("select-visible-preserves-hidden-selection")
+ page.get_by_role("button", name = "Show more (12)", exact = True).click()
+ expect(target).to_be_checked()
+ checks.append("revealed-chat-keeps-its-selection")
+ page.evaluate("""() => {
+ const f = window.__dataFixture;
+ f.rows.push(...Array.from({length: 40}, (_, i) => ({
+ id: `incoming-${i}`, title: `Incoming ${i}`, modelType: 'base', modelId: 'test',
+ createdAt: 1700000000000, updatedAt: 1900000000000 + i + 1,
+ })));
+ window.dispatchEvent(new Event('unsloth-chat-history-updated'));
+ }""")
+ expect(target).to_have_count(0)
+ expect(page.get_by_text("Selected chats: 1", exact = True)).to_be_visible()
+ page.get_by_role("button", name = "Delete", exact = True).click()
+ expect(page.get_by_role("alertdialog").get_by_role("heading")).to_have_text("Delete chats (1)")
+ page.get_by_role("alertdialog").get_by_role("button", name = "Cancel", exact = True).click()
+ page.get_by_role("button", name = "Archive", exact = True).click()
+ page.wait_for_function(
+ "window.__dataFixture.rows.find(r => r.id === 'selection-19').archived === true"
+ )
+ assert page.evaluate(
+ "window.__dataFixture.requests.filter(r => r.method === 'PATCH').map(r => r.path)"
+ ) == ["/api/chat/threads/selection-19"]
+ checks.append("bulk-action-retains-original-selected-id")
+ # Explicit filter changes still clear selections.
+ page.get_by_role("checkbox", name = 'Select "Incoming 18"', exact = True).click()
+ page.get_by_role("searchbox", name = "Search chats or projects", exact = True).fill("Incoming 18")
+ expect(
+ page.get_by_role("checkbox", name = 'Select "Incoming 18"', exact = True)
+ ).not_to_be_checked()
+ expect(page.get_by_role("button", name = "Archive", exact = True)).to_have_count(0)
+ checks.append("explicit-filter-change-clears-selection")
+ return checks
+
+
+def run_library_collation(page):
+ checks = []
+ titles = ["阿", "八", "中", "张", "曾", "Zebra", "苹果", "橙子", "東京", "大阪"]
+ for shelf in ["manage", "chats", "images", "videos", "audio"]:
+ page.evaluate("window.__settingsSmoke.close()")
+ expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
+ page.evaluate(
+ """async ({shelf, titles}) => {
+ await (await import('/src/i18n/index.ts')).setLocale('en');
+ const f = window.__dataFixture;
+ Object.assign(f, {requests: [], failMutation: false, holdMutation: false, listFail: false, failPage: false, stallPage: false});
+ f.rows = titles.map((title, i) => ({id: `collation-${i}`, title, modelType: 'base', modelId: 'test',
+ createdAt: 1700000000000, updatedAt: 1700000000000, archived: shelf === 'chats'}));
+ f.projects = titles.map((name, i) => ({id: `project-${i}`, name, createdAt: 1, updatedAt: 1}));
+ f.media = Object.fromEntries(['images', 'videos', 'audio'].map(kind => [kind, titles.map((prompt, i) => ({
+ id: `${kind}-${i}`, prompt, url: '/unused',
+ created_at: kind === 'images' ? 1700000000 : '2023-11-14T22:13:20Z',
+ }))]));
+ if(shelf === 'manage') window.__settingsSmoke.open('data');
+ else window.__settingsSmoke.openArchived(shelf);
+ }""",
+ {"shelf": shelf, "titles": titles},
+ )
+ if shelf == "manage":
+ page.locator('[data-settings-label="Manage chats"]').get_by_role(
+ "button", name = "Manage", exact = True
+ ).click()
+ page.get_by_role("button", name = "Filter and sort", exact = True).click()
+ page.get_by_role("menuitemradio", name = "Alphabetical", exact = True).click()
+ for locale in ["en", "zh-CN", "ja"]:
+ info = page.evaluate(
+ """async ({locale, titles}) => {
+ const api = await import('/src/i18n/index.ts');
+ await api.setLocale(locale);
+ return {expected: [...titles].sort(new Intl.Collator(locale).compare),
+ projectFilter: api.translate('settings.data.library.filterProject')};
+ }""",
+ {"locale": locale, "titles": titles},
+ )
+ if shelf in ["manage", "chats"]:
+ rows = page.locator("main section .divide-y button[title]:not([aria-label])")
+ else:
+ rows = page.locator("[data-archived-id] p[title]")
+ expect(rows).to_have_text(info["expected"])
+ checks.append(f"{shelf}-alphabetical-{locale}")
+ if shelf in ["manage", "chats"]:
+ page.get_by_role("button", name = info["projectFilter"], exact = True).click()
+ assert page.get_by_role("option").all_text_contents()[2:] == info["expected"]
+ page.keyboard.press("Escape")
+ checks.append(f"{shelf}-projects-{locale}")
+ page.evaluate("async () => {await (await import('/src/i18n/index.ts')).setLocale('en');}")
+ return checks
+
+
+def run_restore_notifications(page):
+ checks = []
+ page.evaluate("""() => {
+ window.addEventListener('unsloth:gallery-changed', event => {
+ window.__dataFixture.notifications.push(event.detail.kind);
+ });
+ }""")
+ for kind in ["images", "videos", "audio"]:
+ for count, action, failure_index in [
+ (23, "restore", None),
+ (23, "restore", 2),
+ (23, "restore", 0),
+ (1, "restore", None),
+ (3, "delete", None),
+ ]:
+ page.evaluate("window.__settingsSmoke.close()")
+ expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
+ page.evaluate(
+ """({kind, count, failureIndex}) => {
+ const f = window.__dataFixture;
+ Object.assign(f, {requests: [], notifications: [], failMutation: false,
+ holdMutation: false, failPage: false, stallPage: false,
+ failMutationId: failureIndex === null ? null : `${kind}-${failureIndex}`});
+ f.media[kind] = Array.from({length: count}, (_, i) => ({
+ id: `${kind}-${i}`, prompt: `Restore ${i}`, url: '/unused',
+ created_at: kind === 'images' ? 1700000000 : '2023-11-14T22:13:20Z',
+ }));
+ window.__settingsSmoke.openArchived(kind);
+ }""",
+ {"kind": kind, "count": count, "failureIndex": failure_index},
+ )
+ trigger = "Unarchive all" if action == "restore" else "Delete all"
+ page.get_by_role("button", name = trigger, exact = True).click()
+ dialog = page.get_by_role("alertdialog")
+ heading = "Unarchive items" if action == "restore" else "Delete archived items"
+ expect(dialog.get_by_role("heading")).to_have_text(f"{heading} ({count})")
+ confirm = "Unarchive" if action == "restore" else "Delete"
+ dialog.get_by_role("button", name = confirm, exact = True).click()
+ expect(dialog).to_have_count(0)
+ completed = count if failure_index is None else failure_index
+ expected_events = [kind] if completed and action == "restore" else []
+ observed = page.evaluate("window.__dataFixture.notifications")
+ assert observed == expected_events, {
+ "kind": kind,
+ "completed": completed,
+ "events": observed,
+ }
+ assert (
+ page.evaluate("kind => window.__dataFixture.media[kind].length", kind)
+ == count - completed
+ )
+ mutations = page.evaluate(
+ "window.__dataFixture.requests.filter(r => ['PATCH', 'DELETE'].includes(r.method)).length"
+ )
+ assert mutations == completed + (failure_index is not None)
+ checks.append(f"{kind}-{action}-{count}-notification-failure-{failure_index}")
+ return checks
+
+
+def run_thumbnail_retention(page):
+ checks = []
+ for kind in ["images", "videos"]:
+ page.evaluate("window.__settingsSmoke.close()")
+ expect(page.get_by_role("dialog", include_hidden = True)).to_have_count(0)
+ page.evaluate(
+ """kind => {
+ const f = window.__dataFixture;
+ Object.assign(f, {requests: [], thumbnailRequests: 0, failPage: false, stallPage: false});
+ const originalFetch = window.fetch;
+ f.restoreFetch = () => { window.fetch = originalFetch; };
+ window.fetch = async (input, init) => {
+ const url = new URL(typeof input === 'string' ? input : input.url, location.origin);
+ if (url.pathname.endsWith('/content')) {
+ f.thumbnailRequests += 1;
+ const png = Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAIAAAADnC86AAAAMklEQVR4nO3NAQ0AMAgAoPtMhrOGjY3h5qAAkV1vw19ZxWKxWCwWi8VisVgsFovFR+MBbzgBjTOVo70AAAAASUVORK5CYII='), c => c.charCodeAt(0));
+ const bytes = new Uint8Array(6 * 1024 * 1024);
+ bytes.set(png);
+ return new Response(bytes, {headers: {'Content-Type': 'image/png'}});
+ }
+ return originalFetch(input, init);
+ };
+ f.media[kind] = Array.from({length: 6}, (_, i) => ({
+ id: `thumbnail-${i}`, prompt: `Sample ${5-i}`,
+ url: `/api/inference/images/gallery/thumbnail-${i}/content`,
+ created_at: kind === 'images' ? 1700000000 : '2023-11-14T22:13:20Z',
+ }));
+ window.__settingsSmoke.openArchived(kind);
+ }""",
+ kind,
+ )
+ try:
+ page.wait_for_function("""() => {
+ const images = [...document.querySelectorAll('[data-archived-id] img')];
+ return images.length === 6 && images.every(img => img.complete && img.naturalWidth > 0);
+ }""")
+ assert page.evaluate("window.__dataFixture.thumbnailRequests") == 6, page.evaluate(
+ "window.__dataFixture.thumbnailRequests"
+ )
+ page.get_by_role("button", name = "Filter and sort", exact = True).click()
+ page.get_by_role("menuitemradio", name = "Alphabetical", exact = True).click()
+ expect(page.locator("[data-archived-id] p[title]").first).to_have_text("Sample 0")
+ page.wait_for_timeout(200)
+ assert page.evaluate("window.__dataFixture.thumbnailRequests") == 6, page.evaluate(
+ "window.__dataFixture.thumbnailRequests"
+ )
+ checks.append(f"{kind}-sort-retains-visible-thumbnails-over-budget")
+ page.get_by_role("searchbox").fill("Sample")
+ expect(page.locator("[data-archived-id]")).to_have_count(6)
+ page.wait_for_timeout(200)
+ assert page.evaluate("window.__dataFixture.thumbnailRequests") == 6, page.evaluate(
+ "window.__dataFixture.thumbnailRequests"
+ )
+ checks.append(f"{kind}-search-retains-visible-thumbnails-over-budget")
+ finally:
+ page.evaluate("window.__dataFixture.restoreFetch()")
+ return checks
+
+
+def main():
+ engine = os.environ.get("PW_ENGINE", "chromium")
+ port = int(os.environ.get("PW_PORT", "5412"))
+ output = Path(os.environ.get("PW_OUT", "logs/data_settings_report.json"))
+ server = start_vite(port)
+ try:
+ url = f"http://127.0.0.1:{port}/smoke-settings.html"
+ wait_for_smoke_page(url, "smoke-settings-main.tsx", proc = server, timeout_s = 60)
+ with sync_playwright() as p:
+ options = {"headless": True}
+ if os.environ.get("PW_EXECUTABLE"):
+ options["executable_path"] = os.environ["PW_EXECUTABLE"]
+ if os.environ.get("PW_CHANNEL"):
+ options["channel"] = os.environ["PW_CHANNEL"]
+ browser = getattr(p, engine).launch(**options)
+ page = browser.new_page(viewport = {"width": 1280, "height": 1000})
+ page.add_init_script(FIXTURE)
+ page.goto(url, wait_until = "domcontentloaded")
+ page.wait_for_function("!!window.__settingsSmoke", timeout = 120000)
+ output.parent.mkdir(parents = True, exist_ok = True)
+ result = {"engine": engine, "version": browser.version}
+ try:
+ result.update(run(page))
+ except Exception as error:
+ result["error"] = str(error)
+ page.screenshot(path = str(output.with_suffix(".png")))
+ raise
+ finally:
+ output.write_text(json.dumps(result, indent = 2), encoding = "utf-8")
+ print(f"{engine}: {len(result['checks'])} Data settings checks passed", flush = True)
+ browser.close()
+ finally:
+ stop_process(server)
+
+
+if __name__ == "__main__":
+ main()