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: keep project chats in Recents, add a Projects sidebar section (#8932)

Michael Han2643d0ef6f71
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 51af8ea6642..3c8e730d31c 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -1947,7 +1947,7 @@ SIDEBAR_NAV_ITEM_DEFAULTS = {
"hub": True,
"projects": True,
"images": True,
- "video": False,
+ "video": True,
"audio": False,
"train": True,
"recipes": False,
diff --git a/studio/backend/tests/test_personalization_settings.py b/studio/backend/tests/test_personalization_settings.py
index e145a653ea4..aacaa5425cb 100644
--- a/studio/backend/tests/test_personalization_settings.py
+++ b/studio/backend/tests/test_personalization_settings.py
@@ -157,7 +157,7 @@ FRONTEND_SHIPPED_SIDEBAR_NAV = [
("hub", True),
("projects", True),
("images", True),
- ("video", False),
+ ("video", True),
("audio", False),
("train", True),
("recipes", False),
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index e83eb82d086..2d699e58ac3 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -19,11 +19,22 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuLabel,
+ ContextMenuSeparator,
+ ContextMenuTrigger,
+} from "@/components/ui/context-menu";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
@@ -63,7 +74,9 @@ import { isTauri } from "@/lib/api-base";
import { useWebUpdateCheck } from "@/hooks/use-web-update-check";
import {
Archive03Icon,
+ ArrowDown01Icon,
ArrowRight02Icon,
+ ArrowUp01Icon,
BadgeInfoIcon,
BookOpen01Icon,
BubbleChatIcon,
@@ -136,8 +149,22 @@ import {
useChatSidebarItems,
usePinnedChatsStore,
usePinnedProjectsStore,
+ rangeBetween,
+ toggleSelected,
useChatPreferencesStore,
usePromptQueueUI,
+ useSidebarOrganizationStore,
+ applyManualOrder,
+ dropEdgeFor,
+ showsInRecents,
+ moveIdBy,
+ projectOrderScope,
+ reorderIds,
+ PINNED_ORDER_SCOPE,
+ PROJECT_ORDER_SCOPE,
+ RECENTS_ORDER_SCOPE,
+ type SidebarChatSort,
+ type SidebarOrganizeBy,
CONVERSATION_MARKDOWN_FORMAT,
CONVERSATION_MARKDOWN_LABEL,
type ProjectRecord,
@@ -256,8 +283,45 @@ type ConversationExportFormat =
| "sharegpt-jsonl"
| typeof CONVERSATION_MARKDOWN_FORMAT;
-// A pinned project shows this many recent chats before "Show more".
-const PINNED_PROJECT_CHAT_LIMIT = 4;
+// An expanded project shows this many recent chats before "Show more".
+const PROJECT_CHAT_LIMIT = 4;
+// And the Projects section shows this many folders before its own "Show more".
+const SIDEBAR_PROJECT_LIMIT = 5;
+
+// The shared radio item ticks on the right; these read as settings, so tick first.
+const menuRadioItemClass =
+ "pl-9 pr-3 [&>[data-slot=dropdown-menu-radio-item-indicator]]:right-auto [&>[data-slot=dropdown-menu-radio-item-indicator]]:left-3";
+
+// Whether cmd or ctrl adds a row to the selection. This is the user's own
+// keyboard, not the host Studio runs on, so it reads the browser rather than
+// the platform store: a Mac browser on a Linux host still uses cmd. Ctrl is
+// left alone on macOS, where ctrl click is the right click chord.
+const SELECT_WITH_META =
+ typeof navigator !== "undefined" &&
+ /mac/i.test(navigator.platform || navigator.userAgent);
+
+// Insertion cue on the edge the row will land on, inset to the pill.
+const DROP_CUE_BASE =
+ "before:absolute before:inset-x-2 before:h-0.5 before:rounded-full before:bg-primary/70 before:content-['']";
+const DROP_CUE_TOP = `${DROP_CUE_BASE} before:-top-px`;
+const DROP_CUE_BOTTOM = `${DROP_CUE_BASE} before:-bottom-px`;
+
+// Every list offers the same three orders.
+const CHAT_SORT_OPTIONS: Array<{
+ value: SidebarChatSort;
+ key: TranslationKey;
+}> = [
+ { value: "priority", key: "shell.organize.priority" },
+ { value: "updated", key: "shell.organize.lastUpdated" },
+ { value: "manual", key: "shell.organize.manualOrder" },
+];
+const ORGANIZE_OPTIONS: Array<{
+ value: SidebarOrganizeBy;
+ key: TranslationKey;
+}> = [
+ { value: "project", key: "shell.organize.byProject" },
+ { value: "list", key: "shell.organize.inOneList" },
+];
const CHAT_EXPORT_OPTIONS: Array<{
label: string;
@@ -878,42 +942,59 @@ export function AppSidebar() {
});
const pinnedIds = usePinnedChatsStore((s) => s.pinnedIds);
const togglePinnedChat = usePinnedChatsStore((s) => s.togglePin);
+ const setPinnedChats = usePinnedChatsStore((s) => s.setPinned);
const unpinChat = usePinnedChatsStore((s) => s.unpin);
const confirmDeleteChats = useChatPreferencesStore(
(s) => s.confirmDeleteChats,
);
+ const alwaysDeleteChatFiles = useChatPreferencesStore(
+ (s) => s.alwaysDeleteChatFiles,
+ );
const pinnedIdSet = useMemo(() => new Set(pinnedIds), [pinnedIds]);
+ const organizeBy = useSidebarOrganizationStore((s) => s.organizeBy);
+ const chatSort = useSidebarOrganizationStore((s) => s.chatSort);
+ const pinnedSort = useSidebarOrganizationStore((s) => s.pinnedSort);
+ const manualOrder = useSidebarOrganizationStore((s) => s.manualOrder);
+ const setOrganizeBy = useSidebarOrganizationStore((s) => s.setOrganizeBy);
+ const setChatSort = useSidebarOrganizationStore((s) => s.setChatSort);
+ const setPinnedSort = useSidebarOrganizationStore((s) => s.setPinnedSort);
+ const setManualOrder = useSidebarOrganizationStore((s) => s.setManualOrder);
+ // With the Projects section on, a project chat lives in its folder and
+ // repeating it here would be noise. With it off there are no folders, so
+ // Recents is where those chats go, and a new project chat still lands
+ // somewhere visible. Pinned chats are held back either way: the Pinned
+ // section renders those.
const recentChatItems = useMemo(
() =>
allChatItems.filter(
- (item) => !item.projectId && !pinnedIdSet.has(item.id),
+ (item) =>
+ !pinnedIdSet.has(item.id) && showsInRecents(item.projectId, organizeBy),
),
- [allChatItems, pinnedIdSet],
+ [allChatItems, pinnedIdSet, organizeBy],
);
const [pinnedOpen, setPinnedOpen] = useState(true);
- // Projects the user pinned, in pin order; the section appears once at least one is pinned.
+ const [projectsOpen, setProjectsOpen] = useState(true);
+ const [showAllProjects, setShowAllProjects] = useState(false);
+ // Pinning a project now sorts it to the top of Projects, not into its own section.
const pinnedProjectIds = usePinnedProjectsStore((s) => s.pinnedIds);
- const unpinProject = usePinnedProjectsStore((s) => s.unpin);
- const pinnedProjectRecords = useMemo(() => {
- const byId = new Map(projects.map((p) => [p.id, p]));
- return pinnedProjectIds
- .map((id) => byId.get(id))
- .filter((p): p is ProjectRecord => Boolean(p));
- }, [projects, pinnedProjectIds]);
- // Pinned chats, in pin order. Includes chats inside a project: pinning promotes a chat here
- // and removes it from the project's nested list, so it never shows twice.
+ const toggleProjectPin = usePinnedProjectsStore((s) => s.togglePin);
+ const pinnedProjectIdSet = useMemo(
+ () => new Set(pinnedProjectIds),
+ [pinnedProjectIds],
+ );
+ // Pinned chats, in pin order. A pinned project chat also stays in its folder.
const pinnedChatItems = useMemo(() => {
const byId = new Map(allChatItems.map((item) => [item.id, item]));
return pinnedIds
.map((id) => byId.get(id))
.filter((item): item is SidebarItem => Boolean(item));
}, [allChatItems, pinnedIds]);
- // A pinned project nests its recent chats; pinned chats are excluded (they render above).
+ // Chats per project, newest first. Pinned ones stay: a chat belongs to its
+ // project either way, and these rows are mirrored in Recents regardless.
const chatsByProjectId = useMemo(() => {
const map = new Map<string, SidebarItem[]>();
for (const item of allChatItems) {
if (!item.projectId) continue;
- if (pinnedIdSet.has(item.id)) continue;
const list = map.get(item.projectId);
if (list) list.push(item);
else map.set(item.projectId, [item]);
@@ -921,7 +1002,41 @@ export function AppSidebar() {
for (const list of map.values())
list.sort((a, b) => b.updatedAt - a.updatedAt);
return map;
- }, [allChatItems, pinnedIdSet]);
+ }, [allChatItems]);
+ // Every project gets a folder: pinned first in pin order, then by activity,
+ // then whatever the user dragged, which outranks both. Activity comes from
+ // the member chats, since a project's own updatedAt only moves when its name,
+ // instructions or archived flag are edited.
+ const sidebarProjectRecords = useMemo(() => {
+ const lastActivityAt = (project: ProjectRecord) => {
+ let latest = project.updatedAt ?? project.createdAt;
+ for (const chat of chatsByProjectId.get(project.id) ?? []) {
+ if (chat.updatedAt > latest) latest = chat.updatedAt;
+ }
+ return latest;
+ };
+ const byId = new Map(projects.map((p) => [p.id, p]));
+ const pinned = pinnedProjectIds
+ .map((id) => byId.get(id))
+ .filter((p): p is ProjectRecord => Boolean(p));
+ const rest = projects
+ .filter((p) => !pinnedProjectIdSet.has(p.id))
+ .sort((a, b) => lastActivityAt(b) - lastActivityAt(a));
+ return applyManualOrder(
+ [...pinned, ...rest],
+ manualOrder[PROJECT_ORDER_SCOPE],
+ (project) => project.id,
+ );
+ }, [
+ projects,
+ pinnedProjectIds,
+ pinnedProjectIdSet,
+ manualOrder,
+ chatsByProjectId,
+ ]);
+ const visibleProjectRecords = showAllProjects
+ ? sidebarProjectRecords
+ : sidebarProjectRecords.slice(0, SIDEBAR_PROJECT_LIMIT);
// Default expanded; the row toggles this. Show-more reveals chats past the limit.
const [collapsedProjectIds, setCollapsedProjectIds] = useState<Set<string>>(
() => new Set(),
@@ -1003,6 +1118,419 @@ export function AppSidebar() {
}, [activeThreadId, allChatItems]);
const activeVisibleThreadIdKey = activeVisibleThreadIds.join("\n");
+ // "Priority" lifts rows wanting attention (generating, queued, unread), then
+ // falls back to recency, which "Last updated" sorts by outright.
+ const chatPriorityRank = useCallback(
+ (item: SidebarItem) => {
+ const ids = getSidebarItemThreadIds(item);
+ if (ids.some((id) => runningByThreadId[id])) return 0;
+ if (ids.some((id) => queueByThreadId[id])) return 1;
+ if (ids.some((id) => unreadThreadIds.has(id))) return 2;
+ return 3;
+ },
+ [runningByThreadId, queueByThreadId, unreadThreadIds],
+ );
+ const sortChatItems = useCallback(
+ (
+ items: SidebarItem[],
+ scope: string,
+ mode: SidebarChatSort,
+ ): SidebarItem[] => {
+ if (mode === "manual") {
+ // Incoming order is the list's own rule, so undragged rows keep it:
+ // newest first in Recents, pin order in Pinned.
+ return applyManualOrder(items, manualOrder[scope], (item) => item.id);
+ }
+ if (mode === "priority") {
+ return [...items].sort(
+ (a, b) =>
+ chatPriorityRank(a) - chatPriorityRank(b) ||
+ b.updatedAt - a.updatedAt,
+ );
+ }
+ return [...items].sort((a, b) => b.updatedAt - a.updatedAt);
+ },
+ [manualOrder, chatPriorityRank],
+ );
+ const sortedRecentChatItems = useMemo(
+ () => sortChatItems(recentChatItems, RECENTS_ORDER_SCOPE, chatSort),
+ [recentChatItems, sortChatItems, chatSort],
+ );
+ const sortedPinnedChatItems = useMemo(
+ () => sortChatItems(pinnedChatItems, PINNED_ORDER_SCOPE, pinnedSort),
+ [pinnedChatItems, sortChatItems, pinnedSort],
+ );
+ const sortedChatsByProjectId = useMemo(() => {
+ const map = new Map<string, SidebarItem[]>();
+ for (const [projectId, items] of chatsByProjectId) {
+ map.set(
+ projectId,
+ sortChatItems(items, projectOrderScope(projectId), chatSort),
+ );
+ }
+ return map;
+ }, [chatsByProjectId, sortChatItems, chatSort]);
+ // One id array per list, shared by every row in it. Built per row, these
+ // would be N arrays of length N on each render.
+ const recentRowIds = useMemo(
+ () => sortedRecentChatItems.map((item) => item.id),
+ [sortedRecentChatItems],
+ );
+ const pinnedRowIds = useMemo(
+ () => sortedPinnedChatItems.map((item) => item.id),
+ [sortedPinnedChatItems],
+ );
+ // Whole lists, not the visible slices, so a drop cannot lose what a
+ // collapsed "Show more" is hiding.
+ const projectRowIds = useMemo(
+ () => sidebarProjectRecords.map((project) => project.id),
+ [sidebarProjectRecords],
+ );
+ const projectChatRowIds = useMemo(() => {
+ const map = new Map<string, string[]>();
+ for (const [projectId, items] of sortedChatsByProjectId) {
+ map.set(
+ projectId,
+ items.map((item) => item.id),
+ );
+ }
+ return map;
+ }, [sortedChatsByProjectId]);
+ // How many nested rows the Projects section renders, so the bottom fade can
+ // re-measure when regrouping or a disclosure changes the list height.
+ const projectChatRowCount = useMemo(() => {
+ if (organizeBy !== "project") return 0;
+ let rows = 0;
+ for (const project of visibleProjectRecords) {
+ if (collapsedProjectIds.has(project.id)) continue;
+ const chats = sortedChatsByProjectId.get(project.id) ?? [];
+ rows += expandedChatProjectIds.has(project.id)
+ ? chats.length
+ : Math.min(chats.length, PROJECT_CHAT_LIMIT);
+ // The "Show more" row counts too.
+ if (chats.length > PROJECT_CHAT_LIMIT) rows += 1;
+ }
+ return rows;
+ }, [
+ organizeBy,
+ visibleProjectRecords,
+ collapsedProjectIds,
+ expandedChatProjectIds,
+ sortedChatsByProjectId,
+ ]);
+
+ // Multi-select. Ids only: a row that gets deleted elsewhere drops out of
+ // selectedChatItems on its own rather than leaving a ghost to act on.
+ const [selectedChatIds, setSelectedChatIds] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ // Which list the anchor belongs to, since one chat can sit in two lists.
+ const selectionAnchorRef = useRef<{ scope: string; id: string } | null>(null);
+ const selectedChatItems = useMemo(
+ () => allChatItems.filter((item) => selectedChatIds.has(item.id)),
+ [allChatItems, selectedChatIds],
+ );
+ const selectionCount = selectedChatItems.length;
+
+ // Projects select separately: a mixed selection has no shared bulk action,
+ // so picking one kind drops the other.
+ const [selectedProjectIds, setSelectedProjectIds] = useState<
+ ReadonlySet<string>
+ >(() => new Set());
+ const projectAnchorRef = useRef<string | null>(null);
+ const selectedProjectRecords = useMemo(
+ () => projects.filter((project) => selectedProjectIds.has(project.id)),
+ [projects, selectedProjectIds],
+ );
+ const projectSelectionCount = selectedProjectRecords.length;
+
+ // Each kind drops the other, anchor included: a stale anchor would shift-select
+ // a range from a row the user can no longer see selected.
+ const dropChatSelection = useCallback(() => {
+ selectionAnchorRef.current = null;
+ setSelectedChatIds((prev) => (prev.size === 0 ? prev : new Set()));
+ }, []);
+ const dropProjectSelection = useCallback(() => {
+ projectAnchorRef.current = null;
+ setSelectedProjectIds((prev) => (prev.size === 0 ? prev : new Set()));
+ }, []);
+
+ const clearSelection = useCallback(() => {
+ dropChatSelection();
+ dropProjectSelection();
+ }, [dropChatSelection, dropProjectSelection]);
+
+ // Escape is the way out of a selection, as it is for the menus.
+ useEffect(() => {
+ if (selectionCount === 0 && projectSelectionCount === 0) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") clearSelection();
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [selectionCount, projectSelectionCount, clearSelection]);
+
+ /** True when the click was a selection gesture, so the row must not navigate. */
+ function handleSelectionClick(
+ event: React.MouseEvent,
+ item: SidebarItem,
+ list: { scope: string; ids: string[] },
+ ): boolean {
+ dropProjectSelection();
+ if (SELECT_WITH_META ? event.metaKey : event.ctrlKey) {
+ setSelectedChatIds((prev) => toggleSelected(prev, item.id));
+ selectionAnchorRef.current = { scope: list.scope, id: item.id };
+ return true;
+ }
+ if (!event.shiftKey) return false;
+ const anchor = selectionAnchorRef.current;
+ const sameList = anchor?.scope === list.scope;
+ // Shift without an anchor in this list starts one here.
+ if (!sameList) selectionAnchorRef.current = { scope: list.scope, id: item.id };
+ setSelectedChatIds(
+ new Set(
+ sameList && anchor
+ ? rangeBetween(list.ids, anchor.id, item.id)
+ : [item.id],
+ ),
+ );
+ return true;
+ }
+
+ /** Right-clicking outside the selection acts on that row alone. */
+ function selectForContextMenu(
+ item: SidebarItem,
+ list: { scope: string; ids: string[] },
+ ) {
+ // Before the early return: the menu that opens acts on chats, so folders
+ // left highlighted would misreport what a bulk action is about to touch.
+ dropProjectSelection();
+ if (selectedChatIds.has(item.id)) return;
+ selectionAnchorRef.current = { scope: list.scope, id: item.id };
+ setSelectedChatIds(new Set([item.id]));
+ }
+
+ /** True when the click selected folders instead of opening one. */
+ function handleProjectSelectionClick(
+ event: React.MouseEvent,
+ projectId: string,
+ ): boolean {
+ const additive = SELECT_WITH_META ? event.metaKey : event.ctrlKey;
+ if (!additive && !event.shiftKey) return false;
+ dropChatSelection();
+ if (additive) {
+ setSelectedProjectIds((prev) => toggleSelected(prev, projectId));
+ projectAnchorRef.current = projectId;
+ return true;
+ }
+ const anchorId = projectAnchorRef.current;
+ if (!anchorId) projectAnchorRef.current = projectId;
+ setSelectedProjectIds(
+ new Set(
+ anchorId ? rangeBetween(projectRowIds, anchorId, projectId) : [projectId],
+ ),
+ );
+ return true;
+ }
+
+ function selectProjectForContextMenu(projectId: string) {
+ dropChatSelection();
+ if (selectedProjectIds.has(projectId)) return;
+ projectAnchorRef.current = projectId;
+ setSelectedProjectIds(new Set([projectId]));
+ }
+
+ const allSelectedProjectsPinned =
+ projectSelectionCount > 0 &&
+ selectedProjectRecords.every((project) =>
+ pinnedProjectIdSet.has(project.id),
+ );
+
+ function pinSelectedProjects(pinned: boolean) {
+ for (const project of selectedProjectRecords) {
+ if (pinnedProjectIdSet.has(project.id) !== pinned) {
+ toggleProjectPin(project.id);
+ }
+ }
+ clearSelection();
+ }
+
+ function deleteSelectedProjects() {
+ if (projectSelectionCount === 0) return;
+ openDeleteDialog({ kind: "projects", projects: selectedProjectRecords });
+ }
+
+ const allSelectedPinned =
+ selectionCount > 0 &&
+ selectedChatItems.every((item) => pinnedIdSet.has(item.id));
+
+ function pinSelected(pinned: boolean) {
+ setPinnedChats(
+ selectedChatItems.map((item) => item.id),
+ pinned,
+ );
+ clearSelection();
+ }
+
+ function markSelectedUnread() {
+ const threadIds = selectedChatItems.flatMap(getSidebarItemThreadIds);
+ clearSelection();
+ setUnreadThreadIds((current) => {
+ const next = new Set(current);
+ for (const threadId of threadIds) next.add(threadId);
+ return next;
+ });
+ }
+
+ async function archiveSelected() {
+ const items = selectedChatItems;
+ clearSelection();
+ // Sequential: each archive can reset the active thread, and two of those
+ // racing would fight over where the chat pane lands.
+ let archived = 0;
+ let failure: unknown;
+ for (const item of items) {
+ // Per item, so one bad chat does not strand the rest of the batch
+ // unarchived with the selection already gone.
+ try {
+ await archiveChatItem(item, activeThreadId, (view) => {
+ navigate({
+ to: "/chat",
+ search: item.projectId
+ ? { project: item.projectId }
+ : { new: view.newThreadNonce },
+ });
+ });
+ archived += 1;
+ } catch (err) {
+ failure = err;
+ }
+ }
+ // One notice for the batch, not one per chat. A partial batch gets both:
+ // where the archived ones went, and that the rest did not make it.
+ if (archived > 0) showArchivedChatsToast();
+ if (archived < items.length) {
+ toast.error(translate("settings.data.failedToArchiveChats"), {
+ description: failure instanceof Error ? failure.message : undefined,
+ });
+ }
+ }
+
+ function deleteSelected() {
+ const items = selectedChatItems;
+ if (items.length === 0) return;
+ if (confirmDeleteChats) {
+ openDeleteDialog({ kind: "chats", items });
+ return;
+ }
+ clearSelection();
+ void (async () => {
+ for (const item of items) {
+ await deleteChatWithCleanup(item, {
+ deleteFiles: alwaysDeleteChatFiles,
+ });
+ }
+ })();
+ }
+
+ // A row must know which list it is dragged within: the same chat can sit in
+ // its project and in Recents, and each list keeps its own order.
+ const [draggingRow, setDraggingRow] = useState<{
+ id: string;
+ scope: string;
+ } | null>(null);
+ const [dropTargetRowId, setDropTargetRowId] = useState<string | null>(null);
+ const manualDragEnabled = chatSort === "manual";
+ const pinnedDragEnabled = pinnedSort === "manual";
+
+ /** The cue class for this row, or undefined when it is not the drop target. */
+ function dropCueClass(
+ scope: string | undefined,
+ orderedIds: string[] | undefined,
+ rowId: string,
+ ): string | undefined {
+ if (
+ scope === undefined ||
+ dropTargetRowId !== rowId ||
+ draggingRow?.scope !== scope ||
+ draggingRow.id === rowId
+ ) {
+ return undefined;
+ }
+ return dropEdgeFor(orderedIds ?? [], draggingRow.id, rowId) === "bottom"
+ ? DROP_CUE_BOTTOM
+ : DROP_CUE_TOP;
+ }
+
+ /**
+ * Menu path to the same reorder dragging does. Touch browsers never fire
+ * dragstart and a keyboard cannot drag, so a manually ordered list is
+ * unreorderable without this.
+ */
+ function renderMoveRowItems(
+ scope: string,
+ orderedIds: string[],
+ rowId: string,
+ // Passed in, not searched for: this runs for every row on every render.
+ at: number,
+ ) {
+ const move = (delta: number) => {
+ const next = moveIdBy(orderedIds, rowId, delta);
+ if (next !== orderedIds) setManualOrder(scope, next);
+ };
+ return (
+ <>
+ <DropdownMenuItem disabled={at <= 0} onSelect={() => move(-1)}>
+ <HugeiconsIcon icon={ArrowUp01Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.organize.moveUp")}</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={at === -1 || at >= orderedIds.length - 1}
+ onSelect={() => move(1)}
+ >
+ <HugeiconsIcon icon={ArrowDown01Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.organize.moveDown")}</span>
+ </DropdownMenuItem>
+ </>
+ );
+ }
+
+ /** Drag handlers for one row of a reorderable list. */
+ function rowDragProps(scope: string, orderedIds: string[], rowId: string) {
+ return {
+ draggable: true,
+ onDragStart: (event: React.DragEvent) => {
+ // Firefox needs a payload to drag at all.
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData("text/plain", rowId);
+ setDraggingRow({ id: rowId, scope });
+ },
+ onDragEnd: () => {
+ setDraggingRow(null);
+ setDropTargetRowId(null);
+ },
+ onDragOver: (event: React.DragEvent) => {
+ if (draggingRow?.scope !== scope) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ if (dropTargetRowId !== rowId) setDropTargetRowId(rowId);
+ },
+ onDragLeave: () => {
+ setDropTargetRowId((prev) => (prev === rowId ? null : prev));
+ },
+ onDrop: (event: React.DragEvent) => {
+ event.preventDefault();
+ const dragged = draggingRow;
+ setDraggingRow(null);
+ setDropTargetRowId(null);
+ // Cross-list drops are ignored: the row is not in this list's order.
+ if (!dragged || dragged.scope !== scope) return;
+ const next = reorderIds(orderedIds, dragged.id, rowId);
+ if (next !== orderedIds) setManualOrder(scope, next);
+ },
+ };
+ }
+
useEffect(() => {
const activeVisibleThreadIdSet = new Set(
activeVisibleThreadIdKey ? activeVisibleThreadIdKey.split("\n") : [],
@@ -1090,6 +1618,16 @@ export function AppSidebar() {
isStudioRoute,
// The update card grows the footer, so the scroll area shrinks under it.
showUpdateCard,
+ // Regrouping, collapsing a folder or revealing more adds and removes rows
+ // with no scroll and no collapsible animation to re-measure off.
+ projectsOpen,
+ projectChatRowCount,
+ visibleProjectRecords.length,
+ // Pinning a project chat adds a Pinned row while Recents and the folder
+ // counts both stay put, so nothing else here moves.
+ pinnedChatItems.length,
+ // And with no chats in them, folders appear and disappear on their own.
+ organizeBy,
]);
// Resizing changes clientHeight without firing onScroll, so the fade would
@@ -1353,6 +1891,22 @@ export function AppSidebar() {
}
}
+ function showArchivedChatsToast() {
+ const toastId = toast(
+ <button
+ type="button"
+ onClick={() => {
+ toast.dismiss(toastId);
+ useSettingsDialogStore.getState().openArchivedChats();
+ }}
+ className="w-full cursor-pointer text-left"
+ >
+ You can view archived chats in Settings
+ </button>,
+ { closeButton: true },
+ );
+ }
+
async function handleArchiveThread(item: SidebarItem) {
try {
await archiveChatItem(item, activeThreadId, (view) => {
@@ -1363,19 +1917,7 @@ export function AppSidebar() {
: { new: view.newThreadNonce },
});
});
- const toastId = toast(
- <button
- type="button"
- onClick={() => {
- toast.dismiss(toastId);
- useSettingsDialogStore.getState().openArchivedChats();
- }}
- className="w-full cursor-pointer text-left"
- >
- You can view archived chats in Settings
- </button>,
- { closeButton: true },
- );
+ showArchivedChatsToast();
} catch (err) {
toast.error("Failed to archive chat", {
description: err instanceof Error ? err.message : undefined,
@@ -1498,7 +2040,9 @@ export function AppSidebar() {
type DeleteTarget =
| { kind: "chat"; item: SidebarItem }
+ | { kind: "chats"; items: SidebarItem[] }
| { kind: "project"; project: ProjectRecord }
+ | { kind: "projects"; projects: ProjectRecord[] }
| { kind: "run"; run: TrainingRunSummary };
const [confirmingDelete, setConfirmingDelete] =
useState<DeleteTarget | null>(null);
@@ -1506,7 +2050,11 @@ export function AppSidebar() {
/** Always through here: a stale switch would delete an unrelated sandbox. */
function openDeleteDialog(target: DeleteTarget) {
- setDeleteFilesOnDelete(false);
+ // Chats follow the preference, so the switch shows what will happen and can
+ // still be turned off for this one delete. A project workspace is a bigger
+ // thing to remove, so it keeps asking from scratch.
+ const chats = target.kind === "chat" || target.kind === "chats";
+ setDeleteFilesOnDelete(chats && alwaysDeleteChatFiles);
setConfirmingDelete(target);
}
@@ -1515,16 +2063,17 @@ export function AppSidebar() {
* its own folder, and deletion never touches the project workspace. */
function deleteTargetHasFiles(target: DeleteTarget | null): boolean {
if (!target) return false;
- return target.kind === "project" || target.kind === "chat";
+ return target.kind !== "run";
}
async function commitDelete() {
const target = confirmingDelete;
if (!target) return;
const shouldDeleteProjectFiles =
- target.kind === "project" && deleteFilesOnDelete;
+ (target.kind === "project" || target.kind === "projects") &&
+ deleteFilesOnDelete;
const shouldDeleteChatFiles =
- deleteTargetHasFiles(target) && target.kind === "chat" && deleteFilesOnDelete;
+ (target.kind === "chat" || target.kind === "chats") && deleteFilesOnDelete;
setConfirmingDelete(null);
// Reset so the next delete never inherits this switch.
setDeleteFilesOnDelete(false);
@@ -1534,6 +2083,48 @@ export function AppSidebar() {
});
return;
}
+ if (target.kind === "chats") {
+ clearSelection();
+ // Sequential, so one failure's toast is not buried by the next delete.
+ for (const item of target.items) {
+ await deleteChatWithCleanup(item, {
+ deleteFiles: shouldDeleteChatFiles,
+ });
+ }
+ return;
+ }
+ if (target.kind === "projects") {
+ clearSelection();
+ // Only what actually went: a failed delete leaves that project in place,
+ // and redirecting off it would strand the user for nothing.
+ const deletedIds = new Set<string>();
+ for (const project of target.projects) {
+ try {
+ await deleteChatProject(project.id, {
+ deleteFiles: shouldDeleteProjectFiles,
+ });
+ deletedIds.add(project.id);
+ } catch (err) {
+ toast.error("Failed to delete project", {
+ description: err instanceof Error ? err.message : undefined,
+ });
+ }
+ }
+ // The same cleanup one delete does, once for the batch: refresh history so
+ // member chats do not linger as rows, and leave a deleted project's page.
+ // Unconditional, since a delete that threw may still have removed chats.
+ notifyChatHistoryUpdated();
+ const runtimeProjectId = useChatRuntimeStore.getState().activeProjectId;
+ if (
+ isChatRoute &&
+ ((activeProjectId !== null && deletedIds.has(activeProjectId)) ||
+ (runtimeProjectId !== null && deletedIds.has(runtimeProjectId)))
+ ) {
+ useChatRuntimeStore.getState().setActiveProjectId(null);
+ navigate({ to: "/chat", search: { new: createNavigationNonce() } });
+ }
+ return;
+ }
if (target.kind === "project") {
try {
await deleteChatProject(target.project.id, {
@@ -1630,9 +2221,155 @@ export function AppSidebar() {
});
}
+ // The "..." every list header carries. Only chat lists regroup, so that half
+ // is opt-in; Pinned takes the sort half alone.
+ function renderSidebarHeaderMenu(options: {
+ ariaLabel: string;
+ sortLabel: string;
+ sortValue: SidebarChatSort;
+ onSortChange: (next: SidebarChatSort) => void;
+ includeOrganize?: boolean;
+ }) {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={options.ariaLabel}
+ className="sidebar-header-action"
+ >
+ <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-icon" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="bottom"
+ align="end"
+ sideOffset={2}
+ className="unsloth-plus-menu w-56"
+ >
+ {options.includeOrganize && (
+ <>
+ <DropdownMenuLabel>
+ {t("shell.organize.sidebarHeading")}
+ </DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={organizeBy}
+ onValueChange={(value) =>
+ setOrganizeBy(value as SidebarOrganizeBy)
+ }
+ >
+ {ORGANIZE_OPTIONS.map((option) => (
+ <DropdownMenuRadioItem
+ key={option.value}
+ value={option.value}
+ className={menuRadioItemClass}
+ >
+ {t(option.key)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </>
+ )}
+ <DropdownMenuLabel>{options.sortLabel}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={options.sortValue}
+ onValueChange={(value) =>
+ options.onSortChange(value as SidebarChatSort)
+ }
+ >
+ {CHAT_SORT_OPTIONS.map((option) => (
+ <DropdownMenuRadioItem
+ key={option.value}
+ value={option.value}
+ className={menuRadioItemClass}
+ >
+ {t(option.key)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ }
+
+ /** Bulk actions for selected folders, on right-click of any project row. */
+ function renderProjectContextMenu() {
+ if (projectSelectionCount === 0) return null;
+ return (
+ <ContextMenuContent className="unsloth-plus-menu menu-flat-destructive w-52">
+ {projectSelectionCount > 1 && (
+ <ContextMenuLabel>
+ {t("shell.selection.countSelected", {
+ count: projectSelectionCount,
+ })}
+ </ContextMenuLabel>
+ )}
+ <ContextMenuItem
+ onSelect={() => pinSelectedProjects(!allSelectedProjectsPinned)}
+ >
+ <HugeiconsIcon icon={allSelectedProjectsPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
+ <span>
+ {allSelectedProjectsPinned
+ ? t("shell.selection.unpinProjects")
+ : t("shell.selection.pinProjects")}
+ </span>
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ variant="destructive"
+ onSelect={() => deleteSelectedProjects()}
+ >
+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.selection.deleteProjects")}</span>
+ </ContextMenuItem>
+ </ContextMenuContent>
+ );
+ }
+
+ /** Bulk actions for the current selection, on right-click of any chat row. */
+ function renderChatContextMenu() {
+ if (selectionCount === 0) return null;
+ return (
+ <ContextMenuContent className="unsloth-plus-menu menu-flat-destructive w-52">
+ {selectionCount > 1 && (
+ <ContextMenuLabel>
+ {t("shell.selection.countSelected", { count: selectionCount })}
+ </ContextMenuLabel>
+ )}
+ <ContextMenuItem onSelect={() => pinSelected(!allSelectedPinned)}>
+ <HugeiconsIcon icon={allSelectedPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
+ <span>
+ {allSelectedPinned
+ ? t("shell.selection.unpinChats")
+ : t("shell.selection.pinChats")}
+ </span>
+ </ContextMenuItem>
+ <ContextMenuItem onSelect={() => void archiveSelected()}>
+ <HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.selection.archiveChats")}</span>
+ </ContextMenuItem>
+ <ContextMenuItem onSelect={() => markSelectedUnread()}>
+ <HugeiconsIcon icon={BubbleChatIcon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.selection.markUnread")}</span>
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem variant="destructive" onSelect={() => deleteSelected()}>
+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.selection.deleteChats")}</span>
+ </ContextMenuItem>
+ </ContextMenuContent>
+ );
+ }
+
function renderChatSidebarItem(
item: SidebarItem,
variant: "project" | "recent",
+ // Manual order only: the list this row drags within, its ids to reorder,
+ // and this row's slot in them.
+ drag?: { scope: string; orderedIds: string[]; index: number },
+ // The list this row is rendered in, for shift-click ranges. Always passed;
+ // `drag` only turns up when the list is manually ordered.
+ list?: { scope: string; ids: string[] },
) {
const threadIds = getSidebarItemThreadIds(item);
const isPinned = pinnedIdSet.has(item.id);
@@ -1733,314 +2470,341 @@ export function AppSidebar() {
}
return (
- <SidebarMenuItem key={item.id} className={itemClass}>
- <SidebarMenuButton
- data-testid="recent-thread"
- data-thread-type={item.type}
- data-thread-id={item.id}
- data-generating={isGenerating ? "true" : undefined}
- aria-busy={isGenerating || undefined}
- isActive={activeThreadId === item.id}
- className={buttonClass}
- onClick={() => {
- clearChatNotifications(item);
- navigate({
- to: "/chat",
- search:
- item.type === "single"
- ? {
- thread: item.id,
- ...(item.projectId ? { project: item.projectId } : {}),
- }
- : {
- compare: item.id,
- ...(item.projectId ? { project: item.projectId } : {}),
- },
- });
- closeMobileIfOpen();
- }}
- >
- {isPinned && variant !== "project" && (
- <HugeiconsIcon icon={BubbleChatIcon} strokeWidth={1.75} className="size-icon! shrink-0" />
- )}
- <span className="truncate">
- {pendingRename?.id === item.id ? pendingRename.title : item.title}
- </span>
- {showWorkSpinner && (
- <Spinner
- data-testid="chat-row-spinner"
- // role="status" + label: announced, not motion-only.
- label={
- isGenerating
- ? translate("shell.navigation.chatGenerating")
- : "Queued"
- }
- className="ml-auto size-3.5 shrink-0 text-muted-foreground"
- />
- )}
- </SidebarMenuButton>
- {hasUnreadActivity ? (
- <span
+ <ContextMenu key={item.id}>
+ <ContextMenuTrigger asChild>
+ <SidebarMenuItem
className={cn(
- "pointer-events-none absolute right-2 top-1/2 z-10 flex size-4 -translate-y-1/2 items-center justify-center text-muted-foreground transition-opacity",
- variant === "project"
- ? "group-hover/project-chat-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:opacity-0"
- : "group-hover/recent-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/recent-item:opacity-0",
+ itemClass,
+ draggingRow?.id === item.id && "opacity-50",
+ dropCueClass(drag?.scope, drag?.orderedIds, item.id),
)}
- aria-hidden
- >
- {/* Neutral: a finished reply is news, not a fault. */}
- <span className="size-2 rounded-full bg-muted-foreground/60" />
- </span>
- ) : null}
- {variant === "project" && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- togglePinnedChat(item.id);
- }}
- aria-label={isPinned ? "Unpin chat" : "Pin chat"}
- className="sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/project-chat-item:opacity-100 group-hover/project-chat-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"
- >
- <span className="sidebar-row-action-glyph">
- <HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
- </span>
- </button>
- )}
- {variant === "recent" && isPinned && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- togglePinnedChat(item.id);
- }}
- aria-label="Unpin chat"
- className="sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"
+ onContextMenu={() => list && selectForContextMenu(item, list)}
+ {...(drag
+ ? rowDragProps(drag.scope, drag.orderedIds, item.id)
+ : undefined)}
>
- <span className="sidebar-row-action-glyph">
- <HugeiconsIcon icon={PinOffIcon} strokeWidth={1.75} className="size-icon" />
- </span>
- </button>
- )}
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- onClick={(e) => e.stopPropagation()}
- aria-label="Chat options"
- className={actionClass}
+ <SidebarMenuButton
+ data-testid="recent-thread"
+ data-thread-type={item.type}
+ data-thread-id={item.id}
+ data-generating={isGenerating ? "true" : undefined}
+ aria-busy={isGenerating || undefined}
+ isActive={activeThreadId === item.id}
+ data-selected={selectedChatIds.has(item.id) ? "true" : undefined}
+ className={buttonClass}
+ onClick={(event) => {
+ if (list && handleSelectionClick(event, item, list)) return;
+ clearSelection();
+ clearChatNotifications(item);
+ navigate({
+ to: "/chat",
+ search:
+ item.type === "single"
+ ? {
+ thread: item.id,
+ ...(item.projectId ? { project: item.projectId } : {}),
+ }
+ : {
+ compare: item.id,
+ ...(item.projectId ? { project: item.projectId } : {}),
+ },
+ });
+ closeMobileIfOpen();
+ }}
>
- <span className="sidebar-row-action-glyph">
- <HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" />
+ {isPinned && variant !== "project" && (
+ <HugeiconsIcon icon={BubbleChatIcon} strokeWidth={1.75} className="size-icon! shrink-0" />
+ )}
+ <span className="truncate">
+ {pendingRename?.id === item.id ? pendingRename.title : item.title}
+ </span>
+ {showWorkSpinner && (
+ <Spinner
+ data-testid="chat-row-spinner"
+ // role="status" + label: announced, not motion-only.
+ label={
+ isGenerating
+ ? translate("shell.navigation.chatGenerating")
+ : "Queued"
+ }
+ className="ml-auto size-3.5 shrink-0 text-muted-foreground"
+ />
+ )}
+ </SidebarMenuButton>
+ {hasUnreadActivity ? (
+ <span
+ className={cn(
+ "pointer-events-none absolute right-2 top-1/2 z-10 flex size-4 -translate-y-1/2 items-center justify-center text-muted-foreground transition-opacity",
+ variant === "project"
+ ? "group-hover/project-chat-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:opacity-0"
+ : "group-hover/recent-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/recent-item:opacity-0",
+ )}
+ aria-hidden
+ >
+ {/* Neutral: a finished reply is news, not a fault. */}
+ <span className="size-2 rounded-full bg-muted-foreground/60" />
</span>
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side="bottom"
- align="start"
- sideOffset={0}
- className="unsloth-plus-menu menu-flat-destructive w-56"
- >
- <DropdownMenuItem onSelect={() => openRenameChat(item)}>
- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
- <span>Rename</span>
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => togglePinnedChat(item.id)}>
- <HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
- <span>{isPinned ? "Unpin chat" : "Pin chat"}</span>
- </DropdownMenuItem>
- {sandboxSessionId ? (
- isTauri ? (
- <DropdownMenuItem
- title="Open the folder this chat's tool calls read and write"
- onSelect={() => {
- void (async () => {
- try {
- // A chat moved between projects keeps the sandbox it
- // wrote to, so its own history names the folder, not
- // current membership. Every pane is read, since a
- // compare row can hold one folder per pane.
- // One at a time, not Promise.all: this file's export
- // contract forbids a concurrent await here, and two
- // panes win nothing. A failed read stops the loop and
- // is reported below rather than being caught per pane,
- // which would read as "never ran a tool" and fall back
- // to current membership, the answer the recorded id
- // exists to override.
- const ids =
- threadIds.length > 0 ? threadIds : [item.id];
- const recorded: (string | undefined)[] = [];
- for (const threadId of ids) {
- recorded.push(
- recordedSandboxSessionId(
- await listStoredChatMessages(threadId),
- ),
- );
- }
- let distinct = [...new Set(recorded.filter(Boolean))];
- if (distinct.length === 0 && item.projectId) {
- // Chats stored before results carried a session
- // recorded nothing, so one that ran loose and has
- // since joined a project would be sent to the project
- // workspace. Its thread sandbox is the only other
- // candidate, and files there are this chat's. Only in
- // this direction: a chat moved OUT wrote under
- // project-<id>, and nothing retains which one.
- const held: string[] = [];
- for (const threadId of ids) {
- if (await sandboxHasFiles(threadId)) {
- held.push(threadId);
- }
- }
- distinct = [...new Set(held)];
- }
- if (distinct.length > 1) {
- toast.error("This chat wrote to more than one folder.", {
- description:
- "Its panes ran before it joined this project, so open the folder from a tool card instead.",
- });
- return;
- }
- await revealSandbox(distinct[0] ?? sandboxSessionId);
- } catch (error) {
- toast.error("Could not open the chat folder.", {
- description:
- error instanceof Error
- ? error.message
- : String(error),
- });
- }
- })();
- }}
- >
- <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />
- <span>Open chat folder</span>
- </DropdownMenuItem>
- ) : (
- <OpenChatFolderUnavailableItem />
- )
) : null}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />
- <span>Move to project</span>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent
- sideOffset={0}
- alignOffset={-4}
- className="unsloth-plus-menu w-52"
+ {variant === "project" && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ togglePinnedChat(item.id);
+ }}
+ aria-label={isPinned ? "Unpin chat" : "Pin chat"}
+ className="sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/project-chat-item:opacity-100 group-hover/project-chat-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"
>
- <DropdownMenuItem
- onSelect={() => {
- setProjectCreateMoveTarget(item);
- setCreatingProject(true);
- }}
+ <span className="sidebar-row-action-glyph">
+ <HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
+ </span>
+ </button>
+ )}
+ {variant === "recent" && isPinned && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ togglePinnedChat(item.id);
+ }}
+ aria-label="Unpin chat"
+ className="sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"
+ >
+ <span className="sidebar-row-action-glyph">
+ <HugeiconsIcon icon={PinOffIcon} strokeWidth={1.75} className="size-icon" />
+ </span>
+ </button>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ onClick={(e) => e.stopPropagation()}
+ aria-label="Chat options"
+ className={actionClass}
>
- <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />
- <span>New project</span>
+ <span className="sidebar-row-action-glyph">
+ <HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" />
+ </span>
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="bottom"
+ align="start"
+ sideOffset={0}
+ className="unsloth-plus-menu menu-flat-destructive w-56"
+ >
+ <DropdownMenuItem onSelect={() => openRenameChat(item)}>
+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
+ <span>Rename</span>
</DropdownMenuItem>
- <DropdownMenuItem
- disabled={!item.projectId}
- onSelect={() => void moveChatToProject(item, null)}
- >
- <span>Recents</span>
+ <DropdownMenuItem onSelect={() => togglePinnedChat(item.id)}>
+ <HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
+ <span>{isPinned ? "Unpin chat" : "Pin chat"}</span>
</DropdownMenuItem>
- {projects.map((project) => (
- <DropdownMenuItem
- key={project.id}
- disabled={item.projectId === project.id}
- onSelect={() => void moveChatToProject(item, project.id)}
+ {drag &&
+ renderMoveRowItems(
+ drag.scope,
+ drag.orderedIds,
+ item.id,
+ drag.index,
+ )}
+ {sandboxSessionId ? (
+ isTauri ? (
+ <DropdownMenuItem
+ title="Open the folder this chat's tool calls read and write"
+ onSelect={() => {
+ void (async () => {
+ try {
+ // A chat moved between projects keeps the sandbox it
+ // wrote to, so its own history names the folder, not
+ // current membership. Every pane is read, since a
+ // compare row can hold one folder per pane.
+ // One at a time, not Promise.all: this file's export
+ // contract forbids a concurrent await here, and two
+ // panes win nothing. A failed read stops the loop and
+ // is reported below rather than being caught per pane,
+ // which would read as "never ran a tool" and fall back
+ // to current membership, the answer the recorded id
+ // exists to override.
+ const ids =
+ threadIds.length > 0 ? threadIds : [item.id];
+ const recorded: (string | undefined)[] = [];
+ for (const threadId of ids) {
+ recorded.push(
+ recordedSandboxSessionId(
+ await listStoredChatMessages(threadId),
+ ),
+ );
+ }
+ let distinct = [...new Set(recorded.filter(Boolean))];
+ if (distinct.length === 0 && item.projectId) {
+ // Chats stored before results carried a session
+ // recorded nothing, so one that ran loose and has
+ // since joined a project would be sent to the project
+ // workspace. Its thread sandbox is the only other
+ // candidate, and files there are this chat's. Only in
+ // this direction: a chat moved OUT wrote under
+ // project-<id>, and nothing retains which one.
+ const held: string[] = [];
+ for (const threadId of ids) {
+ if (await sandboxHasFiles(threadId)) {
+ held.push(threadId);
+ }
+ }
+ distinct = [...new Set(held)];
+ }
+ if (distinct.length > 1) {
+ toast.error("This chat wrote to more than one folder.", {
+ description:
+ "Its panes ran before it joined this project, so open the folder from a tool card instead.",
+ });
+ return;
+ }
+ await revealSandbox(distinct[0] ?? sandboxSessionId);
+ } catch (error) {
+ toast.error("Could not open the chat folder.", {
+ description:
+ error instanceof Error
+ ? error.message
+ : String(error),
+ });
+ }
+ })();
+ }}
+ >
+ <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />
+ <span>Open chat folder</span>
+ </DropdownMenuItem>
+ ) : (
+ <OpenChatFolderUnavailableItem />
+ )
+ ) : null}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />
+ <span>Move to project</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ sideOffset={0}
+ alignOffset={-4}
+ className="unsloth-plus-menu w-52"
>
- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
- <span className="truncate">{project.name}</span>
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />
- <span>Export</span>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">
- {CHAT_EXPORT_OPTIONS.map(({ label, format }) => (
- <DropdownMenuItem
- key={label}
- onSelect={async () => {
- try {
- const ids = item.type === "single"
- ? [item.id]
- : (await listStoredChatThreads({ pairId: item.id })).map((t) => t.id);
- for (const id of ids) {
- await exportConversationByFormat(id, format);
- }
- } catch (error) {
- if (!isDownloadCancelled(error)) {
- toast.error("Export failed.");
- }
+ <DropdownMenuItem
+ onSelect={() => {
+ setProjectCreateMoveTarget(item);
+ setCreatingProject(true);
+ }}
+ >
+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />
+ <span>New project</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!item.projectId}
+ onSelect={() => void moveChatToProject(item, null)}
+ >
+ <span>Recents</span>
+ </DropdownMenuItem>
+ {projects.map((project) => (
+ <DropdownMenuItem
+ key={project.id}
+ disabled={item.projectId === project.id}
+ onSelect={() => void moveChatToProject(item, project.id)}
+ >
+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
+ <span className="truncate">{project.name}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />
+ <span>Export</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">
+ {CHAT_EXPORT_OPTIONS.map(({ label, format }) => (
+ <DropdownMenuItem
+ key={label}
+ onSelect={async () => {
+ try {
+ const ids = item.type === "single"
+ ? [item.id]
+ : (await listStoredChatThreads({ pairId: item.id })).map((t) => t.id);
+ for (const id of ids) {
+ await exportConversationByFormat(id, format);
+ }
+ } catch (error) {
+ if (!isDownloadCancelled(error)) {
+ toast.error("Export failed.");
+ }
+ }
+ }}
+ >
+ {label}
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator />
+ {/* Bulk export and import live in Settings -> Data. */}
+ <DropdownMenuItem
+ onSelect={() =>
+ useSettingsDialogStore.getState().openDialog("data")
}
- }}
- >
- {label}
- </DropdownMenuItem>
- ))}
+ >
+ Export all chats…
+ </DropdownMenuItem>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <HugeiconsIcon icon={BookOpen01Icon} strokeWidth={1.75} className="size-icon" />
+ <span>Save to project sources</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">
+ {projects.length === 0 && (
+ <DropdownMenuItem disabled>No projects yet</DropdownMenuItem>
+ )}
+ {projects.map((project) => (
+ <DropdownMenuItem
+ key={project.id}
+ onSelect={async () => {
+ try {
+ await saveChatToProjectSources(item, project.id);
+ } catch {
+ toast.error("Failed to save to project sources.");
+ }
+ }}
+ >
+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
+ <span className="truncate">{project.name}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
<DropdownMenuSeparator />
- {/* Bulk export and import live in Settings -> Data. */}
+ <DropdownMenuItem onSelect={() => void handleArchiveThread(item)}>
+ <HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />
+ <span>Archive</span>
+ </DropdownMenuItem>
<DropdownMenuItem
+ variant="destructive"
onSelect={() =>
- useSettingsDialogStore.getState().openDialog("data")
+ confirmDeleteChats
+ ? openDeleteDialog({ kind: "chat", item })
+ : void deleteChatWithCleanup(item, {
+ deleteFiles: alwaysDeleteChatFiles,
+ })
}
>
- Export all chats…
+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
+ <span>Delete</span>
</DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <HugeiconsIcon icon={BookOpen01Icon} strokeWidth={1.75} className="size-icon" />
- <span>Save to project sources</span>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">
- {projects.length === 0 && (
- <DropdownMenuItem disabled>No projects yet</DropdownMenuItem>
- )}
- {projects.map((project) => (
- <DropdownMenuItem
- key={project.id}
- onSelect={async () => {
- try {
- await saveChatToProjectSources(item, project.id);
- } catch {
- toast.error("Failed to save to project sources.");
- }
- }}
- >
- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
- <span className="truncate">{project.name}</span>
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSeparator />
- <DropdownMenuItem onSelect={() => void handleArchiveThread(item)}>
- <HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />
- <span>Archive</span>
- </DropdownMenuItem>
- <DropdownMenuItem
- variant="destructive"
- onSelect={() =>
- confirmDeleteChats
- ? openDeleteDialog({ kind: "chat", item })
- : void deleteChatWithCleanup(item)
- }
- >
- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
- <span>Delete</span>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </SidebarMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SidebarMenuItem>
+ </ContextMenuTrigger>
+ {renderChatContextMenu()}
+ </ContextMenu>
);
}
@@ -2455,125 +3219,248 @@ export function AppSidebar() {
</SidebarGroupContent>
</SidebarGroup>
- {/* Pinned: pinned projects (with their chats) and pinned chats */}
+ {/* Pinned chats */}
+ {!isStudioRoute && !showTrainingRecents && pinnedChatItems.length > 0 && (
+ <Collapsible open={pinnedOpen} onOpenChange={setPinnedOpen} asChild>
+ <SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">
+ <SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1", scrolled && "is-scrolled")}>
+ <CollapsibleTrigger className="cursor-pointer flex min-w-0 flex-1 items-center gap-1 group/sb-collap">
+ Pinned
+ <ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
+ </CollapsibleTrigger>
+ {/* Pinning is the grouping, so no organize half and no "+". */}
+ {renderSidebarHeaderMenu({
+ ariaLabel: t("shell.organize.sortPinnedChats"),
+ sortLabel: t("shell.organize.sortPinnedBy"),
+ sortValue: pinnedSort,
+ onSortChange: setPinnedSort,
+ })}
+ </SidebarGroupLabel>
+ <CollapsibleContent>
+ <SidebarGroupContent className={scrollRowPadding}>
+ <SidebarMenu>
+ {sortedPinnedChatItems.map((item, index) =>
+ renderChatSidebarItem(
+ item,
+ "recent",
+ pinnedDragEnabled
+ ? {
+ scope: PINNED_ORDER_SCOPE,
+ orderedIds: pinnedRowIds,
+ index,
+ }
+ : undefined,
+ { scope: PINNED_ORDER_SCOPE, ids: pinnedRowIds },
+ ),
+ )}
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </CollapsibleContent>
+ </SidebarGroup>
+ </Collapsible>
+ )}
+
+ {/* Projects: one folder per project, its chats nested underneath */}
{!isStudioRoute &&
!showTrainingRecents &&
- (pinnedProjectRecords.length > 0 ||
- pinnedChatItems.length > 0) && (
- <Collapsible open={pinnedOpen} onOpenChange={setPinnedOpen} asChild>
+ organizeBy === "project" &&
+ sidebarProjectRecords.length > 0 && (
+ <Collapsible
+ open={projectsOpen}
+ onOpenChange={setProjectsOpen}
+ asChild
+ >
<SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">
- <SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following", scrolled && "is-scrolled")} asChild>
- <CollapsibleTrigger className="cursor-pointer flex w-full items-center gap-1 group/sb-collap">
- Pinned
+ {/* Trigger takes the free space; the actions reveal beside it. */}
+ <SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1", scrolled && "is-scrolled")}>
+ <CollapsibleTrigger className="cursor-pointer flex min-w-0 flex-1 items-center gap-1 group/sb-collap">
+ {t("shell.navigation.projects")}
<ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
</CollapsibleTrigger>
+ {renderSidebarHeaderMenu({
+ ariaLabel: t("shell.organize.organizeProjects"),
+ includeOrganize: true,
+ sortLabel: t("shell.organize.sortChatsBy"),
+ sortValue: chatSort,
+ onSortChange: setChatSort,
+ })}
+ <button
+ type="button"
+ aria-label="New project"
+ onClick={() => {
+ setProjectCreateMoveTarget(null);
+ setCreatingProject(true);
+ }}
+ className="sidebar-header-action"
+ >
+ <HugeiconsIcon icon={PlusSignIcon} strokeWidth={1.75} className="size-icon" />
+ </button>
</SidebarGroupLabel>
<CollapsibleContent>
<SidebarGroupContent className={scrollRowPadding}>
<SidebarMenu>
- {pinnedProjectRecords.map((project) => {
+ {visibleProjectRecords.map((project, projectIndex) => {
const projectChats =
- chatsByProjectId.get(project.id) ?? [];
+ sortedChatsByProjectId.get(project.id) ?? [];
+ const projectChatIds =
+ projectChatRowIds.get(project.id) ?? [];
const expanded = !collapsedProjectIds.has(project.id);
const showAll = expandedChatProjectIds.has(project.id);
const visibleChats =
expanded && !showAll
- ? projectChats.slice(0, PINNED_PROJECT_CHAT_LIMIT)
+ ? projectChats.slice(0, PROJECT_CHAT_LIMIT)
: projectChats;
+ const isProjectPinned = pinnedProjectIdSet.has(
+ project.id,
+ );
return (
<Fragment key={project.id}>
- <SidebarMenuItem
- className="group/recent-item relative"
- >
- <SidebarMenuButton
- // Highlight the folder only on the project home; with a chat open, only that row is active.
- isActive={activeProjectId === project.id && !activeThreadId}
- onClick={() => toggleProjectCollapsed(project.id)}
- className="sidebar-nav-btn h-[33px] rounded-full gap-[8.5px] pl-3 pr-2.5 font-medium group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8"
- >
- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon! shrink-0" />
- <span className="truncate text-ui-14p5 leading-ui-19 tracking-nav">{project.name}</span>
- </SidebarMenuButton>
- {/* New chat in this project */}
- <button
- type="button"
- aria-label="New chat"
- onClick={(e) => {
- e.stopPropagation();
- openNewChat(project.id);
- }}
- className="sidebar-row-action is-unpin-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"
- >
- <span className="sidebar-row-action-glyph">
- <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />
- </span>
- </button>
- {/* Project options */}
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
+ {/* Folders drag to reorder whatever the chat sort is. */}
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
+ <SidebarMenuItem
+ className={cn(
+ "group/recent-item relative",
+ draggingRow?.id === project.id && "opacity-50",
+ dropCueClass(
+ PROJECT_ORDER_SCOPE,
+ projectRowIds,
+ project.id,
+ ),
+ )}
+ onContextMenu={() =>
+ selectProjectForContextMenu(project.id)
+ }
+ {...rowDragProps(
+ PROJECT_ORDER_SCOPE,
+ projectRowIds,
+ project.id,
+ )}
+ >
+ <SidebarMenuButton
+ // Highlight the folder only on the project home; with a chat open, only that row is active.
+ isActive={activeProjectId === project.id && !activeThreadId}
+ data-selected={
+ selectedProjectIds.has(project.id)
+ ? "true"
+ : undefined
+ }
+ onClick={(event) => {
+ if (
+ handleProjectSelectionClick(event, project.id)
+ )
+ return;
+ clearSelection();
+ toggleProjectCollapsed(project.id);
+ }}
+ className="sidebar-nav-btn h-[33px] rounded-full gap-[8.5px] pl-3 pr-2.5 font-medium group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8 [@media(pointer:coarse)]:pr-16"
+ >
+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon! shrink-0" />
+ <span className="truncate text-ui-14p5 leading-ui-19 tracking-nav">{project.name}</span>
+ </SidebarMenuButton>
+ {/* New chat in this project */}
<button
type="button"
- onClick={(e) => e.stopPropagation()}
- aria-label="Project options"
- className="sidebar-row-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"
+ aria-label="New chat"
+ onClick={(e) => {
+ e.stopPropagation();
+ openNewChat(project.id);
+ }}
+ className="sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"
>
<span className="sidebar-row-action-glyph">
- <HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" />
+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />
</span>
</button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side="bottom"
- align="start"
- sideOffset={0}
- className="unsloth-plus-menu menu-flat-destructive w-56"
- >
- <DropdownMenuItem onSelect={() => openProject(project.id)}>
- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
- <span>Project home</span>
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => openNewChat(project.id)}>
- <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />
- <span>New chat</span>
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => {
- // Seed the shared draft so the dialog opens with the current name, not stale text.
- setRenameDraft(project.name);
- setRenamingTarget({
- kind: "project",
- project,
- current: project.name,
- });
- }}
- >
- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
- <span>Rename project</span>
- </DropdownMenuItem>
- <DropdownMenuItem onSelect={() => unpinProject(project.id)}>
- <HugeiconsIcon icon={PinOffIcon} strokeWidth={1.75} className="size-icon" />
- <span>Unpin project</span>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onSelect={() => {
- // Start each delete with the file toggle off: Cancel closes programmatically and skips the
- openDeleteDialog({ kind: "project", project });
- }}
- >
- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
- <span>Delete project</span>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </SidebarMenuItem>
+ {/* Project options */}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ onClick={(e) => e.stopPropagation()}
+ aria-label="Project options"
+ className="sidebar-row-action sidebar-touch-reveal group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"
+ >
+ <span className="sidebar-row-action-glyph">
+ <HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" />
+ </span>
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="bottom"
+ align="start"
+ sideOffset={0}
+ className="unsloth-plus-menu menu-flat-destructive w-56"
+ >
+ <DropdownMenuItem onSelect={() => openProject(project.id)}>
+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
+ <span>Project home</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => openNewChat(project.id)}>
+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />
+ <span>New chat</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => {
+ // Seed the shared draft so the dialog opens with the current name, not stale text.
+ setRenameDraft(project.name);
+ setRenamingTarget({
+ kind: "project",
+ project,
+ current: project.name,
+ });
+ }}
+ >
+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
+ <span>Rename project</span>
+ </DropdownMenuItem>
+ {renderMoveRowItems(
+ PROJECT_ORDER_SCOPE,
+ projectRowIds,
+ project.id,
+ projectIndex,
+ )}
+ <DropdownMenuItem onSelect={() => toggleProjectPin(project.id)}>
+ <HugeiconsIcon icon={isProjectPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
+ <span>{isProjectPinned ? "Unpin project" : "Pin project"}</span>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onSelect={() => {
+ // Start each delete with the file toggle off: Cancel closes programmatically and skips the
+ openDeleteDialog({ kind: "project", project });
+ }}
+ >
+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
+ <span>Delete project</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SidebarMenuItem>
+ </ContextMenuTrigger>
+ {renderProjectContextMenu()}
+ </ContextMenu>
{expanded &&
- visibleChats.map((chat) =>
- renderChatSidebarItem(chat, "project"),
+ visibleChats.map((chat, index) =>
+ renderChatSidebarItem(
+ chat,
+ "project",
+ manualDragEnabled
+ ? {
+ scope: projectOrderScope(project.id),
+ orderedIds: projectChatIds,
+ index,
+ }
+ : undefined,
+ {
+ scope: projectOrderScope(project.id),
+ ids: projectChatIds,
+ },
+ ),
)}
{expanded &&
- projectChats.length > PINNED_PROJECT_CHAT_LIMIT && (
+ projectChats.length > PROJECT_CHAT_LIMIT && (
<SidebarMenuItem>
<SidebarMenuButton
onClick={() => toggleProjectShowAll(project.id)}
@@ -2582,7 +3469,11 @@ export function AppSidebar() {
className="sidebar-nav-btn h-[30px] rounded-full pl-9 pr-4 font-medium text-nav-fg-muted!"
>
<span className="text-ui-13 leading-ui-18 tracking-nav">
- {showAll ? "Show less" : "Show more"}
+ {t(
+ showAll
+ ? "shell.navigation.showLess"
+ : "shell.navigation.showMore",
+ )}
</span>
</SidebarMenuButton>
</SidebarMenuItem>
@@ -2590,8 +3481,22 @@ export function AppSidebar() {
</Fragment>
);
})}
- {pinnedChatItems.map((item) =>
- renderChatSidebarItem(item, "recent"),
+ {/* Long project lists stay one row deep until asked. */}
+ {sidebarProjectRecords.length > SIDEBAR_PROJECT_LIMIT && (
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ onClick={() => setShowAllProjects((prev) => !prev)}
+ className="sidebar-nav-btn h-[30px] rounded-full pl-3 pr-4 font-medium text-nav-fg-muted!"
+ >
+ <span className="text-ui-13 leading-ui-18 tracking-nav">
+ {t(
+ showAllProjects
+ ? "shell.navigation.showLess"
+ : "shell.navigation.showMore",
+ )}
+ </span>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
)}
</SidebarMenu>
</SidebarGroupContent>
@@ -2605,22 +3510,48 @@ export function AppSidebar() {
<SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0">
<SidebarGroupLabel
className={cn(
- "sidebar-sticky-label sidebar-sticky-label-following",
+ "sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1",
scrolled && "is-scrolled",
usesDesktopTitlebar && "translate-x-[2px]",
)}
- asChild
>
- <CollapsibleTrigger className="cursor-pointer flex w-full items-center gap-1 group/sb-collap">
+ <CollapsibleTrigger className="cursor-pointer flex min-w-0 flex-1 items-center gap-1 group/sb-collap">
{t("shell.navigation.recents")}
<ChevronDown className="size-3.5 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-collap:opacity-100 group-focus-visible/sb-collap:opacity-100 data-[state=open]:rotate-0 [[data-state=closed]_&]:rotate-[-90deg] [[data-state=closed]_&]:opacity-100" />
</CollapsibleTrigger>
+ {renderSidebarHeaderMenu({
+ ariaLabel: t("shell.organize.organizeChats"),
+ includeOrganize: true,
+ sortLabel: t("shell.organize.sortChatsBy"),
+ sortValue: chatSort,
+ onSortChange: setChatSort,
+ })}
+ {/* Starts a chat outside any project, whatever page is open. */}
+ <button
+ type="button"
+ aria-label={t("shell.navigation.newChat")}
+ onClick={() => openNewChat(null)}
+ className="sidebar-header-action"
+ >
+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />
+ </button>
</SidebarGroupLabel>
<CollapsibleContent>
<SidebarGroupContent className={scrollRowPadding}>
<SidebarMenu>
- {recentChatItems.map((item) =>
- renderChatSidebarItem(item, "recent"),
+ {sortedRecentChatItems.map((item, index) =>
+ renderChatSidebarItem(
+ item,
+ "recent",
+ manualDragEnabled
+ ? {
+ scope: RECENTS_ORDER_SCOPE,
+ orderedIds: recentRowIds,
+ index,
+ }
+ : undefined,
+ { scope: RECENTS_ORDER_SCOPE, ids: recentRowIds },
+ ),
)}
</SidebarMenu>
{/* "No chats yet" only when there is truly no history:
@@ -3004,7 +3935,11 @@ export function AppSidebar() {
? t("shell.dialog.deleteRun.title")
: confirmingDelete?.kind === "project"
? "Delete project"
- : t("shell.dialog.deleteChat.title")}
+ : confirmingDelete?.kind === "chats"
+ ? t("shell.selection.deleteTitle")
+ : confirmingDelete?.kind === "projects"
+ ? t("shell.selection.deleteProjectsTitle")
+ : t("shell.dialog.deleteChat.title")}
</DialogTitle>
<DialogDescription>
{confirmingDelete?.kind === "run" ? (
@@ -3019,6 +3954,14 @@ export function AppSidebar() {
"shell.dialog.deleteChat.description",
confirmingDelete.item.title,
)
+ ) : confirmingDelete?.kind === "chats" ? (
+ t("shell.selection.deleteDescription", {
+ count: confirmingDelete.items.length,
+ })
+ ) : confirmingDelete?.kind === "projects" ? (
+ t("shell.selection.deleteProjectsDescription", {
+ count: confirmingDelete.projects.length,
+ })
) : confirmingDelete?.kind === "project" ? (
<>
Delete{" "}
@@ -3034,20 +3977,24 @@ export function AppSidebar() {
<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="delete-files-on-delete" className="min-w-0 space-y-1">
<span className="block text-sm font-medium text-foreground">
- Delete files and sandbox folder
+ {t("shell.selection.deleteFilesLabel")}
</span>
<span className="block break-words text-xs leading-5 text-muted-foreground">
{confirmingDelete?.kind === "project"
? (confirmingDelete.project.rootPath ??
"The project workspace folder will be removed from disk.")
- : "This chat's own sandbox folder is removed from disk. Files it wrote inside a project stay in that project's workspace."}
+ : confirmingDelete?.kind === "projects"
+ ? t("shell.selection.deleteProjectsFilesDescription")
+ : confirmingDelete?.kind === "chats"
+ ? t("shell.selection.deleteFilesDescription")
+ : t("shell.selection.deleteChatFilesDescription")}
</span>
</label>
<Switch
id="delete-files-on-delete"
checked={deleteFilesOnDelete}
onCheckedChange={setDeleteFilesOnDelete}
- aria-label="Delete files and sandbox folder"
+ aria-label={t("shell.selection.deleteFilesLabel")}
/>
</div>
) : null}
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 76a3ba2997d..320c6d5940b 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -64,6 +64,7 @@ import {
INVENTORY_FRESHNESS_WINDOW_MS,
useDeviceInventorySources,
} from "@/features/hub/inventory";
+import { DeleteChatFilesSwitch } from "./components/delete-chat-files-switch";
import { chatLocalModelOptions } from "./local-model-options";
import {
type NativeIntent,
@@ -1256,6 +1257,9 @@ function ProjectLanding({
const confirmDeleteChats = useChatPreferencesStore(
(s) => s.confirmDeleteChats,
);
+ const alwaysDeleteChatFiles = useChatPreferencesStore(
+ (s) => s.alwaysDeleteChatFiles,
+ );
const pinnedChatIdSet = useMemo(
() => new Set(pinnedChatIds),
[pinnedChatIds],
@@ -1263,6 +1267,9 @@ function ProjectLanding({
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 [deleteFilesOnDelete, setDeleteFilesOnDelete] = useState(false);
// Landing has no active thread selected, so the onView callback here is a
// no-op; the items list refreshes itself once storage emits its update.
@@ -1282,9 +1289,11 @@ function ProjectLanding({
);
const runDelete = useCallback(
- async (item: SidebarItem) => {
+ async (item: SidebarItem, deleteFiles: boolean) => {
try {
- await deleteChatItem(item, activeThreadId ?? undefined, noopView);
+ await deleteChatItem(item, activeThreadId ?? undefined, noopView, {
+ deleteFiles,
+ });
} catch (err) {
toast.error("Failed to delete chat", {
description: err instanceof Error ? err.message : undefined,
@@ -1296,10 +1305,15 @@ function ProjectLanding({
const handleDelete = useCallback(
(item: SidebarItem) => {
- if (confirmDeleteChats) setConfirmingDelete(item);
- else void runDelete(item);
+ if (confirmDeleteChats) {
+ setDeleteFilesOnDelete(alwaysDeleteChatFiles);
+ setConfirmingDelete(item);
+ return;
+ }
+ // No confirmation to preselect, so the preference is the answer.
+ void runDelete(item, alwaysDeleteChatFiles);
},
- [confirmDeleteChats, runDelete],
+ [confirmDeleteChats, runDelete, alwaysDeleteChatFiles],
);
const handleMoveToProject = useCallback(
@@ -1771,13 +1785,19 @@ function ProjectLanding({
be undone.
</AlertDialogDescription>
</AlertDialogHeader>
+ <DeleteChatFilesSwitch
+ id="chat-landing-delete-files"
+ checked={deleteFilesOnDelete}
+ onCheckedChange={setDeleteFilesOnDelete}
+ />
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
const target = confirmingDelete;
+ const deleteFiles = deleteFilesOnDelete;
setConfirmingDelete(null);
- if (target) void runDelete(target);
+ if (target) void runDelete(target, deleteFiles);
}}
>
Delete
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
new file mode 100644
index 00000000000..72b04ddf385
--- /dev/null
+++ b/studio/frontend/src/features/chat/components/delete-chat-files-switch.tsx
@@ -0,0 +1,45 @@
+// 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 { Switch } from "@/components/ui/switch";
+import { useT } from "@/i18n";
+
+/**
+ * The file half of a chat delete, shown wherever one is confirmed.
+ *
+ * "Always delete files" makes the delete destructive beyond the chat itself, so
+ * every confirmation has to say so and let the user turn it off for this one.
+ */
+export function DeleteChatFilesSwitch({
+ id,
+ checked,
+ onCheckedChange,
+ description,
+}: {
+ id: string;
+ checked: boolean;
+ onCheckedChange: (next: boolean) => void;
+ /** For a delete covering more than one chat, which reads differently. */
+ description?: string;
+}) {
+ const t = useT();
+ const label = 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">
+ <span className="block text-sm font-medium text-foreground">
+ {label}
+ </span>
+ <span className="block break-words text-xs leading-5 text-muted-foreground">
+ {description ?? t("shell.selection.deleteChatFilesDescription")}
+ </span>
+ </label>
+ <Switch
+ id={id}
+ checked={checked}
+ onCheckedChange={onCheckedChange}
+ aria-label={label}
+ />
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 080eb3959aa..fa89c769152 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -77,6 +77,23 @@ export { PermissionModeDropdown } from "./permission-mode-select";
export { useChatSearchStore } from "./stores/chat-search-store";
export { usePinnedChatsStore } from "./stores/pinned-chats-store";
export { usePinnedProjectsStore } from "./stores/pinned-projects-store";
+export {
+ applyManualOrder,
+ dropEdgeFor,
+ moveIdBy,
+ showsInRecents,
+ PINNED_ORDER_SCOPE,
+ PROJECT_ORDER_SCOPE,
+ projectOrderScope,
+ RECENTS_ORDER_SCOPE,
+ reorderIds,
+ SIDEBAR_ORGANIZATION_STORAGE_KEY,
+ useSidebarOrganizationStore,
+} from "./stores/sidebar-organization-store";
+export type {
+ SidebarChatSort,
+ SidebarOrganizeBy,
+} from "./stores/sidebar-organization-store";
export { useChatPreferencesStore } from "./stores/chat-preferences-store";
export {
usePromptQueueUI,
@@ -110,6 +127,7 @@ export {
shouldAbortPendingQueueForSettingsChange,
} from "./utils/prompt-queue-model-boundary";
export { chatHistoryClearBoundary } from "./utils/chat-history-clear-boundary";
+export { rangeBetween, toggleSelected } from "./utils/row-selection";
export {
addQueuedChatRunSettingsThreadIds,
consumeQueuedChatRunSettings,
@@ -138,6 +156,7 @@ export {
} from "./external-providers";
export { ApiProviderLogo } from "./api-provider-logo";
export { useExternalProvidersStore } from "./stores/external-providers-store";
+export { DeleteChatFilesSwitch } from "./components/delete-chat-files-switch";
export { ChatSearchDialog } from "./components/chat-search-dialog";
export { StopRunningChatsDialog } from "./components/stop-running-chats-dialog";
export { setTrainingCompareHandoff } from "./lib/training-compare-handoff";
diff --git a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
index 74fd37d1280..9871de0f0ae 100644
--- a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
@@ -6,6 +6,8 @@ import { persist } from "zustand/middleware";
// Client-side chat UI prefs kept in localStorage, not the chat DB.
// confirmDeleteChats: when off, deleting a chat skips the confirm dialog.
+// alwaysDeleteChatFiles: when on, deleting a chat also removes its sandbox
+// folder, without having to ask for it each time.
// showModelDisclaimer: when off, hide the "LLMs can make mistakes" footer note.
// showResponseModel: when on, assistant responses show the producing model.
// collapseThinkingByDefault: when on, thinking stays collapsed instead of
@@ -13,6 +15,8 @@ import { persist } from "zustand/middleware";
export interface ChatPreferencesState {
confirmDeleteChats: boolean;
setConfirmDeleteChats: (value: boolean) => void;
+ alwaysDeleteChatFiles: boolean;
+ setAlwaysDeleteChatFiles: (value: boolean) => void;
showModelDisclaimer: boolean;
setShowModelDisclaimer: (value: boolean) => void;
showResponseModel: boolean;
@@ -27,6 +31,10 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
confirmDeleteChats: true,
setConfirmDeleteChats: (confirmDeleteChats) =>
set({ confirmDeleteChats }),
+ // Off by default: deleting files is the destructive half, so it stays opt in.
+ alwaysDeleteChatFiles: false,
+ setAlwaysDeleteChatFiles: (alwaysDeleteChatFiles) =>
+ set({ alwaysDeleteChatFiles }),
showModelDisclaimer: true,
setShowModelDisclaimer: (showModelDisclaimer) =>
set({ showModelDisclaimer }),
@@ -44,6 +52,7 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
return {
...current,
confirmDeleteChats: saved?.confirmDeleteChats ?? true,
+ alwaysDeleteChatFiles: saved?.alwaysDeleteChatFiles ?? false,
showModelDisclaimer: saved?.showModelDisclaimer ?? true,
showResponseModel: saved?.showResponseModel ?? false,
collapseThinkingByDefault: saved?.collapseThinkingByDefault ?? false,
diff --git a/studio/frontend/src/features/chat/stores/pinned-chats-store.ts b/studio/frontend/src/features/chat/stores/pinned-chats-store.ts
index 0abb6cef498..53c198be421 100644
--- a/studio/frontend/src/features/chat/stores/pinned-chats-store.ts
+++ b/studio/frontend/src/features/chat/stores/pinned-chats-store.ts
@@ -11,6 +11,8 @@ export interface PinnedChatsState {
pinnedIds: string[];
togglePin: (id: string) => void;
unpin: (id: string) => void;
+ /** Pins or unpins a whole selection in one write. */
+ setPinned: (ids: string[], pinned: boolean) => void;
}
export const usePinnedChatsStore = create<PinnedChatsState>()(
@@ -27,6 +29,19 @@ export const usePinnedChatsStore = create<PinnedChatsState>()(
set((state) => ({
pinnedIds: state.pinnedIds.filter((x) => x !== id),
})),
+ setPinned: (ids, pinned) =>
+ set((state) => {
+ if (!pinned) {
+ const dropping = new Set(ids);
+ return {
+ pinnedIds: state.pinnedIds.filter((id) => !dropping.has(id)),
+ };
+ }
+ // Already pinned chats keep their place; the rest lead, as one pin does.
+ const additions = ids.filter((id) => !state.pinnedIds.includes(id));
+ if (additions.length === 0) return state;
+ return { pinnedIds: [...additions, ...state.pinnedIds] };
+ }),
}),
{
name: "unsloth_pinned_chats",
diff --git a/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts b/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
new file mode 100644
index 00000000000..ef8624787c5
--- /dev/null
+++ b/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
@@ -0,0 +1,170 @@
+// 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 { create } from "zustand";
+import { persist } from "zustand/middleware";
+
+/** How the sidebar arranges chats that belong to a project. */
+export type SidebarOrganizeBy = "project" | "list";
+/** How chat rows are ordered inside whichever list they land in. */
+export type SidebarChatSort = "priority" | "updated" | "manual";
+
+// Exported so the preference reset clears the same key this store writes.
+export const SIDEBAR_ORGANIZATION_STORAGE_KEY = "unsloth_sidebar_organization";
+
+// Manual order is per list: dragging a chat in one project must not move it in
+// another list showing the same chat. Each list gets its own key.
+export const RECENTS_ORDER_SCOPE = "recents";
+export const PINNED_ORDER_SCOPE = "pinned";
+// The project folders themselves, which drag regardless of the chat sort.
+export const PROJECT_ORDER_SCOPE = "projects";
+
+export function projectOrderScope(projectId: string): string {
+ return `project:${projectId}`;
+}
+
+export interface SidebarOrganizationState {
+ organizeBy: SidebarOrganizeBy;
+ chatSort: SidebarChatSort;
+ // Pinned sorts on its own. Pin order already is a manual order, so it
+ // defaults to "manual" and stays put while the lists below re-sort.
+ pinnedSort: SidebarChatSort;
+ /** Scope key -> row ids, in the order the user dragged them into. */
+ manualOrder: Record<string, string[]>;
+ setOrganizeBy: (value: SidebarOrganizeBy) => void;
+ setChatSort: (value: SidebarChatSort) => void;
+ setPinnedSort: (value: SidebarChatSort) => void;
+ setManualOrder: (scope: string, ids: string[]) => void;
+}
+
+/**
+ * Moves `draggedId` into `targetId`'s slot, keeping the rest in order. Returns
+ * `ids` itself when either row is missing, so a stale drop is a no-op.
+ */
+export function reorderIds(
+ ids: string[],
+ draggedId: string,
+ targetId: string,
+): string[] {
+ if (draggedId === targetId) return ids;
+ const from = ids.indexOf(draggedId);
+ const to = ids.indexOf(targetId);
+ if (from === -1 || to === -1) return ids;
+ const next = [...ids];
+ next.splice(from, 1);
+ next.splice(to, 0, draggedId);
+ return next;
+}
+
+/**
+ * Whether a chat belongs in Recents. With the Projects section on, a project
+ * chat lives in its folder and listing it twice is noise; with it off there are
+ * no folders, so Recents is the only place it can appear.
+ */
+export function showsInRecents(
+ projectId: string | null | undefined,
+ organizeBy: SidebarOrganizeBy,
+): boolean {
+ return organizeBy === "list" || !projectId;
+}
+
+/**
+ * Which edge of the target row the drop indicator belongs on, matching where
+ * `reorderIds` actually lands the row: after the target when dragging down,
+ * before it when dragging up.
+ */
+export function dropEdgeFor(
+ ids: string[],
+ draggedId: string,
+ targetId: string,
+): "top" | "bottom" {
+ const from = ids.indexOf(draggedId);
+ const to = ids.indexOf(targetId);
+ return from !== -1 && to !== -1 && from < to ? "bottom" : "top";
+}
+
+/**
+ * Moves a row one slot up or down. The menu path to the same reorder that
+ * dragging does, for touch and keyboard, which never see a `dragstart`.
+ */
+export function moveIdBy(
+ ids: string[],
+ id: string,
+ delta: number,
+): string[] {
+ const from = ids.indexOf(id);
+ if (from === -1) return ids;
+ const to = from + delta;
+ if (to < 0 || to >= ids.length) return ids;
+ const next = [...ids];
+ next.splice(from, 1);
+ next.splice(to, 0, id);
+ return next;
+}
+
+/**
+ * Applies a saved order to `items`, leaving rows it does not mention in their
+ * incoming order and on top. A row the user never dragged is new to the list,
+ * so it stays where the list's own rule put it rather than sinking.
+ */
+export function applyManualOrder<T>(
+ items: T[],
+ order: string[] | undefined,
+ getId: (item: T) => string,
+): T[] {
+ if (!order?.length) return items;
+ const rank = new Map(order.map((id, index) => [id, index]));
+ // Sort is stable, so two unranked rows keep their relative order.
+ return [...items].sort(
+ (a, b) => (rank.get(getId(a)) ?? -1) - (rank.get(getId(b)) ?? -1),
+ );
+}
+
+export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
+ persist(
+ (set) => ({
+ organizeBy: "project",
+ chatSort: "priority",
+ pinnedSort: "manual",
+ manualOrder: {},
+ setOrganizeBy: (value) => set({ organizeBy: value }),
+ setChatSort: (value) => set({ chatSort: value }),
+ setPinnedSort: (value) => set({ pinnedSort: value }),
+ setManualOrder: (scope, ids) =>
+ set((state) => ({
+ manualOrder: { ...state.manualOrder, [scope]: ids },
+ })),
+ }),
+ {
+ name: SIDEBAR_ORGANIZATION_STORAGE_KEY,
+ merge: (persisted, current) => {
+ const saved = persisted as
+ | Partial<SidebarOrganizationState>
+ | undefined;
+ // Validated per field: an old or half-written payload keeps defaults.
+ const organizeBy: SidebarOrganizeBy =
+ saved?.organizeBy === "list" ? "list" : "project";
+ const readSort = (
+ value: unknown,
+ fallback: SidebarChatSort,
+ ): SidebarChatSort =>
+ value === "priority" || value === "updated" || value === "manual"
+ ? value
+ : fallback;
+ const chatSort = readSort(saved?.chatSort, "priority");
+ const pinnedSort = readSort(saved?.pinnedSort, "manual");
+ const manualOrder: Record<string, string[]> = {};
+ if (saved?.manualOrder && typeof saved.manualOrder === "object") {
+ for (const [scope, ids] of Object.entries(saved.manualOrder)) {
+ if (Array.isArray(ids)) {
+ manualOrder[scope] = ids.filter(
+ (id): id is string => typeof id === "string",
+ );
+ }
+ }
+ }
+ return { ...current, organizeBy, chatSort, pinnedSort, manualOrder };
+ },
+ },
+ ),
+);
diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
index ddf66f88f6b..0a6e6764397 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -987,13 +987,17 @@ export interface ClearStoredChatsResult {
let clearStoredChatsPromise: Promise<ClearStoredChatsResult> | null = null;
-export function clearStoredChats(): Promise<ClearStoredChatsResult> {
+export function clearStoredChats(
+ options: { deleteFiles?: boolean } = {},
+): Promise<ClearStoredChatsResult> {
+ // A clear already in flight wins: the dedupe is what keeps two clears from
+ // racing, and only one caller can start one.
if (clearStoredChatsPromise) return clearStoredChatsPromise;
threadRecordClearEpoch += 1;
failedThreadRecordByThreadId.clear();
const reopenAdmission = threadRecordWrites.closeAdmission();
- const operation = clearStoredChatsWithAdmissionClosed();
+ const operation = clearStoredChatsWithAdmissionClosed(options);
const tracked = operation.finally(() => {
reopenAdmission();
if (clearStoredChatsPromise === tracked) {
@@ -1004,7 +1008,9 @@ export function clearStoredChats(): Promise<ClearStoredChatsResult> {
return tracked;
}
-async function clearStoredChatsWithAdmissionClosed(): Promise<ClearStoredChatsResult> {
+async function clearStoredChatsWithAdmissionClosed(
+ options: { deleteFiles?: boolean },
+): Promise<ClearStoredChatsResult> {
// Admission is closed before this one-shot fence snapshot.
const pendingThreadIds = threadRecordWrites.idsRequiringFence();
const operationId = crypto.randomUUID();
@@ -1026,6 +1032,7 @@ async function clearStoredChatsWithAdmissionClosed(): Promise<ClearStoredChatsRe
clearBackendChats({
notify: false,
operationId,
+ deleteFiles: options.deleteFiles,
// the transaction finds existing rows itself; these ids additionally fence legacy rows and
// writes that have not committed yet
tombstoneThreadIds: idsToFence,
diff --git a/studio/frontend/src/features/chat/utils/clear-all-chats.ts b/studio/frontend/src/features/chat/utils/clear-all-chats.ts
index e2c6bbe834f..fa9ee4b9389 100644
--- a/studio/frontend/src/features/chat/utils/clear-all-chats.ts
+++ b/studio/frontend/src/features/chat/utils/clear-all-chats.ts
@@ -9,7 +9,7 @@ import { stopChatThread } from "./stop-chat-thread";
export const countAllChats = countStoredChats;
-export async function clearAllChats() {
+export async function clearAllChats(options: { deleteFiles?: boolean } = {}) {
// Invalidate fresh-thread initialization before either queue cancellation or
// storage enumeration can yield. A late initializer must not recreate a chat
// after this clear finishes.
@@ -25,5 +25,5 @@ export async function clearAllChats() {
stopChatThread(threadId);
}
requestPromptQueueStop();
- return await clearStoredChats();
+ return await clearStoredChats(options);
}
diff --git a/studio/frontend/src/features/chat/utils/row-selection.ts b/studio/frontend/src/features/chat/utils/row-selection.ts
new file mode 100644
index 00000000000..9b407492bf5
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/row-selection.ts
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Multi-select for sidebar rows: cmd or ctrl click toggles one row, shift click
+ * takes the block between the anchor and the clicked row.
+ */
+
+/** Rows from `anchorId` to `targetId` inclusive, in list order, either way round. */
+export function rangeBetween(
+ ids: string[],
+ anchorId: string,
+ targetId: string,
+): string[] {
+ const from = ids.indexOf(anchorId);
+ const to = ids.indexOf(targetId);
+ // A missing anchor means the list changed under the selection, so the click
+ // stands on its own rather than selecting an arbitrary block.
+ if (from === -1 || to === -1) return to === -1 ? [] : [targetId];
+ return from <= to ? ids.slice(from, to + 1) : ids.slice(to, from + 1);
+}
+
+/** The set with `id` added, or removed when it was already there. */
+export function toggleSelected(
+ selected: ReadonlySet<string>,
+ id: string,
+): Set<string> {
+ const next = new Set(selected);
+ if (!next.delete(id)) next.add(id);
+ return next;
+}
diff --git a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
index 4d0761bea88..bdbc0873e37 100644
--- a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
+++ b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
@@ -39,7 +39,9 @@ const PUSH_DEBOUNCE_MS = 800;
// locale). Version 1 always serialized the resolved locale, so its "en" is
// usually the old default rather than an explicit pick.
// Version 3 migrates untouched sidebar layouts to keep Video under More.
-const PERSONALIZATION_VERSION = 3;
+// Version 4 pins Video under Images. Without this bump a synced profile
+// rehydrates its stored layout over the local migration.
+const PERSONALIZATION_VERSION = 4;
type ProfileSnapshot = {
displayName: string;
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 43b2900fbed..e6a1a6e25c8 100644
--- a/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx
+++ b/studio/frontend/src/features/settings/components/archived-chats-dialog.tsx
@@ -13,6 +13,7 @@ import {
} from "@/components/ui/alert-dialog";
import {
type SidebarItem,
+ DeleteChatFilesSwitch,
deleteChatItem,
unarchiveChatItem,
useChatPreferencesStore,
@@ -55,9 +56,15 @@ export function ArchivedChatsView() {
const confirmDeleteChats = useChatPreferencesStore(
(s) => s.confirmDeleteChats,
);
+ 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 [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);
@@ -83,17 +90,22 @@ export function ArchivedChatsView() {
}
}
- async function handleDelete(item: SidebarItem) {
+ async function handleDelete(item: SidebarItem, deleteFiles: boolean) {
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 },
- });
- });
+ await deleteChatItem(
+ item,
+ openChatId,
+ (view) => {
+ navigate({
+ to: "/chat",
+ search: item.projectId
+ ? { project: item.projectId }
+ : { new: view.newThreadNonce },
+ });
+ },
+ { deleteFiles },
+ );
toast.success("Chat deleted");
} catch (err) {
toast.error("Failed to delete chat", {
@@ -103,8 +115,13 @@ export function ArchivedChatsView() {
}
function requestDelete(item: SidebarItem) {
- if (confirmDeleteChats) setConfirmingDelete(item);
- else void handleDelete(item);
+ if (confirmDeleteChats) {
+ setDeleteFilesOnDelete(alwaysDeleteChatFiles);
+ setConfirmingDelete(item);
+ return;
+ }
+ // No confirmation to preselect, so the preference is the answer.
+ void handleDelete(item, alwaysDeleteChatFiles);
}
return (
@@ -199,14 +216,20 @@ export function ArchivedChatsView() {
? This cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
+ <DeleteChatFilesSwitch
+ id="archived-chat-delete-files"
+ checked={deleteFilesOnDelete}
+ onCheckedChange={setDeleteFilesOnDelete}
+ />
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={() => {
const item = confirmingDelete;
+ const deleteFiles = deleteFilesOnDelete;
setConfirmingDelete(null);
- if (item) void handleDelete(item);
+ if (item) void handleDelete(item, deleteFiles);
}}
>
Delete
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 f4c58818bd4..e5564f5b2db 100644
--- a/studio/frontend/src/features/settings/components/recent-dictations-view.tsx
+++ b/studio/frontend/src/features/settings/components/recent-dictations-view.tsx
@@ -25,7 +25,9 @@ import {
SelectValue,
} from "@/components/ui/select";
import {
+ DeleteChatFilesSwitch,
deleteChatItem,
+ useChatPreferencesStore,
useChatRuntimeStore,
type SidebarItem,
} from "@/features/chat";
@@ -87,6 +89,9 @@ export function RecentDictationsView({
(s) => s.clearRecentDictations,
);
const [pendingDelete, setPendingDelete] = useState<PendingDelete>(null);
+ // Only "Delete chat and dictation" removes a chat, so only that path shows
+ // the switch. Preselected from the preference, off for this one if asked.
+ const [deleteFilesOnDelete, setDeleteFilesOnDelete] = useState(false);
const [search, setSearch] = useState("");
const [sortOrder, setSortOrder] = useState<SortOrder>("newest");
// Pagination is keyed to the search/sort inputs so changing either restarts
@@ -95,6 +100,9 @@ export function RecentDictationsView({
const [page, setPage] = useState({ key: pageKey, count: PAGE_SIZE });
const visibleCount = page.key === pageKey ? page.count : PAGE_SIZE;
const navigate = useNavigate();
+ const alwaysDeleteChatFiles = useChatPreferencesStore(
+ (s) => s.alwaysDeleteChatFiles,
+ );
const closeSettings = useSettingsDialogStore((s) => s.closeDialog);
const selected =
recentDictations.find((dictation) => dictation.id === selectedId) ?? null;
@@ -145,7 +153,7 @@ export function RecentDictationsView({
}
// Delete a linked dictation together with the chat it was used in.
- async function confirmDeleteWithChat() {
+ async function confirmDeleteWithChat(deleteFiles: boolean) {
if (pendingDelete?.kind !== "one") {
return;
}
@@ -170,6 +178,7 @@ export function RecentDictationsView({
search: { new: crypto.randomUUID() },
});
},
+ { deleteFiles },
);
} catch (error) {
toast.error(t("settings.voice.recents.deleteWithChatFailed"), {
@@ -252,7 +261,10 @@ export function RecentDictationsView({
variant="outline"
size="sm"
onClick={() =>
- setPendingDelete({ kind: "one", dictation: selected })
+ {
+ setDeleteFilesOnDelete(alwaysDeleteChatFiles);
+ setPendingDelete({ kind: "one", dictation: selected });
+ }
}
className="text-destructive hover:border-destructive/60 hover:text-destructive"
>
@@ -420,7 +432,10 @@ export function RecentDictationsView({
<button
type="button"
onClick={() =>
- setPendingDelete({ kind: "one", dictation })
+ {
+ setDeleteFilesOnDelete(alwaysDeleteChatFiles);
+ setPendingDelete({ kind: "one", dictation });
+ }
}
aria-label={t("settings.voice.recents.delete")}
title={t("settings.voice.recents.delete")}
@@ -480,6 +495,14 @@ export function RecentDictationsView({
: t("settings.voice.recents.deleteDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
+ {/* Only the linked case offers a chat delete, so only it can remove files. */}
+ {pendingDelete?.kind === "one" && pendingDelete.dictation.chatId ? (
+ <DeleteChatFilesSwitch
+ id="dictation-delete-files"
+ checked={deleteFilesOnDelete}
+ onCheckedChange={setDeleteFilesOnDelete}
+ />
+ ) : null}
<AlertDialogFooter>
<AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
{pendingDelete?.kind === "one" && pendingDelete.dictation.chatId ? (
@@ -490,7 +513,7 @@ export function RecentDictationsView({
// Close only through state so the dismissal can't race a
// click on whatever ends up under the pointer.
event.preventDefault();
- void confirmDeleteWithChat();
+ void confirmDeleteWithChat(deleteFilesOnDelete);
}}
>
{t("settings.voice.recents.deleteWithChat")}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index e2e1f42748a..40035a1b7ed 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -97,6 +97,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.chat.artifacts.collapseHtmlBlocks",
"settings.chat.artifacts.allowNetworkAccess",
"settings.chat.modelDisclaimer",
+ "settings.chat.projectsSection",
],
// Chat data management moved to the Data tab; keep these rows findable there.
data: [
@@ -104,6 +105,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.data.archivedChats",
"settings.data.archiveAllChats",
"settings.data.confirmBeforeDeleting",
+ "settings.data.alwaysDeleteFiles",
"settings.data.uploadedFiles",
"settings.chat.exportHistory",
"settings.chat.exportConversations",
diff --git a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
index 0aa52a956c2..1ef6916125c 100644
--- a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
+++ b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
@@ -114,8 +114,8 @@ export const SIDEBAR_NAV_DEFAULT_PINNED: Record<SidebarNavItemId, boolean> = {
hub: true,
projects: true,
images: true,
+ video: true,
// Under "More" until a user pins it.
- video: false,
audio: false,
train: true,
recipes: false,
@@ -125,7 +125,8 @@ export const SIDEBAR_NAV_DEFAULT_PINNED: Record<SidebarNavItemId, boolean> = {
/** Every previously shipped layout, so a migration can tell an untouched install from one the
* user arranged themselves. v3 pinned Video under Images; v4 moved Model hub above Projects;
- * v5 put Video back under "More" and later added API before Audio shipped. */
+ * v5 put Video back under "More" and later added API before Audio shipped; v6 added Audio;
+ * v7 pins Video under Images again. */
const SHIPPED_SIDEBAR_NAV_DEFAULTS: SidebarNavItemPref[][] = [
[
{ id: "projects", pinned: true },
@@ -164,6 +165,17 @@ const SHIPPED_SIDEBAR_NAV_DEFAULTS: SidebarNavItemPref[][] = [
{ id: "export", pinned: false },
{ id: "api", pinned: false },
],
+ [
+ { id: "hub", pinned: true },
+ { id: "projects", pinned: true },
+ { id: "images", pinned: true },
+ { id: "video", pinned: false },
+ { id: "audio", pinned: false },
+ { id: "train", pinned: true },
+ { id: "recipes", pinned: false },
+ { id: "export", pinned: false },
+ { id: "api", pinned: false },
+ ],
];
export const MAX_IMPORTED_FONTS = 3;
@@ -487,14 +499,14 @@ export const useAppearanceCustomStore = create<AppearanceCustomState>()(
}),
{
name: "unsloth_appearance_customization",
- version: 6,
+ version: 7,
storage: createJSONStorage(() => guardedLocalStorage),
migrate: (persisted, version) => {
const state = (persisted ?? {}) as Partial<AppearanceCustomState>;
const customization = migrateShippedSidebarNavDefault(
sanitizeCustomization(state.customization),
version,
- 6,
+ 7,
);
return { customization } as AppearanceCustomState;
},
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index ab0642f6445..931f8944c7e 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -7,6 +7,7 @@ import {
useChatPreferencesStore,
useChatRuntimeStore,
usePlusMenuPrefsStore,
+ useSidebarOrganizationStore,
} from "@/features/chat";
import { useUserProfileStore } from "@/features/profile";
import { type TranslationKey, useT } from "@/i18n";
@@ -161,6 +162,8 @@ export function ChatTab() {
const setShowAllQuantizations = useChatRuntimeStore(
(state) => state.setShowAllQuantizations,
);
+ const organizeBy = useSidebarOrganizationStore((s) => s.organizeBy);
+ const setOrganizeBy = useSidebarOrganizationStore((s) => s.setOrganizeBy);
const showModelDisclaimer = useChatPreferencesStore(
(state) => state.showModelDisclaimer,
);
@@ -242,6 +245,17 @@ export function ChatTab() {
</SettingsSection>
<SettingsSection title={t("settings.general.chatDefaults")}>
+ <SettingsRow
+ label={t("settings.chat.projectsSection")}
+ description={t("settings.chat.projectsSectionDescription")}
+ >
+ <Switch
+ checked={organizeBy === "project"}
+ onCheckedChange={(checked) =>
+ setOrganizeBy(checked ? "project" : "list")
+ }
+ />
+ </SettingsRow>
<SettingsRow
label={t("settings.chat.thinking.collapseByDefault")}
description={t("settings.chat.thinking.collapseByDefaultDescription")}
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index 1ed90977a24..6a417d1e568 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -30,6 +30,7 @@ import {
bulkExportConversationsByScope,
clearAllChats,
countAllChats,
+ DeleteChatFilesSwitch,
downloadArchivedChatExport,
downloadChatExport,
exportFineTuneJsonl,
@@ -96,6 +97,9 @@ export function DataTab() {
(s) => s.consumeArchivedChatsRequest,
);
const [confirmOpen, setConfirmOpen] = useState(false);
+ // Preselected from the preference, so the dialog shows what is about to
+ // happen and can still be turned off for this one clear.
+ const [deleteFilesOnClear, setDeleteFilesOnClear] = useState(false);
const [archiveConfirmOpen, setArchiveConfirmOpen] = useState(false);
// Subpages swap the Data tab body instead of opening nested dialogs.
const [subpage, setSubpage] = useState<
@@ -176,6 +180,12 @@ export function DataTab() {
const confirmDeleteChats = useChatPreferencesStore(
(state) => state.confirmDeleteChats,
);
+ const alwaysDeleteChatFiles = useChatPreferencesStore(
+ (state) => state.alwaysDeleteChatFiles,
+ );
+ const setAlwaysDeleteChatFiles = useChatPreferencesStore(
+ (state) => state.setAlwaysDeleteChatFiles,
+ );
const setConfirmDeleteChats = useChatPreferencesStore(
(state) => state.setConfirmDeleteChats,
);
@@ -405,9 +415,12 @@ export function DataTab() {
const handleClear = async () => {
setClearing(true);
try {
- const result = await clearAllChats();
+ const result = await clearAllChats({
+ deleteFiles: deleteFilesOnClear,
+ });
const clearedCount = result.deletedThreadIds.length;
- // Clear-all has no switch, so the same offer the sidebar makes.
+ // A sandbox the backend could not remove, asked for or not.
+ // After a clear there is no row left to reach it from.
offerToDeleteKeptSandboxes(result.sandboxesKept);
const hasFailedStore =
result.backend === "failed" || result.legacy === "failed";
@@ -720,6 +733,16 @@ export function DataTab() {
/>
</SettingsRow>
+ <SettingsRow
+ label={t("settings.data.alwaysDeleteFiles")}
+ description={t("settings.data.alwaysDeleteFilesDescription")}
+ >
+ <Switch
+ checked={alwaysDeleteChatFiles}
+ onCheckedChange={setAlwaysDeleteChatFiles}
+ />
+ </SettingsRow>
+
<SettingsRow
label={t("settings.chat.exportHistory")}
description={t("settings.chat.exportHistoryDescription")}
@@ -813,7 +836,10 @@ export function DataTab() {
<Button
variant="outline"
size="sm"
- onClick={() => setConfirmOpen(true)}
+ onClick={() => {
+ setDeleteFilesOnClear(alwaysDeleteChatFiles);
+ setConfirmOpen(true);
+ }}
disabled={count === 0}
className="text-destructive hover:text-destructive hover:border-destructive/60"
>
@@ -911,6 +937,13 @@ 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")}
+ />
<DialogFooter>
<Button variant="outline" onClick={() => setConfirmOpen(false)}>
{t("common.cancel")}
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index b9fd31178a4..6bb7f2ce851 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -12,7 +12,11 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
-import { PermissionModeDropdown, useChatRuntimeStore } from "@/features/chat";
+import {
+ PermissionModeDropdown,
+ SIDEBAR_ORGANIZATION_STORAGE_KEY,
+ useChatRuntimeStore,
+} from "@/features/chat";
import {
LOADED_MODELS_PREFERENCE_KEYS,
setShowLoadedModels,
@@ -89,6 +93,8 @@ const PREFS_KEYS: string[] = [
"sidebar_width",
"chat_settings_width",
"unsloth_sidebar_navigate_open",
+ // Grouping, sort and the manual row order.
+ SIDEBAR_ORGANIZATION_STORAGE_KEY,
"unsloth_settings_active_tab",
SETTINGS_PANEL_PREFS_STORAGE_KEY,
// Chat runtime prefs
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index d2cc1f18185..80f522fb15e 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -94,6 +94,8 @@ export const ar = {
export: "تصدير",
recents: "العناصر الأخيرة",
noChatsYet: "لا توجد محادثات بعد",
+ showMore: "عرض المزيد",
+ showLess: "عرض أقل",
settings: "الإعدادات",
api: "API",
lightMode: "الوضع الفاتح",
@@ -108,6 +110,44 @@ export const ar = {
description: "{path} غير موجود.",
backToChat: "العودة إلى المحادثة",
},
+ selection: {
+ pinProjects: "تثبيت المشاريع",
+ unpinProjects: "إلغاء تثبيت المشاريع",
+ deleteProjects: "حذف المشاريع",
+ deleteProjectsTitle: "حذف المشاريع",
+ deleteProjectsDescription:
+ "هل تريد حذف {count} مشاريع؟ ستُحذف محادثاتها نهائيًا.",
+ deleteProjectsFilesDescription:
+ "يُحذف مجلد مساحة عمل كل مشروع من القرص.",
+ countSelected: "{count} محددة",
+ pinChats: "تثبيت المحادثات",
+ unpinChats: "إلغاء تثبيت المحادثات",
+ archiveChats: "أرشفة المحادثات",
+ markUnread: "وضع علامة كغير مقروءة",
+ deleteChats: "حذف المحادثات",
+ deleteTitle: "حذف المحادثات",
+ deleteDescription: "هل تريد حذف {count} محادثة؟ لا يمكن التراجع عن ذلك.",
+ deleteFilesDescription:
+ "يُحذف مجلد بيئة العزل الخاص بكل محادثة من القرص. أما الملفات التي كتبتها داخل مشروع فتبقى في مساحة عمل ذلك المشروع.",
+ deleteFilesLabel: "حذف الملفات ومجلد بيئة العزل",
+ deleteChatFilesDescription:
+ "يُزال مجلد بيئة العزل الخاص بهذه المحادثة من القرص. أما الملفات التي كتبتها داخل مشروع فتبقى في مساحة عمل ذلك المشروع.",
+ },
+ organize: {
+ sidebarHeading: "تنظيم الشريط الجانبي",
+ byProject: "حسب المشروع",
+ inOneList: "في قائمة واحدة",
+ sortChatsBy: "ترتيب المحادثات حسب",
+ sortPinnedBy: "ترتيب المثبتة حسب",
+ priority: "الأولوية",
+ lastUpdated: "آخر تحديث",
+ manualOrder: "ترتيب يدوي",
+ moveUp: "تحريك لأعلى",
+ moveDown: "تحريك لأسفل",
+ organizeChats: "تنظيم المحادثات",
+ organizeProjects: "تنظيم المشاريع",
+ sortPinnedChats: "ترتيب المحادثات المثبتة",
+ },
dialog: {
deleteChat: {
title: "حذف المحادثة",
@@ -939,6 +979,9 @@ export const ar = {
},
},
chat: {
+ projectsSection: "إظهار قسم المشاريع",
+ projectsSectionDescription:
+ "يجمع محادثات المشروع تحت عنوان المشاريع. أوقف هذا الخيار لعرضها ضمن الأخيرة بدلاً من ذلك.",
title: "المحادثة",
description: "خصّص طريقة عمل المحادثة على هذا الجهاز.",
modelSelection: {
@@ -1078,6 +1121,9 @@ export const ar = {
confirmBeforeDeleting: "التأكيد قبل الحذف",
confirmBeforeDeletingDescription:
"يطلب تأكيدًا قبل حذف أي محادثة. عطّله للحذف الفوري.",
+ alwaysDeleteFiles: "حذف الملفات دائمًا",
+ alwaysDeleteFilesDescription:
+ "حذف المحادثة يزيل أيضًا مجلد بيئة العزل الخاص بها من القرص. أما الملفات التي كتبتها داخل مشروع فتبقى في مساحة عمل ذلك المشروع.",
filesSection: "الملفات",
uploadedFiles: "الملفات المرفوعة",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 4dd601478dc..e3ef379d15c 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -97,6 +97,8 @@ export const de = {
export: "Exportieren",
recents: "Zuletzt verwendet",
noChatsYet: "Noch keine Chats",
+ showMore: "Mehr anzeigen",
+ showLess: "Weniger anzeigen",
settings: "Einstellungen",
api: "API",
lightMode: "Heller Modus",
@@ -111,6 +113,44 @@ export const de = {
description: "{path} existiert nicht.",
backToChat: "Zurück zum Chat",
},
+ selection: {
+ pinProjects: "Projekte anheften",
+ unpinProjects: "Projekte lösen",
+ deleteProjects: "Projekte löschen",
+ deleteProjectsTitle: "Projekte löschen",
+ deleteProjectsDescription:
+ "{count} Projekte löschen? Ihre Chats werden dauerhaft gelöscht.",
+ deleteProjectsFilesDescription:
+ "Der Arbeitsbereich-Ordner jedes Projekts wird von der Festplatte entfernt.",
+ countSelected: "{count} ausgewählt",
+ pinChats: "Chats anheften",
+ unpinChats: "Chats lösen",
+ archiveChats: "Chats archivieren",
+ markUnread: "Als ungelesen markieren",
+ deleteChats: "Chats löschen",
+ deleteTitle: "Chats löschen",
+ deleteDescription: "{count} Chats löschen? Das lässt sich nicht rückgängig machen.",
+ deleteFilesDescription:
+ "Der eigene Sandbox-Ordner jedes Chats wird von der Festplatte entfernt. Dateien, die sie in einem Projekt erstellt haben, bleiben im Arbeitsbereich dieses Projekts.",
+ deleteFilesLabel: "Dateien und Sandbox-Ordner löschen",
+ deleteChatFilesDescription:
+ "Der eigene Sandbox-Ordner dieses Chats wird von der Festplatte entfernt. Dateien, die er in einem Projekt geschrieben hat, bleiben im Arbeitsbereich des Projekts.",
+ },
+ organize: {
+ sidebarHeading: "Seitenleiste organisieren",
+ byProject: "Nach Projekt",
+ inOneList: "In einer Liste",
+ sortChatsBy: "Chats sortieren nach",
+ sortPinnedBy: "Angeheftete sortieren nach",
+ priority: "Priorität",
+ lastUpdated: "Zuletzt aktualisiert",
+ manualOrder: "Manuelle Reihenfolge",
+ moveUp: "Nach oben",
+ moveDown: "Nach unten",
+ organizeChats: "Chats organisieren",
+ organizeProjects: "Projekte organisieren",
+ sortPinnedChats: "Angeheftete Chats sortieren",
+ },
dialog: {
deleteChat: {
title: "Chat löschen",
@@ -974,6 +1014,9 @@ export const de = {
},
},
chat: {
+ projectsSection: "Projektbereich anzeigen",
+ projectsSectionDescription:
+ "Gruppiert Projekt-Chats unter einer Überschrift für Projekte. Deaktiviere dies, um sie stattdessen unter den zuletzt verwendeten Chats aufzulisten.",
title: "Chat",
description: "Passen Sie an, wie sich der Chat auf diesem Gerät verhält.",
modelSelection: {
@@ -1117,6 +1160,9 @@ export const de = {
confirmBeforeDeleting: "Vor dem Löschen bestätigen",
confirmBeforeDeletingDescription:
"Fragt vor dem Löschen eines Chats nach einer Bestätigung. Deaktivieren, um sofort zu löschen.",
+ 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.",
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 f7a76d59658..6b30ec93a4e 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -92,6 +92,8 @@ export const en = {
export: "Export",
recents: "Recents",
noChatsYet: "No chats yet",
+ showMore: "Show more",
+ showLess: "Show less",
settings: "Settings",
api: "API",
lightMode: "Light Mode",
@@ -106,6 +108,46 @@ export const en = {
description: "{path} does not exist.",
backToChat: "Back to chat",
},
+ // Bulk actions on a multi-row selection.
+ selection: {
+ pinProjects: "Pin projects",
+ unpinProjects: "Unpin projects",
+ deleteProjects: "Delete projects",
+ deleteProjectsTitle: "Delete projects",
+ deleteProjectsDescription:
+ "Delete {count} projects? Their chats are permanently deleted.",
+ deleteProjectsFilesDescription:
+ "Each project workspace folder is removed from disk.",
+ countSelected: "{count} selected",
+ pinChats: "Pin chats",
+ unpinChats: "Unpin chats",
+ archiveChats: "Archive chats",
+ markUnread: "Mark as unread",
+ deleteChats: "Delete chats",
+ deleteTitle: "Delete chats",
+ deleteDescription: "Delete {count} chats? This cannot be undone.",
+ deleteFilesDescription:
+ "Each chat's own sandbox folder is removed from disk. Files they wrote inside a project stay in that project's workspace.",
+ deleteFilesLabel: "Delete files and sandbox folder",
+ deleteChatFilesDescription:
+ "This chat's own sandbox folder is removed from disk. Files it wrote inside a project stay in that project's workspace.",
+ },
+ // Sidebar list headers: how chats are grouped and ordered.
+ organize: {
+ sidebarHeading: "Organize sidebar",
+ byProject: "By project",
+ inOneList: "In one list",
+ sortChatsBy: "Sort chats by",
+ sortPinnedBy: "Sort pinned by",
+ priority: "Priority",
+ lastUpdated: "Last updated",
+ manualOrder: "Manual order",
+ moveUp: "Move up",
+ moveDown: "Move down",
+ organizeChats: "Organize chats",
+ organizeProjects: "Organize projects",
+ sortPinnedChats: "Sort pinned chats",
+ },
dialog: {
deleteChat: {
title: "Delete chat",
@@ -933,6 +975,9 @@ export const en = {
},
},
chat: {
+ projectsSection: "Show projects section",
+ projectsSectionDescription:
+ "Group project chats under a Projects heading. Turn this off to list them in Recents instead.",
title: "Chat",
description: "Customize how chat behaves on this device.",
modelSelection: {
@@ -1070,6 +1115,9 @@ export const en = {
confirmBeforeDeleting: "Confirm before deleting",
confirmBeforeDeletingDescription:
"Ask for confirmation before a chat is deleted. Turn off to delete instantly.",
+ 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.",
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 ee2c70b7cbf..daeeca4d132 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -96,6 +96,8 @@ export const es = {
export: "Exportar",
recents: "Recientes",
noChatsYet: "Aún no hay chats",
+ showMore: "Mostrar más",
+ showLess: "Mostrar menos",
settings: "Configuración",
api: "API",
lightMode: "Modo claro",
@@ -110,6 +112,44 @@ export const es = {
description: "{path} no existe.",
backToChat: "Volver al chat",
},
+ selection: {
+ pinProjects: "Fijar proyectos",
+ unpinProjects: "Dejar de fijar proyectos",
+ deleteProjects: "Eliminar proyectos",
+ deleteProjectsTitle: "Eliminar proyectos",
+ deleteProjectsDescription:
+ "¿Eliminar {count} proyectos? Sus chats se eliminan de forma permanente.",
+ deleteProjectsFilesDescription:
+ "La carpeta del espacio de trabajo de cada proyecto se elimina del disco.",
+ countSelected: "{count} seleccionados",
+ pinChats: "Fijar chats",
+ unpinChats: "Dejar de fijar chats",
+ archiveChats: "Archivar chats",
+ markUnread: "Marcar como no leído",
+ deleteChats: "Eliminar chats",
+ deleteTitle: "Eliminar chats",
+ deleteDescription: "¿Eliminar {count} chats? Esta acción no se puede deshacer.",
+ deleteFilesDescription:
+ "Se elimina del disco la carpeta de entorno aislado de cada chat. Los archivos que hayan escrito dentro de un proyecto permanecen en el espacio de trabajo de ese proyecto.",
+ deleteFilesLabel: "Eliminar archivos y carpeta de espacio aislado",
+ deleteChatFilesDescription:
+ "La carpeta de espacio aislado propia de este chat se elimina del disco. Los archivos que escribió dentro de un proyecto permanecen en el espacio de trabajo de ese proyecto.",
+ },
+ organize: {
+ sidebarHeading: "Organizar la barra lateral",
+ byProject: "Por proyecto",
+ inOneList: "En una sola lista",
+ sortChatsBy: "Ordenar chats por",
+ sortPinnedBy: "Ordenar fijados por",
+ priority: "Prioridad",
+ lastUpdated: "Última actualización",
+ manualOrder: "Orden manual",
+ moveUp: "Subir",
+ moveDown: "Bajar",
+ organizeChats: "Organizar chats",
+ organizeProjects: "Organizar proyectos",
+ sortPinnedChats: "Ordenar chats fijados",
+ },
dialog: {
deleteChat: {
title: "Eliminar chat",
@@ -965,6 +1005,9 @@ export const es = {
},
},
chat: {
+ projectsSection: "Mostrar la sección Proyectos",
+ projectsSectionDescription:
+ "Agrupa los chats de proyecto bajo un encabezado Proyectos. Desactívalo para listarlos en Recientes.",
title: "Chat",
description: "Personaliza cómo funciona el chat en este dispositivo.",
modelSelection: {
@@ -1107,6 +1150,9 @@ export const es = {
confirmBeforeDeleting: "Confirmar antes de eliminar",
confirmBeforeDeletingDescription:
"Pide confirmación antes de eliminar un chat. Desactívalo para eliminar los chats al instante.",
+ 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.",
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 115dbcbdcdd..8caddadb47f 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -97,6 +97,8 @@ export const fr = {
export: "Exporter",
recents: "Discussions récentes",
noChatsYet: "Aucune discussion pour le moment",
+ showMore: "Afficher plus",
+ showLess: "Afficher moins",
settings: "Paramètres",
api: "API",
lightMode: "Mode clair",
@@ -111,6 +113,44 @@ export const fr = {
description: "{path} n'existe pas.",
backToChat: "Retour à la discussion",
},
+ selection: {
+ pinProjects: "Épingler les projets",
+ unpinProjects: "Détacher les projets",
+ deleteProjects: "Supprimer les projets",
+ deleteProjectsTitle: "Supprimer les projets",
+ deleteProjectsDescription:
+ "Supprimer {count} projets ? Leurs discussions seront supprimées définitivement.",
+ deleteProjectsFilesDescription:
+ "Le dossier de travail de chaque projet est retiré du disque.",
+ countSelected: "{count} sélectionnés",
+ pinChats: "Épingler les discussions",
+ unpinChats: "Détacher les discussions",
+ archiveChats: "Archiver les discussions",
+ markUnread: "Marquer comme non lu",
+ deleteChats: "Supprimer les discussions",
+ deleteTitle: "Supprimer les discussions",
+ deleteDescription: "Supprimer {count} discussions ? Cette action est irréversible.",
+ deleteFilesDescription:
+ "Le dossier bac à sable propre à chaque discussion est supprimé du disque. Les fichiers écrits dans un projet restent dans l'espace de travail de ce projet.",
+ deleteFilesLabel: "Supprimer les fichiers et le dossier bac à sable",
+ deleteChatFilesDescription:
+ "Le dossier bac à sable propre à cette discussion est retiré du disque. Les fichiers écrits dans un projet restent dans l'espace de travail du projet.",
+ },
+ organize: {
+ sidebarHeading: "Organiser la barre latérale",
+ byProject: "Par projet",
+ inOneList: "Dans une seule liste",
+ sortChatsBy: "Trier les discussions par",
+ sortPinnedBy: "Trier les épinglés par",
+ priority: "Priorité",
+ lastUpdated: "Dernière mise à jour",
+ manualOrder: "Ordre manuel",
+ moveUp: "Monter",
+ moveDown: "Descendre",
+ organizeChats: "Organiser les discussions",
+ organizeProjects: "Organiser les projets",
+ sortPinnedChats: "Trier les discussions épinglées",
+ },
dialog: {
deleteChat: {
title: "Supprimer la discussion",
@@ -971,6 +1011,9 @@ export const fr = {
},
},
chat: {
+ projectsSection: "Afficher la section Projets",
+ projectsSectionDescription:
+ "Regroupe les discussions de projet sous un titre Projets. Désactivez cette option pour les lister dans Récents.",
title: "Discussion",
description: "Personnalisez le fonctionnement du chat sur cet appareil.",
modelSelection: {
@@ -1115,6 +1158,9 @@ export const fr = {
confirmBeforeDeleting: "Confirmer avant de supprimer",
confirmBeforeDeletingDescription:
"Demande une confirmation avant de supprimer une discussion. Désactivez cette option pour supprimer immédiatement.",
+ 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.",
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 32f4c892827..1655f41c716 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -97,6 +97,8 @@ export const hi = {
export: "एक्सपोर्ट",
recents: "हाल के",
noChatsYet: "अभी तक कोई चैट नहीं",
+ showMore: "और दिखाएं",
+ showLess: "कम दिखाएं",
settings: "सेटिंग्स",
api: "API",
lightMode: "लाइट मोड",
@@ -111,6 +113,44 @@ export const hi = {
description: "{path} मौजूद नहीं है।",
backToChat: "चैट पर वापस जाएँ",
},
+ selection: {
+ pinProjects: "प्रोजेक्ट पिन करें",
+ unpinProjects: "प्रोजेक्ट अनपिन करें",
+ deleteProjects: "प्रोजेक्ट हटाएँ",
+ deleteProjectsTitle: "प्रोजेक्ट हटाएँ",
+ deleteProjectsDescription:
+ "{count} प्रोजेक्ट हटाएँ? उनकी चैट स्थायी रूप से हट जाएँगी।",
+ deleteProjectsFilesDescription:
+ "हर प्रोजेक्ट का कार्यक्षेत्र फ़ोल्डर डिस्क से हटा दिया जाता है।",
+ countSelected: "{count} चुने गए",
+ pinChats: "चैट पिन करें",
+ unpinChats: "चैट अनपिन करें",
+ archiveChats: "चैट संग्रहित करें",
+ markUnread: "अपठित के रूप में चिह्नित करें",
+ deleteChats: "चैट हटाएँ",
+ deleteTitle: "चैट हटाएँ",
+ deleteDescription: "{count} चैट हटाएँ? इसे पूर्ववत नहीं किया जा सकता।",
+ deleteFilesDescription:
+ "हर चैट का अपना सैंडबॉक्स फ़ोल्डर डिस्क से हटा दिया जाता है। किसी प्रोजेक्ट के अंदर लिखी गई फ़ाइलें उस प्रोजेक्ट के कार्यक्षेत्र में बनी रहती हैं।",
+ deleteFilesLabel: "फ़ाइलें और सैंडबॉक्स फ़ोल्डर हटाएं",
+ deleteChatFilesDescription:
+ "इस चैट का अपना सैंडबॉक्स फ़ोल्डर डिस्क से हटा दिया जाता है। किसी प्रोजेक्ट के अंदर लिखी गई फ़ाइलें उस प्रोजेक्ट के कार्यक्षेत्र में बनी रहती हैं।",
+ },
+ organize: {
+ sidebarHeading: "साइडबार व्यवस्थित करें",
+ byProject: "प्रोजेक्ट के अनुसार",
+ inOneList: "एक ही सूची में",
+ sortChatsBy: "चैट क्रमबद्ध करें",
+ sortPinnedBy: "पिन किए गए क्रमबद्ध करें",
+ priority: "प्राथमिकता",
+ lastUpdated: "अंतिम अपडेट",
+ manualOrder: "मैन्युअल क्रम",
+ moveUp: "ऊपर ले जाएँ",
+ moveDown: "नीचे ले जाएँ",
+ organizeChats: "चैट व्यवस्थित करें",
+ organizeProjects: "प्रोजेक्ट व्यवस्थित करें",
+ sortPinnedChats: "पिन की गई चैट क्रमबद्ध करें",
+ },
dialog: {
deleteChat: {
title: "चैट हटाएँ",
@@ -945,6 +985,9 @@ export const hi = {
},
},
chat: {
+ projectsSection: "प्रोजेक्ट अनुभाग दिखाएँ",
+ projectsSectionDescription:
+ "प्रोजेक्ट चैट को प्रोजेक्ट शीर्षक के नीचे समूहित करता है। बंद करने पर वे हाल ही के अंतर्गत दिखती हैं।",
title: "चैट",
description: "इस डिवाइस पर चैट के व्यवहार को अपनी पसंद के अनुसार बदलें।",
modelSelection: {
@@ -1084,6 +1127,9 @@ export const hi = {
confirmBeforeDeleting: "हटाने से पहले पुष्टि करें",
confirmBeforeDeletingDescription:
"चैट हटाने से पहले पुष्टि मांगता है। तुरंत हटाने के लिए इसे बंद करें।",
+ alwaysDeleteFiles: "फ़ाइलें हमेशा हटाएँ",
+ alwaysDeleteFilesDescription:
+ "चैट हटाने पर उसका अपना सैंडबॉक्स फ़ोल्डर भी डिस्क से हट जाता है। किसी प्रोजेक्ट के अंदर लिखी गई फ़ाइलें उस प्रोजेक्ट के कार्यक्षेत्र में बनी रहती हैं।",
filesSection: "फ़ाइलें",
uploadedFiles: "अपलोड की गई फ़ाइलें",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index f8a43db2570..38a4d47b3b2 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -61,6 +61,8 @@ export const it = {
export: "Esporta",
recents: "Recenti",
noChatsYet: "Ancora nessuna chat",
+ showMore: "Mostra altro",
+ showLess: "Mostra meno",
settings: "Impostazioni",
api: "API",
lightMode: "Tema chiaro",
@@ -75,6 +77,44 @@ export const it = {
description: "{path} non esiste.",
backToChat: "Torna alla chat",
},
+ selection: {
+ pinProjects: "Fissa i progetti",
+ unpinProjects: "Rimuovi i progetti fissati",
+ deleteProjects: "Elimina i progetti",
+ deleteProjectsTitle: "Elimina i progetti",
+ deleteProjectsDescription:
+ "Eliminare {count} progetti? Le loro chat vengono eliminate definitivamente.",
+ deleteProjectsFilesDescription:
+ "La cartella dello spazio di lavoro di ogni progetto viene rimossa dal disco.",
+ countSelected: "{count} selezionate",
+ pinChats: "Fissa le chat",
+ unpinChats: "Rimuovi le chat fissate",
+ archiveChats: "Archivia le chat",
+ markUnread: "Segna come non letta",
+ deleteChats: "Elimina le chat",
+ deleteTitle: "Elimina le chat",
+ deleteDescription: "Eliminare {count} chat? L'operazione non è reversibile.",
+ deleteFilesDescription:
+ "La cartella sandbox di ogni chat viene rimossa dal disco. I file scritti dentro un progetto restano nello spazio di lavoro di quel progetto.",
+ deleteFilesLabel: "Elimina i file e la cartella sandbox",
+ deleteChatFilesDescription:
+ "La cartella sandbox di questa chat viene rimossa dal disco. I file scritti all'interno di un progetto restano nello spazio di lavoro del progetto.",
+ },
+ organize: {
+ sidebarHeading: "Organizza la barra laterale",
+ byProject: "Per progetto",
+ inOneList: "In un solo elenco",
+ sortChatsBy: "Ordina le chat per",
+ sortPinnedBy: "Ordina i fissati per",
+ priority: "Priorità",
+ lastUpdated: "Ultimo aggiornamento",
+ manualOrder: "Ordine manuale",
+ moveUp: "Sposta su",
+ moveDown: "Sposta giù",
+ organizeChats: "Organizza le chat",
+ organizeProjects: "Organizza i progetti",
+ sortPinnedChats: "Ordina le chat fissate",
+ },
dialog: {
deleteChat: {
title: "Elimina la chat",
@@ -938,6 +978,9 @@ export const it = {
},
},
chat: {
+ projectsSection: "Mostra la sezione Progetti",
+ projectsSectionDescription:
+ "Raggruppa le chat di progetto sotto un titolo Progetti. Disattivalo per elencarle in Recenti.",
title: "Chat",
description:
"Personalizza il comportamento della chat su questo dispositivo.",
@@ -1080,6 +1123,9 @@ export const it = {
confirmBeforeDeleting: "Chiedi conferma prima di eliminare",
confirmBeforeDeletingDescription:
"Richiedi una conferma prima di eliminare una chat. Disattiva l'opzione per eliminarla subito.",
+ 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.",
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 582eff7c1f3..61fbed697aa 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -96,6 +96,8 @@ export const ja = {
export: "エクスポート",
recents: "履歴",
noChatsYet: "チャットがまだありません",
+ showMore: "もっと見る",
+ showLess: "表示を減らす",
settings: "設定",
api: "API",
lightMode: "ライトモード",
@@ -110,6 +112,44 @@ export const ja = {
description: "{path} は存在しません。",
backToChat: "チャットに戻る",
},
+ selection: {
+ pinProjects: "プロジェクトをピン留め",
+ unpinProjects: "ピン留めを解除",
+ deleteProjects: "プロジェクトを削除",
+ deleteProjectsTitle: "プロジェクトを削除",
+ deleteProjectsDescription:
+ "{count} 件のプロジェクトを削除しますか。含まれるチャットは完全に削除されます。",
+ deleteProjectsFilesDescription:
+ "各プロジェクトのワークスペースフォルダーがディスクから削除されます。",
+ countSelected: "{count} 件選択中",
+ pinChats: "チャットをピン留め",
+ unpinChats: "ピン留めを解除",
+ archiveChats: "チャットをアーカイブ",
+ markUnread: "未読にする",
+ deleteChats: "チャットを削除",
+ deleteTitle: "チャットを削除",
+ deleteDescription: "{count} 件のチャットを削除しますか。元に戻せません。",
+ deleteFilesDescription:
+ "各チャット専用のサンドボックスフォルダーがディスクから削除されます。プロジェクト内で作成したファイルは、そのプロジェクトのワークスペースに残ります。",
+ deleteFilesLabel: "ファイルとサンドボックスフォルダーを削除",
+ deleteChatFilesDescription:
+ "このチャット専用のサンドボックスフォルダーがディスクから削除されます。プロジェクト内に書き込んだファイルは、そのプロジェクトのワークスペースに残ります。",
+ },
+ organize: {
+ sidebarHeading: "サイドバーの整理",
+ byProject: "プロジェクト別",
+ inOneList: "1つのリストで",
+ sortChatsBy: "チャットの並び順",
+ sortPinnedBy: "ピン留めの並び順",
+ priority: "優先度",
+ lastUpdated: "最終更新",
+ manualOrder: "手動で並べ替え",
+ moveUp: "上へ移動",
+ moveDown: "下へ移動",
+ organizeChats: "チャットを整理",
+ organizeProjects: "プロジェクトを整理",
+ sortPinnedChats: "ピン留めチャットを並べ替え",
+ },
dialog: {
deleteChat: {
title: "チャットの削除",
@@ -928,6 +968,9 @@ export const ja = {
},
},
chat: {
+ projectsSection: "プロジェクトセクションを表示",
+ projectsSectionDescription:
+ "プロジェクトのチャットを「プロジェクト」の見出しにまとめます。オフにすると「最近」に表示されます。",
title: "チャット",
description: "このデバイスでのチャットの動作をカスタマイズします。",
modelSelection: {
@@ -1056,6 +1099,9 @@ export const ja = {
confirmBeforeDeleting: "削除前に確認する",
confirmBeforeDeletingDescription:
"チャットを削除する前に確認を求めます。オフにすると即座に削除します。",
+ alwaysDeleteFiles: "常にファイルを削除",
+ alwaysDeleteFilesDescription:
+ "チャットを削除すると、そのチャット専用のサンドボックスフォルダーもディスクから削除されます。プロジェクト内で作成したファイルは、そのプロジェクトのワークスペースに残ります。",
filesSection: "ファイル",
uploadedFiles: "アップロード済みファイル",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index c5d10b3335d..17f6ffac921 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -94,6 +94,8 @@ export const ko = {
export: "내보내기",
recents: "최근 항목",
noChatsYet: "아직 채팅이 없습니다",
+ showMore: "더 보기",
+ showLess: "간략히 보기",
settings: "설정",
api: "API",
lightMode: "라이트 모드",
@@ -108,6 +110,44 @@ export const ko = {
description: "{path} 경로가 존재하지 않습니다.",
backToChat: "채팅으로 돌아가기",
},
+ selection: {
+ pinProjects: "프로젝트 고정",
+ unpinProjects: "프로젝트 고정 해제",
+ deleteProjects: "프로젝트 삭제",
+ deleteProjectsTitle: "프로젝트 삭제",
+ deleteProjectsDescription:
+ "프로젝트 {count}개를 삭제할까요? 포함된 채팅이 영구히 삭제됩니다.",
+ deleteProjectsFilesDescription:
+ "각 프로젝트의 작업 공간 폴더가 디스크에서 삭제됩니다.",
+ countSelected: "{count}개 선택됨",
+ pinChats: "채팅 고정",
+ unpinChats: "채팅 고정 해제",
+ archiveChats: "채팅 보관",
+ markUnread: "읽지 않음으로 표시",
+ deleteChats: "채팅 삭제",
+ deleteTitle: "채팅 삭제",
+ deleteDescription: "채팅 {count}개를 삭제할까요? 되돌릴 수 없습니다.",
+ deleteFilesDescription:
+ "각 채팅 전용 샌드박스 폴더가 디스크에서 삭제됩니다. 프로젝트 안에서 만든 파일은 해당 프로젝트 작업 공간에 남습니다.",
+ deleteFilesLabel: "파일 및 샌드박스 폴더 삭제",
+ deleteChatFilesDescription:
+ "이 채팅 전용 샌드박스 폴더가 디스크에서 제거됩니다. 프로젝트 안에 기록한 파일은 해당 프로젝트 작업 공간에 남습니다.",
+ },
+ organize: {
+ sidebarHeading: "사이드바 정리",
+ byProject: "프로젝트별",
+ inOneList: "하나의 목록으로",
+ sortChatsBy: "채팅 정렬 기준",
+ sortPinnedBy: "고정됨 정렬 기준",
+ priority: "우선순위",
+ lastUpdated: "최근 업데이트",
+ manualOrder: "수동 정렬",
+ moveUp: "위로 이동",
+ moveDown: "아래로 이동",
+ organizeChats: "채팅 정리",
+ organizeProjects: "프로젝트 정리",
+ sortPinnedChats: "고정된 채팅 정렬",
+ },
dialog: {
deleteChat: {
title: "채팅 삭제",
@@ -937,6 +977,9 @@ export const ko = {
},
},
chat: {
+ projectsSection: "프로젝트 섹션 표시",
+ projectsSectionDescription:
+ "프로젝트 채팅을 프로젝트 제목 아래에 모읍니다. 끄면 최근 항목에 표시됩니다.",
title: "채팅",
description: "이 기기에서 채팅이 작동하는 방식을 사용자 지정합니다.",
modelSelection: {
@@ -1076,6 +1119,9 @@ export const ko = {
confirmBeforeDeleting: "삭제 전 확인",
confirmBeforeDeletingDescription:
"채팅을 삭제하기 전에 확인을 요청합니다. 끄면 즉시 삭제합니다.",
+ alwaysDeleteFiles: "항상 파일 삭제",
+ alwaysDeleteFilesDescription:
+ "채팅을 삭제하면 해당 채팅 전용 샌드박스 폴더도 디스크에서 삭제됩니다. 프로젝트 안에서 만든 파일은 해당 프로젝트 작업 공간에 남습니다.",
filesSection: "파일",
uploadedFiles: "업로드한 파일",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index e9a4573fcc5..ffa911820a5 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -96,6 +96,8 @@ export const ptBR = {
export: "Exportar",
recents: "Recentes",
noChatsYet: "Nenhum chat ainda",
+ showMore: "Mostrar mais",
+ showLess: "Mostrar menos",
settings: "Configurações",
api: "API",
lightMode: "Modo claro",
@@ -110,6 +112,44 @@ export const ptBR = {
description: "{path} não existe.",
backToChat: "Voltar para o chat",
},
+ selection: {
+ pinProjects: "Fixar projetos",
+ unpinProjects: "Desafixar projetos",
+ deleteProjects: "Excluir projetos",
+ deleteProjectsTitle: "Excluir projetos",
+ deleteProjectsDescription:
+ "Excluir {count} projetos? As conversas deles são excluídas permanentemente.",
+ deleteProjectsFilesDescription:
+ "A pasta do espaço de trabalho de cada projeto é removida do disco.",
+ countSelected: "{count} selecionadas",
+ pinChats: "Fixar conversas",
+ unpinChats: "Desafixar conversas",
+ archiveChats: "Arquivar conversas",
+ markUnread: "Marcar como não lida",
+ deleteChats: "Excluir conversas",
+ deleteTitle: "Excluir conversas",
+ deleteDescription: "Excluir {count} conversas? Esta ação não pode ser desfeita.",
+ deleteFilesDescription:
+ "A pasta de sandbox de cada conversa é removida do disco. Os arquivos escritos dentro de um projeto permanecem no espaço de trabalho desse projeto.",
+ deleteFilesLabel: "Excluir arquivos e pasta de sandbox",
+ deleteChatFilesDescription:
+ "A pasta de sandbox deste chat é removida do disco. Os arquivos que ele gravou dentro de um projeto permanecem no espaço de trabalho do projeto.",
+ },
+ organize: {
+ sidebarHeading: "Organizar a barra lateral",
+ byProject: "Por projeto",
+ inOneList: "Em uma lista",
+ sortChatsBy: "Ordenar conversas por",
+ sortPinnedBy: "Ordenar fixadas por",
+ priority: "Prioridade",
+ lastUpdated: "Última atualização",
+ manualOrder: "Ordem manual",
+ moveUp: "Mover para cima",
+ moveDown: "Mover para baixo",
+ organizeChats: "Organizar conversas",
+ organizeProjects: "Organizar projetos",
+ sortPinnedChats: "Ordenar conversas fixadas",
+ },
dialog: {
deleteChat: {
title: "Excluir chat",
@@ -953,6 +993,9 @@ export const ptBR = {
},
},
chat: {
+ projectsSection: "Mostrar a seção Projetos",
+ projectsSectionDescription:
+ "Agrupa as conversas de projeto sob um título Projetos. Desative para listá-las em Recentes.",
title: "Chat",
description: "Personalize o funcionamento do chat neste dispositivo.",
modelSelection: {
@@ -1091,6 +1134,9 @@ export const ptBR = {
confirmBeforeDeleting: "Confirmar antes de excluir",
confirmBeforeDeletingDescription:
"Pede confirmação antes de excluir um chat. Desative para excluir imediatamente.",
+ 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.",
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 1a62398101a..461ca38e10c 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -96,6 +96,8 @@ export const ru = {
export: "Экспорт",
recents: "Недавние",
noChatsYet: "Пока нет чатов",
+ showMore: "Показать больше",
+ showLess: "Показать меньше",
settings: "Настройки",
api: "API",
lightMode: "Светлая тема",
@@ -110,6 +112,44 @@ export const ru = {
description: "{path} не существует.",
backToChat: "Вернуться к чату",
},
+ selection: {
+ pinProjects: "Закрепить проекты",
+ unpinProjects: "Открепить проекты",
+ deleteProjects: "Удалить проекты",
+ deleteProjectsTitle: "Удалить проекты",
+ deleteProjectsDescription:
+ "Удалить проекты ({count})? Их чаты будут удалены безвозвратно.",
+ deleteProjectsFilesDescription:
+ "Рабочая папка каждого проекта удаляется с диска.",
+ countSelected: "Выбрано: {count}",
+ pinChats: "Закрепить чаты",
+ unpinChats: "Открепить чаты",
+ archiveChats: "Архивировать чаты",
+ markUnread: "Отметить как непрочитанное",
+ deleteChats: "Удалить чаты",
+ deleteTitle: "Удалить чаты",
+ deleteDescription: "Удалить чаты ({count})? Это действие необратимо.",
+ deleteFilesDescription:
+ "Собственная папка песочницы каждого чата удаляется с диска. Файлы, созданные внутри проекта, остаются в рабочей папке этого проекта.",
+ deleteFilesLabel: "Удалить файлы и папку песочницы",
+ deleteChatFilesDescription:
+ "Собственная папка песочницы этого чата удаляется с диска. Файлы, записанные им внутри проекта, остаются в рабочей области проекта.",
+ },
+ organize: {
+ sidebarHeading: "Настроить боковую панель",
+ byProject: "По проектам",
+ inOneList: "Одним списком",
+ sortChatsBy: "Сортировать чаты по",
+ sortPinnedBy: "Сортировать закреплённые по",
+ priority: "Приоритету",
+ lastUpdated: "Последнему обновлению",
+ manualOrder: "Вручную",
+ moveUp: "Переместить вверх",
+ moveDown: "Переместить вниз",
+ organizeChats: "Настроить чаты",
+ organizeProjects: "Настроить проекты",
+ sortPinnedChats: "Сортировать закреплённые чаты",
+ },
dialog: {
deleteChat: {
title: "Удалить чат",
@@ -950,6 +990,9 @@ export const ru = {
},
},
chat: {
+ projectsSection: "Показывать раздел «Проекты»",
+ projectsSectionDescription:
+ "Группирует чаты проектов под заголовком «Проекты». Отключите, чтобы они отображались в «Недавних».",
title: "Чат",
description: "Настройка поведения чата на этом устройстве.",
modelSelection: {
@@ -1088,6 +1131,9 @@ export const ru = {
confirmBeforeDeleting: "Подтверждать перед удалением",
confirmBeforeDeletingDescription:
"Запрашивает подтверждение перед удалением чата. Отключите, чтобы удалять сразу.",
+ alwaysDeleteFiles: "Всегда удалять файлы",
+ alwaysDeleteFilesDescription:
+ "При удалении чата с диска удаляется и его собственная папка песочницы. Файлы, созданные внутри проекта, остаются в рабочей папке этого проекта.",
filesSection: "Файлы",
uploadedFiles: "Загруженные файлы",
uploadedFilesDescription:
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index cbf9ef61581..5ee67cbf4d5 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -92,6 +92,8 @@ export const zhCN = {
export: "导出",
recents: "最近",
noChatsYet: "暂无对话",
+ showMore: "显示更多",
+ showLess: "显示更少",
settings: "设置",
api: "API",
lightMode: "浅色模式",
@@ -106,6 +108,44 @@ export const zhCN = {
description: "{path} 不存在。",
backToChat: "返回聊天",
},
+ selection: {
+ pinProjects: "置顶项目",
+ unpinProjects: "取消置顶项目",
+ deleteProjects: "删除项目",
+ deleteProjectsTitle: "删除项目",
+ deleteProjectsDescription:
+ "删除 {count} 个项目?其中的对话将被永久删除。",
+ deleteProjectsFilesDescription:
+ "每个项目的工作区文件夹会从磁盘中删除。",
+ countSelected: "已选择 {count} 个",
+ pinChats: "置顶对话",
+ unpinChats: "取消置顶",
+ archiveChats: "归档对话",
+ markUnread: "标记为未读",
+ deleteChats: "删除对话",
+ deleteTitle: "删除对话",
+ deleteDescription: "删除 {count} 个对话?此操作无法撤销。",
+ deleteFilesDescription:
+ "每个对话自己的沙盒文件夹会从磁盘中删除。它们在项目内写入的文件仍保留在该项目的工作区中。",
+ deleteFilesLabel: "删除文件和沙盒文件夹",
+ deleteChatFilesDescription:
+ "此对话自己的沙盒文件夹将从磁盘中移除。它在项目中写入的文件仍保留在该项目的工作区内。",
+ },
+ organize: {
+ sidebarHeading: "整理侧边栏",
+ byProject: "按项目",
+ inOneList: "合并为一个列表",
+ sortChatsBy: "对话排序方式",
+ sortPinnedBy: "置顶排序方式",
+ priority: "优先级",
+ lastUpdated: "最近更新",
+ manualOrder: "手动排序",
+ moveUp: "上移",
+ moveDown: "下移",
+ organizeChats: "整理对话",
+ organizeProjects: "整理项目",
+ sortPinnedChats: "对置顶对话排序",
+ },
dialog: {
deleteChat: {
title: "删除聊天",
@@ -915,6 +955,9 @@ export const zhCN = {
},
},
chat: {
+ projectsSection: "显示项目分区",
+ projectsSectionDescription:
+ "将项目对话归到「项目」标题下。关闭后改为显示在「最近」中。",
title: "聊天",
description: "自定义此设备上的聊天行为。",
modelSelection: {
@@ -1047,6 +1090,9 @@ export const zhCN = {
confirmBeforeDeleting: "删除前确认",
confirmBeforeDeletingDescription:
"删除聊天前先询问确认。关闭后将立即删除。",
+ alwaysDeleteFiles: "始终删除文件",
+ alwaysDeleteFilesDescription:
+ "删除对话时,同时从磁盘中删除它自己的沙盒文件夹。它在项目内写入的文件仍保留在该项目的工作区中。",
filesSection: "文件",
uploadedFiles: "上传的文件",
uploadedFilesDescription: "查看和管理上传到聊天、项目和知识库的文件。",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 684a7aea8aa..1327fcf84b2 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -1096,11 +1096,20 @@ html[data-chat-font] .aui-root {
color: #fff !important;
}
+ /* Multi-select: the same fill a hovered or active row gets, no outline. */
+ .sidebar-nav-btn[data-selected="true"] {
+ background-color: var(--nav-surface-hover) !important;
+ color: #000 !important;
+ }
+ .dark .sidebar-nav-btn[data-selected="true"] {
+ color: #fff !important;
+ }
+
.sidebar-row-action {
@apply absolute top-0 bottom-0 right-0 inline-flex cursor-pointer items-center justify-end pl-2 pr-1.5 opacity-0 pointer-events-none outline-none;
}
@media (pointer: coarse) {
- /* Only chat rows reserve touch padding (#7276); other rows stay hover-revealed to avoid clipped labels. */
+ /* Chat and project rows reserve touch padding (#7276); other rows stay hover-revealed to avoid clipped labels. */
.sidebar-row-action.sidebar-touch-reveal {
@apply opacity-100 pointer-events-auto;
}
@@ -1108,6 +1117,26 @@ html[data-chat-font] .aui-root {
.sidebar-row-action[data-state="open"] {
@apply opacity-100 pointer-events-auto;
}
+ /* Pinned/Projects/Recents header actions. They sit in the label's flex row,
+ not over a pill, so they reveal on the header's hover. */
+ .sidebar-header-action {
+ @apply inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-md opacity-0 pointer-events-none outline-none transition-opacity duration-150;
+ color: inherit;
+ }
+ .group\/sidebar-header:hover .sidebar-header-action,
+ .sidebar-header-action:focus-visible,
+ .sidebar-header-action[data-state="open"] {
+ @apply opacity-100 pointer-events-auto;
+ }
+ .sidebar-header-action:hover {
+ background-color: var(--nav-surface-hover);
+ }
+ @media (pointer: coarse) {
+ /* No hover to reveal them on touch. */
+ .sidebar-header-action {
+ @apply opacity-100 pointer-events-auto;
+ }
+ }
.sidebar-row-action-glyph {
@apply inline-flex size-6 items-center justify-center rounded-full text-sidebar-foreground/55;
}
diff --git a/studio/frontend/tests/delete-chat-files-preference.test.ts b/studio/frontend/tests/delete-chat-files-preference.test.ts
new file mode 100644
index 00000000000..c94c326d9f4
--- /dev/null
+++ b/studio/frontend/tests/delete-chat-files-preference.test.ts
@@ -0,0 +1,130 @@
+// 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 { readFile } from "node:fs/promises";
+import test from "node:test";
+
+import { useChatPreferencesStore } from "../src/features/chat/stores/chat-preferences-store.ts";
+
+test("deleting a chat leaves its files alone until asked", () => {
+ // Files are the destructive half of a delete, so an install that never saw
+ // this setting must not start removing them.
+ const fresh = useChatPreferencesStore.getInitialState();
+ assert.equal(fresh.alwaysDeleteChatFiles, false);
+});
+
+test("a saved payload without the key still defaults to off", async () => {
+ // Preferences written before this setting existed rehydrate through merge,
+ // and a missing key there must not read as "yes, delete the files".
+ const source = await readFile(
+ new URL("../src/features/chat/stores/chat-preferences-store.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /alwaysDeleteChatFiles: saved\?\.alwaysDeleteChatFiles \?\? false/,
+ );
+});
+
+test("every chat delete path honours the preference", async () => {
+ // Five places delete chats. One skipping the setting would leave sandbox
+ // folders behind depending on which button was used, and after a clear-all
+ // there is no chat row left to reach them from.
+ const files = [
+ "../src/components/app-sidebar.tsx",
+ "../src/features/chat/chat-page.tsx",
+ "../src/features/settings/components/archived-chats-dialog.tsx",
+ "../src/features/settings/components/recent-dictations-view.tsx",
+ "../src/features/settings/tabs/data-tab.tsx",
+ ];
+ for (const file of files) {
+ const source = await readFile(new URL(file, import.meta.url), "utf8");
+ assert.match(
+ source,
+ /alwaysDeleteChatFiles/,
+ `${file} deletes chats without reading the preference`,
+ );
+ }
+});
+
+test("every confirmation discloses the file deletion and can undo it", async () => {
+ // The preference makes a delete destructive past the chat itself. A dialog
+ // that neither says so nor offers the switch removes a sandbox the user was
+ // never shown, and there is no undo.
+ // Every dialog that can reach a delete, with the state each one names.
+ const dialogs: Array<[string, string]> = [
+ ["../src/components/app-sidebar.tsx", "deleteFilesOnDelete"],
+ ["../src/features/chat/chat-page.tsx", "deleteFilesOnDelete"],
+ [
+ "../src/features/settings/components/archived-chats-dialog.tsx",
+ "deleteFilesOnDelete",
+ ],
+ [
+ "../src/features/settings/components/recent-dictations-view.tsx",
+ "deleteFilesOnDelete",
+ ],
+ ["../src/features/settings/tabs/data-tab.tsx", "deleteFilesOnClear"],
+ ];
+ for (const [file, state] of dialogs) {
+ const source = await readFile(new URL(file, import.meta.url), "utf8");
+ // The rendered control, not just the state behind it.
+ assert.ok(
+ source.includes(`checked={${state}}`),
+ `${file} deletes files without a switch to turn it off`,
+ );
+ // Preselected from the preference: the switch has to show what will happen,
+ // not sit off while the delete removes the files anyway.
+ const setter = state.replace(/^delete/, "setDelete");
+ assert.match(
+ source,
+ new RegExp(`${setter}\\([\\s\\S]{0,40}alwaysDeleteChatFiles`),
+ `${file} does not preselect the switch from the preference`,
+ );
+ }
+});
+
+test("the confirmed delete follows the switch, not the preference", async () => {
+ // Reading the preference at delete time would ignore a switch the user just
+ // turned off, which is the whole point of showing it.
+ for (const [file, signature] of [
+ ["../src/features/chat/chat-page.tsx", /item: SidebarItem,\s*deleteFiles: boolean/],
+ [
+ "../src/features/settings/components/archived-chats-dialog.tsx",
+ /item: SidebarItem,\s*deleteFiles: boolean/,
+ ],
+ [
+ "../src/features/settings/components/recent-dictations-view.tsx",
+ /confirmDeleteWithChat\(deleteFiles: boolean\)/,
+ ],
+ ["../src/features/settings/tabs/data-tab.tsx", /deleteFiles: deleteFilesOnClear/],
+ ] as Array<[string, RegExp]>) {
+ const source = await readFile(new URL(file, import.meta.url), "utf8");
+ // The executor is handed the answer instead of reading the store, so the
+ // confirmed value is the one that reaches the request.
+ assert.match(source, signature, `${file} does not take the confirmed value`);
+ assert.equal(
+ /deleteFiles: alwaysDeleteChatFiles/.test(source),
+ false,
+ `${file} still reads the preference past its own switch`,
+ );
+ }
+});
+
+test("the clear-all chain carries deleteFiles to the request", async () => {
+ // Three hops: data-tab -> clearAllChats -> clearStoredChats -> the DELETE.
+ // Any hop dropping the option loses it silently, since each still compiles.
+ const read = (path: string) =>
+ readFile(new URL(path, import.meta.url), "utf8");
+
+ const clearAll = await read("../src/features/chat/utils/clear-all-chats.ts");
+ assert.match(clearAll, /clearStoredChats\(options\)/);
+
+ const storage = await read(
+ "../src/features/chat/utils/chat-history-storage.ts",
+ );
+ assert.match(storage, /deleteFiles: options\.deleteFiles/);
+
+ const api = await read("../src/features/chat/api/chat-api.ts");
+ assert.match(api, /options\.deleteFiles \? "\?delete_files=true" : ""/);
+});
diff --git a/studio/frontend/tests/sidebar-action-rows-inert.test.ts b/studio/frontend/tests/sidebar-action-rows-inert.test.ts
index daa0342f267..0e30f928084 100644
--- a/studio/frontend/tests/sidebar-action-rows-inert.test.ts
+++ b/studio/frontend/tests/sidebar-action-rows-inert.test.ts
@@ -89,8 +89,8 @@ test("every sidebar row pill sits in one shared box", async () => {
);
// New Chat and the footer sit outside the scroller.
assert.equal(source.match(/(?<!const )rowPadding[,}]/g)?.length, 2);
- // Nav rows, pinned projects, Recents, training runs sit inside it.
- assert.equal(source.match(/scrollRowPadding[,}]/g)?.length, 4);
+ // Nav rows, pinned chats, Projects, Recents, training runs sit inside it.
+ assert.equal(source.match(/scrollRowPadding[,}]/g)?.length, 5);
assert.equal(source.match(/"pl-2 pr-\[5px\]"/g), null);
});
diff --git a/studio/frontend/tests/sidebar-nav-migration.test.ts b/studio/frontend/tests/sidebar-nav-migration.test.ts
index 5b6bf09987e..992a1a4ae7d 100644
--- a/studio/frontend/tests/sidebar-nav-migration.test.ts
+++ b/studio/frontend/tests/sidebar-nav-migration.test.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
import test from "node:test";
import {
DEFAULT_CUSTOMIZATION,
@@ -48,13 +49,24 @@ const shippedLayouts: SidebarNavItemPref[][] = [
{ id: "export", pinned: false },
{ id: "api", pinned: false },
],
+ [
+ { id: "hub", pinned: true },
+ { id: "projects", pinned: true },
+ { id: "images", pinned: true },
+ { id: "video", pinned: false },
+ { id: "audio", pinned: false },
+ { id: "train", pinned: true },
+ { id: "recipes", pinned: false },
+ { id: "export", pinned: false },
+ { id: "api", pinned: false },
+ ],
];
test("every previously shipped sidebar adopts the current default", () => {
for (const sidebarNav of shippedLayouts) {
const customization = sanitizeCustomization({ sidebarNav });
assert.deepEqual(
- migrateShippedSidebarNavDefault(customization, 4, 6).sidebarNav,
+ migrateShippedSidebarNavDefault(customization, 4, 7).sidebarNav,
DEFAULT_CUSTOMIZATION.sidebarNav,
);
}
@@ -65,7 +77,7 @@ test("the untouched pre-Audio version-5 sidebar adopts the Audio-aware default",
sidebarNav: shippedLayouts[3],
});
assert.deepEqual(
- migrateShippedSidebarNavDefault(customization, 5, 6).sidebarNav,
+ migrateShippedSidebarNavDefault(customization, 5, 7).sidebarNav,
DEFAULT_CUSTOMIZATION.sidebarNav,
);
});
@@ -84,7 +96,7 @@ test("a customized version-5 sidebar keeps its order and only gains Audio", () =
const customization = sanitizeCustomization({ sidebarNav: customizedV5 });
assert.strictEqual(
- migrateShippedSidebarNavDefault(customization, 5, 6),
+ migrateShippedSidebarNavDefault(customization, 5, 7),
customization,
);
assert.deepEqual(
@@ -101,17 +113,55 @@ test("a user-arranged sidebar survives the migration", () => {
),
});
assert.strictEqual(
- migrateShippedSidebarNavDefault(customization, 4, 6),
+ migrateShippedSidebarNavDefault(customization, 4, 7),
customization,
);
});
+test("an install sitting on the version-6 default picks Video up", () => {
+ // The layout this change replaces. Untouched, so it adopts the new default
+ // rather than being read as a deliberate choice to keep Video under More.
+ const customization = sanitizeCustomization({ sidebarNav: shippedLayouts[4] });
+ const migrated = migrateShippedSidebarNavDefault(customization, 6, 7);
+ assert.deepEqual(migrated.sidebarNav, DEFAULT_CUSTOMIZATION.sidebarNav);
+ const ids = migrated.sidebarNav.filter((item) => item.pinned).map((i) => i.id);
+ assert.deepEqual(ids, ["hub", "projects", "images", "video", "train"]);
+});
+
test("a shipped-looking layout chosen after migration is preserved", () => {
const customization = sanitizeCustomization({
sidebarNav: shippedLayouts[2],
});
assert.strictEqual(
- migrateShippedSidebarNavDefault(customization, 6, 6),
+ migrateShippedSidebarNavDefault(customization, 7, 7),
customization,
);
});
+
+/** The sync module uses path aliases, so read its constant rather than import it. */
+async function personalizationVersion(): Promise<number> {
+ const source = await readFile(
+ new URL(
+ "../src/features/profile/hooks/use-personalization-sync.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const match = /PERSONALIZATION_VERSION = (\d+)/.exec(source);
+ assert.ok(match, "no PERSONALIZATION_VERSION in the sync module");
+ return Number(match[1]);
+}
+
+test("a synced profile picks the layout change up too", async () => {
+ // Remote hydration replaces the local store wholesale, so a nav default that
+ // only migrates locally is overwritten by the stored layout on every login.
+ // PERSONALIZATION_VERSION has to move with the layout for that migration to
+ // run against the remote record.
+ const stored = sanitizeCustomization({ sidebarNav: shippedLayouts[4] });
+ const migrated = migrateShippedSidebarNavDefault(
+ stored,
+ 3,
+ await personalizationVersion(),
+ );
+ assert.deepEqual(migrated.sidebarNav, DEFAULT_CUSTOMIZATION.sidebarNav);
+});
diff --git a/studio/frontend/tests/sidebar-organization-store.test.ts b/studio/frontend/tests/sidebar-organization-store.test.ts
new file mode 100644
index 00000000000..aa1807ea79f
--- /dev/null
+++ b/studio/frontend/tests/sidebar-organization-store.test.ts
@@ -0,0 +1,164 @@
+// 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 { readFile } from "node:fs/promises";
+import test from "node:test";
+
+import {
+ applyManualOrder,
+ dropEdgeFor,
+ moveIdBy,
+ PROJECT_ORDER_SCOPE,
+ projectOrderScope,
+ RECENTS_ORDER_SCOPE,
+ reorderIds,
+ showsInRecents,
+ SIDEBAR_ORGANIZATION_STORAGE_KEY,
+ useSidebarOrganizationStore,
+} from "../src/features/chat/stores/sidebar-organization-store.ts";
+
+const ids = (rows: Array<{ id: string }>) => rows.map((row) => row.id);
+
+test("a dragged chat takes the target's slot and pushes the rest along", () => {
+ assert.deepEqual(reorderIds(["a", "b", "c", "d"], "d", "b"), [
+ "a",
+ "d",
+ "b",
+ "c",
+ ]);
+ assert.deepEqual(reorderIds(["a", "b", "c", "d"], "a", "c"), [
+ "b",
+ "c",
+ "a",
+ "d",
+ ]);
+});
+
+test("a drop that cannot be resolved leaves the order alone", () => {
+ const ids = ["a", "b", "c"];
+ // Same row, and rows the list no longer holds: each returns the input array
+ // itself, which is what tells the caller there is nothing to persist.
+ assert.equal(reorderIds(ids, "b", "b"), ids);
+ assert.equal(reorderIds(ids, "gone", "b"), ids);
+ assert.equal(reorderIds(ids, "b", "gone"), ids);
+});
+
+test("a project chat shows in Recents only when the folders are off", () => {
+ // With folders on it would be listed twice, once in each place.
+ assert.equal(showsInRecents("p1", "project"), false);
+ assert.equal(showsInRecents("p1", "list"), true);
+ // A chat in no project is in Recents either way, or it has nowhere to go.
+ for (const mode of ["project", "list"] as const) {
+ assert.equal(showsInRecents(null, mode), true);
+ assert.equal(showsInRecents(undefined, mode), true);
+ }
+});
+
+test("the drop indicator names the edge the row actually lands on", () => {
+ // Painting the cue on the wrong edge is a lie about where the drop goes, so
+ // check every pair against what reorderIds really does.
+ const rows = ["a", "b", "c", "d"];
+ for (const dragged of rows) {
+ for (const target of rows) {
+ if (dragged === target) continue;
+ const next = reorderIds(rows, dragged, target);
+ const landed = next.indexOf(dragged);
+ const targetAt = next.indexOf(target);
+ const edge = dropEdgeFor(rows, dragged, target);
+ assert.equal(
+ landed,
+ edge === "bottom" ? targetAt + 1 : targetAt - 1,
+ `${dragged} onto ${target} drew ${edge} but landed at ${landed}`,
+ );
+ }
+ }
+});
+
+test("a row moves one slot at a time and stops at the ends", () => {
+ assert.deepEqual(moveIdBy(["a", "b", "c"], "a", 1), ["b", "a", "c"]);
+ assert.deepEqual(moveIdBy(["a", "b", "c"], "c", -1), ["a", "c", "b"]);
+ // Past either end, or a row the list lost, is a no-op.
+ const ids = ["a", "b", "c"];
+ assert.equal(moveIdBy(ids, "a", -1), ids);
+ assert.equal(moveIdBy(ids, "c", 1), ids);
+ assert.equal(moveIdBy(ids, "gone", 1), ids);
+});
+
+test("moving by menu matches dragging onto the neighbour", () => {
+ // The two paths must agree, or the same gesture gives two different orders.
+ const rows = ["a", "b", "c", "d"];
+ assert.deepEqual(moveIdBy(rows, "b", 1), reorderIds(rows, "b", "c"));
+ assert.deepEqual(moveIdBy(rows, "c", -1), reorderIds(rows, "c", "b"));
+});
+
+test("a saved order applies, and undragged rows stay on top in list order", () => {
+ const rows = [{ id: "a" }, { id: "b" }, { id: "c" }, { id: "new" }];
+ assert.deepEqual(
+ ids(applyManualOrder(rows, ["c", "a", "b"], (row) => row.id)),
+ // "new" was never dragged, so it keeps the spot the list gave it.
+ ["new", "c", "a", "b"],
+ );
+ // No saved order returns the input untouched, not a copy.
+ assert.equal(applyManualOrder(rows, undefined, (row) => row.id), rows);
+ assert.equal(applyManualOrder(rows, [], (row) => row.id), rows);
+});
+
+test("project folders order independently of any chat list", () => {
+ const store = useSidebarOrganizationStore.getState();
+ store.setManualOrder(PROJECT_ORDER_SCOPE, ["p2", "p1"]);
+ store.setManualOrder(projectOrderScope("p1"), ["chat-b", "chat-a"]);
+
+ const saved = useSidebarOrganizationStore.getState().manualOrder;
+ assert.deepEqual(saved[PROJECT_ORDER_SCOPE], ["p2", "p1"]);
+ assert.deepEqual(saved["project:p1"], ["chat-b", "chat-a"]);
+});
+
+test("each list keeps its own manual order", () => {
+ const store = useSidebarOrganizationStore.getState();
+ store.setManualOrder(RECENTS_ORDER_SCOPE, ["a", "b"]);
+ store.setManualOrder(projectOrderScope("p1"), ["b", "a"]);
+
+ const saved = useSidebarOrganizationStore.getState().manualOrder;
+ assert.deepEqual(saved[RECENTS_ORDER_SCOPE], ["a", "b"]);
+ assert.deepEqual(saved["project:p1"], ["b", "a"]);
+});
+
+test("the sidebar starts grouped by project, sorted by priority", () => {
+ // Defaults are what an install without saved preferences renders, so they are
+ // part of the layout, not an implementation detail.
+ const fresh = useSidebarOrganizationStore.getInitialState();
+ assert.equal(fresh.organizeBy, "project");
+ assert.equal(fresh.chatSort, "priority");
+ // Pinned defaults to manual because pin order already is one: re-sorting the
+ // chat lists must not silently rearrange the rows the user pinned by hand.
+ assert.equal(fresh.pinnedSort, "manual");
+});
+
+test("Pinned sorts independently of the chat lists", () => {
+ const store = useSidebarOrganizationStore.getState();
+ store.setChatSort("updated");
+ store.setPinnedSort("priority");
+
+ const state = useSidebarOrganizationStore.getState();
+ assert.equal(state.chatSort, "updated");
+ assert.equal(state.pinnedSort, "priority");
+});
+
+// Reset-all is the only in-app way back to the shipped sidebar layout, and it
+// only removes the keys it lists, so an unlisted one survives the reload.
+test("Reset all local preferences clears this key", async () => {
+ const source = await readFile(
+ new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),
+ "utf8",
+ );
+ const keys = source.slice(
+ source.indexOf("const PREFS_KEYS"),
+ source.indexOf("];", source.indexOf("const PREFS_KEYS")),
+ );
+ assert.ok(
+ keys.includes("SIDEBAR_ORGANIZATION_STORAGE_KEY") ||
+ keys.includes(`"${SIDEBAR_ORGANIZATION_STORAGE_KEY}"`),
+ `${SIDEBAR_ORGANIZATION_STORAGE_KEY} missing from PREFS_KEYS`,
+ );
+});
diff --git a/studio/frontend/tests/sidebar-row-selection.test.ts b/studio/frontend/tests/sidebar-row-selection.test.ts
new file mode 100644
index 00000000000..d461b60a6f7
--- /dev/null
+++ b/studio/frontend/tests/sidebar-row-selection.test.ts
@@ -0,0 +1,52 @@
+// 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 {
+ rangeBetween,
+ toggleSelected,
+} from "../src/features/chat/utils/row-selection.ts";
+import { usePinnedChatsStore } from "../src/features/chat/stores/pinned-chats-store.ts";
+
+const rows = ["a", "b", "c", "d"];
+
+test("shift click takes the block between anchor and row, either way round", () => {
+ assert.deepEqual(rangeBetween(rows, "b", "d"), ["b", "c", "d"]);
+ // Dragging the selection upward covers the same rows.
+ assert.deepEqual(rangeBetween(rows, "d", "b"), ["b", "c", "d"]);
+ assert.deepEqual(rangeBetween(rows, "c", "c"), ["c"]);
+});
+
+test("a lost anchor selects only the clicked row", () => {
+ // The anchored chat was deleted or moved to another list; selecting a block
+ // from nothing would grab rows the user never pointed at.
+ assert.deepEqual(rangeBetween(rows, "gone", "c"), ["c"]);
+ assert.deepEqual(rangeBetween(rows, "a", "gone"), []);
+});
+
+test("cmd click adds a row, and takes it back out", () => {
+ const once = toggleSelected(new Set(["a"]), "b");
+ assert.deepEqual([...once].sort(), ["a", "b"]);
+ const twice = toggleSelected(once, "b");
+ assert.deepEqual([...twice], ["a"]);
+ // The input set is never mutated, so React sees a new reference.
+ assert.deepEqual([...once].sort(), ["a", "b"]);
+});
+
+test("pinning a selection leads with the new pins and keeps the rest", () => {
+ const store = usePinnedChatsStore.getState();
+ store.setPinned([], false);
+ usePinnedChatsStore.setState({ pinnedIds: ["old"] });
+
+ usePinnedChatsStore.getState().setPinned(["a", "b"], true);
+ assert.deepEqual(usePinnedChatsStore.getState().pinnedIds, ["a", "b", "old"]);
+
+ // Pinning again must not duplicate, and must not reshuffle.
+ usePinnedChatsStore.getState().setPinned(["a", "old"], true);
+ assert.deepEqual(usePinnedChatsStore.getState().pinnedIds, ["a", "b", "old"]);
+
+ usePinnedChatsStore.getState().setPinned(["a", "old"], false);
+ assert.deepEqual(usePinnedChatsStore.getState().pinnedIds, ["b"]);
+});
diff --git a/studio/frontend/tests/sidebar-scroll-fade-deps.test.ts b/studio/frontend/tests/sidebar-scroll-fade-deps.test.ts
new file mode 100644
index 00000000000..31343a760d9
--- /dev/null
+++ b/studio/frontend/tests/sidebar-scroll-fade-deps.test.ts
@@ -0,0 +1,45 @@
+// 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 { readFile } from "node:fs/promises";
+import test from "node:test";
+
+// onScroll never fires for a list that is not scrolling, so the bottom fade is
+// only re-measured when this effect re-runs. Every input that can add or remove
+// a row has to be in its deps, and a missing one is invisible: the fade just
+// stays wrong until an unrelated scroll or resize.
+
+test("the bottom fade re-measures on every row-count input", async () => {
+ const source = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ const effect =
+ /Recompute bottom-fade on mount[\s\S]*?\}, \[([\s\S]*?)\n \]\);/.exec(
+ source,
+ );
+ assert.ok(effect, "could not find the bottom-fade effect");
+ const deps = effect[1];
+
+ for (const dep of [
+ // Each list that renders rows into the scroller.
+ "recentChatItems.length",
+ "pinnedChatItems.length",
+ "projectChatRowCount",
+ "visibleProjectRecords.length",
+ "runItems.length",
+ // Disclosures, which hide and reveal whole sections.
+ "chatOpen",
+ "runsOpen",
+ "pinnedOpen",
+ "projectsOpen",
+ // Regrouping, which can empty or fill the Projects section outright.
+ "organizeBy",
+ ]) {
+ assert.ok(
+ deps.includes(dep),
+ `${dep} is missing from the bottom-fade deps, so the fade goes stale when it changes`,
+ );
+ }
+});
diff --git a/studio/frontend/tests/sidebar-selection-coverage.test.ts b/studio/frontend/tests/sidebar-selection-coverage.test.ts
new file mode 100644
index 00000000000..e2c730a870e
--- /dev/null
+++ b/studio/frontend/tests/sidebar-selection-coverage.test.ts
@@ -0,0 +1,161 @@
+// 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 { readFile } from "node:fs/promises";
+import test from "node:test";
+
+// A row is only selectable if it is handed the list it belongs to. Dropping
+// that argument still compiles, since it is optional, and the row just stops
+// responding to cmd and shift click.
+
+async function sidebarSource(): Promise<string> {
+ return readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+}
+
+test("every chat list hands its rows a selection list", async () => {
+ const source = await sidebarSource();
+ for (const list of [
+ /\{ scope: PINNED_ORDER_SCOPE, ids: pinnedRowIds \}/,
+ /\{ scope: RECENTS_ORDER_SCOPE, ids: recentRowIds \}/,
+ /scope: projectOrderScope\(project\.id\),\s*ids: projectChatIds,/,
+ ]) {
+ assert.match(source, list);
+ }
+});
+
+test("folder rows select too, and open their own bulk menu", async () => {
+ const source = await sidebarSource();
+ assert.match(source, /handleProjectSelectionClick\(event, project\.id\)/);
+ assert.match(source, /selectProjectForContextMenu\(project\.id\)/);
+ assert.match(source, /\{renderProjectContextMenu\(\)\}/);
+ assert.match(source, /selectedProjectIds\.has\(project\.id\)/);
+});
+
+function bodyOf(source: string, name: string): string {
+ const found = new RegExp(`function ${name}\\(([\\s\\S]*?)\\n \\}`).exec(
+ source,
+ );
+ assert.ok(found, `no ${name}`);
+ return found[1];
+}
+
+test("picking one kind of row drops the other", async () => {
+ // Chats and folders have no shared bulk action, so a mixed selection would
+ // leave the menu unable to say what it acts on. All four entry points, since
+ // one that skips it is what puts the sidebar in that state.
+ const source = await sidebarSource();
+ for (const [name, drop] of [
+ ["handleSelectionClick", "dropProjectSelection()"],
+ ["selectForContextMenu", "dropProjectSelection()"],
+ ["handleProjectSelectionClick", "dropChatSelection()"],
+ ["selectProjectForContextMenu", "dropChatSelection()"],
+ ]) {
+ assert.ok(
+ bodyOf(source, name).includes(drop),
+ `${name} leaves the other kind of row selected`,
+ );
+ }
+});
+
+test("a right-click drops the other kind even on an already-selected row", async () => {
+ // Both menus return early when the row is already selected. Dropping after
+ // that return would keep a mixed selection alive for exactly the rows a bulk
+ // action is most likely to run on.
+ const source = await sidebarSource();
+ for (const [name, drop] of [
+ ["selectForContextMenu", "dropProjectSelection()"],
+ ["selectProjectForContextMenu", "dropChatSelection()"],
+ ]) {
+ const body = bodyOf(source, name);
+ const dropAt = body.indexOf(drop);
+ const returnAt = body.search(/if \(selected\w+\.has\([\w.]+\)\) return;/);
+ assert.ok(dropAt >= 0, `${name} does not drop the other kind`);
+ assert.ok(returnAt >= 0, `${name} lost its early return`);
+ assert.ok(
+ dropAt < returnAt,
+ `${name} drops the other kind only after its early return`,
+ );
+ }
+});
+
+test("dropping a selection clears its anchor too", async () => {
+ // A kept anchor shift-selects a range from a row that no longer looks
+ // selected, which is how a cleared list grows again on the next click.
+ const source = await sidebarSource();
+ assert.match(
+ source,
+ /const dropChatSelection = useCallback\(\(\) => \{\s*selectionAnchorRef\.current = null;/,
+ );
+ assert.match(
+ source,
+ /const dropProjectSelection = useCallback\(\(\) => \{\s*projectAnchorRef\.current = null;/,
+ );
+});
+
+test("the bulk archive failure reads a translated string", async () => {
+ // Its wording already exists as a key, so a literal here would be the one
+ // English toast in an otherwise translated flow.
+ const source = await sidebarSource();
+ const archive = /async function archiveSelected\(([\s\S]*?)\n \}/.exec(source);
+ assert.ok(archive, "no archiveSelected");
+ assert.match(archive[1], /translate\("settings\.data\.failedToArchiveChats"\)/);
+});
+
+test("one failed archive does not abandon the rest of the batch", async () => {
+ // The selection is cleared up front, so chats skipped by an early exit are
+ // left unarchived with nothing left highlighted to retry from. The other two
+ // bulk loops catch per item; this one has to as well.
+ const source = await sidebarSource();
+ const archive = /async function archiveSelected\(([\s\S]*?)\n \}/.exec(source);
+ assert.ok(archive, "no archiveSelected");
+ const body = archive[1];
+ const loopAt = body.indexOf("for (const item of items)");
+ const tryAt = body.indexOf("try {");
+ assert.ok(loopAt >= 0, "no batch loop");
+ assert.ok(tryAt > loopAt, "archiveSelected catches around the loop, not in it");
+ // Reported on what got through, not on whether the loop threw.
+ assert.match(body, /archived \+= 1/);
+ assert.match(body, /if \(archived > 0\) showArchivedChatsToast\(\)/);
+ assert.match(body, /if \(archived < items\.length\)/);
+});
+
+test("deleting folders in bulk cleans up like deleting one", async () => {
+ // Both branches end the same way, or a batch leaves stale chat rows behind
+ // and strands the user on a page whose project is gone.
+ const source = await sidebarSource();
+ const branch = /if \(target\.kind === "projects"\) \{([\s\S]*?)\n return;/.exec(
+ source,
+ );
+ assert.ok(branch, "no bulk project delete branch");
+ assert.match(branch[1], /notifyChatHistoryUpdated\(\)/);
+ assert.match(branch[1], /setActiveProjectId\(null\)/);
+ assert.match(branch[1], /navigate\(\{ to: "\/chat"/);
+
+ // The redirect reads what was actually deleted. Built from the requested
+ // list instead, a delete that failed would still throw the user off a
+ // project that is still there.
+ assert.match(branch[1], /deletedIds\.add\(project\.id\)/);
+ assert.equal(
+ /new Set\(target\.projects\.map/.test(branch[1]),
+ false,
+ "deletedIds is built from the requested projects, not the deleted ones",
+ );
+});
+
+test("both sidebar expanders read translated labels", async () => {
+ // The two sit one control apart, so an English literal next to a translated
+ // twin is the visible half of the omission.
+ // Comments name the control too, so match the rendered ternary, not the words.
+ const source = await sidebarSource();
+ assert.equal(
+ /\?\s*"Show less"\s*:\s*"Show more"/.test(source),
+ false,
+ "a sidebar expander still hard-codes its label",
+ );
+ const uses = source.match(/shell\.navigation\.show(More|Less)/g) ?? [];
+ assert.equal(uses.length, 4, "both expanders read both keys");
+});
diff --git a/studio/frontend/tests/sidebar-touch-reorder.test.ts b/studio/frontend/tests/sidebar-touch-reorder.test.ts
new file mode 100644
index 00000000000..5d05a47bdc6
--- /dev/null
+++ b/studio/frontend/tests/sidebar-touch-reorder.test.ts
@@ -0,0 +1,67 @@
+// 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 { readFile } from "node:fs/promises";
+import test from "node:test";
+
+// Touch never fires dragstart, so the row menu is the only way to reorder a
+// list there. A menu behind a trigger without sidebar-touch-reveal is inert on
+// coarse pointers, which silently takes manual ordering away from touch users.
+
+async function sidebarSource(): Promise<string> {
+ return readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+}
+
+/** The className string of the button carrying `label`. */
+function actionClassFor(source: string, label: string): string {
+ const match = new RegExp(
+ `aria-label="${label}"[\\s\\S]{0,200}?className="([^"]*)"`,
+ ).exec(source);
+ assert.ok(match, `no button renders aria-label="${label}"`);
+ return match[1];
+}
+
+test("only sidebar-touch-reveal actions work on a coarse pointer", async () => {
+ // The rule the rest of this file depends on.
+ const css = await readFile(
+ new URL("../src/index.css", import.meta.url),
+ "utf8",
+ );
+ const coarse = /@media \(pointer: coarse\) \{([\s\S]*?)\n\t\}/.exec(css);
+ assert.ok(coarse, "no coarse-pointer block in index.css");
+ assert.match(coarse[1], /\.sidebar-row-action\.sidebar-touch-reveal/);
+});
+
+test("rows that reorder can open their menu on touch", async () => {
+ const source = await sidebarSource();
+
+ // Chat rows, both variants.
+ const chatActions = source.match(/"sidebar-row-action[^"]*"/g) ?? [];
+ const reorderRowActions = chatActions.filter((cls) =>
+ /group-hover\/(recent-item|project-chat-item)/.test(cls),
+ );
+ assert.ok(reorderRowActions.length > 0, "no chat or project row actions");
+ for (const cls of reorderRowActions) {
+ assert.match(cls, /sidebar-touch-reveal/);
+ }
+
+ // The project folder menu holds the folder reorder controls.
+ assert.match(
+ actionClassFor(source, "Project options"),
+ /sidebar-touch-reveal/,
+ );
+});
+
+test("a folder row reserves the room its touch actions take", async () => {
+ // Revealed without reserved padding, the buttons sit on top of the name.
+ const source = await sidebarSource();
+ const row = /className="(sidebar-nav-btn h-\[33px\] rounded-full gap-\[8\.5px\][^"]*group-hover\/recent-item:pr-16[^"]*)"/.exec(
+ source,
+ );
+ assert.ok(row, "could not find the project folder row");
+ assert.match(row[1], /\[@media\(pointer:coarse\)\]:pr-16/);
+});