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: custom sidebar sections, section menus and drag to reorder (#12016)

Michael Hanb47fb09c32bd
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 1d70882a919..558144eb3f4 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -32,6 +32,7 @@ import {
} from "@/components/ui/context-menu";
import {
DropdownMenu,
+ DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
@@ -82,8 +83,10 @@ import { cn } from "@/lib/utils";
import { copyToClipboardFrom } from "@/lib/copy-to-clipboard";
import { isTauri } from "@/lib/api-base";
import { useWebUpdateCheck } from "@/hooks/use-web-update-check";
+import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";
import {
Archive03Icon,
+ Cancel01Icon,
BadgeInfoIcon,
ChefHatIcon,
CloudIcon,
@@ -94,8 +97,6 @@ import {
Delete02Icon,
Download01Icon,
Edit03Icon,
- FolderAddIcon,
- FolderAttachmentIcon,
FolderExportIcon,
FolderOpenIcon,
Folder01Icon,
@@ -104,6 +105,7 @@ import {
Globe02Icon,
HelpCircleIcon,
Image03Icon,
+ InformationCircleIcon,
LibrariesIcon,
Logout05Icon,
MoreHorizontalIcon,
@@ -118,10 +120,15 @@ import {
LayoutAlignLeftIcon,
Settings02Icon,
Sun03Icon,
+ Tick02Icon,
UserCircleIcon,
ViewIcon,
ViewOffSlashIcon,
ZapIcon,
+ PanelLeftIcon,
+ LeftToRightListBulletIcon,
+ ArrowUpDownIcon,
+ LayerIcon,
} from "@hugeicons/core-free-icons";
import {
MessageCircleIcon,
@@ -180,7 +187,15 @@ import {
PINNED_PROJECT_ORDER_SCOPE,
PROJECT_ORDER_SCOPE,
RECENTS_ORDER_SCOPE,
+ customSectionScope,
+ customSectionIdOf,
+ PROJECTS_SECTION_KEY,
+ PINNED_SECTION_KEY,
+ inSectionOrder,
+ resolveSectionOrder,
+ assignmentMap,
type SidebarChatSort,
+ type SidebarCustomSection,
type SidebarOrganizeBy,
type SidebarProjectSort,
type ProjectRecord,
@@ -192,6 +207,9 @@ import {
openChatItemById,
recentChatItemAtSlot,
useChatNavigationStore,
+ SectionNameDialog,
+ sectionKeyLanding,
+ useSectionDrag,
} from "@/features/chat";
import { sandboxSessionIdFor } from "@/components/assistant-ui/sandbox-files";
import {
@@ -207,6 +225,7 @@ import {
Shortcut,
type ShortcutId,
useShortcut,
+ prefersReducedMotion,
} from "@/features/settings";
import type {
SidebarNavItemId,
@@ -252,6 +271,7 @@ import { toast } from "@/lib/toast";
import {
folderRingKey,
sectionRingKey,
+ DROP_CUE_CLASS,
SIDEBAR_TAIL_SCOPE,
useSidebarDrag,
type SidebarDragItem,
@@ -261,10 +281,7 @@ import {
type SidebarSection,
} from "@/features/chat";
import { ShutdownDialog } from "@/components/shutdown-dialog";
-import {
- buildChatItemMarkdown,
- saveChatItemAsProjectSource,
-} from "@/features/chat/prompt-storage/prompt-storage-dialog";
+import { buildChatItemMarkdown } from "@/features/chat/prompt-storage/prompt-storage-dialog";
import { translate, useT, type TranslationKey } from "@/i18n";
const RECENT_SLOT_NUMBERS = [1, 2, 3, 4, 5, 6] as const;
@@ -330,8 +347,14 @@ const PROJECT_CHAT_LIMIT = 4;
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";
+// A sidebar or account menu's side and top padding (.sidebar-row-menu in index.css, before the
+// UI scale), the 2px margin every menu row keeps, and the gap a submenu keeps from its menu.
+const SIDEBAR_MENU_PAD_X = 8;
+const SIDEBAR_MENU_PAD_Y = 6;
+const MENU_ROW_MARGIN_PX = 2;
+// px-2.5 and the 1px transparent border the account menu draws its edge with.
+const ACCOUNT_MENU_PAD_X = 11;
+const SUBMENU_GAP_PX = 6;
// Whether cmd or ctrl adds a row to the selection. This is the user's own keyboard, not the host
// Unsloth runs on, so it reads the browser rather than the platform store: a Mac browser on a Linux
@@ -344,18 +367,30 @@ const SELECT_WITH_META =
// overflow, and the first and last rows are exactly where a row is dragged to. A border, not a
// filled bar: border widths snap to whole device pixels, so the line keeps one thickness at any
// zoom or UI scale instead of rounding differently per row.
-const DROP_CUE_BASE =
- "before:pointer-events-none before:absolute before:inset-x-2 before:z-10 before:h-0 before:border-t-[1.5px] before:border-primary before:content-['']";
+// DROP_CUE_CLASS: the carried row's copy covers the spot it is aimed at, so the drag draws each
+// cue's border again above it.
+const DROP_CUE_BASE = `${DROP_CUE_CLASS} before:pointer-events-none before:absolute before:inset-x-2 before:z-10 before:h-0 before:border-t-[1.5px] before:border-primary before:content-['']`;
const DROP_CUE_TOP = `${DROP_CUE_BASE} before:top-0`;
// bottom-px: on the last row, DROP_ROW_HIT's extra pixel is clipped by the list.
const DROP_CUE_BOTTOM = `${DROP_CUE_BASE} before:bottom-px`;
+// A line that lands inside a folder starts where its chats' names do, so a drop into the folder
+// reads apart from one below it, whose line runs the full width in the same place.
+const DROP_CUE_IN_FOLDER = "before:left-[calc(39px*var(--ui-space-scale,1))]";
// A row dropped onto a folder or section joins it, so the whole target is tinted and outlined,
// with the same border as the line. Kept inside the box for the same clipping reason.
-const DROP_INTO_CUE =
- "before:pointer-events-none before:absolute before:inset-x-1 before:inset-y-0 before:rounded-2xl before:bg-primary/8 before:border-[1.5px] before:border-primary before:content-['']";
+const DROP_INTO_CUE = `${DROP_CUE_CLASS} before:pointer-events-none before:absolute before:inset-x-1 before:inset-y-0 before:rounded-2xl before:bg-primary/8 before:border-[1.5px] before:border-primary before:content-['']`;
+// "Move to": the whole submenu stays inside the window, and each group's list scrolls past about
+// seven rows, the next one half showing, so a long list of projects keeps the Sections group, and
+// each group's Remove, in reach. No scrollbar: it would take its width out of the rows' right
+// padding and leave the hover pill off centre.
+const MOVE_TO_MENU =
+ "max-h-[var(--radix-dropdown-menu-content-available-height,var(--radix-context-menu-content-available-height))] overflow-y-auto";
+// A scroller keeps its rows' 2px margins (MENU_ROW_MARGIN_PX) from meeting the rows outside it,
+// which doubled the gap at both its ends; -my-0.5 gives that 2px back.
+const MOVE_TO_LIST =
+ "no-scrollbar -my-0.5 max-h-[calc(260px*var(--ui-space-scale,1))] overflow-y-auto overscroll-contain";
// Folder rows match their hover pill.
-const DROP_INTO_ROW_CUE =
- "before:pointer-events-none before:absolute before:inset-x-0 before:top-0 before:bottom-px before:rounded-full before:bg-primary/8 before:border-[1.5px] before:border-primary before:content-['']";
+const DROP_INTO_ROW_CUE = `${DROP_CUE_CLASS} before:pointer-events-none before:absolute before:inset-x-0 before:top-0 before:bottom-px before:rounded-full before:bg-primary/8 before:border-[1.5px] before:border-primary before:content-['']`;
// The menu keeps a 1px gap between rows. A pointer resting on that gap would hit the section
// instead, which answers with its last slot, so each row's box reaches over the gap below it.
const DROP_ROW_HIT = "pb-px -mb-px";
@@ -408,6 +443,14 @@ type ProjectOrderContext = {
sort?: RowSort;
};
+// The rows a "Section" submenu files: one row's own menu, or a selection of several.
+type SectionTarget = {
+ chatIds?: string[];
+ projectIds?: string[];
+ /** Filed from a selection, which is let go afterwards. */
+ selection?: boolean;
+};
+
// One row of the Pinned list, which holds folders and chats together.
type PinnedRow =
| { kind: "project"; id: string; project: ProjectRecord }
@@ -434,6 +477,7 @@ interface RowMenuParts {
sideOffset?: number;
alignOffset?: number;
}>;
+ Label: ComponentType<{ children?: ReactNode }>;
}
const DROPDOWN_ROW_MENU: RowMenuParts = {
@@ -442,6 +486,7 @@ const DROPDOWN_ROW_MENU: RowMenuParts = {
Sub: DropdownMenuSub,
SubTrigger: DropdownMenuSubTrigger,
SubContent: DropdownMenuSubContent,
+ Label: DropdownMenuLabel,
};
const CONTEXT_ROW_MENU: RowMenuParts = {
@@ -450,6 +495,7 @@ const CONTEXT_ROW_MENU: RowMenuParts = {
Sub: ContextMenuSub,
SubTrigger: ContextMenuSubTrigger,
SubContent: ContextMenuSubContent,
+ Label: ContextMenuLabel,
};
// The kebab shows itself while its menu is open; the quick-action beside it was hover-only, so
@@ -459,37 +505,35 @@ const REVEAL_WITH_OPEN_MENU_PROJECT_CHAT =
const REVEAL_WITH_OPEN_MENU_RECENT =
"group-has-[.sidebar-row-action[data-state=open]]/recent-item:opacity-100 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pointer-events-auto";
-// Every list offers the same three orders.
+// Every chat list offers the same two 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 PROJECT_SORT_OPTIONS: Array<{
- value: SidebarProjectSort;
- key: TranslationKey;
}> = [
{ value: "updated", key: "shell.organize.lastUpdated" },
- { value: "name", key: "shell.organize.name" },
- { value: "created", key: "shell.organize.dateCreated" },
{ value: "manual", key: "shell.organize.manualOrder" },
];
const ORGANIZE_OPTIONS: Array<{
value: SidebarOrganizeBy;
key: TranslationKey;
+ icon: typeof ZapIcon;
}> = [
- { value: "project", key: "shell.organize.byProject" },
- { value: "list", key: "shell.organize.inOneList" },
+ { value: "project", key: "shell.organize.byProject", icon: Folder01Icon },
+ { value: "list", key: "shell.organize.inOneList", icon: LeftToRightListBulletIcon },
];
-async function saveChatToProjectSources(
- item: SidebarItem,
- projectId: string,
-): Promise<void> {
- await saveChatItemAsProjectSource(item, projectId);
+/** The sort of the list a drop's `switchSort` names, as the store holds it now. */
+function switchedListSort(
+ state: ReturnType<typeof useSidebarOrganizationStore.getState>,
+ list: NonNullable<SidebarDropEffects["switchSort"]>,
+): SidebarChatSort | SidebarProjectSort | undefined {
+ if (list === "pinned") return state.pinnedSort;
+ if (list === "projects") return state.projectSort;
+ const sectionId = customSectionIdOf(list);
+ if (sectionId) {
+ return state.customSections.find((section) => section.id === sectionId)?.sort;
+ }
+ return state.chatSort;
}
@@ -1076,7 +1120,7 @@ export function AppSidebar() {
!chatOnly && trainingRecentsRoute && runItems.length > 0;
const { displayTitle, avatarDataUrl } = useEffectiveProfile();
- const { projects } = useChatProjects();
+ const { projects, hasLoaded: projectsLoaded } = useChatProjects();
const activeProjectId = isChatRoute
? ((search.project as string | undefined) ?? null)
: null;
@@ -1110,9 +1154,51 @@ export function AppSidebar() {
return map;
}, [allChatItems]);
const organizeBy = useSidebarOrganizationStore((s) => s.organizeBy);
+ // User-made sections, what is filed in them, and which sections "Show" turned off.
+ const customSections = useSidebarOrganizationStore((s) => s.customSections);
+ const sectionByChatId = useSidebarOrganizationStore((s) => s.sectionByChatId);
+ const sectionByProjectId = useSidebarOrganizationStore(
+ (s) => s.sectionByProjectId,
+ );
+ const hiddenSections = useSidebarOrganizationStore((s) => s.hiddenSections);
+ const hiddenSectionSet = useMemo(() => new Set(hiddenSections), [hiddenSections]);
+ const savedSectionOrder = useSidebarOrganizationStore((s) => s.sectionOrder);
+ // Pinned, Projects and the user's sections, top to bottom. Recents is not in it: always last.
+ const orderedSectionKeys = useMemo(
+ () => resolveSectionOrder(savedSectionOrder, customSections),
+ [savedSectionOrder, customSections],
+ );
+ const moveSection = useSidebarOrganizationStore((s) => s.moveSection);
+ // Pinned, Projects and custom sections drag by their headers. The hook draws the drag itself,
+ // so the sidebar re-renders once, on the drop.
+ // Radix measures a submenu's sideOffset from its trigger row, which sits inside the menu's side
+ // padding, so the offset is that padding plus the gap wanted between the two menus. The
+ // submenu is pulled up by its top padding and row margin so its first row meets the trigger.
+ const uiSpaceScale = useUiSpaceScale();
+ const sidebarSubmenuOffsets = {
+ sideOffset: Math.round(SIDEBAR_MENU_PAD_X * uiSpaceScale + SUBMENU_GAP_PX),
+ alignOffset: -Math.round(SIDEBAR_MENU_PAD_Y * uiSpaceScale + MENU_ROW_MARGIN_PX),
+ };
+ // The account menu pads its rows by a fixed amount, unscaled.
+ const accountSubmenuOffsets = {
+ sideOffset: ACCOUNT_MENU_PAD_X + SUBMENU_GAP_PX,
+ alignOffset: -Math.round(SIDEBAR_MENU_PAD_Y * uiSpaceScale + MENU_ROW_MARGIN_PX),
+ };
+ const startSectionDrag = useSectionDrag({
+ onDrop: (key, landing) => moveSection(key, landing.target, landing.edge),
+ reducedMotion: prefersReducedMotion,
+ });
+ const pendingNewChatSection = useSidebarOrganizationStore((s) => s.pendingNewChatSection);
+ const setPendingNewChatSection = useSidebarOrganizationStore(
+ (s) => s.setPendingNewChatSection,
+ );
+ const projectsSectionHidden = hiddenSectionSet.has(PROJECTS_SECTION_KEY);
// Whether the sidebar is set up to list folders at all, which is what the nav row answers to.
+ // Hidden from the menu, the section goes and the nav row comes back as the way into projects.
const projectsSectionConfigured =
- organizeBy === "project" && projects.length > 0;
+ organizeBy === "project" &&
+ !projectsSectionHidden &&
+ (projects.length > 0 || projectsLoaded);
const projectsSectionRendered =
!isStudioRoute && !showTrainingRecents && projectsSectionConfigured;
// Deliberately not the rendered flag: Train and Recipes swap the section for their runs, and a
@@ -1130,16 +1216,33 @@ export function AppSidebar() {
const projectSort = useSidebarOrganizationStore((s) => s.projectSort);
const setProjectSort = useSidebarOrganizationStore((s) => s.setProjectSort);
const setManualOrder = useSidebarOrganizationStore((s) => s.setManualOrder);
+ const createCustomSection = useSidebarOrganizationStore(
+ (s) => s.createCustomSection,
+ );
+ const renameCustomSection = useSidebarOrganizationStore(
+ (s) => s.renameCustomSection,
+ );
+ const deleteCustomSection = useSidebarOrganizationStore(
+ (s) => s.deleteCustomSection,
+ );
+ const setCustomSectionSort = useSidebarOrganizationStore(
+ (s) => s.setCustomSectionSort,
+ );
+ const setChatsSection = useSidebarOrganizationStore((s) => s.setChatsSection);
+ const setProjectsSection = useSidebarOrganizationStore((s) => s.setProjectsSection);
+ const setSectionHidden = useSidebarOrganizationStore((s) => s.setSectionHidden);
// 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. Pinned chats are
- // held back either way: the Pinned section renders those.
+ // held back either way: the Pinned section renders those, as a custom section does its own.
const recentChatItems = useMemo(
() =>
allChatItems.filter(
(item) =>
- !pinnedIdSet.has(item.id) && showsInRecents(item.projectId, organizeBy),
+ !pinnedIdSet.has(item.id) &&
+ !sectionByChatId[item.id] &&
+ showsInRecents(item.projectId, organizeBy),
),
- [allChatItems, pinnedIdSet, organizeBy],
+ [allChatItems, pinnedIdSet, sectionByChatId, organizeBy],
);
const [pinnedOpen, setPinnedOpen] = useState(true);
const [projectsOpen, setProjectsOpen] = useState(true);
@@ -1199,7 +1302,7 @@ export function AppSidebar() {
return latest;
};
const rest = projects
- .filter((p) => !pinnedProjectIdSet.has(p.id))
+ .filter((p) => !pinnedProjectIdSet.has(p.id) && !sectionByProjectId[p.id])
.sort((a, b) =>
projectSort === "name"
? a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" })
@@ -1210,7 +1313,14 @@ export function AppSidebar() {
return projectSort === "manual"
? applyManualOrder(rest, manualOrder[PROJECT_ORDER_SCOPE], (project) => project.id)
: rest;
- }, [projects, pinnedProjectIdSet, manualOrder, chatsByProjectId, projectSort]);
+ }, [
+ projects,
+ pinnedProjectIdSet,
+ sectionByProjectId,
+ manualOrder,
+ chatsByProjectId,
+ projectSort,
+ ]);
// Memoised for its identity, not for the slice. It feeds the rendered-row set the selection guard
// depends on, and that effect sets state: React re-renders once to find the bail-out, which would
// rebuild this array and schedule the effect again, without end.
@@ -1290,6 +1400,55 @@ export function AppSidebar() {
storeThreadId ??
undefined
: undefined;
+ // A chat started from a section's header joins it when its first send gives it an id, which
+ // lands in the store while the address still names the new chat. Leaving that chat first lets
+ // the mark go, so a chat opened afterwards is never filed by mistake. Turning it into a compare
+ // chat before that first send is not leaving it: the compare chat takes the mark, and joins once
+ // its pair is listed, under the id the address gives it.
+ useEffect(() => {
+ if (!pendingNewChatSection) return;
+ const { sectionId, nonce, compare } = pendingNewChatSection;
+ const fresh = isChatRoute && !search.thread && !search.project;
+ if (compare === undefined) {
+ if (fresh && search.new === nonce && !search.compare) {
+ if (storeThreadId) {
+ setChatsSection([storeThreadId], sectionId);
+ setPendingNewChatSection(null);
+ }
+ return;
+ }
+ // Straight from the new chat to a compare chat nothing lists yet: the same chat, now
+ // compared. A compare chat already listed is one opened instead, and lets the mark go.
+ const newCompare =
+ fresh &&
+ !search.new &&
+ search.compare &&
+ !allChatItems.some((item) => item.id === search.compare)
+ ? search.compare
+ : undefined;
+ setPendingNewChatSection(newCompare ? { sectionId, nonce, compare: newCompare } : null);
+ return;
+ }
+ if (!(fresh && !search.new && search.compare === compare)) {
+ setPendingNewChatSection(null);
+ return;
+ }
+ if (allChatItems.some((item) => item.type === "compare" && item.id === compare)) {
+ setChatsSection([compare], sectionId);
+ setPendingNewChatSection(null);
+ }
+ }, [
+ pendingNewChatSection,
+ isChatRoute,
+ search.new,
+ search.thread,
+ search.compare,
+ search.project,
+ storeThreadId,
+ allChatItems,
+ setChatsSection,
+ setPendingNewChatSection,
+ ]);
const queueByThreadId = usePromptQueueUI((s) => s.byThreadId);
// In the navigation store, not local state: the unread chords register outside this tree.
const unreadThreadIds = useChatNavigationStore((s) => s.unreadThreadIds);
@@ -1331,16 +1490,9 @@ export function AppSidebar() {
// 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],
+ [manualOrder],
);
const sortedRecentChatItems = useMemo(
() => sortChatItems(recentChatItems, RECENTS_ORDER_SCOPE, chatSort),
@@ -1381,14 +1533,17 @@ export function AppSidebar() {
map.set(
projectId,
sortChatItems(
- items.filter((item) => !pinnedIdSet.has(item.id)),
+ // A chat filed in a custom section is drawn there, as a pinned one is in Pinned.
+ items.filter(
+ (item) => !pinnedIdSet.has(item.id) && !sectionByChatId[item.id],
+ ),
projectOrderScope(projectId),
chatSort,
),
);
}
return map;
- }, [chatsByProjectId, sortChatItems, chatSort, pinnedIdSet]);
+ }, [chatsByProjectId, sortChatItems, chatSort, pinnedIdSet, sectionByChatId]);
// 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(
@@ -1417,6 +1572,108 @@ export function AppSidebar() {
: rows;
}, [pinnedProjectBase, sortedPinnedChatItems, pinnedSort, manualOrder]);
const pinnedRowIds = useMemo(() => pinnedRows.map((row) => row.id), [pinnedRows]);
+ // Each custom section is one list of folders and chats, as Pinned is: folders lead until a drop
+ // says otherwise. A pinned row stays in Pinned and keeps its section for when it is unpinned.
+ const customSectionRows = useMemo(() => {
+ const folders = new Map<string, PinnedRow[]>();
+ const chats = new Map<string, SidebarItem[]>();
+ for (const section of customSections) {
+ folders.set(section.id, []);
+ chats.set(section.id, []);
+ }
+ for (const project of projects) {
+ const sectionId = sectionByProjectId[project.id];
+ if (!sectionId || pinnedProjectIdSet.has(project.id)) continue;
+ folders.get(sectionId)?.push({ kind: "project", id: project.id, project });
+ }
+ for (const item of allChatItems) {
+ const sectionId = sectionByChatId[item.id];
+ if (!sectionId || pinnedIdSet.has(item.id)) continue;
+ chats.get(sectionId)?.push(item);
+ }
+ const rows = new Map<string, PinnedRow[]>();
+ for (const section of customSections) {
+ const scope = customSectionScope(section.id);
+ const list: PinnedRow[] = [
+ ...(folders.get(section.id) ?? []),
+ ...sortChatItems(chats.get(section.id) ?? [], scope, section.sort).map(
+ (item): PinnedRow => ({ kind: "chat", id: item.id, item }),
+ ),
+ ];
+ rows.set(
+ section.id,
+ section.sort === "manual"
+ ? applyManualOrder(list, manualOrder[scope], (row) => row.id)
+ : list,
+ );
+ }
+ return rows;
+ }, [
+ customSections,
+ projects,
+ allChatItems,
+ sectionByProjectId,
+ sectionByChatId,
+ pinnedProjectIdSet,
+ pinnedIdSet,
+ sortChatItems,
+ manualOrder,
+ ]);
+ const visibleCustomSections = useMemo(
+ () => customSections.filter((section) => !hiddenSectionSet.has(section.id)),
+ [customSections, hiddenSectionSet],
+ );
+ // Per section: every row id (the order a drag rewrites), and the chats and folders alone (for
+ // shift-click ranges within one kind).
+ const customSectionIds = useMemo(() => {
+ const map = new Map<string, { rows: string[]; chats: string[]; folders: string[] }>();
+ for (const [sectionId, rows] of customSectionRows) {
+ map.set(sectionId, {
+ rows: rows.map((row) => row.id),
+ chats: rows.flatMap((row) => (row.kind === "chat" ? [row.id] : [])),
+ folders: rows.flatMap((row) => (row.kind === "project" ? [row.id] : [])),
+ });
+ }
+ return map;
+ }, [customSectionRows]);
+ // Collapsed by the header, like the built-in sections; not persisted, as theirs are not.
+ const [collapsedSectionIds, setCollapsedSectionIds] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ const setCustomSectionOpen = useCallback((sectionId: string, open: boolean) => {
+ setCollapsedSectionIds((prev) => {
+ if (prev.has(sectionId) !== open) return prev;
+ const next = new Set(prev);
+ if (open) next.delete(sectionId);
+ else next.add(sectionId);
+ return next;
+ });
+ }, []);
+ // Rows the open custom sections draw. Creating, filling, hiding or folding one changes the list's
+ // height with no scroll to re-measure the bottom fade off.
+ const customSectionRowCount = useMemo(
+ () =>
+ visibleCustomSections.reduce(
+ (count, section) =>
+ collapsedSectionIds.has(section.id)
+ ? count
+ : count + (customSectionRows.get(section.id)?.length ?? 0),
+ 0,
+ ),
+ [visibleCustomSections, collapsedSectionIds, customSectionRows],
+ );
+ // The folders the custom sections draw, open or not: the bottom fade counts their chats.
+ const customSectionProjectRecords = useMemo(
+ () =>
+ visibleCustomSections.flatMap((section) =>
+ collapsedSectionIds.has(section.id)
+ ? []
+ : (customSectionRows.get(section.id) ?? []).flatMap((row) =>
+ row.kind === "project" ? [row.project] : [],
+ ),
+ ),
+ [visibleCustomSections, collapsedSectionIds, customSectionRows],
+ );
const pinnedProjectRecords = useMemo(
() => pinnedRows.flatMap((row) => (row.kind === "project" ? [row.project] : [])),
[pinnedRows],
@@ -1463,9 +1720,10 @@ export function AppSidebar() {
sortedChatsByProjectId,
],
);
+ // Hidden from the menu, the section is not drawn, so its folders' chats are not walked either.
const sectionProjectChatItems = useMemo(
- () => folderChatItems(projectsOpen, visibleProjectRecords),
- [folderChatItems, projectsOpen, visibleProjectRecords],
+ () => folderChatItems(projectsSectionRendered && projectsOpen, visibleProjectRecords),
+ [folderChatItems, projectsSectionRendered, projectsOpen, visibleProjectRecords],
);
// A collapsed section is not on screen either, so its rows are not walked or
// selected any more than a collapsed folder's are.
@@ -1486,16 +1744,51 @@ export function AppSidebar() {
: [],
[chatListsOnScreen, pinnedOpen, pinnedRows, folderChatItems],
);
- // Every chat row on screen, in draw order: Pinned, then the Projects folders, then Recents.
+ // Each custom section's chats, on the same terms as Pinned's.
+ const customSectionChatItems = useMemo(() => {
+ const bySection = new Map<string, SidebarItem[]>();
+ if (!chatListsOnScreen) return bySection;
+ for (const section of visibleCustomSections) {
+ if (collapsedSectionIds.has(section.id)) continue;
+ bySection.set(
+ section.id,
+ (customSectionRows.get(section.id) ?? []).flatMap((row) =>
+ row.kind === "project" ? folderChatItems(true, [row.project]) : [row.item],
+ ),
+ );
+ }
+ return bySection;
+ }, [
+ chatListsOnScreen,
+ visibleCustomSections,
+ collapsedSectionIds,
+ customSectionRows,
+ folderChatItems,
+ ]);
+ // The sections above Recents in the order they are drawn, split at Pinned: what the walk reads
+ // as the pinned block runs through Pinned, whatever was dragged above it included.
+ const { upToPinnedChatItems, belowPinnedChatItems } = useMemo(() => {
+ const upTo: SidebarItem[] = [];
+ const below: SidebarItem[] = [];
+ let pastPinned = false;
+ for (const key of orderedSectionKeys) {
+ const items =
+ key === PINNED_SECTION_KEY
+ ? pinnedSectionChatItems
+ : key === PROJECTS_SECTION_KEY
+ ? sectionProjectChatItems
+ : (customSectionChatItems.get(key) ?? []);
+ (pastPinned ? below : upTo).push(...items);
+ if (key === PINNED_SECTION_KEY) pastPinned = true;
+ }
+ return { upToPinnedChatItems: upTo, belowPinnedChatItems: below };
+ }, [orderedSectionKeys, pinnedSectionChatItems, sectionProjectChatItems, customSectionChatItems]);
+ // Every chat row on screen, in draw order: the sections above Recents as dragged, then Recents.
// The arrays above already fold in each section's disclosure, each folder's, and the
// per-folder limit, so the walk and the selection need not restate any of it.
const renderedChatItems = useMemo(
- () => [
- ...pinnedSectionChatItems,
- ...sectionProjectChatItems,
- ...visibleRecentItems,
- ],
- [pinnedSectionChatItems, sectionProjectChatItems, visibleRecentItems],
+ () => [...upToPinnedChatItems, ...belowPinnedChatItems, ...visibleRecentItems],
+ [upToPinnedChatItems, belowPinnedChatItems, visibleRecentItems],
);
const renderedChatIds = useMemo(
() => new Set(renderedChatItems.map((item) => item.id)),
@@ -1511,6 +1804,7 @@ export function AppSidebar() {
if (pinnedOpen) {
for (const project of pinnedProjectRecords) ids.add(project.id);
}
+ for (const project of customSectionProjectRecords) ids.add(project.id);
if (projectsOpen && projectsSectionConfigured) {
for (const project of visibleProjectRecords) ids.add(project.id);
}
@@ -1519,6 +1813,7 @@ export function AppSidebar() {
chatListsOnScreen,
pinnedOpen,
pinnedProjectRecords,
+ customSectionProjectRecords,
projectsOpen,
projectsSectionConfigured,
visibleProjectRecords,
@@ -1540,17 +1835,18 @@ export function AppSidebar() {
const publishLists = useChatNavigationStore((s) => s.publishLists);
useEffect(() => {
publishLists({
- // The pinned folders' chats belong to Pinned, which draws them first.
- pinnedItems: pinnedSectionChatItems,
- projectItems: sectionProjectChatItems,
+ // The walk reads these two back to back, so between them they are the sections above
+ // Recents in the order they are drawn, split at Pinned.
+ pinnedItems: upToPinnedChatItems,
+ projectItems: belowPinnedChatItems,
recentItems: visibleRecentItems,
attentionItemIds,
activeItemId: activeThreadId ?? null,
});
}, [
publishLists,
- pinnedSectionChatItems,
- sectionProjectChatItems,
+ upToPinnedChatItems,
+ belowPinnedChatItems,
visibleRecentItems,
attentionItemIds,
activeThreadId,
@@ -1579,7 +1875,11 @@ export function AppSidebar() {
// Only folders list chats, and only this organization has folders that do.
if (organizeBy !== "project") return 0;
let rows = 0;
- for (const project of [...pinnedProjectRecords, ...visibleProjectRecords]) {
+ for (const project of [
+ ...pinnedProjectRecords,
+ ...customSectionProjectRecords,
+ ...visibleProjectRecords,
+ ]) {
if (collapsedProjectIds.has(project.id)) continue;
const chats = sortedChatsByProjectId.get(project.id) ?? [];
rows += expandedChatProjectIds.has(project.id)
@@ -1593,6 +1893,7 @@ export function AppSidebar() {
}, [
organizeBy,
pinnedProjectRecords,
+ customSectionProjectRecords,
visibleProjectRecords,
collapsedProjectIds,
expandedChatProjectIds,
@@ -1847,6 +2148,10 @@ export function AppSidebar() {
async function archiveSelected() {
const items = selectedChatItems;
clearSelection();
+ await archiveChatItems(items);
+ }
+
+ async function archiveChatItems(items: SidebarItem[]) {
// Sequential: each archive can reset the active thread, and two of those
// racing would fight over where the chat pane lands.
let archived = 0;
@@ -1906,14 +2211,23 @@ export function AppSidebar() {
projectSort,
pinnedChatIds: pinnedIdSet,
pinnedProjectIds: pinnedProjectIdSet,
+ sectionByChatId,
+ sectionByProjectId,
+ sectionSort: (sectionId) =>
+ customSections.find((section) => section.id === sectionId)?.sort ?? "manual",
orders: {
pinned: pinnedRowIds,
projects: projectRowIds,
recents: recentRowIds,
projectChats: (projectId) => projectChatRowIds.get(projectId) ?? [],
+ sections: (sectionId) => customSectionIds.get(sectionId)?.rows ?? [],
},
}),
[
+ sectionByChatId,
+ sectionByProjectId,
+ customSections,
+ customSectionIds,
organizeBy,
chatSort,
pinnedSort,
@@ -1942,18 +2256,32 @@ export function AppSidebar() {
}
return;
}
- if (zone.section === "pinned") setPinnedOpen(true);
+ const sectionId = customSectionIdOf(zone.section);
+ if (sectionId) setCustomSectionOpen(sectionId, true);
+ else if (zone.section === "pinned") setPinnedOpen(true);
else if (zone.section === "projects") setProjectsOpen(true);
else setChatOpen(true);
},
- onDrop: (plan) => commitDrop(plan),
+ onDrop: (plan, dragged) => commitDrop(plan, dragged),
+ reducedMotion: prefersReducedMotion,
});
const draggingRow = dnd.drag;
/** Runs a plan. Pin toggles are guarded against a stale plan; a sorted list that would undo
* the drop switches to Manual and says so. */
- function commitDrop(plan: SidebarDropPlan) {
+ function commitDrop(plan: SidebarDropPlan, dragged: SidebarDragItem) {
const { effects } = plan;
+ // A chat dropped again while an earlier drop's move is in flight: this drop is the newer
+ // intent, so the earlier one's slot, pin and filing stand down when its move lands. A move
+ // bumps the generation below; any other drop, a reorder where the row still is included,
+ // bumps it here.
+ const pendingMove = dragged.kind === "chat" ? chatMovesRef.current.get(dragged.id) : undefined;
+ if (pendingMove && !effects.moveChat) {
+ chatMovesRef.current.set(dragged.id, {
+ generation: pendingMove.generation + 1,
+ chain: pendingMove.chain,
+ });
+ }
if (effects.pinChat && !pinnedIdSet.has(effects.pinChat)) {
togglePinnedChat(effects.pinChat);
}
@@ -1991,10 +2319,27 @@ export function AppSidebar() {
setProjectSort("manual");
toast.info(t("shell.organize.switchedToManual"));
}
+ const sortedSection = effects.switchSort
+ ? customSectionIdOf(effects.switchSort)
+ : null;
+ if (sortedSection) {
+ setCustomSectionSort(sortedSection, "manual");
+ toast.info(t("shell.organize.switchedToManual"));
+ }
+ };
+ // Filing waits for a move like the slot does: a chat leaving its section for a folder it has
+ // not reached yet would otherwise flash back into its old list.
+ const applyFiling = () => {
+ const filing = effects.fileInSection;
+ if (!filing) return;
+ if (filing.kind === "chat") setChatsSection([filing.id], filing.sectionId);
+ else setProjectsSection([filing.id], filing.sectionId);
+ if (filing.sectionId) setCustomSectionOpen(filing.sectionId, true);
};
const move = effects.moveChat;
if (!move) {
// Nothing to wait for, so nothing can come between the drop and this.
+ applyFiling();
applyOrders();
return;
}
@@ -2015,19 +2360,22 @@ export function AppSidebar() {
// written into a list still sorted, which is the drop ignored all over again.
const switching = effects.switchSort;
let sortPicked = false;
- const stopWatchingSort = switching
- ? useSidebarOrganizationStore.subscribe((now, before) => {
- sortPicked ||=
- switching === "pinned"
- ? now.pinnedSort !== before.pinnedSort
- : now.chatSort !== before.chatSort;
- })
- : () => {};
+ // The chat stays on screen in its old list until the move lands, so it can be filed from its
+ // menu meanwhile: that is the newer intent, and the drop's filing stands down for it.
+ let filedSince = false;
+ const stopWatchingSort = useSidebarOrganizationStore.subscribe((now, before) => {
+ if (switching) {
+ sortPicked ||=
+ switchedListSort(now, switching) !== switchedListSort(before, switching);
+ }
+ filedSince ||= now.sectionByChatId[item.id] !== before.sectionByChatId[item.id];
+ });
const chain = (previous?.chain ?? Promise.resolve())
.then(() => moveChatToProject(item, move.projectId))
.then((moved) => {
if (!moved || moves.get(item.id)?.generation !== generation) return;
// Read before applyOrders, whose own switch would otherwise trip the watch.
+ if (!filedSince) applyFiling();
applyOrders(ordersBefore, sortPicked);
if (unpinAfter) usePinnedChatsStore.getState().unpin(unpinAfter);
})
@@ -2037,9 +2385,12 @@ export function AppSidebar() {
/** The insertion line for a row, on the landing edge. */
function dropCueClass(scope: string, rowId: string): string | undefined {
- const edge = dnd.lineEdge(scope, rowId);
- if (!edge) return undefined;
- return edge === "bottom" ? DROP_CUE_BOTTOM : DROP_CUE_TOP;
+ const cue = dnd.lineAt(scope, rowId);
+ if (!cue) return undefined;
+ return cn(
+ cue.edge === "bottom" ? DROP_CUE_BOTTOM : DROP_CUE_TOP,
+ cue.inFolder && DROP_CUE_IN_FOLDER,
+ );
}
/** Moves a row one slot without a pointer, under the same sort rule as a drop. */
@@ -2161,6 +2512,11 @@ export function AppSidebar() {
pinnedChatItems.length,
// And with no chats in them, folders appear and disappear on their own.
organizeBy,
+ // Custom sections: an empty one still draws its header and hint, and folding it hides both.
+ visibleCustomSections.length,
+ collapsedSectionIds,
+ customSectionRowCount,
+ projectsSectionHidden,
]);
// Resizing changes clientHeight without firing onScroll, so the fade would
@@ -2404,6 +2760,21 @@ export function AppSidebar() {
closeMobileIfOpen();
}
+ /** A new chat that is filed into `sectionId` as soon as it has an id, i.e. on its first send.
+ * Marked once the new chat is on screen, so the chat being left is never the one filed. */
+ function openNewChatInSection(sectionId: string) {
+ const nonce = createNavigationNonce();
+ clearNewChatDraft();
+ setActiveThreadId(null);
+ useChatRuntimeStore.getState().setActiveProjectId(null);
+ useChatRuntimeStore.getState().setIncognito(false);
+ setPendingNewChatSection(null);
+ void navigate({ to: "/chat", search: { new: nonce } }).then(() =>
+ setPendingNewChatSection({ sectionId, nonce }),
+ );
+ closeMobileIfOpen();
+ }
+
function openProject(projectId: string) {
setActiveThreadId(null);
useChatRuntimeStore.getState().setActiveProjectId(projectId);
@@ -2543,6 +2914,12 @@ export function AppSidebar() {
});
}, [allChatItems, pendingRename]);
const [creatingProject, setCreatingProject] = useState(false);
+ // The section name dialog: a new section, optionally with rows to file into it, or a rename.
+ const [sectionDialog, setSectionDialog] = useState<
+ | ({ mode: "create" } & Omit<SectionTarget, "selection">)
+ | { mode: "rename"; section: SidebarCustomSection }
+ | null
+ >(null);
// The project behind the Edit dialog, or null while it is closed.
const [editingProject, setEditingProject] = useState<ProjectRecord | null>(
null,
@@ -2769,15 +3146,33 @@ export function AppSidebar() {
if (stayedOnRoute) openProject(project.id);
return;
}
+ // As a project picked from the list is, so a filed chat leaves its section for the folder.
+ await moveChatToProjectFromMenu(moveTarget, project.id);
+ }
+
+ /** A project picked from a chat's "Move to". The chat is meant to show in that project's folder,
+ * so the section it is filed in lets it go once the move lands, as it does on a drop on the
+ * folder; a section would otherwise keep drawing it. Not when it was filed again meanwhile,
+ * which is the newer intent, nor while it is pinned or drawn in one list, where no folder
+ * draws it. */
+ async function moveChatToProjectFromMenu(item: SidebarItem, projectId: string) {
+ const store = useSidebarOrganizationStore;
+ let filedSince = false;
+ const stopWatching = store.subscribe((now, before) => {
+ filedSince ||= now.sectionByChatId[item.id] !== before.sectionByChatId[item.id];
+ });
try {
- await moveChatItemToProject(moveTarget, project.id);
- if (activeThreadId === moveTarget.id) {
- useChatRuntimeStore.getState().setActiveProjectId(project.id);
+ if (!(await moveChatToProject(item, projectId)) || filedSince) return;
+ const now = store.getState();
+ if (
+ now.sectionByChatId[item.id] &&
+ now.organizeBy === "project" &&
+ !usePinnedChatsStore.getState().pinnedIds.includes(item.id)
+ ) {
+ setChatsSection([item.id], null);
}
- } catch (err) {
- toast.error("Failed to move chat to the new project", {
- description: err instanceof Error ? err.message : undefined,
- });
+ } finally {
+ stopWatching();
}
}
@@ -3105,22 +3500,266 @@ export function AppSidebar() {
{ enabled: !isTauri },
);
- // 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;
- includeProjectSort?: boolean;
+ /** Files chats into a custom section, or out of every section with null. A pinned chat would
+ * stay drawn in Pinned, so filing one takes its pin, and a hidden or closed target opens. */
+ function fileChatsInSection(chatIds: string[], sectionId: string | null) {
+ if (chatIds.length === 0) return;
+ setChatsSection(chatIds, sectionId);
+ if (!sectionId) return;
+ setPinnedChats(
+ chatIds.filter((id) => pinnedIdSet.has(id)),
+ false,
+ );
+ setSectionHidden(sectionId, false);
+ setCustomSectionOpen(sectionId, true);
+ }
+
+ /** The same for project folders. */
+ function fileProjectsInSection(projectIds: string[], sectionId: string | null) {
+ if (projectIds.length === 0) return;
+ setProjectsSection(projectIds, sectionId);
+ if (!sectionId) return;
+ for (const id of projectIds) {
+ if (pinnedProjectIdSet.has(id)) toggleProjectPin(id);
+ }
+ setSectionHidden(sectionId, false);
+ setCustomSectionOpen(sectionId, true);
+ }
+
+ /** Deletes a section. Nothing in it is deleted: its rows go back where they came from, and the
+ * toast can put the section back with them. */
+ function removeCustomSection(section: SidebarCustomSection) {
+ const state = useSidebarOrganizationStore.getState();
+ const index = state.customSections.findIndex((s) => s.id === section.id);
+ const chatIds = Object.keys(state.sectionByChatId).filter(
+ (id) => state.sectionByChatId[id] === section.id,
+ );
+ const projectIds = Object.keys(state.sectionByProjectId).filter(
+ (id) => state.sectionByProjectId[id] === section.id,
+ );
+ const order = state.manualOrder[customSectionScope(section.id)];
+ const hidden = state.hiddenSections.includes(section.id);
+ // The sections drawn after it, so undo can put it back above the first one still there.
+ const drawnOrder = resolveSectionOrder(state.sectionOrder, state.customSections);
+ const followers = drawnOrder.slice(drawnOrder.indexOf(section.id) + 1);
+ deleteCustomSection(section.id);
+ toast.success(t("shell.sections.deleted", { name: section.name }), {
+ action: {
+ label: t("shell.sections.undo"),
+ onClick: () => {
+ useSidebarOrganizationStore.setState((now) => {
+ if (now.customSections.some((s) => s.id === section.id)) return now;
+ const restored = [...now.customSections];
+ restored.splice(Math.min(index, restored.length), 0, section);
+ const sectionByChatId = assignmentMap(now.sectionByChatId);
+ for (const id of chatIds) sectionByChatId[id] ??= section.id;
+ const sectionByProjectId = assignmentMap(now.sectionByProjectId);
+ for (const id of projectIds) sectionByProjectId[id] ??= section.id;
+ const sectionOrder = resolveSectionOrder(now.sectionOrder, now.customSections);
+ const follower = followers.find((key) => sectionOrder.includes(key));
+ sectionOrder.splice(
+ follower === undefined ? sectionOrder.length : sectionOrder.indexOf(follower),
+ 0,
+ section.id,
+ );
+ return {
+ // In the order the sidebar now draws them, which the sections left behind may have
+ // been dragged out of since: the Show and Section lists read top to bottom like it.
+ customSections: inSectionOrder(restored, sectionOrder),
+ sectionOrder,
+ sectionByChatId,
+ sectionByProjectId,
+ hiddenSections: hidden
+ ? [...now.hiddenSections, section.id]
+ : now.hiddenSections,
+ manualOrder: order
+ ? { ...now.manualOrder, [customSectionScope(section.id)]: order }
+ : now.manualOrder,
+ };
+ });
+ },
+ },
+ });
+ }
+
+ /** One "Sort ... by" row, whose options open to the side. */
+ function renderSortSubmenu<T extends string>(config: {
+ label: string;
+ value: T;
+ onChange: (next: T) => void;
+ options: Array<{ value: T; key: TranslationKey }>;
}) {
return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <HugeiconsIcon icon={ArrowUpDownIcon} strokeWidth={1.75} className="size-icon" />
+ <span className="min-w-0 flex-1 truncate">{config.label}</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent {...sidebarSubmenuOffsets} className="unsloth-plus-menu sidebar-row-menu sidebar-menu w-44">
+ <DropdownMenuRadioGroup
+ value={config.value}
+ onValueChange={(value) => config.onChange(value as T)}
+ >
+ {config.options.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ {t(option.key)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+ }
+
+ // The "..." on each list header, carrying only what that list is about, as ChatGPT does: Pinned
+ // sorts its pins, Projects groups the sidebar and sorts its folders, and Recents adds which
+ // sections show and a new one. A custom section's own "..." manages that section.
+ function renderSidebarHeaderMenu(
+ options: { ariaLabel: string } & (
+ | { kind: "pinned" | "projects" | "recents" }
+ | { kind: "section"; section: SidebarCustomSection }
+ ),
+ ) {
+ // Keeps the menu open, so several sections can be toggled in one visit.
+ const stayOpen = (event: Event) => event.preventDefault();
+ const organizeSubmenu = (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <HugeiconsIcon icon={PanelLeftIcon} strokeWidth={1.75} className="size-icon" />
+ <span className="min-w-0 flex-1 truncate">
+ {t("shell.organize.sidebarHeading")}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent {...sidebarSubmenuOffsets} className="unsloth-plus-menu sidebar-row-menu sidebar-menu w-44">
+ <DropdownMenuRadioGroup
+ value={organizeBy}
+ onValueChange={(value) => setOrganizeBy(value as SidebarOrganizeBy)}
+ >
+ {ORGANIZE_OPTIONS.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ <HugeiconsIcon icon={option.icon} strokeWidth={1.75} className="size-icon" />
+ <span className="min-w-0 flex-1 truncate">{t(option.key)}</span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+ let body: ReactNode = null;
+ if (options.kind === "pinned") {
+ // Pinning is the grouping, so the sort is all there is: straight in, no submenu.
+ body = (
+ <DropdownMenuRadioGroup
+ value={pinnedSort}
+ onValueChange={(value) => setPinnedSort(value as SidebarChatSort)}
+ >
+ {CHAT_SORT_OPTIONS.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ {t(option.key)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ );
+ } else if (options.kind === "projects") {
+ body = (
+ <>
+ {organizeSubmenu}
+ {renderSortSubmenu({
+ label: t("shell.organize.sortChatsBy"),
+ value: chatSort,
+ onChange: setChatSort,
+ options: CHAT_SORT_OPTIONS,
+ })}
+ </>
+ );
+ } else if (options.kind === "recents") {
+ body = (
+ <>
+ {organizeSubmenu}
+ {renderSortSubmenu({
+ label: t("shell.organize.sortChatsBy"),
+ value: chatSort,
+ onChange: setChatSort,
+ options: CHAT_SORT_OPTIONS,
+ })}
+ {/* Pinned always shows, as it does in ChatGPT; Recents never hides, since this menu
+ lives on its header. That leaves Projects and the user's own sections. */}
+ {(projectsLoaded || customSections.length > 0) && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>{t("shell.organize.show")}</DropdownMenuLabel>
+ {projectsLoaded && (
+ <DropdownMenuCheckboxItem
+ // In one list there are no folders to show, and the grouping is the setting to change.
+ disabled={organizeBy !== "project"}
+ checked={organizeBy === "project" && !projectsSectionHidden}
+ onCheckedChange={(on) => setSectionHidden(PROJECTS_SECTION_KEY, !on)}
+ onSelect={stayOpen}
+ >
+ {t("shell.navigation.projects")}
+ </DropdownMenuCheckboxItem>
+ )}
+ {customSections.map((candidate) => (
+ <DropdownMenuCheckboxItem
+ key={candidate.id}
+ checked={!hiddenSectionSet.has(candidate.id)}
+ onCheckedChange={(on) => setSectionHidden(candidate.id, !on)}
+ onSelect={stayOpen}
+ >
+ <span className="min-w-0 truncate">{candidate.name}</span>
+ </DropdownMenuCheckboxItem>
+ ))}
+ </>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => setSectionDialog({ mode: "create" })}>
+ <HugeiconsIcon icon={PlusSignIcon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.organize.newSection")}</span>
+ </DropdownMenuItem>
+ </>
+ );
+ } else if (options.kind === "section") {
+ // As ChatGPT's: edit, bulk actions on the section's own chats, then remove.
+ const { section } = options;
+ const chats = (customSectionRows.get(section.id) ?? []).flatMap((row) =>
+ row.kind === "chat" ? [row.item] : [],
+ );
+ const threadIds = chats.flatMap(getSidebarItemThreadIds);
+ body = (
+ <>
+ <DropdownMenuItem onSelect={() => setSectionDialog({ mode: "rename", section })}>
+ <HugeiconsIcon icon={Settings02Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.sections.edit")}</span>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={!threadIds.some((id) => unreadThreadIds.has(id))}
+ onSelect={() => clearThreadsUnread(threadIds)}
+ >
+ <HugeiconsIcon icon={Tick02Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.sections.markAllRead")}</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem disabled={chats.length === 0} onSelect={() => void archiveChatItems(chats)}>
+ <HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.selection.archiveChats")}</span>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => removeCustomSection(section)}>
+ <HugeiconsIcon icon={Cancel01Icon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.sections.remove")}</span>
+ </DropdownMenuItem>
+ </>
+ );
+ }
+ return (
+ // Opens out to the right from the "...", over the chat, as ChatGPT's does, rather than
+ // squeezed back inside the sidebar.
<NonModalDropdownMenu
side="bottom"
- align="end"
- sideOffset={2}
- className="unsloth-plus-menu w-56"
+ align="start"
+ alignOffset={-6}
+ sideOffset={4}
+ className={cn("unsloth-plus-menu sidebar-row-menu sidebar-menu", options.kind === "pinned" ? "w-40" : "w-48")}
trigger={(triggerRef) => (
<button
ref={triggerRef}
@@ -3132,81 +3771,504 @@ export function AppSidebar() {
</button>
)}
>
- {options.includeOrganize && (
- <>
- <DropdownMenuLabel>
- {t("shell.organize.sidebarHeading")}
- </DropdownMenuLabel>
- <DropdownMenuRadioGroup
- value={organizeBy}
- onValueChange={(value) =>
- setOrganizeBy(value as SidebarOrganizeBy)
- }
+ {body}
+ </NonModalDropdownMenu>
+ );
+ }
+
+ /** One section above Recents, in the box a section drag reads and draws its line on. */
+ function renderOrderedSection(key: string): ReactNode {
+ let content: ReactNode = null;
+ if (key === PINNED_SECTION_KEY) content = renderPinnedSection();
+ else if (key === PROJECTS_SECTION_KEY) content = renderProjectsSection();
+ else {
+ const section = customSections.find((candidate) => candidate.id === key);
+ if (section) content = renderCustomSection(section);
+ }
+ if (content === null) return null;
+ return (
+ <div
+ data-sidebar-section={key}
+ onPointerDown={(event) => startSectionDrag(event, key)}
+ // Alt + arrow on the header moves the section, as it moves a row: the path to the same
+ // reorder for a keyboard, which never starts a pointer drag.
+ onKeyDown={(event) => {
+ const landing = sectionKeyLanding(event, key);
+ if (!landing) return;
+ event.preventDefault();
+ moveSection(key, landing.target, landing.edge);
+ }}
+ className="relative"
+ >
+ {content}
+ </div>
+ );
+ }
+
+ // The sections above Recents, each drawn by its own function so the order the user dragged
+ // them into decides where it goes.
+ // Pinned: folders and chats in one list, in the order they were dropped into.
+ function renderPinnedSection(): ReactNode {
+ if (isStudioRoute || showTrainingRecents || pinnedRows.length === 0) return null;
+ return (
+ <Collapsible open={pinnedOpen} onOpenChange={setPinnedOpen} asChild>
+ {/* While open, the next section rides up over the tail strip below, so the strip adds
+ no space. */}
+ <SidebarGroup className="group/sb-section group-data-[collapsible=icon]:hidden px-0 py-0 data-[state=open]:-mb-[calc(8px*var(--ui-space-scale,1))]">
+ {/* The header takes drops too: above the first row, or into a closed section. */}
+ <SidebarGroupLabel
+ className={cn(
+ "sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1",
+ headerInset,
+ scrolled && "is-scrolled",
+ )}
+ {...dnd.dropZoneProps(
+ {
+ section: "pinned",
+ header: true,
+ row: {
+ id: pinnedRows[0].id,
+ kind: pinnedRows[0].kind,
+ scope: PINNED_ORDER_SCOPE,
+ },
+ },
+ { closed: !pinnedOpen },
+ )}
+ >
+ <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-section:opacity-100 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"),
+ kind: "pinned",
+ })}
+ </SidebarGroupLabel>
+ <CollapsibleContent>
+ {/* The space under the rows lands a drop last. */}
+ <SidebarGroupContent
+ className={cn(unrailedRowPadding, "relative")}
+ {...dnd.dropZoneProps({ section: "pinned" })}
>
- {ORGANIZE_OPTIONS.map((option) => (
- <DropdownMenuRadioItem
- key={option.value}
- value={option.value}
- className={menuRadioItemClass}
- >
- {t(option.key)}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </>
- )}
- {options.includeProjectSort && (
- <>
- <DropdownMenuLabel>{t("shell.organize.sortProjectsBy")}</DropdownMenuLabel>
- <DropdownMenuRadioGroup
- value={projectSort}
- onValueChange={(value) => setProjectSort(value as SidebarProjectSort)}
+ <SidebarMenu>
+ {pinnedRows.map((row) =>
+ row.kind === "project"
+ ? renderProjectFolderRow(row.project, {
+ scope: PINNED_ORDER_SCOPE,
+ orderedIds: pinnedRowIds,
+ selectionIds: pinnedProjectRowIds,
+ section: "pinned",
+ sort: { value: pinnedSort, set: setPinnedSort },
+ })
+ : renderChatSidebarItem(row.item, "recent", {
+ scope: PINNED_ORDER_SCOPE,
+ ids: pinnedChatRowIds,
+ orderIds: pinnedRowIds,
+ section: "pinned",
+ sort: { value: pinnedSort, set: setPinnedSort },
+ }),
+ )}
+ {/* The end of the list, as somewhere to aim. A folder last in Pinned runs its
+ block to the bottom of the section, so every pixel down there is inside it
+ and a chat meant to go after the folder was filed into it instead.
+ Always drawn, never only while a row is carried: a row appearing at drag
+ start shifts every section under it after the pointer was sampled, and the
+ bottom fade measures a height this one would not be counted in.
+ It draws its own line, since the line under the folder's last chat already
+ means "into the folder, last" and the same pixels cannot mean both. */}
+ <SidebarMenuItem
+ aria-hidden
+ className={cn(
+ // z-[1]: above the next section's header, which overlaps it.
+ "relative z-[1] h-[calc(8px*var(--ui-space-scale,1))]",
+ dropCueClass(SIDEBAR_TAIL_SCOPE, "pinned"),
+ )}
+ {...dnd.dropZoneProps({
+ section: "pinned",
+ blockEnd: { scope: SIDEBAR_TAIL_SCOPE, id: "pinned" },
+ })}
+ />
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </CollapsibleContent>
+ </SidebarGroup>
+ </Collapsible>
+ );
+ }
+
+ // The user's own sections, each one list of folders and chats in the order they were
+ // dropped into, as Pinned is. Drawn empty too: a new section is somewhere to drag to.
+ function renderCustomSection(section: SidebarCustomSection): ReactNode {
+ if (isStudioRoute || showTrainingRecents || hiddenSectionSet.has(section.id)) return null;
+ const scope = customSectionScope(section.id);
+ const rows = customSectionRows.get(section.id) ?? [];
+ const ids = customSectionIds.get(section.id) ?? {
+ rows: [],
+ chats: [],
+ folders: [],
+ };
+ const open = !collapsedSectionIds.has(section.id);
+ const sort: RowSort = {
+ value: section.sort,
+ set: (next) => setCustomSectionSort(section.id, next),
+ };
+ return (
+ <Collapsible
+ key={section.id}
+ open={open}
+ onOpenChange={(next) => setCustomSectionOpen(section.id, next)}
+ asChild
+ >
+ {/* As Pinned: while open, the next section rides up over the tail strip. */}
+ <SidebarGroup
+ className={cn(
+ "group/sb-section group-data-[collapsible=icon]:hidden px-0 py-0",
+ rows.length > 0 &&
+ "data-[state=open]:-mb-[calc(8px*var(--ui-space-scale,1))]",
+ )}
+ >
+ <SidebarGroupLabel
+ className={cn(
+ "sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1",
+ headerInset,
+ scrolled && "is-scrolled",
+ !open &&
+ dnd.ringLit(sectionRingKey(scope)) &&
+ DROP_INTO_HEADER_CUE,
+ )}
+ {...dnd.dropZoneProps(
+ {
+ section: scope,
+ header: true,
+ row: rows[0]
+ ? { id: rows[0].id, kind: rows[0].kind, scope }
+ : undefined,
+ },
+ { closed: !open },
+ )}
+ >
+ <CollapsibleTrigger className="cursor-pointer flex min-w-0 flex-1 items-center gap-1 group/sb-collap">
+ <span className="min-w-0 truncate">{section.name}</span>
+ <ChevronDown className="size-3.5 shrink-0 opacity-0 transition-[transform,opacity] duration-200 group-hover/sb-section:opacity-100 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>
+ {/* As Recents has, a chat started here is filed here. */}
+ <button
+ type="button"
+ aria-label={t("shell.sections.newChatInSection", { name: section.name })}
+ onClick={() => openNewChatInSection(section.id)}
+ className="sidebar-header-action"
>
- {PROJECT_SORT_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)
+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />
+ </button>
+ {renderSidebarHeaderMenu({
+ ariaLabel: t("shell.sections.sectionOptions"),
+ kind: "section",
+ section,
+ })}
+ </SidebarGroupLabel>
+ <CollapsibleContent>
+ {/* The section's own space takes a drop, landing last, or first when empty. */}
+ <SidebarGroupContent
+ className={cn(
+ unrailedRowPadding,
+ "relative",
+ dnd.ringLit(sectionRingKey(scope)) && DROP_INTO_CUE,
+ )}
+ {...dnd.dropZoneProps({ section: scope })}
+ >
+ <SidebarMenu>
+ {rows.map((row) =>
+ row.kind === "project"
+ ? renderProjectFolderRow(row.project, {
+ scope,
+ orderedIds: ids.rows,
+ selectionIds: ids.folders,
+ section: scope,
+ sort,
+ })
+ : renderChatSidebarItem(row.item, "recent", {
+ scope,
+ ids: ids.chats,
+ orderIds: ids.rows,
+ section: scope,
+ sort,
+ }),
+ )}
+ {rows.length === 0 ? (
+ // Gives an empty section a body to hit, as the empty Projects line does.
+ <SidebarMenuItem>
+ <p className="flex h-[calc(30px*var(--ui-space-scale,1))] items-center pl-3 pr-4 text-ui-13 leading-ui-18 tracking-nav text-nav-fg-muted">
+ {t("shell.sections.empty")}
+ </p>
+ </SidebarMenuItem>
+ ) : (
+ // The end of the list, as somewhere to aim; see Pinned's.
+ <SidebarMenuItem
+ aria-hidden
+ className={cn(
+ "relative z-[1] h-[calc(8px*var(--ui-space-scale,1))]",
+ dropCueClass(SIDEBAR_TAIL_SCOPE, scope),
+ )}
+ {...dnd.dropZoneProps({
+ section: scope,
+ blockEnd: { scope: SIDEBAR_TAIL_SCOPE, id: scope },
+ })}
+ />
+ )}
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </CollapsibleContent>
+ </SidebarGroup>
+ </Collapsible>
+ );
+ }
+
+ // One folder per unpinned project. The header owns "New project", so the section stays
+ // even when every project is pinned.
+ function renderProjectsSection(): ReactNode {
+ if (!projectsSectionRendered) return null;
+ return (
+ <Collapsible
+ open={projectsOpen}
+ onOpenChange={setProjectsOpen}
+ asChild
+ >
+ <SidebarGroup className="group/sb-section group-data-[collapsible=icon]:hidden px-0 py-0">
+ {/* Trigger takes the free space; the actions reveal beside it. The header also
+ takes a pinned folder dragged back while the section is closed. */}
+ <SidebarGroupLabel
+ className={cn(
+ "sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1",
+ headerInset,
+ scrolled && "is-scrolled",
+ !projectsOpen &&
+ dnd.ringLit(sectionRingKey("projects")) &&
+ DROP_INTO_HEADER_CUE,
+ )}
+ {...dnd.dropZoneProps(
+ {
+ section: "projects",
+ header: true,
+ row: visibleProjectRecords[0]
+ ? {
+ id: visibleProjectRecords[0].id,
+ kind: "project",
+ scope: PROJECT_ORDER_SCOPE,
+ }
+ : undefined,
+ },
+ { closed: !projectsOpen },
+ )}
+ >
+ <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-section:opacity-100 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>
+ <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>
+ {renderSidebarHeaderMenu({
+ ariaLabel: t("shell.organize.organizeProjects"),
+ kind: "projects",
+ })}
+ </SidebarGroupLabel>
+ <CollapsibleContent>
+ {/* The section itself takes a pinned folder dragged back, landing last. */}
+ <SidebarGroupContent
+ className={cn(
+ unrailedRowPadding,
+ "relative",
+ dnd.ringLit(sectionRingKey("projects")) && DROP_INTO_CUE,
+ )}
+ {...dnd.dropZoneProps({ section: "projects" })}
+ >
+ <SidebarMenu>
+ {visibleProjectRecords.map((project) =>
+ renderProjectFolderRow(project, {
+ scope: PROJECT_ORDER_SCOPE,
+ orderedIds: projectRowIds,
+ section: "projects",
+ sort: { value: projectSort, set: setProjectSort },
+ }),
+ )}
+ {/* Every project is pinned, so the section is drawn with nothing in it. The
+ line gives the body a height: without one it collapses to zero and the
+ hit test walks straight past it, so a pinned folder dragged back has
+ nowhere to land and nothing lights up. */}
+ {visibleProjectRecords.length === 0 && (
+ <SidebarMenuItem>
+ <p className="flex h-[calc(30px*var(--ui-space-scale,1))] items-center pl-3 pr-4 text-ui-13 leading-ui-18 tracking-nav text-nav-fg-muted">
+ {t(
+ projects.length === 0
+ ? "shell.navigation.noProjects"
+ : projects.some((project) => sectionByProjectId[project.id])
+ ? "shell.navigation.allProjectsFiled"
+ : "shell.navigation.allProjectsPinned",
+ )}
+ </p>
+ </SidebarMenuItem>
+ )}
+ {/* 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-[calc(30px*var(--ui-space-scale,1))] 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>
+ </CollapsibleContent>
+ </SidebarGroup>
+ </Collapsible>
+ );
+ }
+
+ /** Files the rows a "Section" submenu was opened for. A selection is let go once filed, as
+ * the other bulk actions let theirs go. */
+ function fileSectionTarget(target: SectionTarget, sectionId: string | null) {
+ fileChatsInSection(target.chatIds ?? [], sectionId);
+ fileProjectsInSection(target.projectIds ?? [], sectionId);
+ if (target.selection) clearSelection();
+ }
+
+ /** The Sections group of a "Move to": New section, every section, then "Remove from section"
+ * last, only where a row has a section to leave. */
+ function renderSectionItems(
+ P: RowMenuParts,
+ config: {
+ target: SectionTarget;
+ /** The section every row is drawn in, which is not offered again. A pinned row keeps its
+ * section while Pinned draws it, and filing it there is how it goes back, so it has none. */
+ current: string | null;
+ /** Whether any row is drawn in a section it was filed in, which "Remove from section"
+ * undoes. Not a pinned row: Pinned draws it, whatever section it goes back to. */
+ anyFiled: boolean;
+ /** Headed, where the group shares a menu with the projects. */
+ heading?: boolean;
+ },
+ ) {
+ const { target } = config;
+ const leaving = config.current
+ ? customSections.find((section) => section.id === config.current)
+ : undefined;
+ // The section the rows are in is not a place to move them to, so it is left out, not greyed.
+ const destinations = customSections.filter((section) => section.id !== config.current);
+ return (
+ <>
+ {config.heading && <P.Label>{t("shell.sections.sectionsHeading")}</P.Label>}
+ <P.Item
+ onSelect={() =>
+ setSectionDialog({
+ mode: "create",
+ chatIds: target.chatIds,
+ projectIds: target.projectIds,
+ })
}
>
- {CHAT_SORT_OPTIONS.map((option) => (
- <DropdownMenuRadioItem
- key={option.value}
- value={option.value}
- className={menuRadioItemClass}
- >
- {t(option.key)}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </NonModalDropdownMenu>
+ <HugeiconsIcon icon={PlusSignIcon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.sections.newSection")}</span>
+ </P.Item>
+ {destinations.length > 0 && (
+ <div className={MOVE_TO_LIST}>
+ {destinations.map((section) => (
+ <P.Item
+ key={section.id}
+ onSelect={() => fileSectionTarget(target, section.id)}
+ >
+ <HugeiconsIcon icon={LayerIcon} strokeWidth={1.75} className="size-icon" />
+ <span className="truncate">{section.name}</span>
+ </P.Item>
+ ))}
+ </div>
+ )}
+ {/* An action, so only where there is something to undo: greyed out it read as a label.
+ It names the section, unless a selection is spread over several. */}
+ {config.anyFiled && (
+ <P.Item onSelect={() => fileSectionTarget(target, null)}>
+ <HugeiconsIcon icon={Cancel01Icon} strokeWidth={1.75} className="size-icon" />
+ <span className="truncate">
+ {leaving
+ ? t("shell.sections.removeFrom", { name: leaving.name })
+ : t("shell.sections.removeFromSection")}
+ </span>
+ </P.Item>
+ )}
+ </>
+ );
+ }
+
+ /** "Section" for rows that only sections take: a folder, or a selection. A chat's own menu
+ * has "Move to", which adds its projects. */
+ function renderSectionSubmenu(
+ P: RowMenuParts,
+ config: {
+ target: SectionTarget;
+ current: string | null;
+ anyFiled: boolean;
+ },
+ ) {
+ return (
+ <P.Sub>
+ <P.SubTrigger>
+ <HugeiconsIcon icon={LayerIcon} strokeWidth={1.75} className="size-icon" />
+ <span>{t("shell.sections.section")}</span>
+ </P.SubTrigger>
+ <P.SubContent
+ {...sidebarSubmenuOffsets}
+ className={cn("unsloth-plus-menu sidebar-row-menu sidebar-menu w-52", MOVE_TO_MENU)}
+ >
+ {renderSectionItems(P, config)}
+ </P.SubContent>
+ </P.Sub>
);
}
+ /** "Section" for a selection of several rows of one kind. */
+ function renderBulkSectionSubmenu(kind: "chat" | "project", ids: string[]) {
+ const assignments = kind === "chat" ? sectionByChatId : sectionByProjectId;
+ const pinned = kind === "chat" ? pinnedIdSet : pinnedProjectIdSet;
+ const sections = new Set(ids.map((id) => (pinned.has(id) ? null : assignments[id] ?? null)));
+ return renderSectionSubmenu(CONTEXT_ROW_MENU, {
+ target:
+ kind === "chat"
+ ? { chatIds: ids, selection: true }
+ : { projectIds: ids, selection: true },
+ current: sections.size === 1 ? [...sections][0] : null,
+ anyFiled: ids.some((id) => !pinned.has(id) && Boolean(assignments[id])),
+ });
+ }
+
/** A folder row's right-click menu. One row gets the same menu its 3-dot opens; a real
* selection of several gets the bulk actions, which right-click is the only pointer way to. */
function renderProjectContextMenu(project: ProjectRecord) {
if (projectSelectionCount <= 1) {
return (
- <ContextMenuContent className="unsloth-plus-menu sidebar-row-menu menu-flat-destructive w-52">
+ <ContextMenuContent className="unsloth-plus-menu sidebar-row-menu sidebar-menu menu-flat-destructive w-52">
{renderProjectRowMenuItems(project, CONTEXT_ROW_MENU)}
</ContextMenuContent>
);
}
return (
- <ContextMenuContent className="unsloth-plus-menu sidebar-row-menu menu-flat-destructive w-48">
+ <ContextMenuContent className="unsloth-plus-menu sidebar-row-menu sidebar-menu menu-flat-destructive w-48">
{projectSelectionCount > 1 && (
<ContextMenuLabel>
{t("shell.selection.countSelected", {
@@ -3224,6 +4286,10 @@ export function AppSidebar() {
: t("shell.selection.pinProjects")}
</span>
</ContextMenuItem>
+ {renderBulkSectionSubmenu(
+ "project",
+ selectedProjectRecords.map((selected) => selected.id),
+ )}
<ContextMenuSeparator />
<ContextMenuItem
variant="destructive"
@@ -3241,13 +4307,13 @@ export function AppSidebar() {
function renderChatContextMenu(item: SidebarItem, list: ChatListContext) {
if (selectionCount <= 1) {
return (
- <ContextMenuContent className="unsloth-plus-menu sidebar-row-menu menu-flat-destructive w-52">
+ <ContextMenuContent className="unsloth-plus-menu sidebar-row-menu sidebar-menu menu-flat-destructive w-52">
{renderChatRowMenuItems(item, list, CONTEXT_ROW_MENU)}
</ContextMenuContent>
);
}
return (
- <ContextMenuContent className="unsloth-plus-menu sidebar-row-menu menu-flat-destructive w-48">
+ <ContextMenuContent className="unsloth-plus-menu sidebar-row-menu sidebar-menu menu-flat-destructive w-48">
{selectionCount > 1 && (
<ContextMenuLabel>
{t("shell.selection.countSelected", { count: selectionCount })}
@@ -3261,6 +4327,10 @@ export function AppSidebar() {
: t("shell.selection.pinChats")}
</span>
</ContextMenuItem>
+ {renderBulkSectionSubmenu(
+ "chat",
+ selectedChatItems.map((selected) => selected.id),
+ )}
<ContextMenuItem onSelect={() => void archiveSelected()}>
<HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />
<span>{t("shell.selection.archiveChats")}</span>
@@ -3385,69 +4455,63 @@ export function AppSidebar() {
<OpenChatFolderUnavailableItem Item={P.Item} />
)
) : null}
+ {/* Projects and sections in one place: both are where the chat is kept. */}
<P.Sub>
<P.SubTrigger>
<HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />
- <span>Project</span>
+ <span>{t("shell.sections.moveTo")}</span>
</P.SubTrigger>
<P.SubContent
- sideOffset={0}
- alignOffset={-4}
- className="unsloth-plus-menu sidebar-row-menu w-48"
+ {...sidebarSubmenuOffsets}
+ className={cn("unsloth-plus-menu sidebar-row-menu sidebar-menu w-52", MOVE_TO_MENU)}
>
- {/* Actions above the rule, destinations below it. */}
+ {/* Two groups, each with its New first and its Remove last. */}
+ <P.Label>{t("shell.navigation.projects")}</P.Label>
<P.Item
onSelect={() => {
setProjectCreateMoveTarget(item);
setCreatingProject(true);
}}
>
- <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />
+ <HugeiconsIcon icon={PlusSignIcon} strokeWidth={1.75} className="size-icon" />
<span>New project</span>
</P.Item>
- <P.Sub>
- <P.SubTrigger>
- <HugeiconsIcon icon={FolderAttachmentIcon} strokeWidth={1.75} className="size-icon" />
- <span>Project sources</span>
- </P.SubTrigger>
- <P.SubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu sidebar-row-menu w-48">
- {projects.length === 0 && (
- <P.Item disabled>No projects yet</P.Item>
- )}
- {projects.map((project) => (
+ {/* The project the chat is in is not a place to move it to: left out, not greyed. */}
+ {projects.some((project) => project.id !== item.projectId) && (
+ <div className={MOVE_TO_LIST}>
+ {projects.filter((project) => project.id !== item.projectId).map((project) => (
<P.Item
key={project.id}
- onSelect={async () => {
- try {
- await saveChatToProjectSources(item, project.id);
- } catch {
- toast.error("Failed to save to project sources.");
- }
- }}
+ onSelect={() => void moveChatToProjectFromMenu(item, project.id)}
>
<HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />
<span className="truncate">{project.name}</span>
</P.Item>
))}
- </P.SubContent>
- </P.Sub>
- <P.Separator />
- <P.Item
- disabled={!item.projectId}
- onSelect={() => void moveChatToProject(item, null)}
- >
- <span>Recents</span>
- </P.Item>
- {projects.map((project) => (
- <P.Item
- 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>
+ </div>
+ )}
+ {/* An action, as the section's Remove is: only where there is a project to leave,
+ and named after it. */}
+ {item.projectId && (
+ <P.Item onSelect={() => void moveChatToProject(item, null)}>
+ <HugeiconsIcon icon={Cancel01Icon} strokeWidth={1.75} className="size-icon" />
+ <span className="truncate">
+ {(() => {
+ const leaving = projects.find((project) => project.id === item.projectId);
+ return leaving
+ ? t("shell.sections.removeFrom", { name: leaving.name })
+ : t("shell.sections.removeFromProject");
+ })()}
+ </span>
</P.Item>
- ))}
+ )}
+ <P.Separator />
+ {renderSectionItems(P, {
+ target: { chatIds: [item.id] },
+ current: pinnedIdSet.has(item.id) ? null : sectionByChatId[item.id] ?? null,
+ anyFiled: !pinnedIdSet.has(item.id) && Boolean(sectionByChatId[item.id]),
+ heading: true,
+ })}
</P.SubContent>
</P.Sub>
<P.Sub>
@@ -3455,7 +4519,7 @@ export function AppSidebar() {
<HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />
<span>Export</span>
</P.SubTrigger>
- <P.SubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu sidebar-row-menu w-48">
+ <P.SubContent {...sidebarSubmenuOffsets} className="unsloth-plus-menu sidebar-row-menu sidebar-menu w-48">
{chatExportOptions().map(({ label, format }) => (
<P.Item
key={label}
@@ -3619,7 +4683,7 @@ export function AppSidebar() {
<SidebarMenuItem
className={cn(
itemClass,
- draggingRow?.id === item.id && "opacity-50",
+ draggingRow?.id === item.id && "opacity-40",
dropCueClass(list.scope, item.id),
)}
onContextMenu={() => list && selectForContextMenu(item, list)}
@@ -3757,7 +4821,7 @@ export function AppSidebar() {
side="bottom"
align="start"
sideOffset={0}
- className="unsloth-plus-menu sidebar-row-menu menu-flat-destructive w-52"
+ className="unsloth-plus-menu sidebar-row-menu sidebar-menu menu-flat-destructive w-52"
trigger={(triggerRef) => (
<button
ref={triggerRef}
@@ -3802,9 +4866,14 @@ export function AppSidebar() {
</P.Item>
{/* Name, instructions and folders are one dialog, so Edit rather than Rename. */}
<P.Item onSelect={() => setEditingProject(project)}>
- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
+ <HugeiconsIcon icon={Settings02Icon} strokeWidth={1.75} className="size-icon" />
<span>Edit</span>
</P.Item>
+ {renderSectionSubmenu(P, {
+ target: { projectIds: [project.id] },
+ current: pinnedProjectIdSet.has(project.id) ? null : sectionByProjectId[project.id] ?? null,
+ anyFiled: !pinnedProjectIdSet.has(project.id) && Boolean(sectionByProjectId[project.id]),
+ })}
<P.Separator />
<P.Item
variant="destructive"
@@ -3857,7 +4926,7 @@ export function AppSidebar() {
className={cn(
"group/recent-item relative",
DROP_ROW_HIT,
- draggingRow?.id === project.id && "opacity-50",
+ draggingRow?.id === project.id && "opacity-40",
dropCueClass(order.scope, project.id),
// Lit while a chat is over the folder row or any of the chats inside it.
dnd.ringLit(folderRingKey(project.id)) && DROP_INTO_ROW_CUE,
@@ -3940,7 +5009,7 @@ export function AppSidebar() {
side="bottom"
align="start"
sideOffset={0}
- className="unsloth-plus-menu sidebar-row-menu menu-flat-destructive w-52"
+ className="unsloth-plus-menu sidebar-row-menu sidebar-menu menu-flat-destructive w-52"
trigger={(triggerRef) => (
<button
ref={triggerRef}
@@ -4423,207 +5492,11 @@ export function AppSidebar() {
</SidebarGroupContent>
</SidebarGroup>
- {/* Pinned: folders and chats in one list, in the order they were dropped into. */}
- {!isStudioRoute && !showTrainingRecents && pinnedRows.length > 0 && (
- <Collapsible open={pinnedOpen} onOpenChange={setPinnedOpen} asChild>
- {/* While open, the next section rides up over the tail strip below, so the strip adds
- no space. */}
- <SidebarGroup className="group/sb-section group-data-[collapsible=icon]:hidden px-0 py-0 data-[state=open]:-mb-[calc(8px*var(--ui-space-scale,1))]">
- {/* The header takes drops too: above the first row, or into a closed section. */}
- <SidebarGroupLabel
- className={cn(
- "sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1",
- headerInset,
- scrolled && "is-scrolled",
- )}
- {...dnd.dropZoneProps(
- {
- section: "pinned",
- header: true,
- row: {
- id: pinnedRows[0].id,
- kind: pinnedRows[0].kind,
- scope: PINNED_ORDER_SCOPE,
- },
- },
- { closed: !pinnedOpen },
- )}
- >
- <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-section:opacity-100 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>
- {/* The space under the rows lands a drop last. */}
- <SidebarGroupContent
- className={cn(unrailedRowPadding, "relative")}
- {...dnd.dropZoneProps({ section: "pinned" })}
- >
- <SidebarMenu>
- {pinnedRows.map((row) =>
- row.kind === "project"
- ? renderProjectFolderRow(row.project, {
- scope: PINNED_ORDER_SCOPE,
- orderedIds: pinnedRowIds,
- selectionIds: pinnedProjectRowIds,
- section: "pinned",
- sort: { value: pinnedSort, set: setPinnedSort },
- })
- : renderChatSidebarItem(row.item, "recent", {
- scope: PINNED_ORDER_SCOPE,
- ids: pinnedChatRowIds,
- orderIds: pinnedRowIds,
- section: "pinned",
- sort: { value: pinnedSort, set: setPinnedSort },
- }),
- )}
- {/* The end of the list, as somewhere to aim. A folder last in Pinned runs its
- block to the bottom of the section, so every pixel down there is inside it
- and a chat meant to go after the folder was filed into it instead.
- Always drawn, never only while a row is carried: a row appearing at drag
- start shifts every section under it after the pointer was sampled, and the
- bottom fade measures a height this one would not be counted in.
- It draws its own line, since the line under the folder's last chat already
- means "into the folder, last" and the same pixels cannot mean both. */}
- <SidebarMenuItem
- aria-hidden
- className={cn(
- // z-[1]: above the next section's header, which overlaps it.
- "relative z-[1] h-[calc(8px*var(--ui-space-scale,1))]",
- dropCueClass(SIDEBAR_TAIL_SCOPE, "pinned"),
- )}
- {...dnd.dropZoneProps({
- section: "pinned",
- blockEnd: { scope: SIDEBAR_TAIL_SCOPE, id: "pinned" },
- })}
- />
- </SidebarMenu>
- </SidebarGroupContent>
- </CollapsibleContent>
- </SidebarGroup>
- </Collapsible>
- )}
-
- {/* One folder per unpinned project. The header owns "New project", so the section stays
- even when every project is pinned. */}
- {projectsSectionRendered && (
- <Collapsible
- open={projectsOpen}
- onOpenChange={setProjectsOpen}
- asChild
- >
- <SidebarGroup className="group/sb-section group-data-[collapsible=icon]:hidden px-0 py-0">
- {/* Trigger takes the free space; the actions reveal beside it. The header also
- takes a pinned folder dragged back while the section is closed. */}
- <SidebarGroupLabel
- className={cn(
- "sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1",
- headerInset,
- scrolled && "is-scrolled",
- !projectsOpen &&
- dnd.ringLit(sectionRingKey("projects")) &&
- DROP_INTO_HEADER_CUE,
- )}
- {...dnd.dropZoneProps(
- {
- section: "projects",
- header: true,
- row: visibleProjectRecords[0]
- ? {
- id: visibleProjectRecords[0].id,
- kind: "project",
- scope: PROJECT_ORDER_SCOPE,
- }
- : undefined,
- },
- { closed: !projectsOpen },
- )}
- >
- <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-section:opacity-100 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>
- <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>
- {renderSidebarHeaderMenu({
- ariaLabel: t("shell.organize.organizeProjects"),
- includeOrganize: true,
- includeProjectSort: true,
- sortLabel: t("shell.organize.sortChatsBy"),
- sortValue: chatSort,
- onSortChange: setChatSort,
- })}
- </SidebarGroupLabel>
- <CollapsibleContent>
- {/* The section itself takes a pinned folder dragged back, landing last. */}
- <SidebarGroupContent
- className={cn(
- unrailedRowPadding,
- "relative",
- dnd.ringLit(sectionRingKey("projects")) && DROP_INTO_CUE,
- )}
- {...dnd.dropZoneProps({ section: "projects" })}
- >
- <SidebarMenu>
- {visibleProjectRecords.map((project) =>
- renderProjectFolderRow(project, {
- scope: PROJECT_ORDER_SCOPE,
- orderedIds: projectRowIds,
- section: "projects",
- sort: { value: projectSort, set: setProjectSort },
- }),
- )}
- {/* Every project is pinned, so the section is drawn with nothing in it. The
- line gives the body a height: without one it collapses to zero and the
- hit test walks straight past it, so a pinned folder dragged back has
- nowhere to land and nothing lights up. */}
- {visibleProjectRecords.length === 0 && (
- <SidebarMenuItem>
- <p className="flex h-[calc(30px*var(--ui-space-scale,1))] items-center pl-3 pr-4 text-ui-13 leading-ui-18 tracking-nav text-nav-fg-muted">
- {t("shell.navigation.allProjectsPinned")}
- </p>
- </SidebarMenuItem>
- )}
- {/* 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-[calc(30px*var(--ui-space-scale,1))] 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>
- </CollapsibleContent>
- </SidebarGroup>
- </Collapsible>
- )}
+ {/* Pinned, the user's sections and Projects, in the order they were dragged into.
+ Recents stays last, under them all. */}
+ {orderedSectionKeys.map((key) => (
+ <Fragment key={key}>{renderOrderedSection(key)}</Fragment>
+ ))}
{!isStudioRoute && !showTrainingRecents && (
<Collapsible open={chatOpen} onOpenChange={setChatOpen} asChild>
@@ -4667,10 +5540,7 @@ export function AppSidebar() {
</button>
{renderSidebarHeaderMenu({
ariaLabel: t("shell.organize.organizeChats"),
- includeOrganize: true,
- sortLabel: t("shell.organize.sortChatsBy"),
- sortValue: chatSort,
- onSortChange: setChatSort,
+ kind: "recents",
})}
</SidebarGroupLabel>
<CollapsibleContent>
@@ -4693,6 +5563,21 @@ export function AppSidebar() {
sort: { value: chatSort, set: setChatSort },
}),
)}
+ {sortedRecentChatItems.length > 0 && (
+ // The end of the list, as somewhere to aim; see Pinned's. The empty sidebar
+ // below it aims here too (use-sidebar-drag.ts).
+ <SidebarMenuItem
+ aria-hidden
+ className={cn(
+ "relative z-[1] h-[calc(8px*var(--ui-space-scale,1))]",
+ dropCueClass(SIDEBAR_TAIL_SCOPE, "recents"),
+ )}
+ {...dnd.dropZoneProps({
+ section: "recents",
+ blockEnd: { scope: SIDEBAR_TAIL_SCOPE, id: "recents" },
+ })}
+ />
+ )}
</SidebarMenu>
{/* "No chats yet" only when there is truly no history:
project-scoped and archived threads leave Recents empty
@@ -4901,7 +5786,7 @@ export function AppSidebar() {
side="top"
align="center"
sideOffset={8}
- className="app-user-menu menu-soft-surface-up ring-0 w-[calc(16rem*var(--ui-space-scale,1))] rounded-[20px] border border-transparent px-2.5 py-2.5 font-heading dark:border-[rgb(255_255_255_/_calc(0.05*var(--contrast-edge-gain,1)))]"
+ className="app-user-menu sidebar-menu menu-soft-surface-up ring-0 w-[round(calc(16rem*var(--ui-space-scale,1)),1px)] rounded-[20px] border border-transparent px-2.5 py-2.5 font-heading dark:border-[rgb(255_255_255_/_calc(0.05*var(--contrast-edge-gain,1)))]"
trigger={(triggerRef) => (
<SidebarMenuButton
ref={triggerRef}
@@ -5009,9 +5894,8 @@ export function AppSidebar() {
<span>{t("common.help")}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent
- sideOffset={8}
- alignOffset={-4}
- className="unsloth-plus-menu sidebar-row-menu w-56"
+ {...accountSubmenuOffsets}
+ className="unsloth-plus-menu sidebar-row-menu sidebar-menu w-56"
>
{HELP_GROUPS.map((group, index) => (
<DropdownMenuGroup key={group[0]}>
@@ -5037,7 +5921,7 @@ export function AppSidebar() {
<DropdownMenuItem
onSelect={() => useSettingsDialogStore.getState().openDialog("about")}
>
- <HugeiconsIcon icon={BadgeInfoIcon} strokeWidth={1.75} className="size-icon" />
+ <HugeiconsIcon icon={InformationCircleIcon} strokeWidth={1.75} className="size-icon" />
<span>{t("shell.helpMenu.about")}</span>
</DropdownMenuItem>
</DropdownMenuSubContent>
@@ -5261,6 +6145,34 @@ export function AppSidebar() {
submitLabel={projectCreateMoveTarget ? "Create and move" : "Create project"}
onCreated={afterCreateProject}
/>
+ <SectionNameDialog
+ open={sectionDialog !== null}
+ mode={sectionDialog?.mode ?? "create"}
+ initialName={sectionDialog?.mode === "rename" ? sectionDialog.section.name : ""}
+ onOpenChange={(open) => {
+ if (!open) setSectionDialog(null);
+ }}
+ onSubmit={(name) => {
+ if (!sectionDialog) return;
+ if (sectionDialog.mode === "rename") {
+ renameCustomSection(sectionDialog.section.id, name);
+ return;
+ }
+ const sectionId = createCustomSection(name);
+ if (!sectionId) return;
+ // The rows just filed leave the selection they were filed from, as any bulk action's do.
+ fileSectionTarget(
+ {
+ chatIds: sectionDialog.chatIds,
+ projectIds: sectionDialog.projectIds,
+ selection: Boolean(
+ sectionDialog.chatIds?.length || sectionDialog.projectIds?.length,
+ ),
+ },
+ sectionId,
+ );
+ }}
+ />
<EditProjectDialog
project={editingProject}
onOpenChange={(open) => {
diff --git a/studio/frontend/src/components/help-actions.ts b/studio/frontend/src/components/help-actions.ts
index 882ee76bac1..23ac42ae665 100644
--- a/studio/frontend/src/components/help-actions.ts
+++ b/studio/frontend/src/components/help-actions.ts
@@ -5,12 +5,12 @@ import { type SettingsTab, settingsTabVisible, useSettingsDialogStore } from "@/
import type { TranslationKey } from "@/i18n";
import { openLink } from "@/lib/open-link";
import {
- ActivityIcon,
Book03Icon,
- KeyboardIcon,
+ ComputerTerminal01Icon,
+ CpuIcon,
+ EnergyRectangleIcon,
MessageNotification01Icon,
NewReleasesIcon,
- Wrench01Icon,
} from "@hugeicons/core-free-icons";
import type { IconSvgElement } from "@hugeicons/react";
@@ -29,12 +29,13 @@ export const HELP_GROUPS: HelpAction[][] = [
["help-troubleshooting", "help-system-status", "help-send-feedback"],
];
+/** Icons match where each item leads: its Settings tab, or the About page's link. */
export const HELP_ITEMS: Record<HelpAction, { label: TranslationKey; icon: IconSvgElement }> = {
"help-documentation": { label: "shell.helpMenu.documentation", icon: Book03Icon },
- "help-keyboard-shortcuts": { label: "shell.helpMenu.keyboardShortcuts", icon: KeyboardIcon },
+ "help-keyboard-shortcuts": { label: "shell.helpMenu.keyboardShortcuts", icon: EnergyRectangleIcon },
"help-whats-new": { label: "shell.helpMenu.whatsNew", icon: NewReleasesIcon },
- "help-troubleshooting": { label: "shell.helpMenu.troubleshooting", icon: Wrench01Icon },
- "help-system-status": { label: "shell.helpMenu.systemStatus", icon: ActivityIcon },
+ "help-troubleshooting": { label: "shell.helpMenu.troubleshooting", icon: ComputerTerminal01Icon },
+ "help-system-status": { label: "shell.helpMenu.systemStatus", icon: CpuIcon },
"help-send-feedback": { label: "shell.helpMenu.sendFeedback", icon: MessageNotification01Icon },
};
diff --git a/studio/frontend/src/components/ui/combobox.tsx b/studio/frontend/src/components/ui/combobox.tsx
index 8f48ccbde5a..82b6303f4be 100644
--- a/studio/frontend/src/components/ui/combobox.tsx
+++ b/studio/frontend/src/components/ui/combobox.tsx
@@ -18,8 +18,9 @@ import {
InputGroupButton,
InputGroupInput,
} from "@/components/ui/input-group";
-import { Tick02Icon } from "@/lib/tick-icon";
+import { MenuTickIcon } from "@/lib/tick-icon";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
+import { useSnappedPaddingRef } from "@/lib/snap-padding";
import { cn } from "@/lib/utils";
import { Cancel01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -156,6 +157,7 @@ function ComboboxContent({
container?: HTMLElement | null;
}): React.ReactElement {
const dialogContainer = useDialogPortalContainer();
+ const snappedRef = useSnappedPaddingRef<HTMLDivElement>(undefined);
return (
<ComboboxPrimitive.Portal container={container ?? dialogContainer ?? undefined}>
<ComboboxPrimitive.Positioner
@@ -167,6 +169,7 @@ function ComboboxContent({
className="isolate z-[120] pointer-events-auto"
>
<ComboboxPrimitive.Popup
+ ref={snappedRef}
data-slot="combobox-content"
data-chips={!!anchor}
onWheel={(event) => {
@@ -225,7 +228,7 @@ function ComboboxItem({
<ComboboxPrimitive.Item
data-slot="combobox-item"
className={cn(
- "data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground gap-2 rounded-[10px] py-2 pr-2 pl-3 text-sm [&[aria-selected=true]]:pr-7 [&_svg:not([class*='size-'])]:size-4 relative flex w-full cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
+ "data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground gap-2 rounded-[10px] py-2 pr-2 pl-3 text-sm [&[aria-selected=true]]:pr-9 [&_svg:not([class*='size-'])]:size-4 relative flex w-full cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className,
)}
{...props}
@@ -233,11 +236,11 @@ function ComboboxItem({
{children}
<ComboboxPrimitive.ItemIndicator
render={
- <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
+ <span className="pointer-events-none absolute right-3 flex size-4 items-center justify-center" />
}
>
<HugeiconsIcon
- icon={Tick02Icon}
+ icon={MenuTickIcon}
strokeWidth={2}
className="pointer-events-none"
/>
diff --git a/studio/frontend/src/components/ui/command.tsx b/studio/frontend/src/components/ui/command.tsx
index 47031d1a629..f766bc8bcdc 100644
--- a/studio/frontend/src/components/ui/command.tsx
+++ b/studio/frontend/src/components/ui/command.tsx
@@ -14,7 +14,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { InputGroup, InputGroupAddon } from "@/components/ui/input-group";
-import { Tick02Icon } from "@/lib/tick-icon";
+import { MenuTickIcon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
import { Search01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -171,7 +171,7 @@ function CommandItem({
>
{children}
<HugeiconsIcon
- icon={Tick02Icon}
+ icon={MenuTickIcon}
strokeWidth={2}
className="ml-auto opacity-0 group-has-[[data-slot=command-shortcut]]/command-item:hidden group-data-[checked=true]/command-item:opacity-100"
/>
@@ -187,7 +187,7 @@ function CommandShortcut({
<span
data-slot="command-shortcut"
className={cn(
- "text-muted-foreground group-data-selected/command-item:text-foreground ml-auto text-xs tracking-widest",
+ "text-muted-foreground group-data-selected/command-item:text-foreground ml-auto -mr-[0.1em] text-xs tracking-widest",
className,
)}
{...props}
diff --git a/studio/frontend/src/components/ui/context-menu.tsx b/studio/frontend/src/components/ui/context-menu.tsx
index 7afc3cf7995..f26b5181bee 100644
--- a/studio/frontend/src/components/ui/context-menu.tsx
+++ b/studio/frontend/src/components/ui/context-menu.tsx
@@ -6,12 +6,11 @@
import { ContextMenu as ContextMenuPrimitive } from "radix-ui";
import type * as React from "react";
-import { Tick02Icon } from "@/lib/tick-icon";
+import { MenuChevronRightIcon } from "@/lib/chevron-icons";
+import { MenuTickIcon } from "@/lib/tick-icon";
+import { useSnappedPaddingRef } from "@/lib/snap-padding";
import { cn } from "@/lib/utils";
import { HugeiconsIcon } from "@hugeicons/react";
-import {
- ChevronRightIcon,
-} from "lucide-react";
function ContextMenu({
...props
@@ -67,13 +66,16 @@ function ContextMenuRadioGroup({
function ContextMenuContent({
className,
+ ref,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left";
}) {
+ const snappedRef = useSnappedPaddingRef(ref);
return (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
+ ref={snappedRef}
data-slot="context-menu-content"
className={cn(
"data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-[color-mix(in_oklab,var(--foreground)_calc(5%*var(--contrast-edge-gain,1)),transparent)] bg-popover text-popover-foreground min-w-48 max-w-[calc(100vw-32px)] rounded-2xl p-1 shadow-2xl ring-1 duration-100 z-50 max-h-(--radix-context-menu-content-available-height) origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto",
@@ -127,8 +129,9 @@ function ContextMenuSubTrigger({
{...props}
>
{children}
- <ChevronRightIcon
- strokeWidth={2}
+ <HugeiconsIcon
+ icon={MenuChevronRightIcon}
+ strokeWidth={1.5}
className="ml-auto size-[calc(12px*var(--ui-space-scale,1))]"
/>
</ContextMenuPrimitive.SubTrigger>
@@ -137,14 +140,17 @@ function ContextMenuSubTrigger({
function ContextMenuSubContent({
className,
+ ref,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
+ const snappedRef = useSnappedPaddingRef(ref);
return (
// Portaled like DropdownMenuSubContent, for the same reason: rendered inline, the fixed
// popper wrapper sits inside ContextMenuContent, whose open animation transforms it. That
// makes it the containing block and its overflow clips the submenu away.
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.SubContent
+ ref={snappedRef}
data-slot="context-menu-sub-content"
className={cn(
"data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 bg-popover text-popover-foreground min-w-32 max-w-[calc(100vw-32px)] rounded-md border p-1 shadow-lg duration-100 z-50 origin-(--radix-context-menu-content-transform-origin) overflow-hidden",
@@ -166,15 +172,15 @@ function ContextMenuCheckboxItem({
<ContextMenuPrimitive.CheckboxItem
data-slot="context-menu-checkbox-item"
className={cn(
- "focus:bg-accent focus:text-accent-foreground gap-2 rounded-xl py-2 pr-8 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-default items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
+ "focus:bg-accent focus:text-accent-foreground gap-2 rounded-xl py-2 pr-9 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-default items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className,
)}
checked={checked}
{...props}
>
- <span className="absolute right-2 pointer-events-none">
+ <span className="absolute right-3 pointer-events-none">
<ContextMenuPrimitive.ItemIndicator>
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
@@ -198,7 +204,7 @@ function ContextMenuRadioItem({
>
<span className="absolute right-2 pointer-events-none">
<ContextMenuPrimitive.ItemIndicator>
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
@@ -247,7 +253,7 @@ function ContextMenuShortcut({
<span
data-slot="context-menu-shortcut"
className={cn(
- "text-muted-foreground group-focus/context-menu-item:text-accent-foreground ml-auto text-xs tracking-widest",
+ "text-muted-foreground group-focus/context-menu-item:text-accent-foreground ml-auto -mr-[0.1em] text-xs tracking-widest",
className,
)}
{...props}
diff --git a/studio/frontend/src/components/ui/dropdown-menu.tsx b/studio/frontend/src/components/ui/dropdown-menu.tsx
index 9fb4b7d827c..5795775f431 100644
--- a/studio/frontend/src/components/ui/dropdown-menu.tsx
+++ b/studio/frontend/src/components/ui/dropdown-menu.tsx
@@ -4,9 +4,10 @@
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
import * as React from "react";
-import { Tick02Icon } from "@/lib/tick-icon";
-import { ChevronRightStandardIcon } from "@/lib/chevron-icons";
+import { MenuTickIcon } from "@/lib/tick-icon";
+import { MenuChevronRightIcon } from "@/lib/chevron-icons";
import { useIsMobile } from "@/hooks/use-mobile";
+import { snapRowInsets, useSnappedPaddingRef } from "@/lib/snap-padding";
import { cn } from "@/lib/utils";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -40,19 +41,24 @@ function DropdownMenuContent({
align = "start",
sideOffset = 0,
children,
+ ref,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
+ const snappedRef = useSnappedPaddingRef(ref);
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
+ ref={snappedRef}
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
align={align}
className={cn(
+ // Width in whole pixels: Firefox draws a row's hover pill a device pixel off centre in a
+ // menu of fractional width (padding and margin are rounded as it mounts).
// The 3px alignment nudge must be margin, not translate: a transform
// here makes this scroll container the containing block for nested
// position:fixed submenu wrappers, clipping every submenu.
- "data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 bg-popover text-popover-foreground min-w-48 max-w-[calc(100vw-32px)] rounded-lg p-1 duration-100 z-50 max-h-(--radix-dropdown-menu-content-available-height) w-[calc(var(--radix-dropdown-menu-trigger-width)_+_6px*var(--ui-space-scale,1))] data-[align=start]:-ml-[calc(3px*var(--ui-space-scale,1))] data-[align=end]:ml-[calc(3px*var(--ui-space-scale,1))] origin-(--radix-dropdown-menu-content-transform-origin) flex flex-col overflow-hidden",
+ "data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 bg-popover text-popover-foreground min-w-48 max-w-[calc(100vw-32px)] rounded-lg p-1 duration-100 z-50 max-h-(--radix-dropdown-menu-content-available-height) w-[round(calc(var(--radix-dropdown-menu-trigger-width)_+_6px*var(--ui-space-scale,1)),1px)] data-[align=start]:-ml-[calc(3px*var(--ui-space-scale,1))] data-[align=end]:ml-[calc(3px*var(--ui-space-scale,1))] origin-(--radix-dropdown-menu-content-transform-origin) flex flex-col overflow-hidden",
className,
)}
{...props}
@@ -112,18 +118,18 @@ function DropdownMenuCheckboxItem({
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
- "focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-[11px] py-2 pr-8 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
+ "focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-[11px] py-2 pr-9 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className,
)}
checked={checked}
{...props}
>
<span
- className="pointer-events-none absolute right-2 flex items-center justify-center pointer-events-none"
+ className="pointer-events-none absolute right-3 flex items-center justify-center"
data-slot="dropdown-menu-checkbox-item-indicator"
>
<DropdownMenuPrimitive.ItemIndicator>
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
@@ -151,17 +157,17 @@ function DropdownMenuRadioItem({
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
- "focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-[11px] py-2 pr-8 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
+ "focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground gap-2.5 rounded-[11px] py-2 pr-9 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 relative flex cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className,
)}
{...props}
>
<span
- className="pointer-events-none absolute right-2 flex items-center justify-center pointer-events-none"
+ className="pointer-events-none absolute right-3 flex items-center justify-center"
data-slot="dropdown-menu-radio-item-indicator"
>
<DropdownMenuPrimitive.ItemIndicator>
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
@@ -210,7 +216,7 @@ function DropdownMenuShortcut({
<span
data-slot="dropdown-menu-shortcut"
className={cn(
- "text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ml-auto text-xs tracking-widest",
+ "text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground ml-auto -mr-[0.1em] text-xs tracking-widest",
className,
)}
{...props}
@@ -252,7 +258,7 @@ function DropdownMenuSubTrigger({
>
{children}
<HugeiconsIcon
- icon={ChevronRightStandardIcon}
+ icon={MenuChevronRightIcon}
strokeWidth={1.5}
className="ml-auto size-[calc(12px*var(--ui-space-scale,1))]"
/>
@@ -280,6 +286,7 @@ function DropdownMenuSubContent({
resizeObserverRef.current = null;
assignRef(ref, element);
if (!element) return;
+ snapRowInsets(element);
const updateContentWidth = () => {
setContentWidth(element.offsetWidth);
diff --git a/studio/frontend/src/components/ui/menubar.tsx b/studio/frontend/src/components/ui/menubar.tsx
index d7f738e848c..d46773dc65f 100644
--- a/studio/frontend/src/components/ui/menubar.tsx
+++ b/studio/frontend/src/components/ui/menubar.tsx
@@ -7,8 +7,9 @@ import { Menubar as MenubarPrimitive } from "radix-ui";
import type * as React from "react";
import { Tick02Icon } from "@/lib/tick-icon";
+import { useSnappedPaddingRef } from "@/lib/snap-padding";
import { cn } from "@/lib/utils";
-import { ChevronRightStandardIcon } from "@/lib/chevron-icons";
+import { MenuChevronRightIcon } from "@/lib/chevron-icons";
import { HugeiconsIcon } from "@hugeicons/react";
function Menubar({
@@ -74,11 +75,14 @@ function MenubarContent({
align = "start",
alignOffset = -4,
sideOffset = 0,
+ ref,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
+ const snappedRef = useSnappedPaddingRef(ref);
return (
<MenubarPortal>
<MenubarPrimitive.Content
+ ref={snappedRef}
data-slot="menubar-content"
align={align}
alignOffset={alignOffset}
@@ -207,7 +211,7 @@ function MenubarShortcut({
<span
data-slot="menubar-shortcut"
className={cn(
- "text-muted-foreground group-focus/menubar-item:text-accent-foreground text-xs tracking-widest ml-auto",
+ "text-muted-foreground group-focus/menubar-item:text-accent-foreground text-xs tracking-widest ml-auto -mr-[0.1em]",
className,
)}
{...props}
@@ -241,7 +245,7 @@ function MenubarSubTrigger({
>
{children}
<HugeiconsIcon
- icon={ChevronRightStandardIcon}
+ icon={MenuChevronRightIcon}
strokeWidth={1.5}
className="ml-auto size-[calc(12px*var(--ui-space-scale,1))]"
/>
@@ -251,10 +255,13 @@ function MenubarSubTrigger({
function MenubarSubContent({
className,
+ ref,
...props
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
+ const snappedRef = useSnappedPaddingRef(ref);
return (
<MenubarPrimitive.SubContent
+ ref={snappedRef}
data-slot="menubar-sub-content"
className={cn(
"bg-popover text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-[color-mix(in_oklab,var(--foreground)_calc(5%*var(--contrast-edge-gain,1)),transparent)] min-w-32 rounded-2xl p-1 shadow-2xl ring-1 duration-100 z-50 origin-(--radix-menubar-content-transform-origin) overflow-hidden",
diff --git a/studio/frontend/src/components/ui/popover.tsx b/studio/frontend/src/components/ui/popover.tsx
index 1f4c2f60016..66b6b43d51d 100644
--- a/studio/frontend/src/components/ui/popover.tsx
+++ b/studio/frontend/src/components/ui/popover.tsx
@@ -7,6 +7,7 @@ import { Popover as PopoverPrimitive } from "radix-ui";
import type * as React from "react";
import { useDialogPortalContainer } from "@/components/ui/dialog";
+import { useSnappedPaddingRef } from "@/lib/snap-padding";
import { cn } from "@/lib/utils";
function Popover({
@@ -26,10 +27,12 @@ function PopoverContent({
align = "center",
sideOffset = 0,
container,
+ ref,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content> & {
container?: HTMLElement | null;
}) {
+ const snappedRef = useSnappedPaddingRef(ref);
// Inside a modal dialog the body scroll lock swallows wheel events on
// body-portaled content; portal into the dialog instead (like Select).
const dialogContainer = useDialogPortalContainer();
@@ -38,6 +41,7 @@ function PopoverContent({
container={container ?? dialogContainer ?? undefined}
>
<PopoverPrimitive.Content
+ ref={snappedRef}
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
diff --git a/studio/frontend/src/components/ui/select.tsx b/studio/frontend/src/components/ui/select.tsx
index 148305bfd82..a2e93eec975 100644
--- a/studio/frontend/src/components/ui/select.tsx
+++ b/studio/frontend/src/components/ui/select.tsx
@@ -7,11 +7,12 @@ import { Select as SelectPrimitive } from "radix-ui";
import type * as React from "react";
import { createContext, useContext, useState } from "react";
-import { Tick02Icon } from "@/lib/tick-icon";
+import { MenuTickIcon } from "@/lib/tick-icon";
import {
ChevronDownStandardIcon,
ChevronUpStandardIcon,
} from "@/lib/chevron-icons";
+import { useSnappedPaddingRef } from "@/lib/snap-padding";
import { cn } from "@/lib/utils";
import { useDialogPortalContainer } from "@/components/ui/dialog";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -115,14 +116,17 @@ function SelectContent({
position = "popper",
align = "center",
container,
+ ref,
...props
}: React.ComponentProps<typeof SelectPrimitive.Content> & {
container?: HTMLElement | null;
}) {
const dialogContainer = useDialogPortalContainer();
+ const snappedRef = useSnappedPaddingRef(ref);
return (
<SelectPrimitive.Portal container={container ?? dialogContainer ?? undefined}>
<SelectPrimitive.Content
+ ref={snappedRef}
data-slot="select-content"
data-align-trigger={position === "item-aligned"}
className={cn(
@@ -180,15 +184,15 @@ function SelectItem({
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
- "focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2.5 rounded-[11px] py-2 pr-8 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2 relative flex w-full cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
+ "focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground gap-2.5 rounded-[11px] py-2 pr-9 pl-3 text-sm [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2 relative flex w-full cursor-pointer items-center outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
className,
)}
{...props}
>
- <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
+ <span className="pointer-events-none absolute right-3 flex size-4 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<HugeiconsIcon
- icon={Tick02Icon}
+ icon={MenuTickIcon}
strokeWidth={2}
className="pointer-events-none"
/>
diff --git a/studio/frontend/src/features/chat/components/section-name-dialog.tsx b/studio/frontend/src/features/chat/components/section-name-dialog.tsx
new file mode 100644
index 00000000000..4433580eb7d
--- /dev/null
+++ b/studio/frontend/src/features/chat/components/section-name-dialog.tsx
@@ -0,0 +1,124 @@
+// 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 { useState } from "react";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { useT } from "@/i18n";
+
+import {
+ CUSTOM_SECTION_NAME_MAX,
+ normalizeSectionName,
+} from "../stores/sidebar-organization-store";
+
+// Names a custom sidebar section: a new one, or an existing one being renamed. The caller owns
+// what the name is for, so this only collects it.
+export function SectionNameDialog({
+ open,
+ mode,
+ initialName = "",
+ onOpenChange,
+ onSubmit,
+}: {
+ open: boolean;
+ mode: "create" | "rename";
+ initialName?: string;
+ onOpenChange: (open: boolean) => void;
+ onSubmit: (name: string) => void;
+}) {
+ // What the open dialog was opened for, kept through the close animation: the caller clears its
+ // state on close, which would otherwise flip a rename to "New section" as it fades out.
+ const [shown, setShown] = useState({ mode, initialName });
+ if (open && (shown.mode !== mode || shown.initialName !== initialName)) {
+ setShown({ mode, initialName });
+ }
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="corner-squircle dialog-soft-surface gap-5 sm:max-w-md">
+ {/* Content unmounts on close, so each open starts from its own name, not the last draft. */}
+ <SectionNameForm
+ mode={shown.mode}
+ initialName={shown.initialName}
+ onCancel={() => onOpenChange(false)}
+ onSubmit={(name) => {
+ onSubmit(name);
+ onOpenChange(false);
+ }}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function SectionNameForm({
+ mode,
+ initialName,
+ onCancel,
+ onSubmit,
+}: {
+ mode: "create" | "rename";
+ initialName: string;
+ onCancel: () => void;
+ onSubmit: (name: string) => void;
+}) {
+ const t = useT();
+ const [name, setName] = useState(initialName);
+ const clean = normalizeSectionName(name);
+ const unchanged = mode === "rename" && clean === normalizeSectionName(initialName);
+
+ function submit() {
+ if (!clean || unchanged) return;
+ onSubmit(clean);
+ }
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle className="text-ui-21">
+ {mode === "create"
+ ? t("shell.sections.createTitle")
+ : t("shell.sections.renameTitle")}
+ </DialogTitle>
+ <DialogDescription>
+ {mode === "create"
+ ? t("shell.sections.createDescription")
+ : t("shell.sections.renameDescription")}
+ </DialogDescription>
+ </DialogHeader>
+ <input
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ submit();
+ }
+ }}
+ onFocus={(event) => {
+ if (mode === "rename") event.currentTarget.select();
+ }}
+ autoFocus
+ maxLength={CUSTOM_SECTION_NAME_MAX}
+ placeholder={t("shell.sections.namePlaceholder")}
+ aria-label={t("shell.sections.namePlaceholder")}
+ className="w-full rounded-[14px] border border-border bg-background px-4 py-3 text-base outline-none transition-colors placeholder:text-muted-foreground focus:border-ring dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:focus:border-ring"
+ />
+ <DialogFooter className="flex-wrap gap-2 sm:justify-end">
+ <Button type="button" variant="ghost" onClick={onCancel}>
+ {t("common.cancel")}
+ </Button>
+ <Button type="button" onClick={submit} disabled={!clean || unchanged}>
+ {mode === "create" ? t("shell.sections.create") : t("common.save")}
+ </Button>
+ </DialogFooter>
+ </>
+ );
+}
diff --git a/studio/frontend/src/features/chat/hooks/use-section-drag.ts b/studio/frontend/src/features/chat/hooks/use-section-drag.ts
new file mode 100644
index 00000000000..e6a351f6b67
--- /dev/null
+++ b/studio/frontend/src/features/chat/hooks/use-section-drag.ts
@@ -0,0 +1,408 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Reordering the sidebar's sections by their headers. The grabbed header lifts and follows the
+// pointer, the section it came from dims, and one line glides to the gap it would land in. All
+// of that is drawn straight onto the DOM: the sidebar is one large component, and redrawing it
+// on every pointer move is what made the drag lag. React only hears about the drop.
+//
+// Pointer events, for the same reason as the row drag: the desktop webview never forwards the
+// HTML5 drag API to the page.
+
+import { useCallback, useEffect, useRef } from "react";
+
+import type { DropEdge } from "../lib/sidebar-drag.ts";
+import { placeIdAt } from "../stores/sidebar-organization-store.ts";
+import {
+ DRAG_THRESHOLD_PX,
+ EDGE_PX,
+ EDGE_STEP_PX,
+ dragLayer,
+ markDragging,
+ scrollerOf,
+ sidebarOf,
+} from "./use-sidebar-drag.ts";
+
+/** Marks a draggable section's box with its key. */
+export const SECTION_ATTR = "data-sidebar-section";
+/** Set on the section being carried, which the stylesheet dims. */
+export const SECTION_DRAGGING_ATTR = "data-section-dragging";
+const HEADER_SELECTOR = '[data-sidebar="group-label"]';
+/** The header's own buttons ("+", "..."), which keep their press. */
+const HEADER_ACTION_SELECTOR = ".sidebar-header-action";
+/** How long a dropped section takes to slide from where it was let go into its slot. */
+const SETTLE_MS = 180;
+
+export type SectionLanding = { target: string; edge: DropEdge };
+
+/** A drawn section, top to bottom, as the landing reads it. */
+export type SectionBlock = { key: string; top: number; bottom: number };
+
+/**
+ * Where a section carried to `y` lands among `blocks` (the carried one left out): against the
+ * top of the first block whose middle is below the pointer, or under the last block. Null with
+ * nowhere to go.
+ */
+export function sectionLandingAt(
+ blocks: readonly SectionBlock[],
+ y: number,
+): SectionLanding | null {
+ for (const block of blocks) {
+ if (y < (block.top + block.bottom) / 2) return { target: block.key, edge: "top" };
+ }
+ const last = blocks.at(-1);
+ return last ? { target: last.key, edge: "bottom" } : null;
+}
+
+/** Whether landing `key` there changes the order `drawn` shows. A landing that leaves it as it
+ * is draws no line, so a line always means the drop will do something. */
+export function landingMoves(
+ drawn: readonly string[],
+ key: string,
+ landing: SectionLanding,
+): boolean {
+ const next = placeIdAt([...drawn], key, landing.target, landing.edge);
+ return next.some((id, index) => id !== drawn[index]);
+}
+
+/** The height of the gap above a header's text, where its line is drawn: the header carries the
+ * space between sections as its own top padding. */
+function lineYAbove(header: Element): number {
+ const box = header.getBoundingClientRect();
+ const text = (header.querySelector("button") ?? header).getBoundingClientRect();
+ return Math.round(box.top + (text.top - box.top) / 2);
+}
+
+/** The next drawn element after `element` that has a header of its own. */
+function headedSiblingAfter(element: Element | undefined): Element | null {
+ for (let next = element?.nextElementSibling; next; next = next.nextElementSibling) {
+ if (next instanceof HTMLElement && next.offsetHeight > 0 && next.querySelector(HEADER_SELECTOR)) {
+ return next;
+ }
+ }
+ return null;
+}
+
+/**
+ * Where Alt + Up or Down on a section's header moves the section: past the drawn section above or
+ * below it. The keyboard's way to the reorder a drag does, as alt + arrow is for a row. Null for
+ * any other key, a press outside the header or on its buttons, and at either end of the list.
+ */
+export function sectionKeyLanding(
+ event: React.KeyboardEvent<HTMLElement>,
+ key: string,
+): SectionLanding | null {
+ if (!event.altKey || (event.key !== "ArrowUp" && event.key !== "ArrowDown")) return null;
+ const pressed = event.target as Element;
+ const header = pressed.closest(HEADER_SELECTOR);
+ if (!header || !event.currentTarget.contains(header)) return null;
+ if (pressed.closest(HEADER_ACTION_SELECTOR)) return null;
+ const list = event.currentTarget.parentElement;
+ if (!list) return null;
+ const drawn = [...list.querySelectorAll<HTMLElement>(`:scope > [${SECTION_ATTR}]`)]
+ .filter((element) => element.offsetHeight > 0)
+ .map((element) => element.getAttribute(SECTION_ATTR));
+ const up = event.key === "ArrowUp";
+ const at = drawn.indexOf(key);
+ const neighbour = at === -1 ? undefined : drawn[at + (up ? -1 : 1)];
+ return neighbour ? { target: neighbour, edge: up ? "top" : "bottom" } : null;
+}
+
+export interface UseSectionDragOptions {
+ /** Commits a drop that changes the order. */
+ onDrop: (key: string, landing: SectionLanding) => void;
+ /** Read on drop: whether the section may slide into place or should just appear there. */
+ reducedMotion?: () => boolean;
+}
+
+/** Returns the header's pointerdown handler; spread it on the box marked with SECTION_ATTR. */
+export function useSectionDrag(
+ options: UseSectionDragOptions,
+): (event: React.PointerEvent<HTMLElement>, key: string) => void {
+ const optionsRef = useRef(options);
+ useEffect(() => {
+ optionsRef.current = options;
+ });
+ /** The gesture in flight, so a second press cannot start another over it. */
+ const gesture = useRef<{ end: () => void } | null>(null);
+ useEffect(() => () => gesture.current?.end(), []);
+
+ return useCallback((event: React.PointerEvent<HTMLElement>, key: string) => {
+ // Touch scrolls the sidebar, the right button opens a menu, and "+" or "..." keep their press.
+ if (event.button !== 0 || event.pointerType === "touch" || !event.isPrimary) return;
+ const pressed = event.target as Element;
+ const header = pressed.closest(HEADER_SELECTOR);
+ if (!header || !event.currentTarget.contains(header)) return;
+ if (pressed.closest(HEADER_ACTION_SELECTOR)) return;
+ const block = event.currentTarget;
+ const parent = block.parentElement;
+ if (!parent) return;
+ // Typed here, not narrowed: the handlers below are hoisted and would lose the narrowing.
+ const list: HTMLElement = parent;
+ gesture.current?.end();
+
+ const pointerId = event.pointerId;
+ const startX = event.clientX;
+ const startY = event.clientY;
+ let pointerY = startY;
+ let started = false;
+ let escaped = false;
+ let frame = 0;
+ let landing: SectionLanding | null = null;
+ let scroller: HTMLElement = list;
+ let ghost: HTMLElement | null = null;
+ /** Where the copy was put when it lifted; it moves by a transform from there. */
+ let ghostTop = 0;
+ let line: HTMLElement | null = null;
+ // Where on the header text the press landed, so the lifted copy does not jump.
+ const text = header.querySelector("button") ?? header;
+ const grab = startY - text.getBoundingClientRect().top;
+
+ const drawnBlocks = () =>
+ [...list.querySelectorAll<HTMLElement>(`:scope > [${SECTION_ATTR}]`)].filter(
+ (element) => element.offsetHeight > 0,
+ );
+
+ /** A copy of the header's text on a raised pill, over the header it came from. */
+ const lift = () => {
+ const textRect = text.getBoundingClientRect();
+ const headerRect = header.getBoundingClientRect();
+ const style = getComputedStyle(header);
+ ghost = document.createElement("div");
+ ghost.setAttribute("aria-hidden", "true");
+ ghost.className = "sidebar-section-ghost";
+ const copy = text.cloneNode(true) as HTMLElement;
+ copy.removeAttribute("id");
+ copy.tabIndex = -1;
+ ghost.append(copy);
+ const inset = 10;
+ // Lifted where the header is, raised as place() raises it, so a frame drawn before its
+ // first transform lands shows it there, not at the top of the window.
+ ghostTop = textRect.top - 6;
+ Object.assign(ghost.style, {
+ top: `${ghostTop}px`,
+ left: `${textRect.left - inset}px`,
+ width: `${headerRect.right - 8 - (textRect.left - inset)}px`,
+ height: `${textRect.height + 12}px`,
+ paddingInline: `${inset}px`,
+ fontFamily: style.fontFamily,
+ fontSize: style.fontSize,
+ fontWeight: style.fontWeight,
+ letterSpacing: style.letterSpacing,
+ color: style.color,
+ });
+ line = document.createElement("div");
+ line.setAttribute("aria-hidden", "true");
+ line.className = "sidebar-section-drop-line";
+ dragLayer().append(ghost, line);
+ };
+
+ const place = () => {
+ const view = scroller.getBoundingClientRect();
+ if (ghost) {
+ const height = ghost.offsetHeight;
+ const top = Math.min(
+ Math.max(pointerY - grab - 6, view.top),
+ view.bottom - height,
+ );
+ ghost.style.transform = `translate3d(0, ${Math.round(top - ghostTop)}px, 0)`;
+ }
+ const blocks = drawnBlocks();
+ const drawn = blocks.map((element) => element.getAttribute(SECTION_ATTR)!);
+ const others = blocks.filter((element) => element !== block);
+ const hit = sectionLandingAt(
+ others.map((element) => {
+ const rect = element.getBoundingClientRect();
+ return { key: element.getAttribute(SECTION_ATTR)!, top: rect.top, bottom: rect.bottom };
+ }),
+ pointerY,
+ );
+ landing = hit && landingMoves(drawn, key, hit) ? hit : null;
+ if (!line) return;
+ let y: number | null = null;
+ if (landing) {
+ const { target: targetKey, edge } = landing;
+ const target = others.find((element) => element.getAttribute(SECTION_ATTR) === targetKey);
+ // Under the last section is the gap above whatever follows it: Recents' header.
+ const below = edge === "top" ? target : headedSiblingAfter(target);
+ const belowHeader = below?.querySelector(HEADER_SELECTOR);
+ if (belowHeader) y = lineYAbove(belowHeader);
+ else if (target) y = Math.round(target.getBoundingClientRect().bottom);
+ }
+ if (y === null || y < view.top || y > view.bottom) {
+ line.style.opacity = "0";
+ return;
+ }
+ const shown = line.style.opacity === "1";
+ // Glides between gaps once it is up; the first placement is instant. Shown and placed in
+ // one change, by `top`, so it is never drawn a frame early at the top of the window.
+ line.style.transition = shown ? "" : "none";
+ Object.assign(line.style, {
+ left: `${view.left + 8}px`,
+ width: `${view.width - 16}px`,
+ top: `${y - 0.75}px`,
+ opacity: "1",
+ });
+ };
+
+ /** One step of the edge scroll, from the frame loop: a pointer resting at the edge sends no
+ * moves, and the list must keep going. */
+ const edgeScroll = () => {
+ const view = scroller.getBoundingClientRect();
+ if (pointerY < view.top + EDGE_PX) scroller.scrollTop -= EDGE_STEP_PX;
+ else if (pointerY > view.bottom - EDGE_PX) scroller.scrollTop += EDGE_STEP_PX;
+ };
+
+ const onFrame = () => {
+ if (!started || escaped) {
+ frame = 0;
+ return;
+ }
+ frame = requestAnimationFrame(onFrame);
+ edgeScroll();
+ place();
+ };
+
+ /** Takes down everything the drag drew. Returns where the lifted copy was, for the settle. */
+ const putDown = (): number | null => {
+ const ghostTop = ghost ? ghost.getBoundingClientRect().top + 6 : null;
+ ghost?.remove();
+ line?.remove();
+ ghost = null;
+ line = null;
+ block.removeAttribute(SECTION_DRAGGING_ATTR);
+ markDragging(null, false);
+ return ghostTop;
+ };
+
+ const detach = () => {
+ if (gesture.current === self) gesture.current = null;
+ if (frame) cancelAnimationFrame(frame);
+ frame = 0;
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", onUp);
+ window.removeEventListener("pointercancel", onCancel);
+ window.removeEventListener("keydown", onKey, true);
+ if (document.body.hasPointerCapture?.(pointerId)) {
+ document.body.releasePointerCapture(pointerId);
+ }
+ };
+
+ // Abandons the gesture whole: an unmount, or a new press that never saw this one's release.
+ const self = {
+ end: () => {
+ detach();
+ if (started) putDown();
+ },
+ };
+ gesture.current = self;
+
+ /** The release clicks the header it lands on, which would fold the section just moved. */
+ const swallowClick = () => {
+ const stop = (clicked: MouseEvent) => {
+ clicked.preventDefault();
+ clicked.stopPropagation();
+ };
+ window.addEventListener("click", stop, { capture: true, once: true });
+ window.setTimeout(() => window.removeEventListener("click", stop, { capture: true }), 0);
+ };
+
+ /** Slides the dropped section from where it was let go into its new slot. */
+ const settle = (from: number) => {
+ if (optionsRef.current.reducedMotion?.()) return;
+ // Two frames: the drop re-renders the list, and the section is measured once it has moved.
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ const moved = list.querySelector<HTMLElement>(
+ `:scope > [${SECTION_ATTR}="${CSS.escape(key)}"]`,
+ );
+ const movedHeader = moved?.querySelector(HEADER_SELECTOR);
+ if (!moved || !movedHeader) return;
+ const to = (movedHeader.querySelector("button") ?? movedHeader).getBoundingClientRect().top;
+ const delta = from - to;
+ if (Math.abs(delta) < 2) return;
+ moved.style.transition = "none";
+ moved.style.transform = `translateY(${delta}px)`;
+ moved.style.zIndex = "1";
+ moved.getBoundingClientRect();
+ moved.style.transition = `transform ${SETTLE_MS}ms cubic-bezier(0.2, 0.8, 0.2, 1)`;
+ moved.style.transform = "";
+ window.setTimeout(() => {
+ moved.style.transition = "";
+ moved.style.zIndex = "";
+ }, SETTLE_MS + 20);
+ }),
+ );
+ };
+
+ function onMove(moved: PointerEvent) {
+ if (moved.pointerId !== pointerId || escaped) return;
+ pointerY = moved.clientY;
+ if (!started) {
+ if (
+ Math.abs(moved.clientX - startX) < DRAG_THRESHOLD_PX &&
+ Math.abs(moved.clientY - startY) < DRAG_THRESHOLD_PX
+ ) {
+ return;
+ }
+ started = true;
+ scroller = scrollerOf(list) ?? list;
+ markDragging(sidebarOf(list), true);
+ // Without capture a release outside the window never arrives and the drag sticks.
+ try {
+ document.body.setPointerCapture(pointerId);
+ } catch {
+ // Window listeners still carry the drag inside the window.
+ }
+ block.setAttribute(SECTION_DRAGGING_ATTR, "");
+ lift();
+ // Placed now, so the copy and line are right in the frame that first shows them.
+ place();
+ frame = requestAnimationFrame(onFrame);
+ }
+ // The frame loop places everything, once a frame: moves come faster than frames on many
+ // mice, and each placement reads every section's box.
+ moved.preventDefault();
+ }
+
+ function onUp(released: PointerEvent) {
+ if (released.pointerId !== pointerId) return;
+ detach();
+ if (!started) return;
+ swallowClick();
+ if (escaped) return;
+ pointerY = released.clientY;
+ place();
+ const dropped = landing;
+ const from = putDown();
+ if (!dropped) return;
+ optionsRef.current.onDrop(key, dropped);
+ if (from !== null) settle(from);
+ }
+
+ function onCancel(aborted: PointerEvent) {
+ if (aborted.pointerId !== pointerId) return;
+ detach();
+ if (started) putDown();
+ }
+
+ function onKey(keyEvent: KeyboardEvent) {
+ if (keyEvent.key !== "Escape" || escaped) return;
+ if (!started) {
+ // Nothing was lifted, so a click after this is still the header's.
+ detach();
+ return;
+ }
+ keyEvent.preventDefault();
+ keyEvent.stopPropagation();
+ // The button is still down: keep listening, so its release does not fold the section.
+ escaped = true;
+ putDown();
+ }
+
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", onUp);
+ window.addEventListener("pointercancel", onCancel);
+ window.addEventListener("keydown", onKey, true);
+ }, []);
+}
diff --git a/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts b/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
index b0311690396..f15da6fa9cc 100644
--- a/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
+++ b/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
@@ -4,6 +4,11 @@
// The React side of sidebar drag-and-drop: the lifted row, the plan under the pointer, and the
// pointer events that feed both. What a drop does is decided in lib/sidebar-drag.ts.
//
+// The carried row lifts as a copy that follows the pointer, the way a section's header does
+// (use-section-drag.ts), while the row it came from dims. The copy is drawn straight onto the
+// DOM and moved from the frame loop, so the sidebar does not redraw as the pointer moves: React
+// only hears when the plan under the pointer changes, and on the drop.
+//
// Pointer events, not the HTML5 drag API. The desktop webview answers every OS drag itself and
// never forwards it to the page, so dragover and drop never fire there and a row wired to them
// is dead. Same reason shared-composer.tsx skips its drop handlers under isTauri.
@@ -41,16 +46,72 @@ export const DRAG_THRESHOLD_PX = 5;
* registration: the hit test reads it back off whatever sits under the pointer. */
export const DROP_ZONE_ATTR = "data-sidebar-drop";
-/** Set on the body for the length of a drag: no text selection, and the grabbing cursor
- * follows the row off its own list. */
-export const DRAGGING_BODY_CLASS = "sidebar-row-dragging";
+/** Set on the box a drag happens in (the sidebar, or the model picker's list) for its length: the
+ * grabbing cursor over its rows, whose buttons set a cursor of their own, and no selection
+ * (index.css). Never on the body: a class or inherited style changed there restyles every element
+ * on the page, which with a long chat open made a visible hitch as a drag started and ended. */
+export const DRAGGING_CLASS = "pointer-dragging";
+
+/** Past the box, text selection is refused as it starts: no style change, so no restyle. */
+function refuseSelection(event: Event) {
+ event.preventDefault();
+}
+
+/** Marks a drag in flight in `box`. Off clears every mark. */
+export function markDragging(box: Element | null, on: boolean) {
+ if (on) {
+ box?.classList.add(DRAGGING_CLASS);
+ window.getSelection()?.removeAllRanges();
+ document.addEventListener("selectstart", refuseSelection, true);
+ return;
+ }
+ document.removeEventListener("selectstart", refuseSelection, true);
+ for (const marked of document.querySelectorAll(`.${DRAGGING_CLASS}`)) {
+ marked.classList.remove(DRAGGING_CLASS);
+ }
+}
+
+/** Holds whatever a drag draws over the page: the lifted copy, the cue drawn over it, a section's
+ * line. Made once and never taken off the body. Taking a body child out while another follows it
+ * restyles every element on the page, which on the drop was a visible hitch; the same child taken
+ * out of this layer costs nothing. */
+export function dragLayer(): HTMLElement {
+ let layer = document.getElementById(DRAG_LAYER_ID);
+ if (!layer) {
+ layer = document.createElement("div");
+ layer.id = DRAG_LAYER_ID;
+ layer.setAttribute("aria-hidden", "true");
+ document.body.append(layer);
+ }
+ return layer;
+}
+
+const DRAG_LAYER_ID = "pointer-drag-layer";
+
+/** The sidebar a drag started in, which markDragging marks. */
+export const sidebarOf = (element: Element): Element | null =>
+ element.closest('[data-sidebar="sidebar"]');
/** Controls that own their own press. A drag never starts from the pin or the kebab. */
const NO_DRAG_SELECTOR = ".sidebar-row-action";
-/** How near an edge of the scroller the pointer scrolls the list, and by how much per move. */
-const EDGE_PX = 48;
-const EDGE_STEP_PX = 12;
+/** The raised copy of a carried row. */
+export const ROW_GHOST_CLASS = "sidebar-row-ghost";
+
+/** On the element that paints the drop cue: the insertion line, or the outline of what the row
+ * would join. */
+export const DROP_CUE_CLASS = "sidebar-drop-cue";
+
+/** The cue's border drawn again above the carried copy, which covers the spot it is aimed at.
+ * The section drag draws its line above its header's copy the same way. */
+const CUE_OVERLAY_CLASS = "sidebar-drop-cue-overlay";
+
+/** How long a dropped row takes to slide from where it was let go into its slot. */
+const SETTLE_MS = 180;
+
+/** How near an edge of the scroller the pointer scrolls the list, and by how much per frame. */
+export const EDGE_PX = 48;
+export const EDGE_STEP_PX = 12;
interface ZoneHit {
zone: SidebarDropZone;
@@ -83,6 +144,28 @@ function zonesUnder(x: number, y: number): ZoneHit[] {
return hits;
}
+/** The end strip Recents draws past its last row. Recents is always the last list, so the empty
+ * sidebar below it is past the end of every list: a drop there lands where it would on the strip. */
+function zonePastRecents(x: number, y: number, list: Element | null): ZoneHit | null {
+ if (typeof document === "undefined") return null;
+ const tail = document.querySelector(
+ `[${ROW_KEY_ATTR}="${CSS.escape(rowKey(SIDEBAR_TAIL_SCOPE, "recents"))}"]`,
+ );
+ if (!tail) return null;
+ const rect = tail.getBoundingClientRect();
+ if (rect.height === 0 || y < rect.bottom || x < rect.left || x > rect.right) return null;
+ // Inside the list, not over the account row under it.
+ if (list && y > list.getBoundingClientRect().bottom) return null;
+ try {
+ const parsed = JSON.parse(tail.getAttribute(DROP_ZONE_ATTR) ?? "") as {
+ zone: SidebarDropZone;
+ };
+ return { zone: parsed.zone, closed: false, rect };
+ } catch {
+ return null;
+ }
+}
+
/** Max distance between a row's bottom and the next row's top for them to share a gap. */
const ADJACENT_PX = 3;
@@ -117,8 +200,188 @@ function rowNextTo(key: string, side: "below" | "above"): ZoneHit | null {
return null;
}
+/** A row's face: its icon and name, without the pin and menu that show on hover. */
+const ROW_FACE_SELECTOR = '[data-sidebar="menu-button"]';
+
+/** Attributes the copy of a row must not carry: it is a picture, not a control, a drop zone, a
+ * row a test or a lookup can find, or the open chat. */
+const GHOST_DROPPED_ATTRS = [
+ "id",
+ DROP_ZONE_ATTR,
+ ROW_KEY_ATTR,
+ "data-active",
+ "data-testid",
+ "data-thread-id",
+ "data-thread-type",
+] as const;
+
+interface RowGhost {
+ element: HTMLElement;
+ /** Where on the row the press landed, so the copy does not jump when it lifts. */
+ grab: number;
+ /** The box the copy stays inside: the list it scrolls in. */
+ view: Element;
+ /** Where the copy was put when it lifted; it moves by a transform from there. */
+ top: number;
+ /** The cues drawn over the copy: the line, and the outline of the folder it lands in. */
+ cues: HTMLElement[];
+}
+
+/** A copy of the row's face on a raised pill, over the row it came from. */
+function liftRow(row: HTMLElement, pressY: number, view: Element): RowGhost | null {
+ const face = row.querySelector<HTMLElement>(ROW_FACE_SELECTOR);
+ if (!face) return null;
+ const rect = face.getBoundingClientRect();
+ const style = getComputedStyle(face);
+ const copy = face.cloneNode(true) as HTMLElement;
+ for (const node of [copy, ...copy.querySelectorAll<HTMLElement>("*")]) {
+ for (const name of GHOST_DROPPED_ATTRS) node.removeAttribute(name);
+ }
+ copy.tabIndex = -1;
+ const element = document.createElement("div");
+ element.setAttribute("aria-hidden", "true");
+ element.className = ROW_GHOST_CLASS;
+ element.append(copy);
+ // Lifted where the row is, so a frame drawn before its first transform lands shows it there,
+ // not at the top of the window.
+ Object.assign(element.style, {
+ top: `${rect.top}px`,
+ left: `${rect.left}px`,
+ width: `${rect.width}px`,
+ height: `${rect.height}px`,
+ borderRadius: style.borderRadius,
+ fontFamily: style.fontFamily,
+ color: style.color,
+ });
+ // The icon size is the sidebar's own variable, which the copy leaves behind on the body.
+ const iconSize = style.getPropertyValue("--icon-size");
+ if (iconSize) element.style.setProperty("--icon-size", iconSize);
+ dragLayer().append(element);
+ return { element, grab: pressY - rect.top, view, top: rect.top, cues: [] };
+}
+
+/** Draws each cue painted under the copy again over it: its border only, since the tint under
+ * the copy would otherwise double where the two meet. Clipped to the list, as the cue is. */
+function placeCue(ghost: RowGhost) {
+ const view = ghost.view.getBoundingClientRect();
+ let shown = 0;
+ for (const cue of document.querySelectorAll<HTMLElement>(`.${DROP_CUE_CLASS}`)) {
+ const style = getComputedStyle(cue, "::before");
+ if (style.content === "none" || cue.offsetHeight === 0) continue;
+ let overlay = ghost.cues[shown];
+ if (!overlay) {
+ overlay = document.createElement("div");
+ overlay.setAttribute("aria-hidden", "true");
+ overlay.className = CUE_OVERLAY_CLASS;
+ dragLayer().append(overlay);
+ ghost.cues.push(overlay);
+ }
+ shown += 1;
+ const box = cue.getBoundingClientRect();
+ // border-box, so the width and height read here include the border.
+ const left = box.left + (parseFloat(style.left) || 0);
+ const top = box.top + (parseFloat(style.top) || 0);
+ const height = parseFloat(style.height) || 0;
+ Object.assign(overlay.style, {
+ display: "block",
+ width: style.width,
+ height: `${height}px`,
+ borderStyle: style.borderStyle,
+ borderColor: style.borderColor,
+ borderTopWidth: style.borderTopWidth,
+ borderRightWidth: style.borderRightWidth,
+ borderBottomWidth: style.borderBottomWidth,
+ borderLeftWidth: style.borderLeftWidth,
+ borderRadius: style.borderRadius,
+ // Placed by left and top, set in the same change that shows it, never a frame late.
+ left: `${left}px`,
+ top: `${top}px`,
+ clipPath: `inset(${Math.max(0, view.top - top)}px 0 ${Math.max(0, top + height - view.bottom)}px 0)`,
+ });
+ }
+ for (const overlay of ghost.cues.slice(shown)) overlay.style.display = "none";
+}
+
+/** Keeps the copy under the pointer, inside the list it came from. */
+function placeGhost(ghost: RowGhost, y: number) {
+ const view = ghost.view.getBoundingClientRect();
+ const height = ghost.element.offsetHeight;
+ const top = Math.min(Math.max(y - ghost.grab, view.top), view.bottom - height);
+ ghost.element.style.transform = `translate3d(0, ${Math.round(top - ghost.top)}px, 0)`;
+}
+
+/** What a drop zone says it is, or null if it cannot be read. */
+function zoneOf(element: Element): SidebarDropZone | null {
+ try {
+ return (JSON.parse(element.getAttribute(DROP_ZONE_ATTR) ?? "") as { zone: SidebarDropZone }).zone;
+ } catch {
+ return null;
+ }
+}
+
+/** Slides a dropped row from where its copy was let go into its new slot, and a folder's open
+ * chats with it. Read once the drop has redrawn the list, so it costs one pass per drop. */
+function settleRow(item: SidebarDragItem, from: number) {
+ // Two frames: the drop re-renders the sidebar, and the row is measured once it has moved.
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ let row: HTMLElement | null = null;
+ const moving: HTMLElement[] = [];
+ for (const element of document.querySelectorAll<HTMLElement>(`[${DROP_ZONE_ATTR}]`)) {
+ if (element.offsetHeight === 0) continue;
+ const zone = zoneOf(element);
+ if (!zone) continue;
+ const isRow = zone.row?.id === item.id && zone.row.kind === item.kind && !zone.header;
+ if (isRow && element.hasAttribute(ROW_KEY_ATTR)) {
+ // The copy of the row nearest where it was let go, should it be drawn twice.
+ const face = element.querySelector(ROW_FACE_SELECTOR) ?? element;
+ const top = face.getBoundingClientRect().top;
+ const best = row?.querySelector(ROW_FACE_SELECTOR) ?? row;
+ if (!best || Math.abs(top - from) < Math.abs(best.getBoundingClientRect().top - from)) {
+ row = element;
+ }
+ }
+ // A folder carries its open chats and its empty line: the spots that name it.
+ if (
+ item.kind === "project" &&
+ zone.folderId === item.id &&
+ zone.row?.kind !== "project" &&
+ !zone.header
+ ) {
+ moving.push(element);
+ }
+ }
+ if (!row) return;
+ const to = (row.querySelector(ROW_FACE_SELECTOR) ?? row).getBoundingClientRect().top;
+ const delta = from - to;
+ if (Math.abs(delta) < 2) return;
+ // Only the outermost of nested spots move, or a spot would move twice.
+ const all = [row, ...moving.filter((element) => element !== row)];
+ const slide = all.filter(
+ (element) => !all.some((other) => other !== element && other.contains(element)),
+ );
+ for (const element of slide) {
+ element.style.transition = "none";
+ element.style.transform = `translateY(${delta}px)`;
+ element.style.zIndex = "1";
+ }
+ row.getBoundingClientRect();
+ for (const element of slide) {
+ element.style.transition = `transform ${SETTLE_MS}ms cubic-bezier(0.2, 0.8, 0.2, 1)`;
+ element.style.transform = "";
+ }
+ window.setTimeout(() => {
+ for (const element of slide) {
+ element.style.transition = "";
+ element.style.zIndex = "";
+ }
+ }, SETTLE_MS + 20);
+ }),
+ );
+}
+
/** The list the row scrolls while it is carried: the nearest ancestor that actually scrolls. */
-function scrollerOf(element: Element | null): HTMLElement | null {
+export function scrollerOf(element: Element | null): HTMLElement | null {
for (let node = element; node; node = node.parentElement) {
if (!(node instanceof HTMLElement)) continue;
const overflow = getComputedStyle(node).overflowY;
@@ -139,10 +402,12 @@ export interface UseSidebarDragOptions {
onDrop: (plan: SidebarDropPlan, drag: SidebarDragItem) => void;
/** Opens the closed folder or section the pointer rested on. */
onSpringOpen?: (zone: SidebarDropZone) => void;
+ /** Read on drop: whether the row may slide into place or should just appear there. */
+ reducedMotion?: () => boolean;
}
export interface SidebarDragApi {
- /** The lifted row, for painting it faded. Null between drags. */
+ /** The carried row, for painting it dimmed where it was. Null between drags. */
drag: SidebarDragItem | null;
/** What the drop under the pointer would do. */
plan: SidebarDropPlan | null;
@@ -155,8 +420,9 @@ export interface SidebarDragApi {
zone: SidebarDropZone,
options?: { closed?: boolean },
) => Record<string, string>;
- /** The edge the insertion line is drawn on for this row in this list, if any. */
- lineEdge: (scope: string, id: string) => DropEdge | undefined;
+ /** The insertion line drawn on this row in this list, if any: its edge, and whether it lands
+ * inside a folder, among its chats, rather than beside the folder in its list. */
+ lineAt: (scope: string, id: string) => { edge: DropEdge; inFolder: boolean } | undefined;
/** Whether the whole target under this key is lit. */
ringLit: (key: string) => boolean;
}
@@ -175,6 +441,7 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
});
const spring = useRef<{ key: string; timer: number } | null>(null);
const scroller = useRef<HTMLElement | null>(null);
+ const ghost = useRef<RowGhost | null>(null);
/** The gesture in flight, so a second pointer cannot start another over the top of it. */
const press = useRef<{ end: () => void } | null>(null);
@@ -196,7 +463,10 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
setSidebarDragSource(null);
cancelSpring();
scroller.current = null;
- document.body.classList.remove(DRAGGING_BODY_CLASS);
+ ghost.current?.element.remove();
+ for (const overlay of ghost.current?.cues ?? []) overlay.remove();
+ ghost.current = null;
+ markDragging(null, false);
setDrag(null);
showPlan(null);
}, [cancelSpring, showPlan]);
@@ -213,7 +483,9 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
const dragged = sidebarDragSource();
if (!dragged) return null;
const context = optionsRef.current.context();
- for (const hit of zonesUnder(x, y)) {
+ const under = zonesUnder(x, y);
+ const past = under.length === 0 ? zonePastRecents(x, y, scroller.current) : null;
+ for (const hit of past ? [past] : under) {
const outcome = planSidebarDrop(
dragged,
hit.zone,
@@ -342,7 +614,9 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
}
frame = requestAnimationFrame(onFrame);
edgeScroll(at.y);
+ if (ghost.current) placeGhost(ghost.current, at.y);
track(at.x, at.y);
+ if (ghost.current) placeCue(ghost.current);
};
// Abandons this gesture whole, for a drop that never came: the same as a cancel.
const self = {
@@ -380,7 +654,13 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
}
started = true;
scroller.current = scrollerOf(row);
- document.body.classList.add(DRAGGING_BODY_CLASS);
+ ghost.current = liftRow(
+ row,
+ startY,
+ scroller.current ?? row.closest('[data-sidebar="content"]') ?? document.documentElement,
+ );
+ if (ghost.current) placeGhost(ghost.current, moved.clientY);
+ markDragging(sidebarOf(row), true);
// Without capture a release outside the window never arrives and the row stays
// stuck. Capture retargets events only, so the hit test still finds the zone.
try {
@@ -406,9 +686,11 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
if (escaped) return;
const dragged = sidebarDragSource();
const aimed = aim(released.clientX, released.clientY);
+ const from = ghost.current?.element.getBoundingClientRect().top ?? null;
clear();
if (dragged && aimed && aimed.outcome !== STAY) {
optionsRef.current.onDrop(aimed.outcome, dragged);
+ if (from !== null && !optionsRef.current.reducedMotion?.()) settleRow(dragged, from);
}
}
@@ -460,12 +742,11 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
[],
);
- const lineEdge = useCallback(
- (scope: string, id: string): DropEdge | undefined => {
+ const lineAt = useCallback(
+ (scope: string, id: string) => {
if (!plan || !("line" in plan.cue)) return undefined;
- return plan.cue.line.rowKey === rowKey(scope, id)
- ? plan.cue.line.edge
- : undefined;
+ const { rowKey: key, edge, folderId } = plan.cue.line;
+ return key === rowKey(scope, id) ? { edge, inFolder: folderId !== undefined } : undefined;
},
[plan],
);
@@ -480,7 +761,7 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
plan,
dragHandleProps,
dropZoneProps,
- lineEdge,
+ lineAt,
ringLit,
};
}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 9caaa1b508b..1270e0e270a 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -141,8 +141,15 @@ export {
useSidebarDrag,
SPRING_OPEN_DELAY_MS,
DRAG_THRESHOLD_PX,
- DRAGGING_BODY_CLASS,
+ markDragging,
+ DROP_CUE_CLASS,
} from "./hooks/use-sidebar-drag";
+export {
+ useSectionDrag,
+ sectionKeyLanding,
+ SECTION_ATTR,
+ type SectionLanding,
+} from "./hooks/use-section-drag";
export { usePinnedChatsStore } from "./stores/pinned-chats-store";
export { usePinnedProjectsStore } from "./stores/pinned-projects-store";
export {
@@ -160,13 +167,24 @@ export {
RECENTS_ORDER_SCOPE,
SIDEBAR_ORGANIZATION_STORAGE_KEY,
useSidebarOrganizationStore,
+ customSectionScope,
+ customSectionIdOf,
+ normalizeSectionName,
+ CUSTOM_SECTION_NAME_MAX,
+ PROJECTS_SECTION_KEY,
+ PINNED_SECTION_KEY,
+ inSectionOrder,
+ resolveSectionOrder,
+ assignmentMap,
} from "./stores/sidebar-organization-store";
export type {
+ SidebarCustomSection,
SidebarChatSort,
SidebarProjectSort,
SidebarOrganizeBy,
} from "./stores/sidebar-organization-store";
export { useChatPreferencesStore } from "./stores/chat-preferences-store";
+export { SectionNameDialog } from "./components/section-name-dialog";
export {
usePromptQueueUI,
type PromptQueueUIEntry,
diff --git a/studio/frontend/src/features/chat/lib/sidebar-drag.ts b/studio/frontend/src/features/chat/lib/sidebar-drag.ts
index 081af12b03a..8e811a89d06 100644
--- a/studio/frontend/src/features/chat/lib/sidebar-drag.ts
+++ b/studio/frontend/src/features/chat/lib/sidebar-drag.ts
@@ -5,6 +5,8 @@
// drop itself all read the same answer.
import {
+ customSectionIdOf,
+ customSectionScope,
dropEdgeAt,
insertIdAt,
PINNED_ORDER_SCOPE,
@@ -18,7 +20,12 @@ import {
} from "../stores/sidebar-organization-store.ts";
export type SidebarRowKind = "chat" | "project";
-export type SidebarSection = "pinned" | "projects" | "recents";
+/** A built-in list, or a custom section keyed by its order scope (`section:<id>`). */
+export type SidebarSection =
+ | "pinned"
+ | "projects"
+ | "recents"
+ | `section:${string}`;
export type DropEdge = "top" | "bottom";
/** The row being carried. */
@@ -58,12 +65,19 @@ export interface SidebarDropContext {
projectSort: SidebarProjectSort;
pinnedChatIds: ReadonlySet<string>;
pinnedProjectIds: ReadonlySet<string>;
- /** Row ids per list, in drawn order. Pinned is one list of folders and chats. */
+ /** The custom section each chat and folder is filed in. Pinned still draws a pinned row. */
+ sectionByChatId: Readonly<Record<string, string>>;
+ sectionByProjectId: Readonly<Record<string, string>>;
+ /** A custom section's chat sort. */
+ sectionSort: (sectionId: string) => SidebarChatSort;
+ /** Row ids per list, in drawn order. Pinned and every custom section are one list of folders
+ * and chats each. */
orders: {
pinned: string[];
projects: string[];
recents: string[];
projectChats: (projectId: string) => string[];
+ sections: (sectionId: string) => string[];
};
}
@@ -72,12 +86,23 @@ export type SidebarDropAction =
| { kind: "reorder" }
| { kind: "pin" }
| { kind: "unpin" }
- | { kind: "move"; projectId: string | null };
+ | { kind: "move"; projectId: string | null }
+ /** Filed into a custom section, or out of one with null. */
+ | { kind: "section"; sectionId: string | null };
/** What to paint: a line on one edge of a row, or a ring around a whole target. Row keys are
* `scope:id`, since one chat can be drawn in two lists. */
export type SidebarDropCue =
- | { line: { rowKey: string; edge: DropEdge } }
+ | {
+ line: {
+ rowKey: string;
+ edge: DropEdge;
+ /** The folder the row lands inside, when the line is between its chats. Unset for a
+ * line under a folder's last chat that lands below the folder, beside it in its list:
+ * the two sit in the same place and would otherwise read the same. */
+ folderId?: string;
+ };
+ }
| { ring: string };
/** Where a chat from another list lands: its slot against a row of that list. Kept beside the
@@ -97,8 +122,11 @@ export interface SidebarDropEffects {
pinProject?: string;
unpinProject?: string;
moveChat?: { chatId: string; projectId: string | null };
- /** The list to switch to Manual, or its own rule undoes the drop. */
- switchSort?: "chats" | "pinned" | "projects";
+ /** The row's custom section, set or cleared. */
+ fileInSection?: { kind: SidebarRowKind; id: string; sectionId: string | null };
+ /** The list to switch to Manual, or its own rule undoes the drop. A custom section is named
+ * by its scope. */
+ switchSort?: "chats" | "pinned" | "projects" | `section:${string}`;
}
export interface SidebarDropPlan {
@@ -123,11 +151,64 @@ export const SIDEBAR_TAIL_SCOPE = "sidebar-tail";
export const rowKey = (scope: string, id: string): string => `${scope}:${id}`;
export const sectionRingKey = (section: SidebarSection): string =>
`section:${section}`;
+
+/** Whether the section is one the user made. */
+export function isCustomSection(
+ section: SidebarSection,
+): section is `section:${string}` {
+ return customSectionIdOf(section) !== null;
+}
+
+/** The custom section a row is drawn in by its own filing: null when it is pinned (Pinned draws
+ * it) or filed nowhere. A chat under a filed folder is drawn there by the folder, not by this. */
+function ownSection(
+ kind: SidebarRowKind,
+ id: string,
+ ctx: SidebarDropContext,
+): string | null {
+ if (kind === "project") {
+ if (ctx.pinnedProjectIds.has(id)) return null;
+ return ctx.sectionByProjectId[id] ?? null;
+ }
+ if (ctx.pinnedChatIds.has(id)) return null;
+ return ctx.sectionByChatId[id] ?? null;
+}
+
+/** A row carried out to a list that is not a custom section leaves its section, or the section
+ * would keep drawing it there and the drop would read as ignored. A reorder moves nothing out,
+ * and neither does a pin: Pinned draws a pinned row whatever its section, which it keeps for when
+ * it is unpinned, as a pin from its menu does. */
+function leavingSection(
+ drag: SidebarDragItem,
+ outcome: SidebarDropOutcome,
+ ctx: SidebarDropContext,
+): SidebarDropOutcome {
+ if (!outcome || outcome === STAY) return outcome;
+ if (outcome.action.kind === "reorder" || outcome.action.kind === "pin") return outcome;
+ const filed =
+ drag.kind === "project" ? ctx.sectionByProjectId[drag.id] : ctx.sectionByChatId[drag.id];
+ if (!filed || outcome.effects.fileInSection) return outcome;
+ return {
+ ...outcome,
+ effects: {
+ ...outcome.effects,
+ fileInSection: { kind: drag.kind, id: drag.id, sectionId: null },
+ },
+ };
+}
export const folderRingKey = (projectId: string): string =>
`folder:${projectId}`;
+const FOLDER_SCOPE_PREFIX = projectOrderScope("");
const line = (scope: string, id: string, edge: DropEdge): SidebarDropCue => ({
- line: { rowKey: rowKey(scope, id), edge },
+ line: {
+ rowKey: rowKey(scope, id),
+ edge,
+ // A line against a folder's chats lands among them.
+ ...(scope.startsWith(FOLDER_SCOPE_PREFIX)
+ ? { folderId: scope.slice(FOLDER_SCOPE_PREFIX.length) }
+ : {}),
+ },
});
const ring = (key: string): SidebarDropCue => ({ ring: key });
@@ -142,9 +223,12 @@ export function planSidebarDrop(
ctx: SidebarDropContext,
): SidebarDropOutcome {
if (zone.header) {
- // Pinned holds both kinds in one order; the other sections hold one each.
+ // Pinned and custom sections hold both kinds in one order; the others hold one each.
const first =
- zone.row && (zone.section === "pinned" || zone.row.kind === drag.kind)
+ zone.row &&
+ (zone.section === "pinned" ||
+ isCustomSection(zone.section) ||
+ zone.row.kind === drag.kind)
? zone.row
: undefined;
zone = {
@@ -155,10 +239,80 @@ export function planSidebarDrop(
};
edge = "top";
}
- if (zone.section === "pinned") return planPinnedDrop(drag, zone, edge, ctx);
- return drag.kind === "project"
- ? planFolderDrop(drag, zone, edge, ctx)
- : planChatDrop(drag, zone, edge, ctx);
+ if (isCustomSection(zone.section)) return planSectionDrop(drag, zone, edge, ctx);
+ if (zone.section === "pinned") {
+ return leavingSection(drag, planPinnedDrop(drag, zone, edge, ctx), ctx);
+ }
+ return leavingSection(
+ drag,
+ drag.kind === "project"
+ ? planFolderDrop(drag, zone, edge, ctx)
+ : planChatDrop(drag, zone, edge, ctx),
+ ctx,
+ );
+}
+
+// A custom section is one list of folders and chats, as Pinned is. A row from anywhere else is
+// filed into it at the slot the line shows; a pinned row loses its pin, since Pinned would
+// otherwise keep drawing it. A chat still files into a folder here by landing on its chats.
+function planSectionDrop(
+ drag: SidebarDragItem,
+ zone: SidebarDropZone,
+ edge: DropEdge,
+ ctx: SidebarDropContext,
+): SidebarDropOutcome {
+ const sectionId = customSectionIdOf(zone.section);
+ if (sectionId === null) return null;
+ const scope = customSectionScope(sectionId);
+ if (zone.folderId === drag.id) return STAY;
+ if (
+ drag.kind === "chat" &&
+ zone.folderId &&
+ (zone.row?.kind !== "project" || edge === "bottom")
+ ) {
+ return leavingSection(drag, planChatDrop(drag, zone, edge, ctx), ctx);
+ }
+ const ids = ctx.orders.sections(sectionId);
+ const inList = ownSection(drag.kind, drag.id, ctx) === sectionId;
+ let target: { id: string; edge: DropEdge } | null = null;
+ if (zone.row) {
+ target =
+ zone.folderId && zone.row.kind === "chat" && zone.block
+ ? { id: zone.folderId, edge: blockEdge(zone.block, edge) }
+ : { id: zone.row.id, edge };
+ } else if (zone.folderId) {
+ target = { id: zone.folderId, edge: "bottom" };
+ } else if (ids.length > 0) {
+ target = { id: ids[ids.length - 1], edge: "bottom" };
+ }
+ if (target?.id === drag.id) return STAY;
+ const switchSort = ctx.sectionSort(sectionId) === "manual" ? undefined : scope;
+ const cue = target
+ ? folderLine(scope, target.id, target.edge, zone)
+ : ring(sectionRingKey(scope));
+ if (inList) {
+ if (!target) return null;
+ const next = insertIdAt(ids, drag.id, target.id, target.edge);
+ if (next === ids) return STAY;
+ return {
+ action: { kind: "reorder" },
+ cue,
+ effects: { orders: [{ scope, ids: next }], switchSort },
+ };
+ }
+ const next = placeIdAt(ids, drag.id, target?.id ?? null, target?.edge ?? "bottom");
+ const effects: SidebarDropEffects = {
+ orders: [{ scope, ids: next }],
+ fileInSection: { kind: drag.kind, id: drag.id, sectionId },
+ switchSort,
+ };
+ if (drag.kind === "project" && ctx.pinnedProjectIds.has(drag.id)) {
+ effects.unpinProject = drag.id;
+ }
+ if (drag.kind === "chat" && ctx.pinnedChatIds.has(drag.id)) {
+ effects.unpinChat = drag.id;
+ }
+ return { action: { kind: "section", sectionId }, cue, effects };
}
/** The line for landing against a folder: above its row, or below the last row of its block. */
@@ -169,7 +323,8 @@ function folderLine(
zone: SidebarDropZone,
): SidebarDropCue {
if (edge === "bottom" && zone.blockEnd) {
- return line(zone.blockEnd.scope, zone.blockEnd.id, "bottom");
+ // Drawn under the folder's last chat, but the row lands below the folder, in `scope`.
+ return { line: { rowKey: rowKey(zone.blockEnd.scope, zone.blockEnd.id), edge: "bottom" } };
}
return line(scope, folderId, edge);
}
@@ -243,6 +398,7 @@ function planFolderDrop(
if (zone.folderId === drag.id) return STAY;
const ids = ctx.orders.projects;
const switchSort = ctx.projectSort === "manual" ? undefined : "projects";
+ const pinned = ctx.pinnedProjectIds.has(drag.id);
let target: { id: string; edge: DropEdge } | null = null;
if (zone.folderId) {
target =
@@ -250,7 +406,7 @@ function planFolderDrop(
? { id: zone.folderId, edge: blockEdge(zone.block, edge) }
: { id: zone.folderId, edge };
}
- if (!ctx.pinnedProjectIds.has(drag.id)) {
+ if (!pinned && ownSection("project", drag.id, ctx) === null) {
// Same list: only a folder is a slot to land against.
if (!target) return null;
const next = insertIdAt(ids, drag.id, target.id, target.edge);
@@ -261,16 +417,16 @@ function planFolderDrop(
effects: { orders: [{ scope: PROJECT_ORDER_SCOPE, ids: next }], switchSort },
};
}
- // Out of Pinned: unpinned, landing against a folder or last.
+ // Out of Pinned or a custom section: unpinned or unfiled, landing against a folder or last.
const next = placeIdAt(ids, drag.id, target?.id ?? null, target?.edge ?? "bottom");
return {
- action: { kind: "unpin" },
+ action: pinned ? { kind: "unpin" } : { kind: "section", sectionId: null },
cue: target
? folderLine(PROJECT_ORDER_SCOPE, target.id, target.edge, zone)
: ring(sectionRingKey("projects")),
effects: {
orders: [{ scope: PROJECT_ORDER_SCOPE, ids: next }],
- unpinProject: drag.id,
+ unpinProject: pinned ? drag.id : undefined,
switchSort,
},
};
@@ -292,16 +448,25 @@ function planChatDrop(
const pinned = ctx.pinnedChatIds.has(drag.id);
// Picked up from the Pinned list itself, not from inside a pinned folder.
const fromPinnedList = drag.scope === PINNED_ORDER_SCOPE;
+ // Drawn in a custom section by its own filing, which a drop anywhere else takes away.
+ const inSection = ownSection("chat", drag.id, ctx) !== null;
if (zone.folderId) {
const folderId = zone.folderId;
const sameFolder = drag.projectId === folderId;
- if (fromPinnedList) {
+ if (fromPinnedList || inSection) {
// Another pinned folder keeps the pin; a folder under Projects takes it away.
if (!sameFolder) {
- return moveChat(drag, zone, edge, ctx, folderId, zone.section !== "pinned");
+ return moveChat(
+ drag,
+ zone,
+ edge,
+ ctx,
+ folderId,
+ fromPinnedList && zone.section !== "pinned",
+ );
}
- // Dropping it on its own folder unpins it.
+ // Dropping it on its own folder unpins it, or takes it back out of its section.
const landing = landingIn(
projectOrderScope(folderId),
ctx.orders.projectChats(folderId),
@@ -311,11 +476,11 @@ function planChatDrop(
ctx.chatSort,
);
return {
- action: { kind: "unpin" },
+ action: fromPinnedList ? { kind: "unpin" } : { kind: "section", sectionId: null },
cue: landing?.cue ?? ring(folderRingKey(folderId)),
effects: {
orders: landing ? [landing.order] : [],
- unpinChat: drag.id,
+ unpinChat: fromPinnedList ? drag.id : undefined,
switchSort: landing?.resorts ? "chats" : undefined,
},
};
@@ -351,9 +516,10 @@ function planChatDrop(
if (zone.section === "recents") {
// Recents holds chats that are neither pinned nor filed, so landing here takes both away.
- // With folders off every chat is a Recents row, and only the pin goes.
+ // With folders off every chat is a Recents row, and only the pin goes. A custom section's
+ // own chat leaves the section the same way.
const filed = drag.projectId !== null && ctx.organizeBy === "project";
- if (pinned || filed) {
+ if (pinned || filed || inSection) {
const landing =
landingIn(
RECENTS_ORDER_SCOPE,
@@ -365,7 +531,11 @@ function planChatDrop(
) ??
lastIn(RECENTS_ORDER_SCOPE, ctx.orders.recents, drag.id, ctx.chatSort);
return {
- action: filed ? { kind: "move", projectId: null } : { kind: "unpin" },
+ action: filed
+ ? { kind: "move", projectId: null }
+ : pinned
+ ? { kind: "unpin" }
+ : { kind: "section", sectionId: null },
cue: landing?.cue ?? ring(sectionRingKey("recents")),
effects: {
orders: landing ? [landing.order] : [],
@@ -375,7 +545,17 @@ function planChatDrop(
},
};
}
- if (zone.row?.kind !== "chat") return null;
+ if (zone.row?.kind !== "chat") {
+ // The end strip, and the empty sidebar below it: last. The rest of the section's own space
+ // stays nothing for its own rows, so a pointer beside a row does not send it to the end.
+ const ids = ctx.orders.recents;
+ const last = ids[ids.length - 1];
+ if (zone.row || zone.blockEnd?.scope !== SIDEBAR_TAIL_SCOPE || last === undefined) {
+ return null;
+ }
+ if (last === drag.id) return STAY;
+ return reorder(drag, RECENTS_ORDER_SCOPE, ids, last, "bottom", "chats", ctx);
+ }
return reorder(
drag,
RECENTS_ORDER_SCOPE,
@@ -507,6 +687,8 @@ function reorder(
export function litRingKey(plan: SidebarDropPlan | null): string | null {
if (!plan) return null;
if ("ring" in plan.cue) return plan.cue.ring;
+ // A line among a folder's chats lands in that folder, a reorder inside it included.
+ if (plan.cue.line.folderId !== undefined) return folderRingKey(plan.cue.line.folderId);
if (plan.action.kind === "move" && plan.action.projectId) {
return folderRingKey(plan.action.projectId);
}
@@ -525,6 +707,7 @@ export function equivalentDrop(a: SidebarDropPlan, b: SidebarDropPlan): boolean
pinProject: plan.effects.pinProject,
unpinProject: plan.effects.unpinProject,
moveChat: plan.effects.moveChat,
+ fileInSection: plan.effects.fileInSection,
switchSort: plan.effects.switchSort,
});
return landing(a) === landing(b);
@@ -535,11 +718,13 @@ export function planKey(plan: SidebarDropPlan | null): string {
if (!plan) return "";
const cue =
"line" in plan.cue
- ? `line:${plan.cue.line.rowKey}:${plan.cue.line.edge}`
+ ? `line:${plan.cue.line.rowKey}:${plan.cue.line.edge}:${plan.cue.line.folderId ?? ""}`
: `ring:${plan.cue.ring}`;
const action =
plan.action.kind === "move"
? `move:${plan.action.projectId ?? ""}`
- : plan.action.kind;
+ : plan.action.kind === "section"
+ ? `section:${plan.action.sectionId ?? ""}`
+ : plan.action.kind;
return `${action}|${cue}`;
}
diff --git a/studio/frontend/src/features/chat/mcp-composer-button.tsx b/studio/frontend/src/features/chat/mcp-composer-button.tsx
index 443faa17094..27de94a9dcd 100644
--- a/studio/frontend/src/features/chat/mcp-composer-button.tsx
+++ b/studio/frontend/src/features/chat/mcp-composer-button.tsx
@@ -1,7 +1,7 @@
// 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 { Tick02Icon } from "@/lib/tick-icon";
+import { MenuTickIcon } from "@/lib/tick-icon";
import { McpServerIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
@@ -266,7 +266,7 @@ export function McpComposerButton({
>
<span className="truncate">{opts.label}</span>
{opts.enabled ? (
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
) : null}
{opts.hint ? (
<Tooltip open={hintKey === opts.key}>
@@ -368,7 +368,7 @@ export function McpComposerButton({
>
<span className="truncate">Blender</span>
{blenderEnabled ? (
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
) : null}
</DropdownMenuItem>
{customServers.length > 0 ? <DropdownMenuSeparator /> : null}
diff --git a/studio/frontend/src/features/chat/permission-mode-select.tsx b/studio/frontend/src/features/chat/permission-mode-select.tsx
index 1cf4a492d67..c35281cff8d 100644
--- a/studio/frontend/src/features/chat/permission-mode-select.tsx
+++ b/studio/frontend/src/features/chat/permission-mode-select.tsx
@@ -26,7 +26,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { SparklesGlyph } from "@/lib/sparkles-icon";
-import { Tick02Icon } from "@/lib/tick-icon";
+import { MenuTickIcon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
import { HugeiconsIcon } from "@hugeicons/react";
import {
@@ -138,7 +138,7 @@ export function PermissionModeMenuItems({
</span>
{permissionMode === option.value ? (
<HugeiconsIcon
- icon={Tick02Icon}
+ icon={MenuTickIcon}
strokeWidth={2}
className="ml-auto mt-0.5 size-4 shrink-0"
/>
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index c9d2b8de303..4bac755dc98 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -23,7 +23,7 @@ import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { BulbIcon } from "@/lib/bulb-icon";
import { MicIcon } from "@/lib/mic-icon";
-import { Tick02Icon } from "@/lib/tick-icon";
+import { MenuTickIcon, Tick02Icon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
@@ -2112,7 +2112,7 @@ export function SharedComposer({
<HugeiconsIcon icon={FileDatabaseIcon} strokeWidth={2} />
Chat with files
{ragEnabled && !ragDisabled ? (
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
) : null}
</DropdownMenuItem>
),
@@ -2125,7 +2125,7 @@ export function SharedComposer({
<HugeiconsIcon icon={McpServerIcon} strokeWidth={2} />
MCP
{mcpEnabledForChat ? (
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
) : null}
</DropdownMenuItem>
),
@@ -2171,7 +2171,7 @@ export function SharedComposer({
>
<Columns2Icon />
Compare chat
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
</DropdownMenuItem>
),
exportChat: (
@@ -2226,7 +2226,7 @@ export function SharedComposer({
<HugeiconsIcon icon={PencilRulerIcon} strokeWidth={2} />
Canvas
{artifactsEnabled ? (
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
+ <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
) : null}
</DropdownMenuItem>
) : null,
@@ -2517,7 +2517,7 @@ export function SharedComposer({
Web search
{toolsEnabled && !searchDisabled ? (
<HugeiconsIcon
- icon={Tick02Icon}
+ icon={MenuTickIcon}
strokeWidth={2}
className="ml-auto"
/>
@@ -2541,7 +2541,7 @@ export function SharedComposer({
Code
{codeToolsEnabled && !codeDisabled ? (
<HugeiconsIcon
- icon={Tick02Icon}
+ icon={MenuTickIcon}
strokeWidth={2}
className="ml-auto"
/>
@@ -2561,7 +2561,7 @@ export function SharedComposer({
Images
{imageToolsEnabled && !imageDisabled ? (
<HugeiconsIcon
- icon={Tick02Icon}
+ icon={MenuTickIcon}
strokeWidth={2}
className="ml-auto"
/>
diff --git a/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts b/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
index b093548f7ed..cd16807409e 100644
--- a/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
+++ b/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts
@@ -7,7 +7,7 @@ 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";
+export type SidebarChatSort = "updated" | "manual";
/** How project folders are ordered in the Projects section. */
export type SidebarProjectSort = "updated" | "name" | "created" | "manual";
@@ -30,6 +30,104 @@ export function projectOrderScope(projectId: string): string {
return `project:${projectId}`;
}
+/** A section the user made: a named list holding chats and project folders. */
+export interface SidebarCustomSection {
+ id: string;
+ name: string;
+ /** How its chats are ordered. Manual by default, like Pinned: it is a list the user built. */
+ sort: SidebarChatSort;
+}
+
+/** The fixed section the "Show" toggles can hide, beside the user's own. Pinned always shows, as
+ * in ChatGPT, and Recents never hides: its header carries the menu that brings the others back. */
+export const PROJECTS_SECTION_KEY = "projects";
+/** Pinned's place in the section order. Only Recents has no place there: it is always last. */
+export const PINNED_SECTION_KEY = "pinned";
+
+// Section ids are generated here, but a hand-edited or restored payload can carry anything, so
+// every scope built from one is prefixed and cannot collide with the fixed scopes above.
+const CUSTOM_SECTION_PREFIX = "section:";
+
+/** The manual-order scope of a custom section, which is also its drop-target section key. */
+export function customSectionScope(sectionId: string): `section:${string}` {
+ return `${CUSTOM_SECTION_PREFIX}${sectionId}`;
+}
+
+/** The custom section a scope names, or null for every built-in list. */
+export function customSectionIdOf(scope: string): string | null {
+ return scope.startsWith(CUSTOM_SECTION_PREFIX)
+ ? scope.slice(CUSTOM_SECTION_PREFIX.length)
+ : null;
+}
+
+export const CUSTOM_SECTION_NAME_MAX = 60;
+
+/**
+ * The order the sections above Recents are drawn in: Pinned, Projects and the user's own, by key
+ * (a custom section by its id). A saved order is read over what exists now, so a key that went
+ * away is dropped and one it never had gets its default place: Pinned first, a custom section
+ * just above Projects in the order the list keeps them, Projects last.
+ */
+export function resolveSectionOrder(
+ saved: readonly string[],
+ customSections: readonly SidebarCustomSection[],
+): string[] {
+ const customIds = customSections.map((section) => section.id);
+ const valid = new Set([PINNED_SECTION_KEY, PROJECTS_SECTION_KEY, ...customIds]);
+ const out: string[] = [];
+ for (const key of saved) {
+ if (valid.has(key) && !out.includes(key)) out.push(key);
+ }
+ if (!out.includes(PINNED_SECTION_KEY)) out.unshift(PINNED_SECTION_KEY);
+ for (const id of customIds) {
+ if (out.includes(id)) continue;
+ const projects = out.indexOf(PROJECTS_SECTION_KEY);
+ out.splice(projects === -1 ? out.length : projects, 0, id);
+ }
+ if (!out.includes(PROJECTS_SECTION_KEY)) out.push(PROJECTS_SECTION_KEY);
+ return out;
+}
+
+/** The custom sections in the order `order` draws them, so every list of them (the Show
+ * toggles, the Section submenus) reads top to bottom like the sidebar. */
+export function inSectionOrder(
+ customSections: SidebarCustomSection[],
+ order: readonly string[],
+): SidebarCustomSection[] {
+ const rank = new Map(order.map((key, index) => [key, index]));
+ return [...customSections].sort(
+ (a, b) => (rank.get(a.id) ?? 0) - (rank.get(b.id) ?? 0),
+ );
+}
+
+function newSectionId(): string {
+ // randomUUID needs a secure context, which a LAN address over plain http is not.
+ return typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
+ ? crypto.randomUUID()
+ : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+}
+
+/** The assignments left once every one `drop` answers true for is gone. */
+/** A row id to section id map with no prototype. Row ids are any string, and on a plain object an
+ * unfiled row named "constructor" or "toString" would read as filed in whatever it inherits, and
+ * drop out of every list. Every map the store holds is made here. */
+export function assignmentMap(from?: Record<string, string>): Record<string, string> {
+ const map = Object.create(null) as Record<string, string>;
+ if (from) for (const [rowId, sectionId] of Object.entries(from)) map[rowId] = sectionId;
+ return map;
+}
+
+function withoutSection(
+ map: Record<string, string>,
+ drop: (sectionId: string) => boolean,
+): Record<string, string> {
+ const next = assignmentMap();
+ for (const [rowId, sectionId] of Object.entries(map)) {
+ if (!drop(sectionId)) next[rowId] = sectionId;
+ }
+ return next;
+}
+
export interface SidebarOrganizationState {
organizeBy: SidebarOrganizeBy;
chatSort: SidebarChatSort;
@@ -40,11 +138,44 @@ export interface SidebarOrganizationState {
projectSort: SidebarProjectSort;
/** Scope key -> row ids, in the order the user dragged them into. */
manualOrder: Record<string, string[]>;
+ /** User-made sections, in the order they are drawn. */
+ customSections: SidebarCustomSection[];
+ /** Chat row id -> the custom section it is filed in. Pinned still wins: a pinned chat shows
+ * in Pinned and keeps its section for when it is unpinned. */
+ sectionByChatId: Record<string, string>;
+ /** Project id -> the custom section its folder is drawn in, on the same terms. */
+ sectionByProjectId: Record<string, string>;
+ /** Section keys the "Show" toggles turned off: Projects or a custom section's id. */
+ hiddenSections: string[];
+ /** The order of the sections above Recents, as dragged; read through resolveSectionOrder. */
+ sectionOrder: string[];
+ /** A new chat started from a custom section's header, filed there once it has an id. Not
+ * saved: it is only good for the new chat on screen now. `compare` is set once that chat was
+ * turned into a compare chat before its first send, which then takes the mark. */
+ pendingNewChatSection: { sectionId: string; nonce: string; compare?: string } | null;
setOrganizeBy: (value: SidebarOrganizeBy) => void;
setChatSort: (value: SidebarChatSort) => void;
setPinnedSort: (value: SidebarChatSort) => void;
setProjectSort: (value: SidebarProjectSort) => void;
setManualOrder: (scope: string, ids: string[]) => void;
+ /** Adds a section at the top of the custom ones and returns its id, or null for a blank name. */
+ createCustomSection: (name: string) => string | null;
+ renameCustomSection: (sectionId: string, name: string) => void;
+ /** Removes the section. Its rows go back to wherever they would be without it. */
+ deleteCustomSection: (sectionId: string) => void;
+ setCustomSectionSort: (sectionId: string, sort: SidebarChatSort) => void;
+ /** Files chats into a section, or out of every section with null. */
+ setChatsSection: (chatIds: string[], sectionId: string | null) => void;
+ setProjectsSection: (projectIds: string[], sectionId: string | null) => void;
+ setSectionHidden: (key: string, hidden: boolean) => void;
+ /** Drops the section `key` against the `edge` side of `targetKey`, as a row drag lands. */
+ moveSection: (key: string, targetKey: string, edge: "top" | "bottom") => void;
+ setPendingNewChatSection: (pending: SidebarOrganizationState["pendingNewChatSection"]) => void;
+}
+
+/** Trims and bounds a section name. Empty when there is nothing to name it with. */
+export function normalizeSectionName(name: string): string {
+ return name.replace(/\s+/g, " ").trim().slice(0, CUSTOM_SECTION_NAME_MAX);
}
/** Drops `draggedId` against the `edge` side of `targetId`, keeping the rest in order. The edge
@@ -159,14 +290,119 @@ export function applyManualOrder<T>(
);
}
+/** Reads a saved payload over the defaults, validated per field: an old, hand-edited or
+ * half-written payload keeps defaults wherever it is wrong. */
+export function mergePersistedOrganization(
+ persisted: unknown,
+ current: SidebarOrganizationState,
+): SidebarOrganizationState {
+ 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 === "updated" || value === "manual" ? value : fallback;
+ // A saved "priority", no longer offered, falls back to each list's default.
+ const chatSort = readSort(saved?.chatSort, "updated");
+ const pinnedSort = readSort(saved?.pinnedSort, "manual");
+ // Folders keep only the order they are dragged into: a saved automatic sort, no longer offered,
+ // could be neither seen nor changed, so it falls back to Manual.
+ const projectSort: SidebarProjectSort = "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",
+ );
+ }
+ }
+ }
+ const customSections: SidebarCustomSection[] = [];
+ const seen = new Set<string>();
+ if (Array.isArray(saved?.customSections)) {
+ for (const raw of saved.customSections as unknown[]) {
+ if (!raw || typeof raw !== "object") continue;
+ const entry = raw as Partial<SidebarCustomSection>;
+ if (typeof entry.id !== "string" || !entry.id || seen.has(entry.id)) continue;
+ // A section is keyed like Pinned and Projects, so one named after them would be drawn as
+ // them, and the rows filed in it would vanish.
+ if (entry.id === PINNED_SECTION_KEY || entry.id === PROJECTS_SECTION_KEY) continue;
+ const name =
+ typeof entry.name === "string" ? normalizeSectionName(entry.name) : "";
+ if (!name) continue;
+ seen.add(entry.id);
+ customSections.push({
+ id: entry.id,
+ name,
+ sort: readSort(entry.sort, "manual"),
+ });
+ }
+ }
+ // An assignment to a section that no longer exists is dropped, so its row comes back.
+ const readAssignments = (value: unknown): Record<string, string> => {
+ const out = assignmentMap();
+ if (!value || typeof value !== "object") return out;
+ for (const [rowId, sectionId] of Object.entries(value)) {
+ if (typeof sectionId === "string" && seen.has(sectionId)) {
+ out[rowId] = sectionId;
+ }
+ }
+ return out;
+ };
+ const hiddenSections = Array.isArray(saved?.hiddenSections)
+ ? [
+ ...new Set(
+ (saved.hiddenSections as unknown[]).filter(
+ (key): key is string =>
+ key === PROJECTS_SECTION_KEY ||
+ (typeof key === "string" && seen.has(key)),
+ ),
+ ),
+ ]
+ : [];
+ const sectionOrder = Array.isArray(saved?.sectionOrder)
+ ? resolveSectionOrder(
+ (saved.sectionOrder as unknown[]).filter(
+ (key): key is string => typeof key === "string",
+ ),
+ customSections,
+ )
+ : [];
+ return {
+ ...current,
+ organizeBy,
+ chatSort,
+ pinnedSort,
+ projectSort,
+ manualOrder,
+ customSections,
+ sectionByChatId: readAssignments(saved?.sectionByChatId),
+ sectionByProjectId: readAssignments(saved?.sectionByProjectId),
+ hiddenSections,
+ sectionOrder,
+ };
+}
+
export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
persist(
(set) => ({
organizeBy: "project",
- chatSort: "priority",
+ chatSort: "updated",
pinnedSort: "manual",
projectSort: "manual",
manualOrder: {},
+ customSections: [],
+ sectionByChatId: assignmentMap(),
+ sectionByProjectId: assignmentMap(),
+ hiddenSections: [],
+ sectionOrder: [],
+ pendingNewChatSection: null,
setOrganizeBy: (value) => set({ organizeBy: value }),
setChatSort: (value) => set({ chatSort: value }),
setPinnedSort: (value) => set({ pinnedSort: value }),
@@ -175,49 +411,107 @@ export const useSidebarOrganizationStore = create<SidebarOrganizationState>()(
set((state) => ({
manualOrder: { ...state.manualOrder, [scope]: ids },
})),
+ createCustomSection: (name) => {
+ const clean = normalizeSectionName(name);
+ if (!clean) return null;
+ const id = newSectionId();
+ set((state) => {
+ // Newest first among the user's own, which open under Pinned unless dragged elsewhere:
+ // it is the one about to be filled, so it opens where the eye already is.
+ const order = resolveSectionOrder(state.sectionOrder, state.customSections);
+ const firstCustom = order.findIndex((key) =>
+ state.customSections.some((section) => section.id === key),
+ );
+ const at = firstCustom !== -1 ? firstCustom : order.indexOf(PINNED_SECTION_KEY) + 1;
+ return {
+ customSections: [{ id, name: clean, sort: "manual" }, ...state.customSections],
+ sectionOrder: [...order.slice(0, at), id, ...order.slice(at)],
+ };
+ });
+ return id;
+ },
+ renameCustomSection: (sectionId, name) => {
+ const clean = normalizeSectionName(name);
+ if (!clean) return;
+ set((state) => ({
+ customSections: state.customSections.map((section) =>
+ section.id === sectionId ? { ...section, name: clean } : section,
+ ),
+ }));
+ },
+ deleteCustomSection: (sectionId) =>
+ set((state) => {
+ const manualOrder = { ...state.manualOrder };
+ delete manualOrder[customSectionScope(sectionId)];
+ const gone = (id: string) => id === sectionId;
+ return {
+ customSections: state.customSections.filter((s) => s.id !== sectionId),
+ sectionByChatId: withoutSection(state.sectionByChatId, gone),
+ sectionByProjectId: withoutSection(state.sectionByProjectId, gone),
+ hiddenSections: state.hiddenSections.filter((key) => key !== sectionId),
+ sectionOrder: state.sectionOrder.filter((key) => key !== sectionId),
+ manualOrder,
+ };
+ }),
+ moveSection: (key, targetKey, edge) =>
+ set((state) => {
+ const order = resolveSectionOrder(state.sectionOrder, state.customSections);
+ const next = insertIdAt(order, key, targetKey, edge);
+ if (next === order) return state;
+ return {
+ sectionOrder: next,
+ customSections: inSectionOrder(state.customSections, next),
+ };
+ }),
+ setPendingNewChatSection: (pending) => set({ pendingNewChatSection: pending }),
+ setCustomSectionSort: (sectionId, sort) =>
+ set((state) => ({
+ customSections: state.customSections.map((section) =>
+ section.id === sectionId ? { ...section, sort } : section,
+ ),
+ })),
+ setChatsSection: (chatIds, sectionId) =>
+ set((state) => {
+ if (sectionId && !state.customSections.some((s) => s.id === sectionId)) {
+ return state;
+ }
+ const next = assignmentMap(state.sectionByChatId);
+ for (const id of chatIds) {
+ if (sectionId) next[id] = sectionId;
+ else delete next[id];
+ }
+ return { sectionByChatId: next };
+ }),
+ setProjectsSection: (projectIds, sectionId) =>
+ set((state) => {
+ if (sectionId && !state.customSections.some((s) => s.id === sectionId)) {
+ return state;
+ }
+ const next = assignmentMap(state.sectionByProjectId);
+ for (const id of projectIds) {
+ if (sectionId) next[id] = sectionId;
+ else delete next[id];
+ }
+ return { sectionByProjectId: next };
+ }),
+ setSectionHidden: (key, hidden) =>
+ set((state) => {
+ const has = state.hiddenSections.includes(key);
+ if (has === hidden) return state;
+ return {
+ hiddenSections: hidden
+ ? [...state.hiddenSections, key]
+ : state.hiddenSections.filter((existing) => existing !== key),
+ };
+ }),
}),
{
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 projectSort: SidebarProjectSort =
- saved?.projectSort === "updated" ||
- saved?.projectSort === "name" ||
- saved?.projectSort === "created"
- ? saved.projectSort
- : "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,
- projectSort,
- manualOrder,
- };
+ merge: mergePersistedOrganization,
+ partialize: (state) => {
+ const saved: Partial<SidebarOrganizationState> = { ...state };
+ delete saved.pendingNewChatSection;
+ return saved;
},
},
),
diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsx
index 40d2c6afeb8..2e4c4357c75 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx
@@ -555,6 +555,8 @@ function ModelSelectorContent({
<PopoverContent
align="start"
alignOffset={10}
+ // Read by the model list, which sets its right inset against the panel's own.
+ data-external={hasExternal || undefined}
aria-label={
visibleConfigTarget
? `Run settings for ${visibleConfigTarget.displayName}`
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index b660e1bf822..d03e945c090 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -6654,9 +6654,12 @@ export function HubModelPicker({
ref={scrollRef}
onScroll={(e) => updateListFades(e.currentTarget)}
className={cn(
- // The list sits within the menu padding so gaps match; scroll-py and symmetric px keep the
- // focus ring off the overflow clip edges during keyboard nav.
- "model-list-scroll max-h-[calc(335px*var(--ui-space-scale,1))] overflow-y-auto scroll-py-1.5 px-0.5 mr-1",
+ // The list sits within the menu padding so gaps match; scroll-py and the side padding keep
+ // the focus ring off the overflow clip edges during keyboard nav. The panel is padded 16px
+ // on the left but 8px on the right (16px with external providers), so the scroller can run
+ // near the edge for its scrollbar; the right inset makes up the difference, and a row's
+ // hover pill sits 18px from both edges.
+ "model-list-scroll max-h-[calc(335px*var(--ui-space-scale,1))] overflow-y-auto scroll-py-1.5 pl-0.5 pr-1.5 mr-1 in-data-[external=true]:pr-0.5 in-data-[external=true]:mr-0",
listScrolled && "is-scrolled",
listMoreBelow && "is-bottom-faded",
)}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/use-pinned-row-drag.ts b/studio/frontend/src/features/model-picker/components/model-selector/use-pinned-row-drag.ts
index 56325220164..ebd298e266d 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/use-pinned-row-drag.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/use-pinned-row-drag.ts
@@ -6,7 +6,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
-import { DRAGGING_BODY_CLASS, DRAG_THRESHOLD_PX } from "@/features/chat";
+import { DRAG_THRESHOLD_PX, markDragging } from "@/features/chat";
export type PinnedDropEdge = "top" | "bottom";
@@ -138,7 +138,7 @@ export function usePinnedRowDrag(
const clear = useCallback(() => {
draggingRef.current = null;
scroller.current = null;
- document.body.classList.remove(DRAGGING_BODY_CLASS);
+ markDragging(null, false);
setDraggingKey(null);
showTarget(null);
}, [showTarget]);
@@ -280,7 +280,8 @@ export function usePinnedRowDrag(
}
started = true;
scroller.current = scrollerOf(row);
- document.body.classList.add(DRAGGING_BODY_CLASS);
+ // The picker's own list, not the body: see markDragging.
+ markDragging(scroller.current ?? row.parentElement, true);
try {
document.body.setPointerCapture(pointerId);
} catch {
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 64b359eb44e..be436e58d83 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -188,6 +188,9 @@ export const ar = {
noChats: "لا توجد محادثات",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "كل المشاريع مثبتة",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "كل المشاريع مثبتة أو ضمن أقسام",
+ noProjects: "لا توجد مشاريع",
showMore: "عرض المزيد",
showLess: "عرض أقل",
settings: "الإعدادات",
@@ -233,14 +236,42 @@ export const ar = {
byProject: "حسب المشروع",
inOneList: "في قائمة واحدة",
sortChatsBy: "ترتيب المحادثات حسب",
- sortPinnedBy: "ترتيب المثبتة حسب",
- priority: "الأولوية",
lastUpdated: "آخر تحديث",
manualOrder: "ترتيب يدوي",
switchedToManual: "الترتيب يدوي الآن: اسحب الصفوف لإعادة ترتيبها",
organizeChats: "تنظيم المحادثات",
organizeProjects: "تنظيم المشاريع",
sortPinnedChats: "ترتيب المحادثات المثبتة",
+ // Header of the menu's section-visibility toggles.
+ show: "إظهار",
+ newSection: "قسم جديد",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "قسم جديد",
+ createDescription: "جمّع المحادثات والمشاريع بالطريقة التي تناسبك",
+ namePlaceholder: "اسم القسم",
+ create: "إنشاء قسم",
+ renameTitle: "إعادة تسمية القسم",
+ renameDescription: "امنح هذا القسم اسمًا جديدًا",
+ edit: "تعديل",
+ remove: "إزالة القسم",
+ markAllRead: "تعليم الكل كمقروء",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "نقل إلى",
+ section: "قسم",
+ sectionsHeading: "الأقسام",
+ removeFromProject: "إزالة من المشروع",
+ newSection: "قسم جديد",
+ removeFromSection: "إزالة من القسم",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "إزالة من {name}",
+ // Shown in a section with nothing filed in it yet.
+ empty: "اسحب المحادثات أو المشاريع إلى هنا",
+ sectionOptions: "خيارات القسم",
+ newChatInSection: "محادثة جديدة في {name}",
+ deleted: "تم حذف القسم «{name}»",
+ undo: "تراجع",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index eb1de4b1aae..e62df06f888 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -191,6 +191,9 @@ export const de = {
noChats: "Keine Chats",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "Alle Projekte angepinnt",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "Alle Projekte sind angeheftet oder in Abschnitten",
+ noProjects: "Keine Projekte",
showMore: "Mehr anzeigen",
showLess: "Weniger anzeigen",
settings: "Einstellungen",
@@ -236,14 +239,42 @@ export const de = {
byProject: "Nach Projekt",
inOneList: "In einer Liste",
sortChatsBy: "Chats sortieren nach",
- sortPinnedBy: "Angeheftete sortieren nach",
- priority: "Priorität",
lastUpdated: "Zuletzt aktualisiert",
manualOrder: "Manuelle Reihenfolge",
switchedToManual: "Manuell sortiert: Zeilen zum Umordnen ziehen",
organizeChats: "Chats organisieren",
organizeProjects: "Projekte organisieren",
sortPinnedChats: "Angeheftete Chats sortieren",
+ // Header of the menu's section-visibility toggles.
+ show: "Anzeigen",
+ newSection: "Neuer Abschnitt",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "Neuer Abschnitt",
+ createDescription: "Gruppiere Chats und Projekte ganz nach Belieben",
+ namePlaceholder: "Name des Abschnitts",
+ create: "Abschnitt erstellen",
+ renameTitle: "Abschnitt umbenennen",
+ renameDescription: "Gib diesem Abschnitt einen neuen Namen",
+ edit: "Bearbeiten",
+ remove: "Abschnitt entfernen",
+ markAllRead: "Alle als gelesen markieren",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "Verschieben nach",
+ section: "Abschnitt",
+ sectionsHeading: "Abschnitte",
+ removeFromProject: "Aus Projekt entfernen",
+ newSection: "Neuer Abschnitt",
+ removeFromSection: "Aus Abschnitt entfernen",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "Aus {name} entfernen",
+ // Shown in a section with nothing filed in it yet.
+ empty: "Chats oder Projekte hierher ziehen",
+ sectionOptions: "Abschnittsoptionen",
+ newChatInSection: "Neuer Chat in {name}",
+ deleted: "Abschnitt „{name}“ gelöscht",
+ undo: "Rückgängig",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 108cce36f08..35b388c1d14 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -192,6 +192,10 @@ export const en = {
noChats: "No chats",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "All projects pinned",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "All projects are pinned or in sections",
+ // Shown in the Projects section when there are no projects yet.
+ noProjects: "No projects",
showMore: "Show more",
showLess: "Show less",
settings: "Settings",
@@ -239,17 +243,42 @@ export const en = {
byProject: "By project",
inOneList: "In one list",
sortChatsBy: "Sort chats by",
- sortPinnedBy: "Sort pinned by",
- sortProjectsBy: "Sort projects by",
- name: "Name",
- dateCreated: "Date created",
- priority: "Priority",
lastUpdated: "Last updated",
manualOrder: "Manual order",
switchedToManual: "Sorted manually: drag rows to reorder",
organizeChats: "Organize chats",
organizeProjects: "Organize projects",
sortPinnedChats: "Sort pinned chats",
+ // Header of the menu's section-visibility toggles.
+ show: "Show",
+ newSection: "New section",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "New section",
+ createDescription: "Group chats and projects however you like",
+ namePlaceholder: "Section name",
+ create: "Create section",
+ renameTitle: "Rename section",
+ renameDescription: "Give this section a new name",
+ edit: "Edit",
+ remove: "Remove section",
+ markAllRead: "Mark all as read",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "Move to",
+ section: "Section",
+ sectionsHeading: "Sections",
+ removeFromProject: "Remove from project",
+ newSection: "New section",
+ removeFromSection: "Remove from section",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "Remove from {name}",
+ // Shown in a section with nothing filed in it yet.
+ empty: "Drag chats or projects here",
+ sectionOptions: "Section options",
+ newChatInSection: "New chat in {name}",
+ deleted: "Deleted section “{name}”",
+ undo: "Undo",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 16ee3a26631..82bff46c195 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -190,6 +190,9 @@ export const es = {
noChats: "Sin chats",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "Todos los proyectos fijados",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "Todos los proyectos están fijados o en secciones",
+ noProjects: "No hay proyectos",
showMore: "Mostrar más",
showLess: "Mostrar menos",
settings: "Configuración",
@@ -235,14 +238,42 @@ export const es = {
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",
switchedToManual: "Orden manual: arrastra las filas para reordenarlas",
organizeChats: "Organizar chats",
organizeProjects: "Organizar proyectos",
sortPinnedChats: "Ordenar chats fijados",
+ // Header of the menu's section-visibility toggles.
+ show: "Mostrar",
+ newSection: "Nueva sección",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "Nueva sección",
+ createDescription: "Agrupa chats y proyectos como quieras",
+ namePlaceholder: "Nombre de la sección",
+ create: "Crear sección",
+ renameTitle: "Renombrar sección",
+ renameDescription: "Dale un nombre nuevo a esta sección",
+ edit: "Editar",
+ remove: "Quitar sección",
+ markAllRead: "Marcar todo como leído",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "Mover a",
+ section: "Sección",
+ sectionsHeading: "Secciones",
+ removeFromProject: "Quitar del proyecto",
+ newSection: "Nueva sección",
+ removeFromSection: "Quitar de la sección",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "Quitar de {name}",
+ // Shown in a section with nothing filed in it yet.
+ empty: "Arrastra chats o proyectos aquí",
+ sectionOptions: "Opciones de sección",
+ newChatInSection: "Nuevo chat en {name}",
+ deleted: "Sección «{name}» eliminada",
+ undo: "Deshacer",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 192e9bd2314..bc504998eeb 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -191,6 +191,9 @@ export const fr = {
noChats: "Aucune discussion",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "Tous les projets sont epingles",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "Tous les projets sont épinglés ou dans des sections",
+ noProjects: "Aucun projet",
showMore: "Afficher plus",
showLess: "Afficher moins",
settings: "Paramètres",
@@ -236,14 +239,42 @@ export const fr = {
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",
switchedToManual: "Tri manuel : faites glisser les lignes pour les réorganiser",
organizeChats: "Organiser les discussions",
organizeProjects: "Organiser les projets",
sortPinnedChats: "Trier les discussions épinglées",
+ // Header of the menu's section-visibility toggles.
+ show: "Afficher",
+ newSection: "Nouvelle section",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "Nouvelle section",
+ createDescription: "Regroupez les discussions et les projets comme vous le souhaitez",
+ namePlaceholder: "Nom de la section",
+ create: "Créer la section",
+ renameTitle: "Renommer la section",
+ renameDescription: "Donnez un nouveau nom à cette section",
+ edit: "Modifier",
+ remove: "Retirer la section",
+ markAllRead: "Tout marquer comme lu",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "Déplacer vers",
+ section: "Section",
+ sectionsHeading: "Sections",
+ removeFromProject: "Retirer du projet",
+ newSection: "Nouvelle section",
+ removeFromSection: "Retirer de la section",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "Retirer de {name}",
+ // Shown in a section with nothing filed in it yet.
+ empty: "Faites glisser des discussions ou des projets ici",
+ sectionOptions: "Options de la section",
+ newChatInSection: "Nouveau chat dans {name}",
+ deleted: "Section « {name} » supprimée",
+ undo: "Annuler",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 5768cf17c3b..da4dac2cd12 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -191,6 +191,9 @@ export const hi = {
noChats: "कोई चैट नहीं",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "सभी प्रोजेक्ट पिन किए गए",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "सभी प्रोजेक्ट पिन किए गए हैं या सेक्शन में हैं",
+ noProjects: "कोई प्रोजेक्ट नहीं",
showMore: "और दिखाएं",
showLess: "कम दिखाएं",
settings: "सेटिंग्स",
@@ -236,14 +239,42 @@ export const hi = {
byProject: "प्रोजेक्ट के अनुसार",
inOneList: "एक ही सूची में",
sortChatsBy: "चैट क्रमबद्ध करें",
- sortPinnedBy: "पिन किए गए क्रमबद्ध करें",
- priority: "प्राथमिकता",
lastUpdated: "अंतिम अपडेट",
manualOrder: "मैन्युअल क्रम",
switchedToManual: "अब मैन्युअल क्रम: पंक्तियाँ खींचकर क्रम बदलें",
organizeChats: "चैट व्यवस्थित करें",
organizeProjects: "प्रोजेक्ट व्यवस्थित करें",
sortPinnedChats: "पिन की गई चैट क्रमबद्ध करें",
+ // Header of the menu's section-visibility toggles.
+ show: "दिखाएँ",
+ newSection: "नया सेक्शन",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "नया सेक्शन",
+ createDescription: "चैट और प्रोजेक्ट को अपनी पसंद से समूहित करें",
+ namePlaceholder: "सेक्शन का नाम",
+ create: "सेक्शन बनाएँ",
+ renameTitle: "सेक्शन का नाम बदलें",
+ renameDescription: "इस सेक्शन को नया नाम दें",
+ edit: "संपादित करें",
+ remove: "सेक्शन हटाएँ",
+ markAllRead: "सभी को पढ़ा हुआ चिह्नित करें",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "यहाँ ले जाएँ",
+ section: "सेक्शन",
+ sectionsHeading: "सेक्शन",
+ removeFromProject: "प्रोजेक्ट से हटाएँ",
+ newSection: "नया सेक्शन",
+ removeFromSection: "सेक्शन से हटाएँ",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "{name} से हटाएँ",
+ // Shown in a section with nothing filed in it yet.
+ empty: "चैट या प्रोजेक्ट यहाँ खींचें",
+ sectionOptions: "सेक्शन विकल्प",
+ newChatInSection: "{name} में नई चैट",
+ deleted: "सेक्शन “{name}” हटाया गया",
+ undo: "पूर्ववत करें",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index a89b8c9bcea..624899697f1 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -151,6 +151,9 @@ export const it = {
noChats: "Nessuna chat",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "Tutti i progetti fissati",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "Tutti i progetti sono fissati o in sezioni",
+ noProjects: "Nessun progetto",
showMore: "Mostra altro",
showLess: "Mostra meno",
settings: "Impostazioni",
@@ -196,14 +199,42 @@ export const it = {
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",
switchedToManual: "Ordinamento manuale: trascina le righe per riordinarle",
organizeChats: "Organizza le chat",
organizeProjects: "Organizza i progetti",
sortPinnedChats: "Ordina le chat fissate",
+ // Header of the menu's section-visibility toggles.
+ show: "Mostra",
+ newSection: "Nuova sezione",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "Nuova sezione",
+ createDescription: "Raggruppa chat e progetti come preferisci",
+ namePlaceholder: "Nome della sezione",
+ create: "Crea sezione",
+ renameTitle: "Rinomina sezione",
+ renameDescription: "Assegna un nuovo nome a questa sezione",
+ edit: "Modifica",
+ remove: "Rimuovi sezione",
+ markAllRead: "Segna tutto come letto",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "Sposta in",
+ section: "Sezione",
+ sectionsHeading: "Sezioni",
+ removeFromProject: "Rimuovi dal progetto",
+ newSection: "Nuova sezione",
+ removeFromSection: "Rimuovi dalla sezione",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "Rimuovi da {name}",
+ // Shown in a section with nothing filed in it yet.
+ empty: "Trascina qui chat o progetti",
+ sectionOptions: "Opzioni della sezione",
+ newChatInSection: "Nuova chat in {name}",
+ deleted: "Sezione «{name}» eliminata",
+ undo: "Annulla",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 5a853484426..e126d2edc32 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -190,6 +190,9 @@ export const ja = {
noChats: "チャットなし",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "すべてのプロジェクトをピン留め済み",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "すべてのプロジェクトがピン留め済みまたはセクション内にあります",
+ noProjects: "プロジェクトはありません",
showMore: "もっと見る",
showLess: "表示を減らす",
settings: "設定",
@@ -235,14 +238,42 @@ export const ja = {
byProject: "プロジェクト別",
inOneList: "1つのリストで",
sortChatsBy: "チャットの並び順",
- sortPinnedBy: "ピン留めの並び順",
- priority: "優先度",
lastUpdated: "最終更新",
manualOrder: "手動で並べ替え",
switchedToManual: "手動の並び順に切り替えました。行をドラッグして並べ替えます",
organizeChats: "チャットを整理",
organizeProjects: "プロジェクトを整理",
sortPinnedChats: "ピン留めチャットを並べ替え",
+ // Header of the menu's section-visibility toggles.
+ show: "表示",
+ newSection: "新しいセクション",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "新しいセクション",
+ createDescription: "チャットやプロジェクトを自由にグループ化できます",
+ namePlaceholder: "セクション名",
+ create: "セクションを作成",
+ renameTitle: "セクション名を変更",
+ renameDescription: "このセクションに新しい名前を付けます",
+ edit: "編集",
+ remove: "セクションを削除",
+ markAllRead: "すべて既読にする",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "移動先",
+ section: "セクション",
+ sectionsHeading: "セクション",
+ removeFromProject: "プロジェクトから削除",
+ newSection: "新しいセクション",
+ removeFromSection: "セクションから削除",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "{name}から削除",
+ // Shown in a section with nothing filed in it yet.
+ empty: "ここにチャットやプロジェクトをドラッグ",
+ sectionOptions: "セクションのオプション",
+ newChatInSection: "{name} に新しいチャット",
+ deleted: "セクション「{name}」を削除しました",
+ undo: "元に戻す",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index e959f03fedd..5f38b1177f5 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -188,6 +188,9 @@ export const ko = {
noChats: "채팅 없음",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "모든 프로젝트가 고정됨",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "모든 프로젝트가 고정되었거나 섹션에 있음",
+ noProjects: "프로젝트 없음",
showMore: "더 보기",
showLess: "간략히 보기",
settings: "설정",
@@ -233,14 +236,42 @@ export const ko = {
byProject: "프로젝트별",
inOneList: "하나의 목록으로",
sortChatsBy: "채팅 정렬 기준",
- sortPinnedBy: "고정됨 정렬 기준",
- priority: "우선순위",
lastUpdated: "최근 업데이트",
manualOrder: "수동 정렬",
switchedToManual: "수동 정렬로 전환됨: 행을 끌어 순서를 바꾸세요",
organizeChats: "채팅 정리",
organizeProjects: "프로젝트 정리",
sortPinnedChats: "고정된 채팅 정렬",
+ // Header of the menu's section-visibility toggles.
+ show: "표시",
+ newSection: "새 섹션",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "새 섹션",
+ createDescription: "채팅과 프로젝트를 원하는 대로 묶어 보세요",
+ namePlaceholder: "섹션 이름",
+ create: "섹션 만들기",
+ renameTitle: "섹션 이름 변경",
+ renameDescription: "이 섹션에 새 이름을 지정하세요",
+ edit: "편집",
+ remove: "섹션 제거",
+ markAllRead: "모두 읽음으로 표시",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "이동",
+ section: "섹션",
+ sectionsHeading: "섹션",
+ removeFromProject: "프로젝트에서 제거",
+ newSection: "새 섹션",
+ removeFromSection: "섹션에서 제거",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "{name}에서 제거",
+ // Shown in a section with nothing filed in it yet.
+ empty: "채팅이나 프로젝트를 여기로 드래그하세요",
+ sectionOptions: "섹션 옵션",
+ newChatInSection: "{name}에 새 채팅",
+ deleted: "“{name}” 섹션 삭제됨",
+ undo: "실행 취소",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 57c0ad60c5d..5fad8a5251d 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -190,6 +190,9 @@ export const ptBR = {
noChats: "Nenhum chat",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "Todos os projetos fixados",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "Todos os projetos estão fixados ou em seções",
+ noProjects: "Nenhum projeto",
showMore: "Mostrar mais",
showLess: "Mostrar menos",
settings: "Configurações",
@@ -235,14 +238,42 @@ export const ptBR = {
byProject: "Por projeto",
inOneList: "Em uma lista",
sortChatsBy: "Ordenar conversas por",
- sortPinnedBy: "Ordenar fixadas por",
- priority: "Prioridade",
lastUpdated: "Última atualização",
manualOrder: "Ordem manual",
switchedToManual: "Ordem manual: arraste as linhas para reordenar",
organizeChats: "Organizar conversas",
organizeProjects: "Organizar projetos",
sortPinnedChats: "Ordenar conversas fixadas",
+ // Header of the menu's section-visibility toggles.
+ show: "Mostrar",
+ newSection: "Nova seção",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "Nova seção",
+ createDescription: "Agrupe conversas e projetos como quiser",
+ namePlaceholder: "Nome da seção",
+ create: "Criar seção",
+ renameTitle: "Renomear seção",
+ renameDescription: "Dê um novo nome a esta seção",
+ edit: "Editar",
+ remove: "Remover seção",
+ markAllRead: "Marcar tudo como lido",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "Mover para",
+ section: "Seção",
+ sectionsHeading: "Seções",
+ removeFromProject: "Remover do projeto",
+ newSection: "Nova seção",
+ removeFromSection: "Remover da seção",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "Remover de {name}",
+ // Shown in a section with nothing filed in it yet.
+ empty: "Arraste conversas ou projetos para cá",
+ sectionOptions: "Opções da seção",
+ newChatInSection: "Novo chat em {name}",
+ deleted: "Seção “{name}” excluída",
+ undo: "Desfazer",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 078362e355a..c6af7ea9946 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -190,6 +190,9 @@ export const ru = {
noChats: "Нет чатов",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "Все проекты закреплены",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "Все проекты закреплены или находятся в разделах",
+ noProjects: "Нет проектов",
showMore: "Показать больше",
showLess: "Показать меньше",
settings: "Настройки",
@@ -235,14 +238,42 @@ export const ru = {
byProject: "По проектам",
inOneList: "Одним списком",
sortChatsBy: "Сортировать чаты по",
- sortPinnedBy: "Сортировать закреплённые по",
- priority: "Приоритету",
lastUpdated: "Последнему обновлению",
manualOrder: "Вручную",
switchedToManual: "Ручной порядок: перетащите строки, чтобы изменить порядок",
organizeChats: "Настроить чаты",
organizeProjects: "Настроить проекты",
sortPinnedChats: "Сортировать закреплённые чаты",
+ // Header of the menu's section-visibility toggles.
+ show: "Показывать",
+ newSection: "Новый раздел",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "Новый раздел",
+ createDescription: "Группируйте чаты и проекты как угодно",
+ namePlaceholder: "Название раздела",
+ create: "Создать раздел",
+ renameTitle: "Переименовать раздел",
+ renameDescription: "Дайте этому разделу новое название",
+ edit: "Изменить",
+ remove: "Удалить раздел",
+ markAllRead: "Отметить все как прочитанные",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "Переместить в",
+ section: "Раздел",
+ sectionsHeading: "Разделы",
+ removeFromProject: "Убрать из проекта",
+ newSection: "Новый раздел",
+ removeFromSection: "Убрать из раздела",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "Убрать из {name}",
+ // Shown in a section with nothing filed in it yet.
+ empty: "Перетащите сюда чаты или проекты",
+ sectionOptions: "Параметры раздела",
+ newChatInSection: "Новый чат в «{name}»",
+ deleted: "Раздел «{name}» удалён",
+ undo: "Отменить",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 80e761f0b96..8840350adb6 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -186,6 +186,9 @@ export const zhCN = {
noChats: "无对话",
// Shown in the Projects section when every project is pinned, so it has no rows.
allProjectsPinned: "所有项目均已置顶",
+ // Same, when some of them are filed in custom sections instead.
+ allProjectsFiled: "所有项目均已置顶或归入分区",
+ noProjects: "暂无项目",
showMore: "显示更多",
showLess: "显示更少",
settings: "设置",
@@ -231,14 +234,42 @@ export const zhCN = {
byProject: "按项目",
inOneList: "合并为一个列表",
sortChatsBy: "对话排序方式",
- sortPinnedBy: "置顶排序方式",
- priority: "优先级",
lastUpdated: "最近更新",
manualOrder: "手动排序",
switchedToManual: "已改为手动排序,拖动行即可重新排序",
organizeChats: "整理对话",
organizeProjects: "整理项目",
sortPinnedChats: "对置顶对话排序",
+ // Header of the menu's section-visibility toggles.
+ show: "显示",
+ newSection: "新建分区",
+ },
+ // User-made sidebar sections that group chats and projects.
+ sections: {
+ createTitle: "新建分区",
+ createDescription: "按你的喜好对对话和项目进行分组",
+ namePlaceholder: "分区名称",
+ create: "创建分区",
+ renameTitle: "重命名分区",
+ renameDescription: "为此分区取一个新名称",
+ edit: "编辑",
+ remove: "移除分区",
+ markAllRead: "全部标为已读",
+ // The row menu's one submenu for projects and sections, and its headings.
+ moveTo: "移动到",
+ section: "分区",
+ sectionsHeading: "分区",
+ removeFromProject: "从项目中移除",
+ newSection: "新建分区",
+ removeFromSection: "从分区中移除",
+ // Names the project or section the row leaves; the two above are for when it is not one.
+ removeFrom: "从{name}中移除",
+ // Shown in a section with nothing filed in it yet.
+ empty: "将对话或项目拖到此处",
+ sectionOptions: "分区选项",
+ newChatInSection: "在 {name} 中新建聊天",
+ deleted: "已删除分区“{name}”",
+ undo: "撤销",
},
dialog: {
deleteChat: {
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index cd75c415d89..4e2fbe82967 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -2021,6 +2021,23 @@ html[data-chat-font] .aui-root {
);
}
+ /* A hair between menu rows, as ChatGPT has. Block margins collapse, so neighbours sit 2px apart. */
+ :is(
+ [data-slot="dropdown-menu-content"],
+ [data-slot="dropdown-menu-sub-content"],
+ [data-slot="context-menu-content"],
+ [data-slot="context-menu-sub-content"],
+ [data-slot="menubar-content"],
+ [data-slot="menubar-sub-content"]
+ )
+ :is(
+ [role="menuitem"],
+ [role="menuitemcheckbox"],
+ [role="menuitemradio"]
+ ) {
+ margin-block: 2px;
+ }
+
/* List menus: one radius in both themes, slightly tighter than --radius-lg
and matching the sidebar buttons. !important beats per-menu rounded-*. */
[data-slot="dropdown-menu-content"],
@@ -2729,6 +2746,72 @@ html[data-chat-font] .aui-root {
box-shadow: 0 4px 14px var(--background);
}
+ /* Sidebar and account menus: flat, no shadow. Important to beat the shared menu shadow. */
+ :is(.unsloth-plus-menu, .app-user-menu).sidebar-menu[data-slot] {
+ box-shadow: none !important;
+ }
+
+ /* System font at 14px, scaled with the UI font size. */
+ :is(.unsloth-plus-menu, .app-user-menu).sidebar-menu[data-slot] {
+ font-family: ui-sans-serif, -apple-system, system-ui, "Segoe UI", Helvetica, "Apple Color Emoji", Arial, sans-serif;
+ --icon-size: calc(1.125rem * var(--ui-font-scale, 1));
+ }
+
+ /* Both classes, to outrank the compact sizing .sidebar-row-menu gives every row further down. */
+ .unsloth-plus-menu.sidebar-row-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-item"],
+ [data-slot="dropdown-menu-sub-trigger"],
+ [data-slot="dropdown-menu-checkbox-item"],
+ [data-slot="dropdown-menu-radio-item"],
+ [data-slot="context-menu-item"],
+ [data-slot="context-menu-sub-trigger"]
+ ) {
+ @apply py-2 text-ui-14;
+ font-weight: 400;
+ line-height: calc(1.25rem * var(--ui-font-scale, 1));
+ }
+
+ .app-user-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-item"],
+ [data-slot="dropdown-menu-sub-trigger"]
+ ) {
+ @apply text-ui-14;
+ font-weight: 400;
+ color: inherit;
+ }
+
+ /* Dark: a step above the sidebar, from the palette so other themes keep their hue, with the
+ rows in full white. Muted labels and shortcuts keep their own color. */
+ .dark :is(.unsloth-plus-menu, .app-user-menu).sidebar-menu[data-slot] {
+ background-color: color-mix(in srgb, var(--card), white 7%);
+ color: #fff;
+ --destructive: #ed716a;
+ }
+
+ .dark :is(.unsloth-plus-menu, .app-user-menu).sidebar-menu :is(
+ [data-slot="dropdown-menu-separator"],
+ [data-slot="context-menu-separator"]
+ ) {
+ background-color: color-mix(in srgb, var(--card), white 16%);
+ }
+
+ /* The account menu's own hover is the accent with foreground text; here it takes the same
+ overlay and white as the sidebar menus beside it. */
+ .dark .app-user-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-item"],
+ [data-slot="dropdown-menu-sub-trigger"]
+ ):is(:focus, [data-state="open"]) {
+ background-color: rgb(255 255 255 / calc(0.1 * var(--contrast-wash-gain, 1)));
+ color: #fff;
+ }
+
+ .dark .app-user-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-item"],
+ [data-slot="dropdown-menu-sub-trigger"]
+ ):is(:focus, [data-state="open"]) *:not([data-slot="dropdown-menu-shortcut"]) {
+ color: #fff !important;
+ }
+
/* Compact items; also applied to portaled sub-content. */
.unsloth-plus-menu :is(
[data-slot="dropdown-menu-item"],
@@ -2773,11 +2856,67 @@ html[data-chat-font] .aui-root {
border-radius: 10px;
}
+ /* A heading opens its group: more room above it than below, so it reads with the rows under it
+ rather than the rule or edge over it. */
.unsloth-plus-menu.sidebar-row-menu :is(
[data-slot="dropdown-menu-label"],
[data-slot="context-menu-label"]
) {
- @apply pl-2.5 pr-2.5 py-1 text-ui-11;
+ @apply pl-2.5 pr-2.5 pt-2 pb-1 text-ui-11;
+ }
+
+ /* Checkbox and radio rows (a sidebar header menu's Show toggles and sorts) shaped like the rows
+ beside them, their tick kept clear on the right. */
+ .unsloth-plus-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-checkbox-item"],
+ [data-slot="dropdown-menu-radio-item"]
+ ) {
+ @apply gap-2.5 pl-2.5 pr-9;
+ border-radius: 10px;
+ }
+
+ /* Tick rows hover like the rows beside them, not with the component's accent. */
+ .unsloth-plus-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-checkbox-item"],
+ [data-slot="dropdown-menu-radio-item"]
+ ):is(:hover, :focus, :focus-visible, [data-highlighted]) {
+ background-color: rgb(0 0 0 / calc(0.06 * var(--contrast-wash-gain, 1))) !important;
+ }
+
+ .dark .unsloth-plus-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-checkbox-item"],
+ [data-slot="dropdown-menu-radio-item"]
+ ):is(:hover, :focus, :focus-visible, [data-highlighted]) {
+ background-color: rgb(255 255 255 / calc(0.1 * var(--contrast-wash-gain, 1))) !important;
+ }
+
+ .unsloth-plus-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-checkbox-item"],
+ [data-slot="dropdown-menu-radio-item"]
+ ):is(:hover, :focus, :focus-visible, [data-highlighted]),
+ .unsloth-plus-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-checkbox-item"],
+ [data-slot="dropdown-menu-radio-item"]
+ ):is(:hover, :focus, :focus-visible, [data-highlighted]) * {
+ color: inherit !important;
+ }
+
+ /* The tick's box sits on the row's right padding, the same 2.5 as its left: the tick is
+ drawn inset like a leading icon (MenuTickIcon), so the two inks land level. */
+ .unsloth-plus-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-checkbox-item-indicator"],
+ [data-slot="dropdown-menu-radio-item-indicator"]
+ ) {
+ @apply right-2.5;
+ }
+
+ .unsloth-plus-menu.sidebar-menu :is(
+ [data-slot="dropdown-menu-checkbox-item"],
+ [data-slot="dropdown-menu-radio-item"]
+ )
+ svg {
+ width: var(--icon-size) !important;
+ height: var(--icon-size) !important;
}
/* Active (green) items keep their primary text and icon color on hover. */
@@ -3535,15 +3674,109 @@ html[data-chat-font] .aui-root {
cursor: pointer;
}
-/* A sidebar row is being carried. The gesture is a pointer drag, not a native one, so the
- selection it would otherwise sweep up and the cursor off the row are ours to hold. */
-body.sidebar-row-dragging,
-body.sidebar-row-dragging * {
+/* A sidebar row or section, or a pinned model, is being carried. The gesture is a pointer drag, not
+ a native one, so the selection it would otherwise sweep up and the cursor off the row are ours to
+ hold. Set on the box the drag is in (markDragging in use-sidebar-drag.ts), never the body: a class
+ or inherited style changed there restyles every element on the page, which a long chat made a
+ visible hitch as a drag started and again as it ended. Selection past the box is refused as it
+ starts. */
+.pointer-dragging,
+.pointer-dragging * {
-webkit-user-select: none;
user-select: none;
cursor: grabbing !important;
}
+/* The row it came from stays pressed while the button is held: it dims, bare, as a carried
+ section does, and the raised copy alone reads as the row in hand. */
+.pointer-dragging [data-sidebar="menu-button"]:active {
+ background-color: transparent;
+}
+
+/* A sidebar section carried by its header: it stays in place, dimmed, while a raised copy of the
+ header follows the pointer and one line marks the gap it would land in. */
+[data-sidebar-section][data-section-dragging] {
+ opacity: 0.4;
+ transition: opacity 120ms ease-out;
+}
+
+/* A carried section header or row: a raised copy under the pointer, over the list it came from. */
+.sidebar-section-ghost,
+/* The layer drag visuals are drawn in (dragLayer). Its children are fixed to the window. */
+#pointer-drag-layer {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 0;
+ height: 0;
+ z-index: 60;
+ pointer-events: none;
+}
+
+.sidebar-row-ghost {
+ position: fixed;
+ top: 0;
+ z-index: 60;
+ display: flex;
+ align-items: center;
+ border-radius: 10px;
+ background: var(--sidebar-accent);
+ box-shadow:
+ 0 0 0 1px color-mix(in oklab, var(--foreground) 8%, transparent),
+ 0 8px 24px -8px rgb(0 0 0 / 0.35);
+ pointer-events: none;
+ will-change: transform;
+}
+
+.sidebar-section-ghost > *,
+.sidebar-row-ghost * {
+ pointer-events: none;
+}
+
+/* The drop cue under a carried row's copy, drawn again above it (use-sidebar-drag.ts). */
+.sidebar-drop-cue-overlay {
+ position: fixed;
+ z-index: 61;
+ display: none;
+ box-sizing: border-box;
+ pointer-events: none;
+}
+
+/* A row's copy is its face as drawn, lit like a hovered row but never like the open chat. */
+.sidebar-row-ghost > [data-sidebar="menu-button"] {
+ width: 100%;
+ height: 100%;
+ background: transparent;
+}
+
+/* The name alone: the header's fold chevron means nothing on a header in flight. */
+.sidebar-section-ghost svg {
+ display: none;
+}
+
+/* Placed by `top`, not a transform from the top of the window: shown and placed in one style
+ change, it cannot be painted at the top for a frame before its transform lands. */
+.sidebar-section-drop-line {
+ position: fixed;
+ z-index: 60;
+ height: 0;
+ border-top: 1.5px solid var(--primary);
+ border-radius: 1px;
+ opacity: 0;
+ pointer-events: none;
+ transition: top 90ms ease-out;
+}
+
+html.force-reduced-motion .sidebar-section-drop-line {
+ transition: none;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ html:not(.force-motion) .sidebar-section-drop-line {
+ transition: none;
+ }
+}
+
/* Flat scrollbar chrome */
* {
scrollbar-width: thin;
diff --git a/studio/frontend/src/lib/chevron-icons.ts b/studio/frontend/src/lib/chevron-icons.ts
index a175970223e..950d44ba1a3 100644
--- a/studio/frontend/src/lib/chevron-icons.ts
+++ b/studio/frontend/src/lib/chevron-icons.ts
@@ -46,3 +46,20 @@ export const ChevronRightStandardIcon: IconSvgElement = [
},
],
];
+
+// A submenu arrow drawn against the right of its box, its tip as far from that edge as a
+// leading icon's stroke is from the left (x=2 less half a stroke). Set flush on a row's right
+// padding, the arrow and the row's icon then sit level, at any icon size.
+export const MenuChevronRightIcon: IconSvgElement = [
+ [
+ "path",
+ {
+ d: "M16 6L22 12L16 18",
+ stroke: "currentColor",
+ strokeLinecap: "round",
+ strokeLinejoin: "round",
+ strokeWidth: "1.5",
+ key: "0",
+ },
+ ],
+];
diff --git a/studio/frontend/src/lib/snap-padding.ts b/studio/frontend/src/lib/snap-padding.ts
new file mode 100644
index 00000000000..4fd1536e0f3
--- /dev/null
+++ b/studio/frontend/src/lib/snap-padding.ts
@@ -0,0 +1,111 @@
+// 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 type * as React from "react";
+import { useCallback } from "react";
+
+/**
+ * Rounds a surface's left and right margin and padding to whole CSS pixels.
+ *
+ * A menu's padding scales with the UI (8px is 7.47px at font size 14), and so does the small
+ * margin that aligns it to its trigger. Chromium draws a row's rounded hover pill on whole CSS
+ * pixels while the menu around it keeps its fraction, so a fractional padding leaves the pill a
+ * device pixel nearer one edge of its menu than the other. Whole pixels give the same gap on both
+ * sides in every engine. Read once, as the surface mounts: a style read, no layout.
+ */
+export function snapInlinePadding(element: HTMLElement | null): void {
+ if (!element || typeof window === "undefined") return;
+ const style = getComputedStyle(element);
+ for (const side of ["paddingLeft", "paddingRight", "marginLeft", "marginRight"] as const) {
+ const px = Number.parseFloat(style[side]);
+ if (!Number.isFinite(px)) continue;
+ const snapped = Math.round(px);
+ if (Math.abs(snapped - px) > 0.001) element.style[side] = `${snapped}px`;
+ }
+}
+
+/** What a surface's hover pills are drawn on: its menu rows, list options and plain buttons. */
+const ROW_SELECTOR =
+ '[role="menuitem"],[role="menuitemcheckbox"],[role="menuitemradio"],[role="option"],[cmdk-item],button';
+
+/** How long a surface waits for rows that render after it opens (a list still loading). */
+const ROW_WAIT_MS = 3000;
+
+/**
+ * Nudges the surface's side padding so its first full-width row sits a whole number of CSS
+ * pixels from each edge. A picker's rows often sit in lists inside the surface, each layer with a
+ * scaled inset of its own; rounding the layers one by one could round the two sides apart, so
+ * this measures the row's actual inset on each side and corrects both at the surface. Rows are
+ * never touched, so every row keeps the same inset. Returns whether a row was there to measure.
+ */
+function balanceRowInsets(surface: HTMLElement): boolean {
+ const width = surface.offsetWidth;
+ if (!width) return false;
+ let row: HTMLElement | undefined;
+ for (const candidate of surface.querySelectorAll<HTMLElement>(ROW_SELECTOR)) {
+ if (candidate.offsetWidth >= width * 0.7) {
+ row = candidate;
+ break;
+ }
+ }
+ if (!row) return false;
+ const box = surface.getBoundingClientRect();
+ const rect = row.getBoundingClientRect();
+ // The open animation scales the surface; offsets scale with it.
+ const scale = box.width / width || 1;
+ const style = getComputedStyle(surface);
+ const left = (rect.left - box.left) / scale;
+ const right = (box.right - rect.right) / scale;
+ // Insets within a pixel of each other are meant to match (the surface's own rounding can
+ // split them), so both land on the same whole pixel; others each round to their nearest.
+ const even = Math.abs(left - right) < 1;
+ const padLeft = Number.parseFloat(style.paddingLeft);
+ const padRight = Number.parseFloat(style.paddingRight);
+ let targetLeft = even ? Math.round((left + right) / 2) : Math.round(left);
+ let targetRight = even ? targetLeft : Math.round(right);
+ // A surface padded less than the correction (a list padded inside a bare surface) can only
+ // widen its inset, so it rounds up instead.
+ if (padLeft + targetLeft - left < 0 || padRight + targetRight - right < 0) {
+ targetLeft = even ? Math.ceil(Math.max(left, right)) : Math.ceil(left);
+ targetRight = even ? targetLeft : Math.ceil(right);
+ }
+ const insets = [
+ ["paddingLeft", padLeft + targetLeft - left],
+ ["paddingRight", padRight + targetRight - right],
+ ] as const;
+ for (const [side, padded] of insets) {
+ if (Math.abs(padded - Number.parseFloat(style[side])) > 0.01) {
+ surface.style[side] = `${padded}px`;
+ }
+ }
+ return true;
+}
+
+/**
+ * Rounds a surface's own padding and margin, then balances its rows' insets, now or once its
+ * rows render.
+ */
+export function snapRowInsets(surface: HTMLElement | null): void {
+ if (!surface || typeof window === "undefined") return;
+ snapInlinePadding(surface);
+ if (balanceRowInsets(surface) || typeof MutationObserver === "undefined") return;
+ const observer = new MutationObserver(() => {
+ if (!surface.isConnected || balanceRowInsets(surface)) observer.disconnect();
+ });
+ observer.observe(surface, { childList: true, subtree: true });
+ window.setTimeout(() => observer.disconnect(), ROW_WAIT_MS);
+}
+
+/** A callback ref that snaps the surface's padding as it mounts and passes the element on. */
+export function useSnappedPaddingRef<T extends HTMLElement>(
+ ref: React.Ref<T> | undefined,
+): (element: T | null) => void {
+ return useCallback(
+ (element: T | null) => {
+ if (typeof ref === "function") ref(element);
+ else if (ref) ref.current = element;
+ snapRowInsets(element);
+ },
+ [ref],
+ );
+}
diff --git a/studio/frontend/src/lib/tick-icon.ts b/studio/frontend/src/lib/tick-icon.ts
index 8914323f4ad..44f03f5a3f4 100644
--- a/studio/frontend/src/lib/tick-icon.ts
+++ b/studio/frontend/src/lib/tick-icon.ts
@@ -19,3 +19,20 @@ export const Tick02Icon: IconSvgElement = [
},
],
];
+
+// The same tick moved right inside its box, so its ink ends as far from the box's right edge
+// as a leading icon's ink starts from its left (x=2 less half a stroke). A trailing tick set
+// flush on a row's right padding then sits as far in as the row's icon, at any size.
+export const MenuTickIcon: IconSvgElement = [
+ [
+ "path",
+ {
+ d: "M7.227 13.299L11.758 17.829L21.873 7.714",
+ stroke: "currentColor",
+ strokeLinecap: "round",
+ strokeLinejoin: "round",
+ strokeWidth: "1.5",
+ key: "0",
+ },
+ ],
+];
diff --git a/studio/frontend/tests/desktop-app-menus.test.ts b/studio/frontend/tests/desktop-app-menus.test.ts
index a3205825b0f..e6879e146b1 100644
--- a/studio/frontend/tests/desktop-app-menus.test.ts
+++ b/studio/frontend/tests/desktop-app-menus.test.ts
@@ -327,3 +327,26 @@ test("Back and Forward follow page history, and zoom steps the interface scale",
assert.match(ROOT, /"zoom-out": zoomBy\(-1\)/);
assert.match(ROOT, /"actual-size": \(\) => useInterfaceScaleStore\.getState\(\)\.reset\(\)/);
});
+
+test("Help items reuse the icon of the Settings tab they open", () => {
+ const dialog = readSrc("features/settings/settings-dialog.tsx");
+ const tabIcon = (id: string) =>
+ dialog.match(new RegExp(`id: "${id}",\\s*labelKey: "[^"]+",\\s*icon: (\\w+)`))?.[1];
+ const helpIcon = (action: string) => HELP.match(new RegExp(`"${action}": \\{[^}]*icon: (\\w+)`))?.[1];
+ for (const [action, tab] of [
+ ["help-keyboard-shortcuts", "keyboard-shortcuts"],
+ ["help-troubleshooting", "debugging"],
+ ["help-system-status", "resources"],
+ ]) {
+ // Both sides must be found: two misses would compare equal and pass.
+ const icon = tabIcon(tab);
+ assert.ok(icon, `the ${tab} tab's icon`);
+ assert.equal(helpIcon(action), icon, action);
+ }
+});
+
+test("About Unsloth uses the info icon Studio uses everywhere else", () => {
+ const sidebar = readSrc("components/app-sidebar.tsx");
+ const about = sidebar.slice(0, sidebar.indexOf('{t("shell.helpMenu.about")}'));
+ assert.match(about.slice(about.lastIndexOf("<HugeiconsIcon")), /^<HugeiconsIcon icon=\{InformationCircleIcon\}/);
+});
diff --git a/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.ts
index fa5ba96461f..5a8dea4dba4 100644
--- a/studio/frontend/tests/keyboard-shortcuts.test.ts
+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts
@@ -1268,6 +1268,11 @@ test("a collapsed sidebar section is not published for the chords", async () =>
APP_SIDEBAR,
/chatListsOnScreen && pinnedOpen\n\s*\? pinnedRows\.flatMap\(/,
);
+ // A custom section closes on its own, as Pinned does, and takes only its own rows.
+ assert.match(
+ APP_SIDEBAR,
+ /visibleCustomSections\.flatMap\(\(section\) =>\n\s*collapsedSectionIds\.has\(section\.id\)\n\s*\? \[\]/,
+ );
assert.match(
APP_SIDEBAR,
/chatListsOnScreen && chatOpen \? sortedRecentChatItems/,
@@ -1280,12 +1285,12 @@ test("a collapsed sidebar section is not published for the chords", async () =>
);
assert.match(
APP_SIDEBAR,
- /folderChatItems\(projectsOpen, visibleProjectRecords\)/,
+ /folderChatItems\(projectsSectionRendered && projectsOpen, visibleProjectRecords\)/,
);
// In one list every project chat is a Recents row, so a folder must not list it again.
assert.match(APP_SIDEBAR, /if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !open\)/);
// And the published lists are the filtered ones.
- assert.match(APP_SIDEBAR, /pinnedItems: pinnedSectionChatItems,/);
+ assert.match(APP_SIDEBAR, /pinnedItems: upToPinnedChatItems,/);
assert.match(APP_SIDEBAR, /recentItems: visibleRecentItems,/);
});
@@ -1604,6 +1609,7 @@ test("the published chat lists stop where the sidebar stops", async () => {
for (const group of [
/if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !open\) return \[\];/,
/chatListsOnScreen && pinnedOpen\n\s*\? pinnedRows\.flatMap\([\s\S]*?: \[\],/,
+ /const customSectionChatItems = useMemo\(\(\) => \{\n\s*const bySection = new Map<string, SidebarItem\[\]>\(\);\n\s*if \(!chatListsOnScreen\) return bySection;/,
/\(chatListsOnScreen && chatOpen \? sortedRecentChatItems : \[\]\)/,
]) {
assert.match(APP_SIDEBAR, group);
@@ -1617,12 +1623,13 @@ test("the published chat lists stop where the sidebar stops", async () => {
);
assert.match(
APP_SIDEBAR,
- /const renderedChatItems = useMemo\(\n\s*\(\) => \[\n\s*\.\.\.pinnedSectionChatItems,\n\s*\.\.\.sectionProjectChatItems,\n\s*\.\.\.visibleRecentItems,/,
+ /const renderedChatItems = useMemo\(\n\s*\(\) => \[\.\.\.upToPinnedChatItems, \.\.\.belowPinnedChatItems, \.\.\.visibleRecentItems\],/,
);
// Gating the arrays is enough because nothing renders from them.
const rendered = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf("return (", selectAll));
for (const name of [
"pinnedSectionChatItems",
+ "customSectionChatItems",
"visibleRecentItems",
"renderedChatItems",
"sectionProjectChatItems",
diff --git a/studio/frontend/tests/menu-row-spacing.test.ts b/studio/frontend/tests/menu-row-spacing.test.ts
new file mode 100644
index 00000000000..edb3c683ff1
--- /dev/null
+++ b/studio/frontend/tests/menu-row-spacing.test.ts
@@ -0,0 +1,117 @@
+// 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 { readSrc } from "./helpers/kit.ts";
+
+test("submenu chevrons sit as far from the right edge as leading icons from the left", () => {
+ // The arrow is drawn against its box's right edge, inset as a leading icon's stroke is on the
+ // left, so a box flush on the row's padding lines up at any icon size: no pixel pull.
+ const chevrons = readSrc("lib/chevron-icons.ts");
+ assert.match(chevrons, /MenuChevronRightIcon[\s\S]*?d: "M16 6L22 12L16 18"/);
+ for (const file of ["dropdown-menu", "context-menu", "menubar"]) {
+ const source = readSrc(`components/ui/${file}.tsx`);
+ assert.match(
+ source,
+ /icon=\{MenuChevronRightIcon\}\n\s*strokeWidth=\{1\.5\}\n\s*className="ml-auto size-\[calc\(12px\*var\(--ui-space-scale,1\)\)\]"\n\s*\/>\n\s*<\/\w+Primitive\.SubTrigger>/,
+ `${file} chevron`,
+ );
+ assert.doesNotMatch(source, /-mr-\[calc\([\d.]+px\*var\(--ui-space-scale/, `${file} pulls a glyph by pixels`);
+ assert.doesNotMatch(source, /lucide-react/, `${file} mixes in another chevron`);
+ }
+});
+
+test("trailing ticks and shortcuts sit as far in as the row's leading edge", () => {
+ // The tick is drawn inset like a leading icon, and its box sits on the row's own padding.
+ assert.match(readSrc("lib/tick-icon.ts"), /MenuTickIcon[\s\S]*?d: "M7\.227 13\.299L11\.758 17\.829L21\.873 7\.714"/);
+ for (const [file, rows] of [
+ ["dropdown-menu", 2],
+ ["select", 1],
+ ["combobox", 1],
+ ] as const) {
+ const source = readSrc(`components/ui/${file}.tsx`);
+ assert.match(source, /py-2 pr-9 pl-3|pl-3[^"]*aria-selected=true\]\]:pr-9/, `${file} row keeps room for the tick`);
+ assert.equal(source.match(/absolute right-3 flex/g)?.length, rows, `${file} tick box off the row padding`);
+ assert.match(source, /icon=\{MenuTickIcon\}/, `${file} tick`);
+ assert.doesNotMatch(source, /icon=\{Tick02Icon\}/, `${file} still uses the centred tick`);
+ }
+ const context = readSrc("components/ui/context-menu.tsx");
+ assert.match(context, /py-2 pr-9 pl-3 text-sm[\s\S]*?absolute right-3 pointer-events-none/);
+ assert.match(context, /pr-8 pl-2 text-sm[\s\S]*?absolute right-2 pointer-events-none/);
+ // tracking-widest leaves 0.1em after the last letter; the shortcut takes it back.
+ for (const file of ["dropdown-menu", "context-menu", "menubar", "command"]) {
+ assert.match(readSrc(`components/ui/${file}.tsx`), /-mr-\[0\.1em\][^"]*tracking-widest|tracking-widest[^"]*-mr-\[0\.1em\]/, `${file} shortcut`);
+ }
+ // Ticks a call site sets at the end of a row use the same trailing tick.
+ for (const file of ["features/chat/shared-composer.tsx", "features/chat/mcp-composer-button.tsx", "features/chat/permission-mode-select.tsx"]) {
+ assert.doesNotMatch(readSrc(file), /icon=\{Tick02Icon\}\s+strokeWidth=\{2\}\s+className="ml-auto/, file);
+ }
+});
+
+test("menu rows keep a small gap between them", () => {
+ const css = readSrc("index.css");
+ assert.match(
+ css,
+ /\[data-slot="context-menu-sub-content"\],[\s\S]*?\[role="menuitemradio"\]\n\s*\) \{\n\s*margin-block: 2px;/,
+ );
+});
+
+// A menu's padding and trigger-aligning margin scale with the UI (8px is 7.47px at font size
+// 14). Chromium draws a row's rounded hover pill on whole CSS pixels while the menu keeps its
+// fraction, so the pill sat a device pixel nearer one edge; Firefox does the same for a
+// fractional width. Every menu surface rounds them as it opens.
+test("menu surfaces keep whole-pixel padding, margin and width, so the hover pill sits centred", async () => {
+ const { snapInlinePadding } = await import("../src/lib/snap-padding.ts");
+ const computed: Record<string, string> = {
+ paddingLeft: "7.466px",
+ paddingRight: "7.466px",
+ marginLeft: "-2.8px",
+ marginRight: "0px",
+ };
+ const element = { style: {} as Record<string, string> };
+ const saved = { window: globalThis.window, getComputedStyle: globalThis.getComputedStyle };
+ Object.assign(globalThis, { window: {}, getComputedStyle: () => computed });
+ try {
+ snapInlinePadding(element as unknown as HTMLElement);
+ } finally {
+ Object.assign(globalThis, saved);
+ }
+ assert.deepEqual(element.style, { paddingLeft: "7px", paddingRight: "7px", marginLeft: "-3px" });
+
+ for (const [file, surfaces] of [
+ ["dropdown-menu", 2],
+ ["context-menu", 2],
+ ["menubar", 2],
+ ["select", 1],
+ ["popover", 1],
+ ["combobox", 1],
+ ] as const) {
+ const source = readSrc(`components/ui/${file}.tsx`);
+ const snapped = (source.match(/ref=\{snappedRef\}/g)?.length ?? 0) + (source.match(/snapRowInsets\(element\);/g)?.length ?? 0);
+ assert.equal(snapped, surfaces, `${file} surfaces rounded as they mount`);
+ }
+ // Rows nested in lists are balanced by their measured inset, corrected at the surface, and a
+ // list still loading is waited for, briefly.
+ const helper = readSrc("lib/snap-padding.ts");
+ // Insets meant to match land on the same whole pixel, whatever the surface's rounding did.
+ assert.match(helper, /const even = Math\.abs\(left - right\) < 1;/);
+ assert.match(helper, /let targetLeft = even \? Math\.round\(\(left \+ right\) \/ 2\) : Math\.round\(left\);/);
+ // A bare surface around a padded list can only widen, so it rounds up.
+ assert.match(helper, /targetLeft = even \? Math\.ceil\(Math\.max\(left, right\)\) : Math\.ceil\(left\);/);
+ assert.match(helper, /new MutationObserver/);
+ assert.match(helper, /window\.setTimeout\(\(\) => observer\.disconnect\(\), ROW_WAIT_MS\)/);
+ // The model picker's panel is padded 16px left, 8px right (16px with external providers) so
+ // its scroller can run near the edge; the list's own right inset evens the rows out.
+ assert.match(
+ readSrc("features/model-picker/components/model-selector/pickers.tsx"),
+ /model-list-scroll [^"]*pl-0\.5 pr-1\.5 mr-1 in-data-\[external=true\]:pr-0\.5 in-data-\[external=true\]:mr-0/,
+ );
+ assert.match(readSrc("features/model-picker/components/model-selector.tsx"), /data-external=\{hasExternal \|\| undefined\}/);
+ assert.match(
+ readSrc("components/ui/dropdown-menu.tsx"),
+ /w-\[round\(calc\(var\(--radix-dropdown-menu-trigger-width\)_\+_6px\*var\(--ui-space-scale,1\)\),1px\)\]/,
+ );
+ assert.match(readSrc("components/app-sidebar.tsx"), /app-user-menu sidebar-menu[^"]*w-\[round\(calc\(16rem\*var\(--ui-space-scale,1\)\),1px\)\]/);
+});
diff --git a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
index 05d29c7d6f4..9f657e62ca2 100644
--- a/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
+++ b/studio/frontend/tests/on-device-dot-and-header-alignment.test.ts
@@ -639,14 +639,15 @@ test("list header actions end where a hovered row's action does", () => {
);
});
-test("all three list headers take the same alignment", () => {
- // Pinned, Projects and Recents share one class string, and none is nudged on its own.
+test("every list header takes the same alignment", () => {
+ // Pinned, the custom sections, Projects and Recents share one class string, and none is
+ // nudged on its own.
// They are drop zones, so the class list is spread over lines.
const shared = (
SIDEBAR.match(
/"sidebar-sticky-label sidebar-sticky-label-following group\/sidebar-header gap-1",\n\s*headerInset,/g,
) ?? []
).length;
- assert.equal(shared, 3, "Pinned, Projects and Recents");
+ assert.equal(shared, 4, "Pinned, custom sections, Projects and Recents");
assert.ok(!SIDEBAR.includes("translate-x-[2px]"));
});
diff --git a/studio/frontend/tests/sidebar-action-rows-inert.test.ts b/studio/frontend/tests/sidebar-action-rows-inert.test.ts
index 3e6f30bf38a..bf40aedc0d2 100644
--- a/studio/frontend/tests/sidebar-action-rows-inert.test.ts
+++ b/studio/frontend/tests/sidebar-action-rows-inert.test.ts
@@ -81,9 +81,9 @@ test("navigation rows align while the profile footer ignores the scroll rail", a
);
// New Chat is the only outside row that aligns with the scroller's rail.
assert.equal(source.match(/(?<!const )rowPadding[,}]/g)?.length, 1);
- // Nav rows, pinned chats, Projects, Recents, and training runs sit inside the
- // scroller; the footer is the sixth unrailed use outside it.
- assert.equal(source.match(/unrailedRowPadding[,}]/g)?.length, 6);
+ // Nav rows, pinned chats, custom sections, Projects, Recents, and training runs sit
+ // inside the scroller; the footer is the seventh unrailed use outside it.
+ assert.equal(source.match(/unrailedRowPadding[,}]/g)?.length, 7);
const footer = source
.split("<SidebarFooter")[1]
diff --git a/studio/frontend/tests/sidebar-custom-sections.test.ts b/studio/frontend/tests/sidebar-custom-sections.test.ts
new file mode 100644
index 00000000000..d17bbf20c65
--- /dev/null
+++ b/studio/frontend/tests/sidebar-custom-sections.test.ts
@@ -0,0 +1,1018 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Custom sidebar sections: user-named lists that hold chats and project folders. The store keeps
+// them, the drop planner files rows in and out of them, and the sidebar draws them between Pinned
+// and Projects with the same header menu every other list carries.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ planSidebarDrop,
+ sectionRingKey,
+ STAY,
+ type SidebarDragItem,
+ type SidebarDropContext,
+ type SidebarDropOutcome,
+ type SidebarDropPlan,
+ type SidebarDropZone,
+} from "../src/features/chat/lib/sidebar-drag.ts";
+import {
+ customSectionIdOf,
+ customSectionScope,
+ mergePersistedOrganization,
+ normalizeSectionName,
+ PINNED_ORDER_SCOPE,
+ projectOrderScope,
+ RECENTS_ORDER_SCOPE,
+ PROJECT_ORDER_SCOPE,
+ PINNED_SECTION_KEY,
+ PROJECTS_SECTION_KEY,
+ resolveSectionOrder,
+ SIDEBAR_ORGANIZATION_STORAGE_KEY,
+ useSidebarOrganizationStore,
+} from "../src/features/chat/stores/sidebar-organization-store.ts";
+import { readSrcAsync } from "./helpers/kit.ts";
+
+const APP_SIDEBAR = await readSrcAsync("components/app-sidebar.tsx");
+const EN = await readSrcAsync("i18n/locales/en.ts");
+
+function plannedDrop(outcome: SidebarDropOutcome): SidebarDropPlan {
+ assert.ok(
+ outcome !== null && outcome !== STAY,
+ `expected a drop plan, got ${String(outcome)}`,
+ );
+ return outcome;
+}
+
+function resetStore() {
+ const initial = useSidebarOrganizationStore.getInitialState();
+ useSidebarOrganizationStore.setState({
+ customSections: initial.customSections,
+ sectionByChatId: initial.sectionByChatId,
+ sectionByProjectId: initial.sectionByProjectId,
+ hiddenSections: initial.hiddenSections,
+ sectionOrder: initial.sectionOrder,
+ pendingNewChatSection: null,
+ manualOrder: {},
+ });
+}
+
+// ---------------------------------------------------------------------------------------------
+// Store
+
+test("a new sidebar has no custom sections and hides nothing", () => {
+ const fresh = useSidebarOrganizationStore.getInitialState();
+ assert.deepEqual(fresh.customSections, []);
+ assert.deepEqual({ ...fresh.sectionByChatId }, {});
+ assert.deepEqual({ ...fresh.sectionByProjectId }, {});
+ assert.deepEqual(fresh.hiddenSections, []);
+});
+
+test("a section is created newest first, named, and manual by default", () => {
+ resetStore();
+ const store = useSidebarOrganizationStore.getState();
+ const first = store.createCustomSection(" Research ");
+ const second = store.createCustomSection("Work\n stuff");
+ assert.ok(first && second && first !== second);
+ const { customSections } = useSidebarOrganizationStore.getState();
+ assert.deepEqual(
+ customSections.map((section) => [section.name, section.sort]),
+ [
+ ["Work stuff", "manual"],
+ ["Research", "manual"],
+ ],
+ );
+});
+
+test("a blank name makes no section and renames nothing", () => {
+ resetStore();
+ const store = useSidebarOrganizationStore.getState();
+ assert.equal(store.createCustomSection(" "), null);
+ const id = store.createCustomSection("Keep")!;
+ store.renameCustomSection(id, " \t ");
+ assert.equal(useSidebarOrganizationStore.getState().customSections[0].name, "Keep");
+ store.renameCustomSection(id, "Kept");
+ assert.equal(useSidebarOrganizationStore.getState().customSections[0].name, "Kept");
+ assert.equal(normalizeSectionName("x".repeat(200)).length, 60);
+});
+
+test("rows file into a section, move between sections, and come back out", () => {
+ resetStore();
+ const store = useSidebarOrganizationStore.getState();
+ const a = store.createCustomSection("A")!;
+ const b = store.createCustomSection("B")!;
+ store.setChatsSection(["c1", "c2"], a);
+ store.setProjectsSection(["p1"], a);
+ store.setChatsSection(["c2"], b);
+ let state = useSidebarOrganizationStore.getState();
+ assert.deepEqual({ ...state.sectionByChatId }, { c1: a, c2: b });
+ assert.deepEqual({ ...state.sectionByProjectId }, { p1: a });
+ store.setChatsSection(["c1"], null);
+ state = useSidebarOrganizationStore.getState();
+ assert.deepEqual({ ...state.sectionByChatId }, { c2: b });
+ // Filing into a section that does not exist is refused rather than stranding the row.
+ store.setChatsSection(["c3"], "missing");
+ assert.equal(useSidebarOrganizationStore.getState().sectionByChatId.c3, undefined);
+});
+
+test("deleting a section returns its rows and forgets its order and visibility", () => {
+ resetStore();
+ const store = useSidebarOrganizationStore.getState();
+ const gone = store.createCustomSection("Gone")!;
+ const kept = store.createCustomSection("Kept")!;
+ store.setChatsSection(["c1"], gone);
+ store.setChatsSection(["c2"], kept);
+ store.setProjectsSection(["p1"], gone);
+ store.setManualOrder(customSectionScope(gone), ["c1", "p1"]);
+ store.setSectionHidden(gone, true);
+ store.deleteCustomSection(gone);
+ const state = useSidebarOrganizationStore.getState();
+ assert.deepEqual(state.customSections.map((section) => section.id), [kept]);
+ assert.deepEqual({ ...state.sectionByChatId }, { c2: kept });
+ assert.deepEqual({ ...state.sectionByProjectId }, {});
+ assert.equal(state.manualOrder[customSectionScope(gone)], undefined);
+ assert.ok(!state.hiddenSections.includes(gone));
+});
+
+test("a section moves by dragging alone, and new sections open among the user's own", () => {
+ resetStore();
+ const store = useSidebarOrganizationStore.getState();
+ const c = store.createCustomSection("C")!;
+ const b = store.createCustomSection("B")!;
+ const a = store.createCustomSection("A")!;
+ const order = () => {
+ const state = useSidebarOrganizationStore.getState();
+ return resolveSectionOrder(state.sectionOrder, state.customSections);
+ };
+ const P = PINNED_SECTION_KEY;
+ const J = PROJECTS_SECTION_KEY;
+ // Newest first, between Pinned and Projects.
+ assert.deepEqual(order(), [P, a, b, c, J]);
+ store.moveSection(c, P, "top");
+ assert.deepEqual(order(), [c, P, a, b, J]);
+ // The list every menu reads follows the drawn order.
+ assert.deepEqual(
+ useSidebarOrganizationStore.getState().customSections.map((section) => section.id),
+ [c, a, b],
+ );
+ // No step-by-step move is left: the header drag is the one way to reorder.
+ assert.equal("moveCustomSection" in useSidebarOrganizationStore.getState(), false);
+ assert.doesNotMatch(APP_SIDEBAR, /\bmoveSectionUp\b|\bmoveSectionDown\b|\bmoveCustomSection\b/);
+});
+
+test("no sidebar list sorts by priority", () => {
+ assert.doesNotMatch(APP_SIDEBAR, /"priority"|PINNED_SORT_OPTIONS/);
+ assert.match(
+ APP_SIDEBAR,
+ /\}> = \[\n \{ value: "updated", key: "shell\.organize\.lastUpdated" \},\n \{ value: "manual", key: "shell\.organize\.manualOrder" \},\n\];/,
+ );
+ // A saved Priority falls back to each list's default.
+ const merged = mergePersistedOrganization(
+ {
+ pinnedSort: "priority",
+ chatSort: "priority",
+ customSections: [{ id: "s", name: "S", sort: "priority" }],
+ },
+ useSidebarOrganizationStore.getInitialState(),
+ );
+ assert.equal(merged.pinnedSort, "manual");
+ assert.equal(merged.chatSort, "updated");
+ assert.equal(merged.customSections[0]?.sort, "manual");
+});
+
+test("a dragged section lands on the edge it was dropped against", () => {
+ resetStore();
+ const store = useSidebarOrganizationStore.getState();
+ const s = store.createCustomSection("S")!;
+ const P = PINNED_SECTION_KEY;
+ const J = PROJECTS_SECTION_KEY;
+ const order = () => {
+ const state = useSidebarOrganizationStore.getState();
+ return resolveSectionOrder(state.sectionOrder, state.customSections);
+ };
+ assert.deepEqual(order(), [P, s, J]);
+ // Projects above Pinned, then Pinned under everything.
+ store.moveSection(J, P, "top");
+ assert.deepEqual(order(), [J, P, s]);
+ store.moveSection(P, s, "bottom");
+ assert.deepEqual(order(), [J, s, P]);
+ // A drop that changes nothing leaves the state alone.
+ const before = useSidebarOrganizationStore.getState();
+ store.moveSection(s, P, "top");
+ assert.equal(useSidebarOrganizationStore.getState(), before);
+ // A new section still opens among the user's own; a deleted one leaves the order.
+ const t2 = store.createCustomSection("T")!;
+ assert.deepEqual(order(), [J, t2, s, P]);
+ store.deleteCustomSection(s);
+ assert.deepEqual(order(), [J, t2, P]);
+});
+
+test("a saved order is read over the sections that exist now", () => {
+ const sections = [
+ { id: "a", name: "A", sort: "manual" as const },
+ { id: "b", name: "B", sort: "manual" as const },
+ ];
+ // Unknown keys and repeats go; missing ones take their default place.
+ assert.deepEqual(resolveSectionOrder(["b", "gone", PROJECTS_SECTION_KEY, "b"], sections), [
+ PINNED_SECTION_KEY,
+ "b",
+ "a",
+ PROJECTS_SECTION_KEY,
+ ]);
+ assert.deepEqual(resolveSectionOrder([], []), [PINNED_SECTION_KEY, PROJECTS_SECTION_KEY]);
+ // Recents has no place in it: it is always last.
+ assert.ok(!resolveSectionOrder(["recents"], sections).includes("recents"));
+ const merged = mergePersistedOrganization(
+ { customSections: sections, sectionOrder: [PROJECTS_SECTION_KEY, "a", 7, "zzz"] },
+ useSidebarOrganizationStore.getInitialState(),
+ );
+ assert.deepEqual(merged.sectionOrder, [PINNED_SECTION_KEY, "b", PROJECTS_SECTION_KEY, "a"]);
+});
+
+test("Show toggles hide Projects and custom sections independently, never Pinned", () => {
+ resetStore();
+ const store = useSidebarOrganizationStore.getState();
+ const id = store.createCustomSection("S")!;
+ store.setSectionHidden(id, true);
+ store.setSectionHidden(id, true);
+ assert.deepEqual(useSidebarOrganizationStore.getState().hiddenSections, [id]);
+ store.setSectionHidden(PROJECTS_SECTION_KEY, true);
+ store.setSectionHidden(id, false);
+ assert.deepEqual(useSidebarOrganizationStore.getState().hiddenSections, [
+ PROJECTS_SECTION_KEY,
+ ]);
+ // Pinned always shows: a "hide Pinned" saved by an earlier build is dropped on load.
+ const merged = mergePersistedOrganization(
+ { hiddenSections: ["pinned", PROJECTS_SECTION_KEY] },
+ useSidebarOrganizationStore.getState(),
+ );
+ assert.deepEqual(merged.hiddenSections, [PROJECTS_SECTION_KEY]);
+});
+
+test("a saved payload keeps only well-formed sections and assignments to them", () => {
+ const merged = mergePersistedOrganization(
+ {
+ customSections: [
+ { id: "s1", name: " Reading ", sort: "updated" },
+ { id: "s1", name: "Duplicate" },
+ { id: "s2", name: " " },
+ { id: 7, name: "Bad id" },
+ { id: "s3", name: "Loose", sort: "sideways" },
+ null,
+ ],
+ sectionByChatId: { c1: "s1", c2: "s2", c3: 4 },
+ sectionByProjectId: { p1: "s3", p2: "nope" },
+ hiddenSections: ["pinned", "s3", "s3", "recents", "nope", 1],
+ },
+ useSidebarOrganizationStore.getInitialState(),
+ );
+ assert.deepEqual(merged.customSections, [
+ { id: "s1", name: "Reading", sort: "updated" },
+ { id: "s3", name: "Loose", sort: "manual" },
+ ]);
+ assert.deepEqual({ ...merged.sectionByChatId }, { c1: "s1" });
+ assert.deepEqual({ ...merged.sectionByProjectId }, { p1: "s3" });
+ // Pinned always shows, so an old "hide Pinned" is dropped with the rest.
+ assert.deepEqual(merged.hiddenSections, ["s3"]);
+ // Reset-all already clears the key everything above lives under.
+ assert.equal(SIDEBAR_ORGANIZATION_STORAGE_KEY, "unsloth_sidebar_organization");
+});
+
+test("a section's scope cannot be mistaken for a built-in list", () => {
+ assert.equal(customSectionIdOf(customSectionScope("abc")), "abc");
+ for (const scope of [
+ RECENTS_ORDER_SCOPE,
+ PINNED_ORDER_SCOPE,
+ PROJECT_ORDER_SCOPE,
+ projectOrderScope("section:abc"),
+ ]) {
+ assert.equal(customSectionIdOf(scope), null, scope);
+ }
+});
+
+// ---------------------------------------------------------------------------------------------
+// Drop planner
+
+// Section S holds folder "lab" and chat s1; chat p1 is pinned; r1 and r2 are Recents rows;
+// folder "home" is under Projects with chat c3.
+const S = "s";
+const SCOPE = customSectionScope(S);
+
+function context(overrides: Partial<SidebarDropContext> = {}): SidebarDropContext {
+ return {
+ organizeBy: "project",
+ chatSort: "updated",
+ pinnedSort: "manual",
+ projectSort: "manual",
+ pinnedChatIds: new Set(["p1"]),
+ pinnedProjectIds: new Set(),
+ sectionByChatId: { s1: S },
+ sectionByProjectId: { lab: S },
+ sectionSort: () => "manual",
+ orders: {
+ pinned: ["p1"],
+ projects: ["home"],
+ recents: ["r1", "r2"],
+ projectChats: (projectId) => ({ home: ["c3"], lab: ["l1"] })[projectId] ?? [],
+ sections: (sectionId) => (sectionId === S ? ["lab", "s1"] : []),
+ },
+ ...overrides,
+ };
+}
+
+const chat = (
+ id: string,
+ section: SidebarDragItem["section"],
+ scope: string,
+ projectId: string | null = null,
+): SidebarDragItem => ({ kind: "chat", id, section, scope, projectId });
+const chatRow = (
+ section: SidebarDropZone["section"],
+ scope: string,
+ id: string,
+ folderId?: string,
+): SidebarDropZone => ({ section, row: { id, kind: "chat", scope }, folderId });
+
+test("a Recents chat dropped on a section is filed there, in the slot shown", () => {
+ const plan = plannedDrop(
+ planSidebarDrop(
+ chat("r1", "recents", RECENTS_ORDER_SCOPE),
+ chatRow(SCOPE, SCOPE, "s1"),
+ "top",
+ context(),
+ ),
+ );
+ assert.deepEqual(plan.action, { kind: "section", sectionId: S });
+ assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "r1", sectionId: S });
+ assert.deepEqual(plan.effects.orders, [{ scope: SCOPE, ids: ["lab", "r1", "s1"] }]);
+ assert.equal(plan.effects.unpinChat, undefined);
+});
+
+test("a pinned chat dropped on a section loses its pin", () => {
+ const plan = plannedDrop(
+ planSidebarDrop(
+ chat("p1", "pinned", PINNED_ORDER_SCOPE),
+ { section: SCOPE },
+ "bottom",
+ context(),
+ ),
+ );
+ assert.equal(plan.effects.unpinChat, "p1");
+ assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "p1", sectionId: S });
+ assert.deepEqual(plan.effects.orders[0].ids, ["lab", "s1", "p1"]);
+});
+
+test("an empty section takes a drop anywhere in it, and rings itself", () => {
+ const empty = context({ sectionByChatId: {}, sectionByProjectId: {} });
+ const plan = plannedDrop(
+ planSidebarDrop(chat("r2", "recents", RECENTS_ORDER_SCOPE), { section: SCOPE }, "top", {
+ ...empty,
+ orders: { ...empty.orders, sections: () => [] },
+ }),
+ );
+ assert.deepEqual(plan.cue, { ring: sectionRingKey(SCOPE) });
+ assert.deepEqual(plan.effects.orders, [{ scope: SCOPE, ids: ["r2"] }]);
+});
+
+test("a folder dropped on a section is filed with its chats", () => {
+ const plan = plannedDrop(
+ planSidebarDrop(
+ { kind: "project", id: "home", section: "projects", scope: PROJECT_ORDER_SCOPE, projectId: null },
+ chatRow(SCOPE, SCOPE, "s1"),
+ "bottom",
+ context(),
+ ),
+ );
+ assert.deepEqual(plan.effects.fileInSection, {
+ kind: "project",
+ id: "home",
+ sectionId: S,
+ });
+ assert.deepEqual(plan.effects.orders[0].ids, ["lab", "s1", "home"]);
+});
+
+test("a row already in the section reorders, switching a sorted section to Manual", () => {
+ const plan = plannedDrop(
+ planSidebarDrop(
+ chat("s1", SCOPE, SCOPE),
+ { section: SCOPE, row: { id: "lab", kind: "project", scope: SCOPE }, folderId: "lab" },
+ "top",
+ context({ sectionSort: () => "updated" }),
+ ),
+ );
+ assert.equal(plan.action.kind, "reorder");
+ assert.equal(plan.effects.fileInSection, undefined);
+ assert.deepEqual(plan.effects.orders, [{ scope: SCOPE, ids: ["s1", "lab"] }]);
+ assert.equal(plan.effects.switchSort, SCOPE);
+});
+
+test("a section's chat dragged to Recents leaves the section", () => {
+ const plan = plannedDrop(
+ planSidebarDrop(
+ chat("s1", SCOPE, SCOPE),
+ chatRow("recents", RECENTS_ORDER_SCOPE, "r1"),
+ "bottom",
+ context(),
+ ),
+ );
+ assert.deepEqual(plan.action, { kind: "section", sectionId: null });
+ assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "s1", sectionId: null });
+ assert.deepEqual(plan.effects.orders[0].ids, ["r1", "s1", "r2"]);
+});
+
+test("a section's chat dragged into a folder moves there and leaves the section", () => {
+ const plan = plannedDrop(
+ planSidebarDrop(
+ chat("s1", SCOPE, SCOPE),
+ chatRow("projects", projectOrderScope("home"), "c3", "home"),
+ "bottom",
+ context(),
+ ),
+ );
+ assert.deepEqual(plan.effects.moveChat, { chatId: "s1", projectId: "home" });
+ assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "s1", sectionId: null });
+ assert.equal(plan.effects.unpinChat, undefined);
+});
+
+test("a section's chat dropped back on its own folder only leaves the section", () => {
+ const plan = plannedDrop(
+ planSidebarDrop(
+ chat("s1", SCOPE, SCOPE, "home"),
+ chatRow("projects", projectOrderScope("home"), "c3", "home"),
+ "top",
+ context(),
+ ),
+ );
+ assert.deepEqual(plan.action, { kind: "section", sectionId: null });
+ assert.equal(plan.effects.moveChat, undefined);
+ assert.equal(plan.effects.unpinChat, undefined);
+ assert.deepEqual(plan.effects.fileInSection, { kind: "chat", id: "s1", sectionId: null });
+});
+
+test("a section's folder dragged to Projects leaves the section", () => {
+ const plan = plannedDrop(
+ planSidebarDrop(
+ { kind: "project", id: "lab", section: SCOPE, scope: SCOPE, projectId: null },
+ { section: "projects", row: { id: "home", kind: "project", scope: PROJECT_ORDER_SCOPE }, folderId: "home" },
+ "bottom",
+ context(),
+ ),
+ );
+ assert.deepEqual(plan.action, { kind: "section", sectionId: null });
+ assert.equal(plan.effects.unpinProject, undefined);
+ assert.deepEqual(plan.effects.fileInSection, { kind: "project", id: "lab", sectionId: null });
+ assert.deepEqual(plan.effects.orders[0].ids, ["home", "lab"]);
+});
+
+test("a chat dropped on a section's folder files into the project, not the section", () => {
+ const plan = plannedDrop(
+ planSidebarDrop(
+ chat("r1", "recents", RECENTS_ORDER_SCOPE),
+ chatRow(SCOPE, projectOrderScope("lab"), "l1", "lab"),
+ "bottom",
+ context(),
+ ),
+ );
+ assert.deepEqual(plan.effects.moveChat, { chatId: "r1", projectId: "lab" });
+ assert.equal(plan.effects.fileInSection, undefined);
+});
+
+test("reordering Pinned keeps a pinned row's section for when it is unpinned", () => {
+ const ctx = context({
+ pinnedChatIds: new Set(["p1", "s1"]),
+ orders: { ...context().orders, pinned: ["p1", "s1"] },
+ });
+ const plan = plannedDrop(
+ planSidebarDrop(
+ chat("s1", "pinned", PINNED_ORDER_SCOPE),
+ chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
+ "top",
+ ctx,
+ ),
+ );
+ assert.equal(plan.action.kind, "reorder");
+ assert.equal(plan.effects.fileInSection, undefined);
+});
+
+test("a section's row dragged into Pinned keeps its section for when it is unpinned", () => {
+ // As a pin from the row's menu does: Pinned draws it, and unpinning sends it back to S.
+ const chatPlan = plannedDrop(
+ planSidebarDrop(chat("s1", SCOPE, SCOPE), chatRow("pinned", PINNED_ORDER_SCOPE, "p1"), "bottom", context()),
+ );
+ assert.equal(chatPlan.action.kind, "pin");
+ assert.equal(chatPlan.effects.pinChat, "s1");
+ assert.equal(chatPlan.effects.fileInSection, undefined);
+ const folderPlan = plannedDrop(
+ planSidebarDrop(
+ { kind: "project", id: "lab", section: SCOPE, scope: SCOPE, projectId: null },
+ chatRow("pinned", PINNED_ORDER_SCOPE, "p1"),
+ "bottom",
+ context(),
+ ),
+ );
+ assert.equal(folderPlan.action.kind, "pin");
+ assert.equal(folderPlan.effects.pinProject, "lab");
+ assert.equal(folderPlan.effects.fileInSection, undefined);
+ // Into a pinned folder is a move into that project, which the section would hide: it leaves.
+ const intoFolder = plannedDrop(
+ planSidebarDrop(
+ chat("s1", SCOPE, SCOPE),
+ chatRow("pinned", projectOrderScope("home"), "c3", "home"),
+ "top",
+ context({ pinnedProjectIds: new Set(["home"]), orders: { ...context().orders, pinned: ["p1", "home"] } }),
+ ),
+ );
+ assert.equal(intoFolder.action.kind, "move");
+ assert.deepEqual(intoFolder.effects.fileInSection, { kind: "chat", id: "s1", sectionId: null });
+});
+
+// ---------------------------------------------------------------------------------------------
+// Sidebar wiring
+
+test("each list header's menu carries only what that list is about, as in ChatGPT", () => {
+ const menu = APP_SIDEBAR.slice(
+ APP_SIDEBAR.indexOf("function renderSidebarHeaderMenu("),
+ APP_SIDEBAR.indexOf("function renderSectionItems("),
+ );
+ const branch = (from: string, to: string) =>
+ menu.slice(menu.indexOf(from), to ? menu.indexOf(to) : undefined);
+ const pinned = branch('if (options.kind === "pinned")', '} else if (options.kind === "projects")');
+ const projects = branch('} else if (options.kind === "projects")', '} else if (options.kind === "recents")');
+ const recents = branch('} else if (options.kind === "recents")', '} else if (options.kind === "section")');
+ const section = branch('} else if (options.kind === "section")', "return (\n <NonModalDropdownMenu");
+ // Pinned sorts its pins straight in the menu: no submenus, no Show, no New section.
+ assert.match(pinned, /value=\{pinnedSort\}/);
+ assert.doesNotMatch(pinned, /organizeSubmenu|renderSortSubmenu|setSectionHidden|mode: "create"/);
+ // Projects groups the sidebar and sorts its chats; the section toggles live on Recents alone.
+ assert.match(projects, /\{organizeSubmenu\}/);
+ assert.match(projects, /shell\.organize\.sortChatsBy/);
+ assert.doesNotMatch(projects, /sortProjectsBy/);
+ // Every header menu is the chat row menu's size, submenus included.
+ assert.match(menu, /className=\{cn\("unsloth-plus-menu sidebar-row-menu sidebar-menu"/);
+ // It opens out to the right of the "...", not squeezed back inside the sidebar.
+ assert.match(menu, /<NonModalDropdownMenu\n\s*side="bottom"\n\s*align="start"/);
+ assert.doesNotMatch(menu, /className="unsloth-plus-menu w-/);
+ assert.match(menu, /icon=\{PanelLeftIcon\}/);
+ assert.match(APP_SIDEBAR, /value: "project", key: "shell\.organize\.byProject", icon: Folder01Icon/);
+ assert.match(APP_SIDEBAR, /value: "list", key: "shell\.organize\.inOneList", icon: LeftToRightListBulletIcon/);
+ assert.doesNotMatch(projects, /setSectionHidden|mode: "create"/);
+ // Recents: organize, sort, then Show (Projects and custom sections only) and New section.
+ assert.match(recents, /\{organizeSubmenu\}[\s\S]*shell\.organize\.sortChatsBy/);
+ assert.match(recents, /t\("shell\.organize\.show"\)/);
+ assert.match(recents, /setSectionHidden\(PROJECTS_SECTION_KEY, !on\)/);
+ assert.match(recents, /setSectionHidden\(candidate\.id, !on\)/);
+ assert.match(recents, /setSectionDialog\(\{ mode: "create" \}\)/);
+ // Pinned always shows, so it has no toggle.
+ assert.doesNotMatch(APP_SIDEBAR, /setSectionHidden\(PINNED_SECTION_KEY/);
+ // A custom section's menu manages that section only.
+ assert.match(section, /mode: "rename", section/);
+ assert.match(section, /removeCustomSection\(section\)/);
+ assert.doesNotMatch(section, /organizeSubmenu|setSectionHidden|mode: "create"/);
+ // The four headers each say which menu they are.
+ for (const kind of ["pinned", "projects", "recents", "section"]) {
+ assert.match(APP_SIDEBAR, new RegExp(`renderSidebarHeaderMenu\\(\\{\\n[^}]*kind: "${kind}",`));
+ }
+ assert.ok(!APP_SIDEBAR.includes("includeOrganize"));
+});
+
+test("chat and folder menus, and bulk selections, can file into a section", () => {
+ assert.match(APP_SIDEBAR, /target: \{ chatIds: \[item\.id\] \},/);
+ assert.match(APP_SIDEBAR, /target: \{ projectIds: \[project\.id\] \},/);
+ assert.match(APP_SIDEBAR, /renderBulkSectionSubmenu\(\n\s*"chat",/);
+ assert.match(APP_SIDEBAR, /renderBulkSectionSubmenu\(\n\s*"project",/);
+});
+
+test("a drop's filing is committed with its slot", () => {
+ const commit = APP_SIDEBAR.slice(
+ APP_SIDEBAR.indexOf("function commitDrop("),
+ APP_SIDEBAR.indexOf("function dropCueClass("),
+ );
+ assert.match(commit, /if \(filing\.kind === "chat"\) setChatsSection\(\[filing\.id\], filing\.sectionId\);/);
+ assert.match(commit, /setCustomSectionSort\(sortedSection, "manual"\);/);
+});
+
+test("the section strings exist in English", () => {
+ for (const key of [
+ 'createTitle: "New section"',
+ 'createDescription: "Group chats and projects however you like"',
+ 'namePlaceholder: "Section name"',
+ 'create: "Create section"',
+ ]) {
+ assert.ok(EN.includes(key), key);
+ }
+});
+
+test("a section's header starts a chat that is filed there on its first send", () => {
+ const section = APP_SIDEBAR.slice(
+ APP_SIDEBAR.indexOf("function renderCustomSection("),
+ APP_SIDEBAR.indexOf("function renderProjectsSection("),
+ );
+ assert.match(section, /onClick=\{\(\) => openNewChatInSection\(section\.id\)\}/);
+ assert.match(section, /icon=\{PencilEdit02Icon\}/);
+ // Marked only once the new chat is on screen, so the chat being left is never filed.
+ assert.match(
+ APP_SIDEBAR,
+ /navigate\(\{ to: "\/chat", search: \{ new: nonce \} \}\)\.then\(\(\) =>\n\s*setPendingNewChatSection\(\{ sectionId, nonce \}\),/,
+ );
+ // Filed when the store gains an id while the address still names that new chat; leaving it
+ // first drops the mark.
+ const effect = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf("if (!pendingNewChatSection) return;"));
+ assert.match(effect, /const fresh = isChatRoute && !search\.thread && !search\.project;/);
+ assert.match(
+ effect,
+ /if \(fresh && search\.new === nonce && !search\.compare\) \{\n\s*if \(storeThreadId\) \{\n\s*setChatsSection\(\[storeThreadId\], sectionId\);\n\s*setPendingNewChatSection\(null\);/,
+ );
+ // Turned into a compare chat before its first send, the compare chat takes the mark; a compare
+ // chat already listed is one opened instead, which lets it go.
+ assert.match(
+ effect,
+ /fresh &&\n\s*!search\.new &&\n\s*search\.compare &&\n\s*!allChatItems\.some\(\(item\) => item\.id === search\.compare\)/,
+ );
+ assert.match(effect, /setPendingNewChatSection\(newCompare \? \{ sectionId, nonce, compare: newCompare \} : null\);/);
+ // Leaving the compare chat lets it go; its pair, listed under the address's id, joins.
+ assert.match(effect, /if \(!\(fresh && !search\.new && search\.compare === compare\)\) \{\n\s*setPendingNewChatSection\(null\);/);
+ assert.match(
+ effect,
+ /allChatItems\.some\(\(item\) => item\.type === "compare" && item\.id === compare\)\) \{\n\s*setChatsSection\(\[compare\], sectionId\);/,
+ );
+ // Not saved: a reload must not file some later chat.
+ const store = useSidebarOrganizationStore.getInitialState();
+ assert.equal(store.pendingNewChatSection, null);
+});
+
+test("sections above Recents drag by their headers, and Recents stays last", async () => {
+ // Drawn in the saved order; Recents is drawn after them and is no key of it.
+ assert.match(
+ APP_SIDEBAR,
+ /\{orderedSectionKeys\.map\(\(key\) => \(\n\s*<Fragment key=\{key\}>\{renderOrderedSection\(key\)\}<\/Fragment>/,
+ );
+ assert.match(APP_SIDEBAR, /data-sidebar-section=\{key\}\n\s*onPointerDown=\{\(event\) => startSectionDrag\(event, key\)\}/);
+ assert.match(
+ APP_SIDEBAR,
+ /useSectionDrag\(\{\n\s*onDrop: \(key, landing\) => moveSection\(key, landing\.target, landing\.edge\),/,
+ );
+ const drag = await readSrcAsync("features/chat/hooks/use-section-drag.ts");
+ // Only from the header, never from its buttons, and not by touch, which scrolls.
+ assert.match(drag, /event\.pointerType === "touch"/);
+ assert.match(drag, /const HEADER_SELECTOR = '\[data-sidebar="group-label"\]';/);
+ assert.match(drag, /if \(pressed\.closest\(HEADER_ACTION_SELECTOR\)\) return;/);
+ // The release lands on the header, which must not fold the section it moved.
+ assert.match(drag, /window\.addEventListener\("click", stop, \{ capture: true, once: true \}\)/);
+ assert.match(drag, /optionsRef\.current\.onDrop\(key, dropped\);/);
+});
+
+
+test("the sidebar and account menus share one flat surface and type; other menus keep theirs", async () => {
+ const css = await readSrcAsync("index.css");
+ // The shared menu surface, which the composer's menus use, is left as it was.
+ assert.match(css, /\.dark \.unsloth-plus-menu\[data-slot\] \{\n\s*background-color: var\(--card\);/);
+ assert.match(
+ css,
+ /\.unsloth-plus-menu\[data-slot\] \{[\s\S]*?box-shadow: 0 2px 8px -2px rgba\(0, 0, 0, 0\.16\);\n\s*\}/,
+ );
+ const tagged = ":is\\(\\.unsloth-plus-menu, \\.app-user-menu\\)\\.sidebar-menu\\[data-slot\\]";
+ // No shadow, over the shared menu shadow's !important.
+ assert.match(css, new RegExp(`${tagged} \\{\\n\\s*box-shadow: none !important;`));
+ assert.match(
+ css,
+ new RegExp(
+ `\\.dark ${tagged} \\{\\n\\s*background-color: color-mix\\(in srgb, var\\(--card\\), white 7%\\);\\n\\s*color: #fff;`,
+ ),
+ );
+ // The system face at 14px, scaled, on sidebar rows and account rows alike.
+ assert.match(css, new RegExp(`${tagged} \\{\\n\\s*font-family: ui-sans-serif,`));
+ assert.match(
+ css,
+ /\.unsloth-plus-menu\.sidebar-row-menu\.sidebar-menu :is\([\s\S]*?\) \{\n\s*@apply py-2 text-ui-14;/,
+ );
+ assert.match(css, /\.app-user-menu\.sidebar-menu :is\([\s\S]*?\) \{\n\s*@apply text-ui-14;\n\s*font-weight: 400;/);
+ // Every sidebar menu is marked, the account menu and its Help submenu included.
+ assert.equal((APP_SIDEBAR.match(/"unsloth-plus-menu sidebar-row-menu sidebar-menu/g) ?? []).length, 13);
+ assert.match(APP_SIDEBAR, /className="app-user-menu sidebar-menu menu-soft-surface-up/);
+});
+
+test("a custom section's menu edits it, acts on its chats, and removes it", () => {
+ const menu = APP_SIDEBAR.slice(
+ APP_SIDEBAR.indexOf('} else if (options.kind === "section") {'),
+ APP_SIDEBAR.indexOf(" return (\n // Opens out to the right"),
+ );
+ const labels = [...menu.matchAll(/t\("(shell\.[\w.]+)"\)/g)].map((match) => match[1]);
+ assert.deepEqual(labels, [
+ "shell.sections.edit",
+ "shell.sections.markAllRead",
+ "shell.selection.archiveChats",
+ "shell.sections.remove",
+ ]);
+ assert.equal((menu.match(/<DropdownMenuSeparator \/>/g) ?? []).length, 2);
+ // Only the section's own chats, and each action is off when it has nothing to do.
+ assert.match(menu, /row\.kind === "chat" \? \[row\.item\] : \[\]/);
+ assert.match(menu, /disabled=\{!threadIds\.some\(\(id\) => unreadThreadIds\.has\(id\)\)\}/);
+ assert.match(menu, /onSelect=\{\(\) => clearThreadsUnread\(threadIds\)\}/);
+ assert.match(menu, /disabled=\{chats\.length === 0\} onSelect=\{\(\) => void archiveChatItems\(chats\)\}/);
+ assert.match(menu, /icon=\{Settings02Icon\}[\s\S]*icon=\{Tick02Icon\}[\s\S]*icon=\{Archive03Icon\}[\s\S]*icon=\{Cancel01Icon\}/);
+ assert.doesNotMatch(menu, /variant="destructive"|renderSortSubmenu/);
+});
+
+test("a section drag draws itself, so the sidebar re-renders only on the drop", async () => {
+ const drag = await readSrcAsync("features/chat/hooks/use-section-drag.ts");
+ // No React state in the hook: the lifted copy, the line and the dimming are DOM, redrawn per frame.
+ assert.doesNotMatch(drag, /useState|setState/);
+ assert.match(drag, /block\.setAttribute\(SECTION_DRAGGING_ATTR, ""\);/);
+ // Drawn in the drag layer, never straight onto the body: taking a body child out while another
+ // follows it restyled the whole page on the drop.
+ assert.match(drag, /dragLayer\(\)\.append\(ghost, line\);/);
+ assert.doesNotMatch(drag, /document\.body\.append/);
+ // Lifted where the header is, so a frame before the first transform never shows it at the top.
+ assert.match(drag, /ghostTop = textRect\.top - 6;\n\s*Object\.assign\(ghost\.style, \{\n\s*top: `\$\{ghostTop\}px`,/);
+ assert.match(drag, /translate3d\(0, \$\{Math\.round\(top - ghostTop\)\}px, 0\)/);
+ assert.match(drag, /line\.style\.top = `\$\{y - 0\.75\}px`|top: `\$\{y - 0\.75\}px`/);
+ // The drag is marked on the sidebar, not the body, whose every change restyles the page.
+ assert.match(drag, /markDragging\(sidebarOf\(list\), true\);/);
+ assert.match(drag, /markDragging\(null, false\);/);
+ assert.doesNotMatch(APP_SIDEBAR, /sectionDrag\b|setSectionDrag/);
+ // As the row drag: pointer capture, edge scroll from the frame loop, and a gesture per pointer.
+ assert.match(drag, /document\.body\.setPointerCapture\(pointerId\);/);
+ assert.match(drag, /frame = requestAnimationFrame\(onFrame\);\n\s*edgeScroll\(\);\n\s*place\(\);/);
+ assert.match(drag, /if \(moved\.pointerId !== pointerId \|\| escaped\) return;/);
+ // Escape puts it down but keeps listening, so the release still cannot fold the section.
+ assert.match(drag, /escaped = true;\n\s*putDown\(\);/);
+ const css = await readSrcAsync("index.css");
+ assert.match(css, /\[data-sidebar-section\]\[data-section-dragging\] \{\n\s*opacity: 0\.4;/);
+ assert.match(css, /\.sidebar-section-drop-line \{[\s\S]*?border-top: 1\.5px solid var\(--primary\);/);
+});
+
+test("a carried section lands against the nearest gap, and only a real move draws a line", async () => {
+ const { sectionLandingAt, landingMoves } = await import("../src/features/chat/hooks/use-section-drag.ts");
+ const blocks = [
+ { key: "pinned", top: 0, bottom: 100 },
+ { key: "a", top: 100, bottom: 400 },
+ { key: "projects", top: 400, bottom: 500 },
+ ];
+ assert.deepEqual(sectionLandingAt(blocks, 40), { target: "pinned", edge: "top" });
+ assert.deepEqual(sectionLandingAt(blocks, 240), { target: "a", edge: "top" });
+ assert.deepEqual(sectionLandingAt(blocks, 260), { target: "projects", edge: "top" });
+ assert.deepEqual(sectionLandingAt(blocks, 480), { target: "projects", edge: "bottom" });
+ assert.equal(sectionLandingAt([], 10), null);
+ const drawn = ["pinned", "b", "a", "projects"];
+ // Above its own neighbour below is where it already is; anywhere else moves it.
+ assert.equal(landingMoves(drawn, "b", { target: "a", edge: "top" }), false);
+ assert.equal(landingMoves(drawn, "b", { target: "pinned", edge: "bottom" }), false);
+ assert.equal(landingMoves(drawn, "b", { target: "pinned", edge: "top" }), true);
+ assert.equal(landingMoves(drawn, "b", { target: "projects", edge: "bottom" }), true);
+});
+
+test("sidebar and account submenus open clear of their menu, first rows level", () => {
+ // Radix measures sideOffset from the trigger row, which sits inside the menu's padding.
+ assert.match(
+ APP_SIDEBAR,
+ /sideOffset: Math\.round\(SIDEBAR_MENU_PAD_X \* uiSpaceScale \+ SUBMENU_GAP_PX\),\n\s*alignOffset: -Math\.round\(SIDEBAR_MENU_PAD_Y \* uiSpaceScale \+ MENU_ROW_MARGIN_PX\),/,
+ );
+ assert.match(APP_SIDEBAR, /sideOffset: ACCOUNT_MENU_PAD_X \+ SUBMENU_GAP_PX,/);
+ assert.equal((APP_SIDEBAR.match(/\{\.\.\.sidebarSubmenuOffsets\}/g) ?? []).length, 5);
+ assert.equal((APP_SIDEBAR.match(/\{\.\.\.accountSubmenuOffsets\}/g) ?? []).length, 1);
+ // No sidebar submenu keeps a hand-set offset that would overlap its menu.
+ assert.doesNotMatch(APP_SIDEBAR, /SubContent[^>]*sideOffset=\{[0-9]+\}[^>]*sidebar-menu/);
+});
+
+test("sidebar and account menus read white on a lighter surface in dark mode", async () => {
+ const css = await readSrcAsync("index.css");
+ assert.match(
+ css,
+ /\.dark \.app-user-menu\.sidebar-menu :is\([\s\S]*?\):is\(:focus, \[data-state="open"\]\) \{\n\s*background-color: rgb\(255 255 255 \/ calc\(0\.1 \* var\(--contrast-wash-gain, 1\)\)\);\n\s*color: #fff;/,
+ );
+ // Tick rows hover as the rows beside them, and their tick sits as far in as the text.
+ assert.match(css, /\[data-slot="dropdown-menu-radio-item-indicator"\]\n\s*\) \{\n\s*@apply right-2\.5;/);
+});
+
+
+test("undoing a removed section puts it back where it was drawn", () => {
+ const start = APP_SIDEBAR.indexOf("function removeCustomSection(");
+ const body = APP_SIDEBAR.slice(start, APP_SIDEBAR.indexOf("function renderSortSubmenu", start));
+ assert.match(body, /const followers = drawnOrder\.slice\(drawnOrder\.indexOf\(section\.id\) \+ 1\);/);
+ assert.match(body, /const follower = followers\.find\(\(key\) => sectionOrder\.includes\(key\)\);/);
+ assert.match(body, /customSections: inSectionOrder\(restored, sectionOrder\),\n\s*sectionOrder,/);
+});
+
+test("the section name dialog keeps its mode while it closes", async () => {
+ const dialog = await readSrcAsync("features/chat/components/section-name-dialog.tsx");
+ assert.match(dialog, /if \(open && \(shown\.mode !== mode \|\| shown\.initialName !== initialName\)\)/);
+ assert.match(dialog, /mode=\{shown\.mode\}\n\s*initialName=\{shown\.initialName\}/);
+});
+
+// Review follow-ups: a payload can name a section after a built-in, and an older one can carry a
+// project sort that no control can change any more.
+// Row ids are any string. On a plain object an unfiled "constructor" or "toString" reads as filed
+// in what it inherits, and the row drops out of Recents and its folder without landing anywhere.
+test("a row id named like an object built-in is unfiled until it is filed", () => {
+ resetStore();
+ const ids = ["constructor", "toString", "hasOwnProperty", "__proto__"];
+ const views = () => {
+ const state = useSidebarOrganizationStore.getState();
+ return [state.sectionByChatId, state.sectionByProjectId];
+ };
+ for (const map of views()) for (const id of ids) assert.equal(map[id], undefined);
+ const store = useSidebarOrganizationStore.getState();
+ const a = store.createCustomSection("A")!;
+ store.setChatsSection(ids, a);
+ store.setProjectsSection(ids, a);
+ for (const map of views()) for (const id of ids) assert.equal(map[id], a);
+ assert.deepEqual(Object.keys(views()[0]).sort(), [...ids].sort());
+ store.setChatsSection(ids, null);
+ for (const id of ids) assert.equal(views()[0][id], undefined);
+ // Filings of these ids survive a reload, and an unfiled one reads as unfiled after one too.
+ const merged = mergePersistedOrganization(
+ JSON.parse(
+ '{"customSections":[{"id":"s","name":"S","sort":"manual"}],"sectionByChatId":{"__proto__":"s","toString":"s"},"sectionByProjectId":{}}',
+ ),
+ useSidebarOrganizationStore.getInitialState(),
+ );
+ assert.equal(merged.sectionByChatId["__proto__"], "s");
+ assert.equal(merged.sectionByChatId.toString, "s" as unknown);
+ assert.equal(merged.sectionByChatId.constructor, undefined);
+ assert.equal(merged.sectionByProjectId.hasOwnProperty, undefined);
+ // Deleting the section drops them all.
+ store.deleteCustomSection(a);
+ for (const map of views()) for (const id of ids) assert.equal(map[id], undefined);
+ resetStore();
+});
+
+// A project picked from a chat's "Move to" is where the chat is meant to show, as a drop on the
+// folder is, so a section it is filed in lets it go once the move lands.
+// A chat dropped into a folder stays on screen in its section until the move lands, so it can be
+// dropped again meanwhile. Any later drop of it, a reorder where it still is included, is the
+// newer intent, and the earlier drop's filing, slot and pin stand down.
+test("a later drop of a chat supersedes its earlier drop's pending move", () => {
+ const commit = APP_SIDEBAR.slice(
+ APP_SIDEBAR.indexOf("function commitDrop("),
+ APP_SIDEBAR.indexOf("/** The insertion line for a row, on the landing edge. */"),
+ );
+ assert.match(commit, /function commitDrop\(plan: SidebarDropPlan, dragged: SidebarDragItem\) \{/);
+ assert.match(
+ commit,
+ /const pendingMove = dragged\.kind === "chat" \? chatMovesRef\.current\.get\(dragged\.id\) : undefined;\n\s*if \(pendingMove && !effects\.moveChat\) \{\n\s*chatMovesRef\.current\.set\(dragged\.id, \{\n\s*generation: pendingMove\.generation \+ 1,\n\s*chain: pendingMove\.chain,/,
+ );
+ // Read before any drop that does not wait for a move commits, so it counts from the first.
+ assert.ok(commit.indexOf("const pendingMove") < commit.indexOf("if (!move) {"));
+ // The earlier move checks its generation before it files, slots or unpins.
+ assert.match(commit, /if \(!moved \|\| moves\.get\(item\.id\)\?\.generation !== generation\) return;/);
+});
+
+test("a chat moved into a project from its menu leaves its section, as a drop does", () => {
+ const fn = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf("async function moveChatToProjectFromMenu("));
+ assert.match(fn, /if \(!\(await moveChatToProject\(item, projectId\)\) \|\| filedSince\) return;/);
+ // Not when it was filed again while the move was in flight: that is the newer intent.
+ assert.match(fn, /filedSince \|\|= now\.sectionByChatId\[item\.id\] !== before\.sectionByChatId\[item\.id\];/);
+ // Only where a folder draws it: not pinned, and not all in one list.
+ assert.match(fn, /now\.organizeBy === "project" &&\n\s*!usePinnedChatsStore\.getState\(\)\.pinnedIds\.includes\(item\.id\)\n\s*\) \{\n\s*setChatsSection\(\[item\.id\], null\);/);
+ assert.match(fn, /\} finally \{\n\s*stopWatching\(\);/);
+ // Both ways in from the menu: an existing project, and a new one.
+ assert.match(APP_SIDEBAR, /onSelect=\{\(\) => void moveChatToProjectFromMenu\(item, project\.id\)\}/);
+ assert.match(APP_SIDEBAR, /await moveChatToProjectFromMenu\(moveTarget, project\.id\);/);
+ assert.doesNotMatch(APP_SIDEBAR, /onSelect=\{\(\) => void moveChatToProject\(item, project\.id\)\}/);
+});
+
+test("a saved section keyed like Pinned or Projects is dropped, and so are its rows' filings", () => {
+ const merged = mergePersistedOrganization(
+ {
+ customSections: [
+ { id: PROJECTS_SECTION_KEY, name: "Impostor", sort: "manual" },
+ { id: PINNED_SECTION_KEY, name: "Impostor", sort: "manual" },
+ { id: "real", name: "Real", sort: "manual" },
+ ],
+ sectionByChatId: { c1: PROJECTS_SECTION_KEY, c2: "real" },
+ sectionByProjectId: { p1: PINNED_SECTION_KEY },
+ },
+ useSidebarOrganizationStore.getInitialState(),
+ );
+ assert.deepEqual(merged.customSections.map((section) => section.id), ["real"]);
+ // The rows filed in them come back to their normal lists.
+ assert.deepEqual({ ...merged.sectionByChatId }, { c2: "real" });
+ assert.deepEqual({ ...merged.sectionByProjectId }, {});
+});
+
+test("a saved automatic project sort, no longer offered, falls back to Manual", () => {
+ for (const projectSort of ["updated", "name", "created", "manual", "bogus"]) {
+ const merged = mergePersistedOrganization(
+ { projectSort },
+ useSidebarOrganizationStore.getInitialState(),
+ );
+ assert.equal(merged.projectSort, "manual", projectSort);
+ }
+});
+
+test("a chat filed from its menu while its drop into a folder is in flight keeps that filing", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /filedSince \|\|= now\.sectionByChatId\[item\.id\] !== before\.sectionByChatId\[item\.id\];/,
+ );
+ assert.match(APP_SIDEBAR, /if \(!filedSince\) applyFiling\(\);\n\s*applyOrders\(ordersBefore, sortPicked\);/);
+});
+
+test("custom sections re-measure the bottom fade when they change the list's height", () => {
+ const deps = APP_SIDEBAR.slice(
+ APP_SIDEBAR.indexOf("// Recompute bottom-fade on mount"),
+ APP_SIDEBAR.indexOf("// Resizing changes clientHeight"),
+ );
+ for (const dep of ["visibleCustomSections.length", "collapsedSectionIds", "customSectionRowCount", "projectsSectionHidden"]) {
+ assert.ok(deps.includes(` ${dep},\n`), dep);
+ }
+});
+
+test("Alt + arrow on a section's header moves it, as it moves a row", async () => {
+ const hook = await readSrcAsync("features/chat/hooks/use-section-drag.ts");
+ assert.match(hook, /export function sectionKeyLanding\(/);
+ // The header only: its "+" and "..." keep their keys, and a row's own Alt + arrow is the row's.
+ assert.match(hook, /const header = pressed\.closest\(HEADER_SELECTOR\);/);
+ assert.match(hook, /if \(pressed\.closest\(HEADER_ACTION_SELECTOR\)\) return null;/);
+ assert.match(hook, /return neighbour \? \{ target: neighbour, edge: up \? "top" : "bottom" \} : null;/);
+ assert.match(
+ APP_SIDEBAR,
+ /onKeyDown=\{\(event\) => \{\n\s*const landing = sectionKeyLanding\(event, key\);\n\s*if \(!landing\) return;\n\s*event\.preventDefault\(\);\n\s*moveSection\(key, landing\.target, landing\.edge\);/,
+ );
+});
+
+test("a pinned row can be filed back into the section it kept while pinned", () => {
+ // Pinned draws it, so its retained section is not where it is; filing there unpins it.
+ assert.match(APP_SIDEBAR, /current: pinnedIdSet\.has\(item\.id\) \? null : sectionByChatId\[item\.id\] \?\? null,/);
+ assert.match(
+ APP_SIDEBAR,
+ /current: pinnedProjectIdSet\.has\(project\.id\) \? null : sectionByProjectId\[project\.id\] \?\? null,/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /new Set\(ids\.map\(\(id\) => \(pinned\.has\(id\) \? null : assignments\[id\] \?\? null\)\)\)/,
+ );
+});
+
+test("a hidden Projects section's chats are not walked or selected", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /folderChatItems\(projectsSectionRendered && projectsOpen, visibleProjectRecords\)/,
+ );
+});
+
+test("signing in as another account drops the previous account's sections", async () => {
+ const { transitionBrowserAccount, BROWSER_ACCOUNT_KEY } = await import(
+ "../src/lib/account-transition.ts"
+ );
+ const memory = (): Storage => {
+ const map = new Map<string, string>();
+ return {
+ get length() {
+ return map.size;
+ },
+ key: (index: number) => [...map.keys()][index] ?? null,
+ getItem: (key: string) => map.get(key) ?? null,
+ setItem: (key: string, value: string) => void map.set(key, value),
+ removeItem: (key: string) => void map.delete(key),
+ clear: () => map.clear(),
+ };
+ };
+ const localStorage = memory();
+ localStorage.setItem(BROWSER_ACCOUNT_KEY, "account:a1:alice");
+ localStorage.setItem(
+ SIDEBAR_ORGANIZATION_STORAGE_KEY,
+ JSON.stringify({ state: { customSections: [{ id: "s1", name: "Alice's", sort: "manual" }] } }),
+ );
+ let reloadedTo = "";
+ const indexedDB = {
+ deleteDatabase() {
+ const request: { onsuccess?: () => void } = {};
+ queueMicrotask(() => request.onsuccess?.());
+ return request;
+ },
+ } as unknown as IDBFactory;
+ const changed = await transitionBrowserAccount({ username: "bob", accountId: "b2" }, "/chat", () => {}, {
+ localStorage,
+ sessionStorage: memory(),
+ indexedDB,
+ location: { replace: (url: string) => void (reloadedTo = url) } as Location,
+ });
+ assert.equal(changed, true);
+ assert.equal(localStorage.getItem(SIDEBAR_ORGANIZATION_STORAGE_KEY), null);
+ // And the page reloads, so the store in memory goes with it.
+ assert.equal(reloadedTo, "/chat");
+});
+
+test("a row's section menu offers Remove from section only when it is in one", async () => {
+ // Shown greyed out on a row in no section, it read as a label ("No section"), not an action.
+ assert.match(
+ APP_SIDEBAR,
+ /\{config\.anyFiled && \(\n\s*<P\.Item onSelect=\{\(\) => fileSectionTarget\(target, null\)\}>/,
+ );
+ assert.doesNotMatch(APP_SIDEBAR, /disabled=\{!config\.anyFiled\}/);
+ // A pinned row is drawn in Pinned, so it has nothing to remove.
+ assert.match(APP_SIDEBAR, /anyFiled: !pinnedIdSet\.has\(item\.id\) && Boolean\(sectionByChatId\[item\.id\]\),/);
+ assert.match(
+ APP_SIDEBAR,
+ /anyFiled: !pinnedProjectIdSet\.has\(project\.id\) && Boolean\(sectionByProjectId\[project\.id\]\),/,
+ );
+ assert.match(APP_SIDEBAR, /anyFiled: ids\.some\(\(id\) => !pinned\.has\(id\) && Boolean\(assignments\[id\]\)\),/);
+ for (const locale of ["en", "de", "ja"]) {
+ const source = await readSrcAsync(`i18n/locales/${locale}.ts`);
+ assert.match(source, /removeFromSection: "/, locale);
+ assert.doesNotMatch(source, /noSection:/, locale);
+ }
+});
diff --git a/studio/frontend/tests/sidebar-organization-store.test.ts b/studio/frontend/tests/sidebar-organization-store.test.ts
index 6139609acb7..b77ee4a0963 100644
--- a/studio/frontend/tests/sidebar-organization-store.test.ts
+++ b/studio/frontend/tests/sidebar-organization-store.test.ts
@@ -248,12 +248,12 @@ test("each list keeps its own manual order", () => {
assert.deepEqual(saved["project:p1"], ["b", "a"]);
});
-test("the sidebar starts grouped by project, sorted by priority", () => {
+test("the sidebar starts grouped by project, sorted by last updated", () => {
// 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");
+ assert.equal(fresh.chatSort, "updated");
// 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");
@@ -261,22 +261,22 @@ test("the sidebar starts grouped by project, sorted by priority", () => {
test("Pinned sorts independently of the chat lists", () => {
const store = useSidebarOrganizationStore.getState();
- store.setChatSort("updated");
- store.setPinnedSort("priority");
+ store.setChatSort("manual");
+ store.setPinnedSort("updated");
const state = useSidebarOrganizationStore.getState();
- assert.equal(state.chatSort, "updated");
- assert.equal(state.pinnedSort, "priority");
+ assert.equal(state.chatSort, "manual");
+ assert.equal(state.pinnedSort, "updated");
});
test("Projects sort on their own, keeping the drag order by default", () => {
assert.equal(useSidebarOrganizationStore.getInitialState().projectSort, "manual");
const store = useSidebarOrganizationStore.getState();
- store.setChatSort("priority");
+ store.setChatSort("updated");
store.setProjectSort("name");
const state = useSidebarOrganizationStore.getState();
assert.equal(state.projectSort, "name");
- assert.equal(state.chatSort, "priority");
+ assert.equal(state.chatSort, "updated");
store.setProjectSort("manual");
});
diff --git a/studio/frontend/tests/sidebar-projects-nav-auto.test.ts b/studio/frontend/tests/sidebar-projects-nav-auto.test.ts
index d152592b99d..1e9afc08604 100644
--- a/studio/frontend/tests/sidebar-projects-nav-auto.test.ts
+++ b/studio/frontend/tests/sidebar-projects-nav-auto.test.ts
@@ -114,10 +114,10 @@ test("the rail keeps the Projects row, since the section is hidden there", async
/const projectsSectionShowing =\n\s*projectsSectionConfigured && \(isMobile \|\| sidebarState !== "collapsed"\);/,
);
// The section itself still mounts on the rail, as it did before, and CSS hides it.
- assert.match(sidebar, /\{projectsSectionRendered && \(/);
+ assert.match(sidebar, /if \(!projectsSectionRendered\) return null;/);
assert.match(
sidebar,
- /\{projectsSectionRendered && \(\n[\s\S]{0,400}?group-data-\[collapsible=icon\]:hidden/,
+ /if \(!projectsSectionRendered\) return null;\n[\s\S]{0,400}?group-data-\[collapsible=icon\]:hidden/,
);
});
@@ -173,7 +173,7 @@ test("a route that borrows the section does not bring the row back", async () =>
const sidebar = await readSrcAsync("components/app-sidebar.tsx");
assert.match(
sidebar,
- /const projectsSectionConfigured =\n\s*organizeBy === "project" && projects\.length > 0;/,
+ /const projectsSectionConfigured =\n\s*organizeBy === "project" &&\n\s*!projectsSectionHidden &&\n\s*\(projects\.length > 0 \|\| projectsLoaded\);/,
);
// The section itself still stands down on those routes; only the row stopped following it.
assert.match(
diff --git a/studio/frontend/tests/sidebar-row-actions.test.ts b/studio/frontend/tests/sidebar-row-actions.test.ts
index 53338a6dfbf..07a72d6f853 100644
--- a/studio/frontend/tests/sidebar-row-actions.test.ts
+++ b/studio/frontend/tests/sidebar-row-actions.test.ts
@@ -197,12 +197,12 @@ test("the pin item says Pin, not what it is pinning", () => {
test("a section's chevron appears on hovering anywhere in it", () => {
assert.equal(
(APP_SIDEBAR.match(/group\/sb-section/g) ?? []).length,
- 4,
+ 5,
"a collapsible section is not its own hover group",
);
assert.equal(
(APP_SIDEBAR.match(/group-hover\/sb-section:opacity-100/g) ?? []).length,
- 4,
+ 5,
"a section chevron still waits for its header to be hovered",
);
// Hovering the header itself still counts, and so does reaching it by keyboard.
diff --git a/studio/frontend/tests/sidebar-row-drag.test.ts b/studio/frontend/tests/sidebar-row-drag.test.ts
index 72730ea0d77..2985c8b8c50 100644
--- a/studio/frontend/tests/sidebar-row-drag.test.ts
+++ b/studio/frontend/tests/sidebar-row-drag.test.ts
@@ -54,6 +54,7 @@ function plannedDrop(
const APP_SIDEBAR = await readSrcAsync("components/app-sidebar.tsx");
const HOOK = await readSrcAsync("features/chat/hooks/use-sidebar-drag.ts");
const EN = await readSrcAsync("i18n/locales/en.ts");
+const CSS = await readSrcAsync("index.css");
// Two folders, "work" pinned and "home" not; chats c1 and c2 in work, c3 in home, r1 and r2 in
// Recents, and p1 pinned from Recents. Pinned is one list: the folder, then the chat.
@@ -62,17 +63,21 @@ function context(
): SidebarDropContext {
return {
organizeBy: "project",
- chatSort: "priority",
+ chatSort: "updated",
pinnedSort: "manual",
projectSort: "manual",
pinnedChatIds: new Set(["p1"]),
pinnedProjectIds: new Set(["work"]),
+ sectionByChatId: {},
+ sectionByProjectId: {},
+ sectionSort: () => "manual",
orders: {
pinned: ["work", "p1"],
projects: ["home", "misc"],
recents: ["r1", "r2"],
projectChats: (projectId) =>
({ work: ["c1", "c2"], home: ["c3"], misc: [] })[projectId] ?? [],
+ sections: () => [],
},
...overrides,
};
@@ -200,7 +205,9 @@ test("a folder reorder or unpin switches a sorted Projects list to Manual", () =
// A pinned project chat shows in Pinned only; its own folder unpins it.
test("a pinned chat is listed once and drops back into its folder unpinned", () => {
assert.ok(
- APP_SIDEBAR.includes("items.filter((item) => !pinnedIdSet.has(item.id))"),
+ APP_SIDEBAR.includes(
+ "(item) => !pinnedIdSet.has(item.id) && !sectionByChatId[item.id],",
+ ),
"a folder still lists its pinned chats",
);
const ctx = context({
@@ -296,6 +303,7 @@ test("a chat dropped on a folder, its chats or its empty line is filed there", (
line: {
rowKey: rowKey(zone.row.scope, zone.row.id),
edge: zone.edge ?? "top",
+ folderId: zone.folderId,
},
}
: { ring: folderRingKey(zone.folderId!) },
@@ -332,7 +340,7 @@ test("a chat filed into a folder on Manual order lands in the slot it dropped on
),
);
assert.deepEqual(plan.cue, {
- line: { rowKey: rowKey(projectOrderScope("work"), "c2"), edge: "top" },
+ line: { rowKey: rowKey(projectOrderScope("work"), "c2"), edge: "top", folderId: "work" },
});
// The slot travels with the snapshot, so a move that lands late can re-aim it.
assert.deepEqual(plan.effects.orders, [
@@ -729,8 +737,10 @@ test("an empty Projects section still shows where a folder would land", () => {
// empty section draws a row. A zero-height box is skipped by elementsFromPoint.
assert.match(
APP_SIDEBAR,
- /\{visibleProjectRecords\.length === 0 && \(\n\s*<SidebarMenuItem>\n\s*<p className="[^"]*text-nav-fg-muted">\n\s*\{t\("shell\.navigation\.allProjectsPinned"\)\}/,
+ /\{visibleProjectRecords\.length === 0 && \(\n\s*<SidebarMenuItem>\n\s*<p className="[^"]*text-nav-fg-muted">\n\s*\{t\(\n\s*projects\.length === 0\n\s*\? "shell\.navigation\.noProjects"\n\s*: projects\.some\(\(project\) => sectionByProjectId\[project\.id\]\)\n\s*\? "shell\.navigation\.allProjectsFiled"\n\s*: "shell\.navigation\.allProjectsPinned",/,
);
+ // With no projects at all the section stays, once they have loaded, and says so.
+ assert.match(EN, /noProjects: "No projects",/);
assert.match(EN, /allProjectsPinned: "All projects pinned",/);
});
@@ -856,7 +866,9 @@ test("every row and section is wired to the planner", () => {
'scope: RECENTS_ORDER_SCOPE,\n ids: recentRowIds,\n section: "recents",',
'orderedIds: projectRowIds,\n section: "projects",',
]) {
- assert.ok(APP_SIDEBAR.includes(wiring), `missing ${wiring}`);
+ // Whitespace-free, since the sections are drawn by functions at their own indent.
+ const flat = (text: string) => text.replace(/\s+/g, "");
+ assert.ok(flat(APP_SIDEBAR).includes(flat(wiring)), `missing ${wiring}`);
}
});
@@ -1064,11 +1076,11 @@ test("a drop that moves writes its slot and takes the pin off after the move", (
);
assert.match(
APP_SIDEBAR,
- /const move = effects\.moveChat;\n\s*if \(!move\) \{\n(?:\s*\/\/[^\n]*\n)*\s*applyOrders\(\);\n\s*return;\n\s*\}/,
+ /const move = effects\.moveChat;\n\s*if \(!move\) \{\n(?:\s*\/\/[^\n]*\n)*\s*applyFiling\(\);\n\s*applyOrders\(\);\n\s*return;\n\s*\}/,
);
assert.match(
APP_SIDEBAR,
- /\.then\(\(\) => moveChatToProject\(item, move\.projectId\)\)\n\s*\.then\(\(moved\) => \{\n\s*if \(!moved \|\| moves\.get\(item\.id\)\?\.generation !== generation\) return;\n(?:\s*\/\/[^\n]*\n)*\s*applyOrders\(ordersBefore, sortPicked\);\n\s*if \(unpinAfter\) usePinnedChatsStore\.getState\(\)\.unpin\(unpinAfter\);/,
+ /\.then\(\(\) => moveChatToProject\(item, move\.projectId\)\)\n\s*\.then\(\(moved\) => \{\n\s*if \(!moved \|\| moves\.get\(item\.id\)\?\.generation !== generation\) return;\n(?:\s*\/\/[^\n]*\n)*\s*if \(!filedSince\) applyFiling\(\);\n\s*applyOrders\(ordersBefore, sortPicked\);\n\s*if \(unpinAfter\) usePinnedChatsStore\.getState\(\)\.unpin\(unpinAfter\);/,
);
// And nothing else in commitDrop writes an order on its own.
const commit = APP_SIDEBAR.slice(
@@ -1110,13 +1122,18 @@ test("a sort picked while a move is in flight is not overwritten", () => {
// for it would leave the slot written into a list still sorted, undoing the drop.
assert.match(
commit,
- /const stopWatchingSort = switching\n\s*\? useSidebarOrganizationStore\.subscribe\(\(now, before\) => \{\n\s*sortPicked \|\|=\n\s*switching === "pinned"\n\s*\? now\.pinnedSort !== before\.pinnedSort\n\s*: now\.chatSort !== before\.chatSort;\n\s*\}\)\n\s*: \(\) => \{\};/,
+ /const stopWatchingSort = useSidebarOrganizationStore\.subscribe\(\(now, before\) => \{\n\s*if \(switching\) \{\n\s*sortPicked \|\|=\n\s*switchedListSort\(now, switching\) !== switchedListSort\(before, switching\);\n\s*\}/,
+ );
+ // Each list reads its own sort, custom sections included.
+ assert.match(
+ APP_SIDEBAR,
+ /if \(list === "pinned"\) return state\.pinnedSort;\n\s*if \(list === "projects"\) return state\.projectSort;\n\s*const sectionId = customSectionIdOf\(list\);/,
);
assert.match(commit, /const switching = effects\.switchSort;/);
// Only the path that waits. Nothing can come between a drop and a switch applied in the turn.
assert.match(
commit,
- /if \(!move\) \{\n(?:\s*\/\/[^\n]*\n)*\s*applyOrders\(\);\n\s*return;\n\s*\}/,
+ /if \(!move\) \{\n(?:\s*\/\/[^\n]*\n)*\s*applyFiling\(\);\n\s*applyOrders\(\);\n\s*return;\n\s*\}/,
);
// Read before applyOrders, whose own setChatSort would otherwise trip the watch it reads.
assert.match(commit, /applyOrders\(ordersBefore, sortPicked\);/);
@@ -1214,8 +1231,8 @@ test("a chat can be dropped after a folder that ends the Pinned list", () => {
// Part of the layout, not summoned by the drag: a row mounting at drag start shifts every
// section below it after the pointer was sampled, and the cue and the drop then disagree.
const pinnedMenu = APP_SIDEBAR.slice(
- APP_SIDEBAR.indexOf('{/* Pinned: folders and chats in one list'),
- APP_SIDEBAR.indexOf("{/* One folder per unpinned project."),
+ APP_SIDEBAR.indexOf("function renderPinnedSection(): ReactNode {"),
+ APP_SIDEBAR.indexOf("function renderCustomSection("),
);
assert.ok(pinnedMenu.length > 0, "the Pinned section moved");
assert.match(
@@ -1246,7 +1263,7 @@ test("a chat can be dropped after a folder that ends the Pinned list", () => {
// springs open under it, and when the sidebar re-renders, and only the frame loop is there to
// see it. The release hit-tests the layout as it is, so the cue has to as well.
test("the edge keeps scrolling while the pointer rests on it", () => {
- assert.match(HOOK, /const onFrame = \(\) => \{[^]*?frame = requestAnimationFrame\(onFrame\);\n\s*edgeScroll\(at\.y\);\n\s*track\(at\.x, at\.y\);/);
+ assert.match(HOOK, /const onFrame = \(\) => \{[^]*?frame = requestAnimationFrame\(onFrame\);\n\s*edgeScroll\(at\.y\);\n\s*if \(ghost\.current\) placeGhost\(ghost\.current, at\.y\);\n\s*track\(at\.x, at\.y\);/);
// Unconditionally: a re-aim only on the frames that scrolled leaves every other cause stale.
assert.ok(!/if \(edgeScroll\(/.test(HOOK));
// Started with the drag and cancelled with it, and it stops itself if the drag is gone.
@@ -1257,6 +1274,48 @@ test("the edge keeps scrolling while the pointer rests on it", () => {
assert.ok(!/const track = useCallback\(\n\s*\(x: number, y: number\) => \{\n\s*(auto|edge)Scroll/.test(HOOK));
});
+// A carried chat or folder lifts as a copy under the pointer, as a section header does, while the
+// row it came from dims. The copy is DOM the hook draws and moves itself: no render per move.
+test("a carried row lifts a copy that follows the pointer", () => {
+ // Lifted when the press becomes a drag, from the row's face, and kept inside its list.
+ assert.match(HOOK, /started = true;\n\s*scroller\.current = scrollerOf\(row\);\n\s*ghost\.current = liftRow\(/);
+ assert.match(HOOK, /const face = row\.querySelector<HTMLElement>\(ROW_FACE_SELECTOR\);/);
+ assert.match(HOOK, /Math\.min\(Math\.max\(y - ghost\.grab, view\.top\), view\.bottom - height\)/);
+ // Lifted where the row is and moved from there, so a frame before the first transform shows it
+ // over the row, not at the top of the window.
+ assert.match(HOOK, /top: `\$\{rect\.top\}px`,/);
+ assert.match(HOOK, /translate3d\(0, \$\{Math\.round\(top - ghost\.top\)\}px, 0\)/);
+ // In the drag layer, which is never taken off the body; the copy and its cues come and go in it.
+ assert.match(HOOK, /dragLayer\(\)\.append\(element\);/);
+ assert.match(HOOK, /dragLayer\(\)\.append\(overlay\);/);
+ assert.doesNotMatch(HOOK, /document\.body\.append\((element|overlay)\)/);
+ assert.match(CSS, /#pointer-drag-layer \{\n\tposition: fixed;[\s\S]*?z-index: 60;\n\tpointer-events: none;/);
+ // A picture only: no drop zone, row key, id, test id or open-chat mark rides along, so no hit
+ // test, lookup or test finds it, and it takes no pointer.
+ for (const attr of ["DROP_ZONE_ATTR", "ROW_KEY_ATTR", '"id"', '"data-active"', '"data-testid"', '"data-thread-id"']) {
+ assert.match(HOOK, new RegExp(`GHOST_DROPPED_ATTRS = \\[[^\\]]*${attr.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
+ }
+ assert.match(CSS, /\.sidebar-row-ghost \* \{\n\s*pointer-events: none;/);
+ // Every way a drag ends takes it down: clear() is the one exit.
+ assert.match(HOOK, /const clear = useCallback\(\(\) => \{[^]*?ghost\.current\?\.element\.remove\(\);\n\s*for \(const overlay of ghost\.current\?\.cues \?\? \[\]\) overlay\.remove\(\);\n\s*ghost\.current = null;/);
+ // The row it came from dims as a section does, bare of its pressed look.
+ assert.equal(APP_SIDEBAR.match(/draggingRow\?\.id === (item|project)\.id && "opacity-40"/g)?.length, 2);
+ assert.match(CSS, /\.pointer-dragging \[data-sidebar="menu-button"\]:active \{\n\s*background-color: transparent;/);
+ // Marked on the sidebar, never the body: a body class restyles every element on the page.
+ assert.match(HOOK, /markDragging\(sidebarOf\(row\), true\);/);
+ assert.doesNotMatch(HOOK, /document\.body\.classList/);
+ assert.match(CSS, /\.pointer-dragging,\n\.pointer-dragging \* \{/);
+});
+
+test("a dropped row slides from where it was let go, unless motion is reduced", () => {
+ assert.match(HOOK, /const from = ghost\.current\?\.element\.getBoundingClientRect\(\)\.top \?\? null;\n\s*clear\(\);/);
+ assert.match(HOOK, /onDrop\(aimed\.outcome, dragged\);\n\s*if \(from !== null && !optionsRef\.current\.reducedMotion\?\.\(\)\) settleRow\(dragged, from\);/);
+ assert.match(APP_SIDEBAR, /onDrop: \(plan, dragged\) => commitDrop\(plan, dragged\),\n\s*reducedMotion: prefersReducedMotion,/);
+ // A folder carries its open chats: the spots naming it slide with its row, each once.
+ assert.match(HOOK, /zone\.folderId === item\.id &&/);
+ assert.match(HOOK, /!all\.some\(\(other\) => other !== element && other\.contains\(element\)\)/);
+});
+
// The window hears every pointer, not just the one that pressed the row. Without this a finger
// could drive, and drop, a drag the mouse started, which is exactly what touch is kept out of.
test("only the pointer that started the drag drives it", () => {
@@ -1320,7 +1379,7 @@ test("a chat can be dropped at the bottom of a pinned project", () => {
),
);
assert.deepEqual(arriving.cue, {
- line: { rowKey: rowKey(workScope, "p2"), edge: "bottom" },
+ line: { rowKey: rowKey(workScope, "p2"), edge: "bottom", folderId: "work" },
});
assert.equal(arriving.effects.switchSort, "chats");
assert.deepEqual(arriving.effects.orders[0]?.ids, ["p1", "p2", "r1"]);
@@ -1346,7 +1405,7 @@ test("a chat can be dropped at the bottom of a pinned project", () => {
);
assert.deepEqual(tail.action, { kind: "reorder" });
assert.deepEqual(tail.cue, {
- line: { rowKey: rowKey(workScope, "p2"), edge: "bottom" },
+ line: { rowKey: rowKey(workScope, "p2"), edge: "bottom", folderId: "work" },
});
assert.deepEqual(tail.effects.orders[0]?.ids, ["p2", "p1", "p3"]);
@@ -1448,3 +1507,91 @@ test("a drop into a folder lights the folder, even while a line shows the slot",
assert.equal(litRingKey(null), null);
assert.match(HOOK, /\(key: string\): boolean => litRingKey\(plan\) === key/);
});
+
+// The end of Recents: its strip past the last row, and the empty sidebar below it.
+test("a Recents chat dropped past the last row moves to the end", () => {
+ const tail: SidebarDropZone = {
+ section: "recents",
+ blockEnd: { scope: SIDEBAR_TAIL_SCOPE, id: "recents" },
+ };
+ const plan = plannedDrop(
+ planSidebarDrop(chat("r1", "recents", RECENTS_ORDER_SCOPE, null), tail, "bottom", context()),
+ );
+ assert.deepEqual(plan.effects.orders, [{ scope: RECENTS_ORDER_SCOPE, ids: ["r2", "r1"] }]);
+ assert.deepEqual(plan.cue, { line: { rowKey: rowKey(RECENTS_ORDER_SCOPE, "r2"), edge: "bottom" } });
+ // Already last: nothing to do, and the section does not answer instead.
+ assert.equal(
+ planSidebarDrop(chat("r2", "recents", RECENTS_ORDER_SCOPE, null), tail, "bottom", context()),
+ STAY,
+ );
+ // A chat from elsewhere lands last too, as it does on the section.
+ const pinned = plannedDrop(
+ planSidebarDrop(chat("p1", "pinned", PINNED_ORDER_SCOPE, null), tail, "bottom", context()),
+ );
+ assert.deepEqual(pinned.effects.orders.at(-1)?.ids.at(-1), "p1");
+});
+
+test("Recents draws an end strip, and the empty sidebar below it aims there", () => {
+ assert.match(
+ APP_SIDEBAR,
+ /dropCueClass\(SIDEBAR_TAIL_SCOPE, "recents"\),\n\s*\)\}\n\s*\{\.\.\.dnd\.dropZoneProps\(\{\n\s*section: "recents",\n\s*blockEnd: \{ scope: SIDEBAR_TAIL_SCOPE, id: "recents" \},/,
+ );
+ assert.match(HOOK, /const past = under\.length === 0 \? zonePastRecents\(x, y, scroller\.current\) : null;/);
+ // Only below the strip and inside the list, not over the account row under it.
+ assert.match(HOOK, /y < rect\.bottom \|\| x < rect\.left \|\| x > rect\.right\) return null;/);
+ assert.match(HOOK, /if \(list && y > list\.getBoundingClientRect\(\)\.bottom\) return null;/);
+});
+
+test("the drop cue is drawn again above the carried row's copy", () => {
+ // Every cue carries the marker the overlay looks for.
+ for (const name of ["DROP_CUE_BASE", "DROP_INTO_CUE", "DROP_INTO_ROW_CUE"]) {
+ assert.match(APP_SIDEBAR, new RegExp(`const ${name} = \`\\$\\{DROP_CUE_CLASS\\} `), name);
+ }
+ // Painted each frame after the plan is tracked, and removed with the copy.
+ assert.match(HOOK, /track\(at\.x, at\.y\);\n\s*if \(ghost\.current\) placeCue\(ghost\.current\);/);
+ assert.match(HOOK, /for \(const overlay of ghost\.current\?\.cues \?\? \[\]\) overlay\.remove\(\);/);
+ // Every cue on screen, the line and the folder it lands in both.
+ assert.match(HOOK, /for \(const cue of document\.querySelectorAll<HTMLElement>\(`\.\$\{DROP_CUE_CLASS\}`\)\)/);
+ // Its border only: the tint under the copy would double.
+ assert.doesNotMatch(HOOK.slice(HOOK.indexOf("function placeCue"), HOOK.indexOf("function zoneOf")), /background/);
+ assert.match(CSS, /\.sidebar-drop-cue-overlay \{\n\tposition: fixed;[\s\S]*?z-index: 61;[\s\S]*?pointer-events: none;/);
+});
+
+// Under a folder's last chat, a line can mean "into the folder, last" or "below the folder, in
+// its list". They sit in the same place, so the cue says which: a line inside the folder names
+// it, which indents the line to its chats and lights the folder; one below it does neither.
+test("a line under a folder's last chat says whether the row lands in the folder or below it", () => {
+ const workScope = projectOrderScope("work");
+ const lastChat: SidebarDropZone = {
+ ...chatRow("pinned", workScope, "c2", "work", { index: 1, count: 2 }),
+ blockEnd: { scope: workScope, id: "c2" },
+ };
+ // A chat lands in the folder, after its last chat.
+ const into = plannedDrop(
+ planSidebarDrop(chat("r1", "recents", RECENTS_ORDER_SCOPE, null), lastChat, "bottom", context()),
+ );
+ assert.deepEqual(into.cue, { line: { rowKey: rowKey(workScope, "c2"), edge: "bottom", folderId: "work" } });
+ assert.equal(litRingKey(into), folderRingKey("work"));
+ // A folder lands below it, in Pinned: the same spot, but nothing names or lights the folder.
+ const below = plannedDrop(
+ planSidebarDrop(folder("home", "projects", PROJECT_ORDER_SCOPE), lastChat, "bottom", context()),
+ );
+ assert.deepEqual(below.cue, { line: { rowKey: rowKey(workScope, "c2"), edge: "bottom" } });
+ assert.equal(litRingKey(below), null);
+ // A reorder among a folder's own chats is inside it too.
+ const within = plannedDrop(
+ planSidebarDrop(
+ chat("c1", "projects", projectOrderScope("work"), "work"),
+ lastChat,
+ "bottom",
+ context({ chatSort: "manual" }),
+ ),
+ );
+ assert.equal(litRingKey(within), folderRingKey("work"));
+ // The painted line: indented to the folder's chats inside it, full width below it.
+ assert.match(HOOK, /return key === rowKey\(scope, id\) \? \{ edge, inFolder: folderId !== undefined \} : undefined;/);
+ assert.match(APP_SIDEBAR, /const DROP_CUE_IN_FOLDER = "before:left-\[calc\(39px\*var\(--ui-space-scale,1\)\)\]";/);
+ assert.match(APP_SIDEBAR, /cue\.inFolder && DROP_CUE_IN_FOLDER,/);
+ // The folder's chats start there too, so the line lines up with their names.
+ assert.match(APP_SIDEBAR, /variant === "project" \? "pl-\[calc\(39px\*var\(--ui-space-scale,1\)\)\]" : "pl-3"/);
+});
diff --git a/studio/frontend/tests/sidebar-row-menu-and-pinned-folders.test.ts b/studio/frontend/tests/sidebar-row-menu-and-pinned-folders.test.ts
index ada2d2323bd..daccefdc3e0 100644
--- a/studio/frontend/tests/sidebar-row-menu-and-pinned-folders.test.ts
+++ b/studio/frontend/tests/sidebar-row-menu-and-pinned-folders.test.ts
@@ -99,31 +99,61 @@ test("an empty open folder says it is empty", () => {
assert.match(APP_SIDEBAR, /if \(chats\.length === 0\) rows \+= 1;/);
});
-// The submenu holds actions and destinations. The rule separates them, actions above.
-test("the Project submenu puts its actions above the destinations", () => {
+// A chat's "Move to" holds projects and sections, each its own group under a heading: its New
+// first, then the destinations, then its Remove last and only where there is one to leave.
+test("a chat's Move to submenu groups projects and sections, New first and Remove last", () => {
const sub = APP_SIDEBAR.slice(
- APP_SIDEBAR.indexOf("<span>Project</span>"),
+ APP_SIDEBAR.indexOf("{/* Projects and sections in one place"),
APP_SIDEBAR.indexOf("<span>Export</span>"),
);
- assert.ok(sub.length > 0, "the Project submenu moved");
- const newProject = sub.indexOf("<span>New project</span>");
- const sources = sub.indexOf("<span>Project sources</span>");
- const rule = sub.indexOf("<P.Separator />");
- const recents = sub.indexOf("<span>Recents</span>");
- for (const [name, at] of Object.entries({
- newProject,
- sources,
- rule,
- recents,
- })) {
- assert.notEqual(at, -1, `${name} is gone from the Project submenu`);
+ assert.ok(sub.length > 0, "the Move to submenu moved");
+ const at = {
+ trigger: sub.indexOf('<span>{t("shell.sections.moveTo")}</span>'),
+ projects: sub.indexOf('<P.Label>{t("shell.navigation.projects")}</P.Label>'),
+ newProject: sub.indexOf("<span>New project</span>"),
+ destinations: sub.indexOf("{projects.filter((project) => project.id !== item.projectId).map((project) => ("),
+ removeProject: sub.indexOf('t("shell.sections.removeFromProject")'),
+ rule: sub.indexOf("<P.Separator />"),
+ sections: sub.indexOf("{renderSectionItems(P, {"),
+ };
+ for (const [name, index] of Object.entries(at)) {
+ assert.notEqual(index, -1, `${name} is gone from the Move to submenu`);
}
- assert.ok(newProject < sources, "Project sources is not under New project");
- assert.ok(sources < rule, "Project sources fell below the rule");
- assert.ok(rule < recents, "the destinations are not under the rule");
- // The old wording is gone.
- assert.ok(!APP_SIDEBAR.includes("<span>Move to project</span>"));
- assert.ok(!APP_SIDEBAR.includes("<span>Save to project sources</span>"));
+ const order = Object.values(at);
+ assert.deepEqual([...order].sort((a, b) => a - b), order, "the Move to submenu is out of order");
+ // Remove from project only where there is one to leave.
+ assert.match(sub, /\{item\.projectId && \(\n\s*<P\.Item onSelect=\{\(\) => void moveChatToProject\(item, null\)\}>/);
+ // New project and New section share one icon.
+ assert.match(sub, /icon=\{PlusSignIcon\}[^\n]*\n\s*<span>New project<\/span>/);
+ const items = APP_SIDEBAR.slice(
+ APP_SIDEBAR.indexOf("function renderSectionItems("),
+ APP_SIDEBAR.indexOf('/** "Move to" for rows that only sections take'),
+ );
+ assert.match(items, /icon=\{PlusSignIcon\}[^\n]*\n\s*<span>\{t\("shell\.sections\.newSection"\)\}<\/span>/);
+ // Sections run New section, the sections, then Remove from section, only where there is one.
+ const newSection = items.indexOf('t("shell.sections.newSection")');
+ const list = items.indexOf("{destinations.map((section) => (");
+ // The project or section the row is already in is left out, not offered greyed out.
+ assert.match(items, /const destinations = customSections\.filter\(\(section\) => section\.id !== config\.current\);/);
+ assert.doesNotMatch(APP_SIDEBAR, /disabled=\{config\.current === section\.id\}|disabled=\{item\.projectId === project\.id\}/);
+ const remove = items.indexOf("{config.anyFiled && (");
+ assert.ok(newSection < list && list < remove, "the Sections group is out of order");
+ // No Project sources, no separate Project or Section submenus, no ellipsis on New section.
+ assert.ok(!APP_SIDEBAR.includes("<span>Project sources</span>"));
+ assert.ok(!APP_SIDEBAR.includes("<span>Project</span>"));
+ // A folder or a selection only goes to sections, so its submenu is "Section", as ChatGPT's is,
+ // under the icon its sections carry.
+ const sectionOnly = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf("function renderSectionSubmenu("));
+ assert.match(
+ sectionOnly,
+ /<P\.SubTrigger>\n\s*<HugeiconsIcon icon=\{LayerIcon\} strokeWidth=\{1\.75\} className="size-icon" \/>\n\s*<span>\{t\("shell\.sections\.section"\)\}<\/span>/,
+ );
+ // Edit opens a settings dialog for a folder as for a section: the cog, not a pencil.
+ assert.match(
+ APP_SIDEBAR,
+ /<P\.Item onSelect=\{\(\) => setEditingProject\(project\)\}>\n\s*<HugeiconsIcon icon=\{Settings02Icon\}/,
+ );
+ assert.ok(!APP_SIDEBAR.includes("newSectionEllipsis"));
});
// The folder menu: pin beside Project home, Edit for the dialog that owns the name, and no
@@ -186,7 +216,7 @@ test("a pinned folder is a row of Pinned, not of Projects", () => {
APP_SIDEBAR.indexOf("const sidebarProjectRecords = useMemo("),
APP_SIDEBAR.indexOf("const visibleProjectRecords"),
);
- assert.match(records, /\.filter\(\(p\) => !pinnedProjectIdSet\.has\(p\.id\)\)/);
+ assert.match(records, /\.filter\(\(p\) => !pinnedProjectIdSet\.has\(p\.id\) && !sectionByProjectId\[p\.id\]\)/);
assert.ok(
!records.includes("pinnedProjectIds"),
"the Projects list still folds the pinned folders in",
@@ -194,13 +224,13 @@ test("a pinned folder is a row of Pinned, not of Projects", () => {
// The header owns "New project", so its test counts every project, pinned or not.
assert.match(
APP_SIDEBAR,
- /const projectsSectionConfigured =\n\s*organizeBy === "project" && projects\.length > 0;/,
+ /const projectsSectionConfigured =\n\s*organizeBy === "project" &&\n\s*!projectsSectionHidden &&\n\s*\(projects\.length > 0 \|\| projectsLoaded\);/,
);
assert.match(
APP_SIDEBAR,
/const projectsSectionRendered =\n[\s\S]{0,200}?projectsSectionConfigured;/,
);
- assert.match(APP_SIDEBAR, /\{projectsSectionRendered && \(/);
+ assert.match(APP_SIDEBAR, /if \(!projectsSectionRendered\) return null;/);
});
// Moving a folder into Pinned must not undo an order the user had already dragged it into: the
@@ -255,9 +285,15 @@ test("the walk reads the rows in the order Pinned draws them", () => {
APP_SIDEBAR,
/const pinnedSectionChatItems = useMemo\(\n\s*\(\) =>\n\s*chatListsOnScreen && pinnedOpen\n\s*\? pinnedRows\.flatMap\(\(row\) =>\n\s*row\.kind === "project"\n\s*\? folderChatItems\(true, \[row\.project\]\)\n\s*: \[row\.item\],/,
);
+ // The walk reads pinnedItems then projectItems, so the two are every section above Recents in
+ // the order the user dragged them into, split at Pinned.
assert.match(
APP_SIDEBAR,
- /pinnedItems: pinnedSectionChatItems,\n\s*projectItems: sectionProjectChatItems,/,
+ /pinnedItems: upToPinnedChatItems,\n(?:\s*\/\/[^\n]*\n)*\s*projectItems: belowPinnedChatItems,/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /for \(const key of orderedSectionKeys\) \{\n\s*const items =\n\s*key === PINNED_SECTION_KEY\n\s*\? pinnedSectionChatItems\n\s*: key === PROJECTS_SECTION_KEY\n\s*\? sectionProjectChatItems/,
);
});
@@ -297,12 +333,12 @@ test("the sort options are names, with nothing written under them", () => {
APP_SIDEBAR.indexOf("const ORGANIZE_OPTIONS"),
);
assert.ok(!options.includes("hint"), "the sort options still carry captions");
- assert.match(APP_SIDEBAR, /\{CHAT_SORT_OPTIONS\.map\(\(option\) => \(/);
- const menu = APP_SIDEBAR.slice(APP_SIDEBAR.indexOf("{CHAT_SORT_OPTIONS.map("));
+ // Every sort opens as a submenu of plain names, ticked on the right like the rest of the menu.
assert.match(
- menu.slice(0, menu.indexOf("</DropdownMenuRadioGroup>")),
- /className=\{menuRadioItemClass\}\n\s*>\n\s*\{t\(option\.key\)\}/,
+ APP_SIDEBAR,
+ /\{config\.options\.map\(\(option\) => \(\n\s*<DropdownMenuRadioItem key=\{option\.value\} value=\{option\.value\}>\n\s*\{t\(option\.key\)\}\n\s*<\/DropdownMenuRadioItem>/,
);
+ assert.match(APP_SIDEBAR, /options: CHAT_SORT_OPTIONS,/);
// And the strings go with them, in every language.
for (const key of ["priorityHint", "lastUpdatedHint", "manualOrderHint"]) {
assert.ok(!APP_SIDEBAR.includes(key), `${key} is still read`);
@@ -386,3 +422,38 @@ test("a pinned folder in one list is a way in, not a second copy of its chats",
/const projectChatRowCount = useMemo\(\(\) => \{\n[^\n]*\n\s*if \(organizeBy !== "project"\) return 0;/,
);
});
+
+// "Remove from <name>", and lists that scroll: forty projects ran the submenu off the window,
+// taking the Sections group and both Removes out of reach.
+test("Move to names what a row leaves, and its lists scroll inside the window", async () => {
+ assert.match(
+ APP_SIDEBAR,
+ /leaving\n\s*\? t\("shell\.sections\.removeFrom", \{ name: leaving\.name \}\)\n\s*: t\("shell\.sections\.removeFromProject"\);/,
+ );
+ assert.match(
+ APP_SIDEBAR,
+ /\{leaving\n\s*\? t\("shell\.sections\.removeFrom", \{ name: leaving\.name \}\)\n\s*: t\("shell\.sections\.removeFromSection"\)\}/,
+ );
+ for (const locale of ["en", "de", "ja"]) {
+ const source = await readSrcAsync(`i18n/locales/${locale}.ts`);
+ assert.match(source, /removeFrom: "[^"]*\{name\}[^"]*",/, locale);
+ }
+ // Each group's list scrolls past about seven rows, with no scrollbar to eat the right padding,
+ // and the submenu as a whole stays inside the window.
+ assert.match(APP_SIDEBAR, /const MOVE_TO_LIST =\n\s*"no-scrollbar -my-0\.5 max-h-\[calc\(260px\*var\(--ui-space-scale,1\)\)\] overflow-y-auto overscroll-contain";/);
+ // Rows keep one gap across the list's ends, and Remove reads with an X like a close.
+ assert.match(APP_SIDEBAR, /const MENU_ROW_MARGIN_PX = 2;/);
+ assert.equal((APP_SIDEBAR.match(/icon=\{Cancel01Icon\}[^\n]*\n\s*<span className="truncate">/g) ?? []).length, 2);
+ assert.doesNotMatch(APP_SIDEBAR, /MinusSignCircleIcon/);
+ assert.match(APP_SIDEBAR, /const MOVE_TO_MENU =\n\s*"max-h-\[var\(--radix-dropdown-menu-content-available-height,var\(--radix-context-menu-content-available-height\)\)\] overflow-y-auto";/);
+ assert.equal((APP_SIDEBAR.match(/<div className=\{MOVE_TO_LIST\}>/g) ?? []).length, 2);
+ assert.equal((APP_SIDEBAR.match(/sidebar-menu w-52", MOVE_TO_MENU\)/g) ?? []).length, 2);
+});
+
+test("a sidebar menu heading has more room above it than below", async () => {
+ const css = await readSrcAsync("index.css");
+ assert.match(
+ css,
+ /\.unsloth-plus-menu\.sidebar-row-menu :is\(\n\s*\[data-slot="dropdown-menu-label"\],\n\s*\[data-slot="context-menu-label"\]\n\s*\) \{\n\s*@apply pl-2\.5 pr-2\.5 pt-2 pb-1 text-ui-11;/,
+ );
+});
diff --git a/studio/frontend/tests/sidebar-selection-coverage.test.ts b/studio/frontend/tests/sidebar-selection-coverage.test.ts
index 51452a30350..45a2bb4df06 100644
--- a/studio/frontend/tests/sidebar-selection-coverage.test.ts
+++ b/studio/frontend/tests/sidebar-selection-coverage.test.ts
@@ -102,8 +102,8 @@ 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 = APP_SIDEBAR;
- const archive = /async function archiveSelected\(([\s\S]*?)\n \}/.exec(source);
- assert.ok(archive, "no archiveSelected");
+ const archive = /async function archiveChatItems\(([\s\S]*?)\n \}/.exec(source);
+ assert.ok(archive, "no archiveChatItems");
assert.match(archive[1], /translate\("settings\.data\.failedToArchiveChats"\)/);
});
@@ -112,13 +112,15 @@ test("one failed archive does not abandon the rest of the batch", async () => {
// 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 = APP_SIDEBAR;
- const archive = /async function archiveSelected\(([\s\S]*?)\n \}/.exec(source);
- assert.ok(archive, "no archiveSelected");
+ // The selection and a section's "Archive chats" share one batch.
+ assert.match(source, /async function archiveSelected\(\) \{\s*const items = selectedChatItems;\s*clearSelection\(\);\s*await archiveChatItems\(items\);/);
+ const archive = /async function archiveChatItems\(([\s\S]*?)\n \}/.exec(source);
+ assert.ok(archive, "no archiveChatItems");
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");
+ assert.ok(tryAt > loopAt, "archiveChatItems 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\(\)/);