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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: give a project one home in the sidebar, and fix the row menus around it (#11370)
Michael Han63c63415a8bc
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex a95fb40e1e5..217ec0312a0 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -3450,20 +3450,23 @@ def _default_sidebar_menu() -> "list[PersonalizationSidebarMenuItem]":]+SidebarNavItemId = Literal[+ "hub",+ "projects",+ "images",+ "video",+ "audio",+ "train",+ "recipes",+ "export",+ "api",+]++class PersonalizationSidebarNavItem(BaseModel):model_config = ConfigDict(extra = "ignore")- id: Literal[- "hub",- "projects",- "images",- "video",- "audio",- "train",- "recipes",- "export",- "api",- ]+ id: SidebarNavItemIdpinned: bool = True@@ -3517,6 +3520,22 @@ class PersonalizationCustomization(BaseModel):default_factory = _default_sidebar_nav,max_length = MAX_SIDEBAR_NAV_INPUT_ITEMS,)+ # Rows still following an automatic rule rather than a choice the user made. None means the+ # record predates the field, which the client tells apart from an explicit empty list: a+ # server-filled default would reapply a rule the user had already overruled.+ sidebarNavAuto: Optional[list[SidebarNavItemId]] = Field(+ None, max_length = MAX_SIDEBAR_NAV_INPUT_ITEMS+ )++ @field_validator("sidebarNavAuto")+ @classmethod+ def _validate_sidebar_nav_auto(+ cls, value: Optional[list[str]]+ ) -> Optional[list[str]]:+ if value is None:+ return None+ seen: set[str] = set()+ return [item for item in value if not (item in seen or seen.add(item))]@field_validator("sidebarMenu")@classmethoddiff --git a/studio/backend/tests/test_personalization_settings.py b/studio/backend/tests/test_personalization_settings.pyindex cd0c4271f16..b0aa1c110d0 100644--- a/studio/backend/tests/test_personalization_settings.py+++ b/studio/backend/tests/test_personalization_settings.py@@ -257,6 +257,51 @@ def test_customization_sidebar_nav_rejects_pathological_length():PersonalizationPayload.model_validate(_sidebar_nav(huge))+def _sidebar_nav_auto(value):+ return {"appearance": {"customization": {"sidebarNavAuto": value}}}+++def test_customization_sidebar_nav_auto_defaults_to_none():+ # None, not a list: the client reads it as "this record predates the field" and works the+ # placement out from the layout. A default list would answer for a user who never chose.+ assert PersonalizationPayload().appearance.customization.sidebarNavAuto is None+++def test_customization_sidebar_nav_auto_keeps_an_explicit_empty_list():+ # The user decided the Projects row's placement themselves, so no rule applies to it. That+ # is the opposite of an absent field and has to survive the round trip.+ p = PersonalizationPayload.model_validate(_sidebar_nav_auto([]))+ assert p.appearance.customization.sidebarNavAuto == []+++def test_customization_sidebar_nav_auto_dedupes_and_validates():+ p = PersonalizationPayload.model_validate(_sidebar_nav_auto(["projects", "projects"]))+ assert p.appearance.customization.sidebarNavAuto == ["projects"]+ with pytest.raises(ValidationError):+ PersonalizationPayload.model_validate(_sidebar_nav_auto(["chats"]))+ with pytest.raises(ValidationError):+ PersonalizationPayload.model_validate(+ _sidebar_nav_auto(["hub"] * (MAX_SIDEBAR_NAV_INPUT_ITEMS + 1))+ )+++def test_personalization_put_round_trips_sidebar_nav_auto(monkeypatch):+ # Pinning Projects while the rule hides it leaves the layout at the shipped default, so the+ # choice lives in this field alone. Dropping it on the way in would undo it on the next load.+ store: dict = {}+ client = _shared_setup_1(monkeypatch, store)+ put = client.put(+ "/api/settings/personalization",+ json = _sidebar_nav_auto([]),+ )+ assert put.status_code == 200+ assert put.json()["appearance"]["customization"]["sidebarNavAuto"] == []+ stored = store[pers.PERSONALIZATION_SETTING_KEY]["appearance"]["customization"]+ assert stored["sidebarNavAuto"] == []+ body = client.get("/api/settings/personalization").json()+ assert body["appearance"]["customization"]["sidebarNavAuto"] == []++def test_customization_imported_fonts_validated():ok = PersonalizationPayload.model_validate({@@ -485,6 +530,8 @@ def test_personalization_route_roundtrip_real_shape(monkeypatch):{"id": "export", "pinned": False},{"id": "api", "pinned": False},],+ # This layout was arranged by hand, so no row is left on a rule.+ "sidebarNavAuto": [],},},}diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 1ed4ca8a1c6..69ceba73e92 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -76,7 +76,6 @@ import { useWebUpdateCheck } from "@/hooks/use-web-update-check";import {Archive03Icon,BadgeInfoIcon,- BookOpen01Icon,BubbleChatIcon,ChefHatIcon,CloudIcon,@@ -89,9 +88,11 @@ import {DownloadSquare01Icon,Edit03Icon,FolderAddIcon,+ FolderAttachmentIcon,FolderExportIcon,FolderOpenIcon,Folder01Icon,+ Folder02Icon,FlimSlateIcon,Globe02Icon,HelpCircleIcon,@@ -138,6 +139,7 @@ import {archiveChatItem,ChatSearchDialog,clearNewChatDraft,+ EditProjectDialog,deleteChatProject,deleteChatItem,listStoredChatMessages,@@ -146,7 +148,6 @@ import {allRecordedSandboxSessionIds,notifyChatHistoryUpdated,renameChatItem,- renameChatProject,useChatRuntimeStore,useChatProjects,useChatSearchStore,@@ -165,6 +166,7 @@ import {projectOrderScope,reorderIds,PINNED_ORDER_SCOPE,+ PINNED_PROJECT_ORDER_SCOPE,PROJECT_ORDER_SCOPE,RECENTS_ORDER_SCOPE,type SidebarChatSort,@@ -188,6 +190,7 @@ import {} from "@/components/assistant-ui/sandbox-reveal";import { NewProjectDialog } from "@/features/chat/components/new-project-dialog";import {+ sidebarNavRowPinned,useAppearanceCustomStore,useSettingsDialogStore,isSurfaceBackgrounded,@@ -196,7 +199,10 @@ import {type ShortcutId,useShortcut,} from "@/features/settings";-import type { SidebarNavItemId } from "@/features/settings";+import type {+ SidebarNavItemId,+ SidebarNavItemPref,+} from "@/features/settings";import { useEffectiveProfile, UserAvatar } from "@/features/profile";import { resolveNavRowState } from "@/components/nav-row-state";import { fetchDeviceType, usePlatformStore } from "@/config/env";@@ -317,6 +323,13 @@ const DROP_CUE_BASE =const DROP_CUE_TOP = `${DROP_CUE_BASE} before:-top-px`;const DROP_CUE_BOTTOM = `${DROP_CUE_BASE} before:-bottom-px`;+// The kebab shows itself while its menu is open; the quick-action beside it was hover-only, so+// it slid in over the title. The row reserves room for both, so reveal both.+const REVEAL_WITH_OPEN_MENU_PROJECT_CHAT =+ "group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:opacity-100 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:pointer-events-auto";+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.const CHAT_SORT_OPTIONS: Array<{value: SidebarChatSort;@@ -751,6 +764,9 @@ export function AppSidebar() {const sidebarNav = useAppearanceCustomStore((s) => s.customization.sidebarNav,);+ const sidebarNavAuto = useAppearanceCustomStore(+ (s) => s.customization.sidebarNavAuto,+ );const [usesCustomTitlebar] = useState(shouldUseCustomWindowTitlebar);const [usesNativeMacTitlebar] = useState(shouldUseNativeMacWindowTitlebar);// Read from the shortcuts store, not the shipped default: a rebound or cleared action must not@@ -1043,6 +1059,15 @@ export function AppSidebar() {return map;}, [allChatItems]);const organizeBy = useSidebarOrganizationStore((s) => s.organizeBy);+ const projectsSectionRendered =+ !isStudioRoute &&+ !showTrainingRecents &&+ organizeBy === "project" &&+ projects.length > 0;+ // The icon rail hides the section in CSS without unmounting it, so the nav row only stands+ // down while the section is really on screen.+ const projectsSectionShowing =+ projectsSectionRendered && (isMobile || sidebarState !== "collapsed");const chatSort = useSidebarOrganizationStore((s) => s.chatSort);const pinnedSort = useSidebarOrganizationStore((s) => s.pinnedSort);const manualOrder = useSidebarOrganizationStore((s) => s.manualOrder);@@ -1064,7 +1089,7 @@ export function AppSidebar() {const [pinnedOpen, setPinnedOpen] = useState(true);const [projectsOpen, setProjectsOpen] = useState(true);const [showAllProjects, setShowAllProjects] = useState(false);- // Pinning a project now sorts it to the top of Projects, not into its own section.+ // Pinning a project moves its folder into the Pinned section, beside the pinned chats.const pinnedProjectIds = usePinnedProjectsStore((s) => s.pinnedIds);const toggleProjectPin = usePinnedProjectsStore((s) => s.togglePin);const pinnedProjectIdSet = useMemo(@@ -1092,9 +1117,24 @@ export function AppSidebar() {list.sort((a, b) => b.updatedAt - a.updatedAt);return map;}, [allChatItems]);- // Every project gets a folder: pinned first in pin order, then by activity, then whatever the user- // dragged, which outranks both. Activity comes from the member chats, since a project's own- // updatedAt only moves when its name, instructions or archived flag are edited.+ // Pinned folders, in pin order then manual order. They render in Pinned, so they carry its scope.+ const pinnedProjectRecords = useMemo(() => {+ const byId = new Map(projects.map((p) => [p.id, p]));+ const pinned = pinnedProjectIds+ .map((id) => byId.get(id))+ .filter((p): p is ProjectRecord => Boolean(p));+ return applyManualOrder(+ pinned,+ // Until Pinned records an order of its own, the one these folders were dragged into while+ // they were rows of Projects still stands: it covers them and pin order does not.+ manualOrder[PINNED_PROJECT_ORDER_SCOPE]?.length+ ? manualOrder[PINNED_PROJECT_ORDER_SCOPE]+ : manualOrder[PROJECT_ORDER_SCOPE],+ (project) => project.id,+ );+ }, [projects, pinnedProjectIds, manualOrder]);+ // The folders Projects still owns: unpinned, by activity, then manual order. Activity comes from+ // the member chats, since a project's own updatedAt only moves when it is edited.const sidebarProjectRecords = useMemo(() => {const lastActivityAt = (project: ProjectRecord) => {let latest = project.updatedAt ?? project.createdAt;@@ -1103,25 +1143,15 @@ export function AppSidebar() {}return latest;};- const byId = new Map(projects.map((p) => [p.id, p]));- const pinned = pinnedProjectIds- .map((id) => byId.get(id))- .filter((p): p is ProjectRecord => Boolean(p));const rest = projects.filter((p) => !pinnedProjectIdSet.has(p.id)).sort((a, b) => lastActivityAt(b) - lastActivityAt(a));return applyManualOrder(- [...pinned, ...rest],+ rest,manualOrder[PROJECT_ORDER_SCOPE],(project) => project.id,);- }, [- projects,- pinnedProjectIds,- pinnedProjectIdSet,- manualOrder,- chatsByProjectId,- ]);+ }, [projects, pinnedProjectIdSet, manualOrder, chatsByProjectId]);// 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.@@ -1319,29 +1349,39 @@ export function AppSidebar() {// unread would take it over the open chat. Navigation is exempt: it moves the chat the user IS// looking at, and the sheet is closed for most of its life on a narrow window.const chatRowsOnScreen = chatListsOnScreen && (!isMobile || openMobile);- const renderedProjectChatItems = useMemo(() => {- if (!chatListsOnScreen || organizeBy !== "project" || !projectsOpen)- return [];- const out: SidebarItem[] = [];- for (const project of visibleProjectRecords) {- if (collapsedProjectIds.has(project.id)) continue;- const chats = sortedChatsByProjectId.get(project.id) ?? [];- out.push(- ...(expandedChatProjectIds.has(project.id)- ? chats- : chats.slice(0, PROJECT_CHAT_LIMIT)),- );- }- return out;- }, [- chatListsOnScreen,- organizeBy,- projectsOpen,- visibleProjectRecords,- collapsedProjectIds,- expandedChatProjectIds,- sortedChatsByProjectId,- ]);+ // The chats a section's folders show, in row order. A pinned folder leaves with Pinned's+ // disclosure, not the Projects one, so each section collects its own.+ const folderChatItems = useCallback(+ (open: boolean, records: ProjectRecord[]) => {+ if (!chatListsOnScreen || organizeBy !== "project" || !open) return [];+ const out: SidebarItem[] = [];+ for (const project of records) {+ if (collapsedProjectIds.has(project.id)) continue;+ const chats = sortedChatsByProjectId.get(project.id) ?? [];+ out.push(+ ...(expandedChatProjectIds.has(project.id)+ ? chats+ : chats.slice(0, PROJECT_CHAT_LIMIT)),+ );+ }+ return out;+ },+ [+ chatListsOnScreen,+ organizeBy,+ collapsedProjectIds,+ expandedChatProjectIds,+ sortedChatsByProjectId,+ ],+ );+ const pinnedProjectChatItems = useMemo(+ () => folderChatItems(pinnedOpen, pinnedProjectRecords),+ [folderChatItems, pinnedOpen, pinnedProjectRecords],+ );+ const sectionProjectChatItems = useMemo(+ () => folderChatItems(projectsOpen, visibleProjectRecords),+ [folderChatItems, 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.const visiblePinnedItems = useMemo(@@ -1352,29 +1392,54 @@ export function AppSidebar() {() => (chatListsOnScreen && chatOpen ? sortedRecentChatItems : []),[chatListsOnScreen, chatOpen, sortedRecentChatItems],);- // Every row on screen, in one set. The three arrays above already fold in- // each section's disclosure, each folder's, and the per-folder limit, so a- // selection can be held to what is rendered without restating any of it.- const renderedChatIds = useMemo(() => {- const ids = new Set<string>();- for (const item of visiblePinnedItems) ids.add(item.id);- for (const item of renderedProjectChatItems) ids.add(item.id);- for (const item of visibleRecentItems) ids.add(item.id);- return ids;- }, [visiblePinnedItems, renderedProjectChatItems, visibleRecentItems]);+ // Pinned draws its folders above its chats, so the section's rows read in that order.+ const pinnedSectionChatItems = useMemo(+ () => [...pinnedProjectChatItems, ...visiblePinnedItems],+ [pinnedProjectChatItems, visiblePinnedItems],+ );+ // Every chat row on screen, in draw order: Pinned, then the Projects folders, 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],+ );+ const renderedChatIds = useMemo(+ () => new Set(renderedChatItems.map((item) => item.id)),+ [renderedChatItems],+ );// The folder rows, selectable in their own right and leaving the screen on their own terms: the// section closes, the sidebar organizes by date, or a "show less" takes back the overflow. The chat// sets above say nothing about that, since a folder with no chats in view is still a row.const renderedProjectIds = useMemo(() => {- if (!chatListsOnScreen || organizeBy !== "project" || !projectsOpen) {+ if (!chatListsOnScreen || organizeBy !== "project") {return new Set<string>();}- return new Set(visibleProjectRecords.map((project) => project.id));- }, [chatListsOnScreen, organizeBy, projectsOpen, visibleProjectRecords]);+ const ids = new Set<string>();+ // Each folder leaves with its own section.+ if (pinnedOpen) {+ for (const project of pinnedProjectRecords) ids.add(project.id);+ }+ if (projectsOpen) {+ for (const project of visibleProjectRecords) ids.add(project.id);+ }+ return ids;+ }, [+ chatListsOnScreen,+ organizeBy,+ pinnedOpen,+ pinnedProjectRecords,+ projectsOpen,+ visibleProjectRecords,+ ]);// Rows wanting attention, most urgent first. Same rule the Priority sort uses.const attentionItemIds = useMemo(() =>- [...visiblePinnedItems, ...renderedProjectChatItems, ...visibleRecentItems]+ renderedChatItems.filter((item) => chatPriorityRank(item) < 3).sort((a, b) =>@@ -1382,27 +1447,23 @@ export function AppSidebar() {b.updatedAt - a.updatedAt,).map((item) => item.id),- [- visiblePinnedItems,- renderedProjectChatItems,- visibleRecentItems,- chatPriorityRank,- ],+ [renderedChatItems, chatPriorityRank],);// Publish the finished order, so the chords cannot disagree with the screen.const publishLists = useChatNavigationStore((s) => s.publishLists);useEffect(() => {publishLists({- pinnedItems: visiblePinnedItems,- projectItems: renderedProjectChatItems,+ // The pinned folders' chats belong to Pinned, which draws them first.+ pinnedItems: pinnedSectionChatItems,+ projectItems: sectionProjectChatItems,recentItems: visibleRecentItems,attentionItemIds,activeItemId: activeThreadId ?? null,});}, [publishLists,- visiblePinnedItems,- renderedProjectChatItems,+ pinnedSectionChatItems,+ sectionProjectChatItems,visibleRecentItems,attentionItemIds,activeThreadId,@@ -1412,6 +1473,10 @@ export function AppSidebar() {() => sidebarProjectRecords.map((project) => project.id),[sidebarProjectRecords],);+ const pinnedProjectRowIds = useMemo(+ () => pinnedProjectRecords.map((project) => project.id),+ [pinnedProjectRecords],+ );const projectChatRowIds = useMemo(() => {const map = new Map<string, string[]>();for (const [projectId, items] of sortedChatsByProjectId) {@@ -1422,23 +1487,24 @@ export function AppSidebar() {}return map;}, [sortedChatsByProjectId]);- // How many nested rows the Projects section renders, so the bottom fade can- // re-measure when regrouping or a disclosure changes the list height.+ // Nested rows across both sections, so the bottom fade re-measures when the list height changes.const projectChatRowCount = useMemo(() => {if (organizeBy !== "project") return 0;let rows = 0;- for (const project of visibleProjectRecords) {+ for (const project of [...pinnedProjectRecords, ...visibleProjectRecords]) {if (collapsedProjectIds.has(project.id)) continue;const chats = sortedChatsByProjectId.get(project.id) ?? [];rows += expandedChatProjectIds.has(project.id)? chats.length: Math.min(chats.length, PROJECT_CHAT_LIMIT);- // The "Show more" row counts too.+ // "Show more" and an empty folder's "No chats" are rows too.if (chats.length > PROJECT_CHAT_LIMIT) rows += 1;+ if (chats.length === 0) rows += 1;}return rows;}, [organizeBy,+ pinnedProjectRecords,visibleProjectRecords,collapsedProjectIds,expandedChatProjectIds,@@ -1528,23 +1594,13 @@ export function AppSidebar() {/** Select every chat row on screen, pinned block included. */const selectAllChats = useCallback(() => {if (!chatRowsOnScreen) return;- const ids = [- ...visiblePinnedItems,- ...renderedProjectChatItems,- ...visibleRecentItems,- ].map((item) => item.id);+ const ids = renderedChatItems.map((item) => item.id);if (ids.length === 0) return;dropProjectSelection();// No anchor: a shift click after this one has no row to reach back to.selectionAnchorRef.current = null;setSelectedChatIds(new Set(ids));- }, [- chatRowsOnScreen,- visiblePinnedItems,- renderedProjectChatItems,- visibleRecentItems,- dropProjectSelection,- ]);+ }, [chatRowsOnScreen, renderedChatItems, dropProjectSelection]);// Escape leaves a selection, as it does the menus. A passive listener rather than one that consumes// the key: dictation's Escape reads defaultPrevented first, and a stale selection must not outrank@@ -1615,6 +1671,8 @@ export function AppSidebar() {function handleProjectSelectionClick(event: React.MouseEvent,projectId: string,+ // The list this row is in: Pinned holds folders too, and its ids are not Projects'.+ orderedIds: string[],): boolean {const additive = SELECT_WITH_META ? event.metaKey : event.ctrlKey;if (!additive && !event.shiftKey) return false;@@ -1625,10 +1683,14 @@ export function AppSidebar() {return true;}const anchorId = projectAnchorRef.current;- if (!anchorId) projectAnchorRef.current = projectId;+ // Shift without an anchor in this list starts one here, as the chat rows do.+ const sameList = anchorId !== null && orderedIds.includes(anchorId);+ if (!sameList) projectAnchorRef.current = projectId;setSelectedProjectIds(new Set(- anchorId ? rangeBetween(projectRowIds, anchorId, projectId) : [projectId],+ sameList && anchorId+ ? rangeBetween(orderedIds, anchorId, projectId)+ : [projectId],),);return true;@@ -1896,6 +1958,8 @@ export function AppSidebar() {projectsOpen,projectChatRowCount,visibleProjectRecords.length,+ // Pinning a folder moves rows between sections, leaving both counts above unchanged.+ pinnedProjectRecords.length,// Pinning a project chat adds a Pinned row while Recents and the folder// counts both stay put, so nothing else here moves.pinnedChatItems.length,@@ -2097,13 +2161,16 @@ export function AppSidebar() {},},};+ // The Projects row repeats the section, so it only earns its place while the section is absent.+ const navRowPinned = (item: SidebarNavItemPref) =>+ sidebarNavRowPinned(item, sidebarNavAuto, { projectsSectionShowing });const unpinnedNavIds = sidebarNav- .filter((item) => !item.pinned)+ .filter((item) => !navRowPinned(item)).map((item) => item.id);// More needs two or more rows to be worth a click; with exactly one unpinned, the menu and that row are both dropped.const overflowNavIds = unpinnedNavIds.length > 1 ? unpinnedNavIds : [];const inlineNavIds = sidebarNav- .filter((item) => item.pinned)+ .filter((item) => navRowPinned(item)).map((item) => item.id);// Mirrors ImagesWorkflowList's own test: it decides which row owns the highlight.const imagesWorkflowsListed =@@ -2209,8 +2276,16 @@ export function AppSidebar() {type RenameTarget =// `inline` is the row's own pill, and a chord has no row under the cursor// and may have none on screen at all, so it opens the dialog instead.- | { kind: "chat"; item: SidebarItem; current: string; inline: boolean }- | { kind: "project"; project: ProjectRecord; current: string }+ // `rowScope` is the list the pill belongs to. A pinned project chat is two rows at once, and+ // both mounted an autofocused input: the second stole focus and the first's blur cancelled the+ // rename. The row that opened the menu owns the pill.+ | {+ kind: "chat";+ item: SidebarItem;+ current: string;+ inline: boolean;+ rowScope?: string;+ }| { kind: "run"; run: TrainingRunSummary; current: string };const [renamingTarget, setRenamingTarget] = useState<RenameTarget | null>(null,@@ -2236,6 +2311,10 @@ export function AppSidebar() {});}, [allChatItems, pendingRename]);const [creatingProject, setCreatingProject] = useState(false);+ // The project behind the Edit dialog, or null while it is closed.+ const [editingProject, setEditingProject] = useState<ProjectRecord | null>(+ null,+ );const [projectCreateMoveTarget, setProjectCreateMoveTarget] =useState<SidebarItem | null>(null);const renameTrimmed = renameDraft.trim();@@ -2244,15 +2323,19 @@ export function AppSidebar() {renamingTarget !== null &&(renamingTarget.kind === "chat"? renameTrimmed.length > 0 && renameTrimmed !== renamingTarget.current- : renamingTarget.kind === "project"- ? renameTrimmed.length > 0 && renameTrimmed !== renamingTarget.current: renameTrimmed.length > 0? renameTrimmed !== renamingTarget.current: renamingTarget.run.display_name != null);- function openRenameChat(item: SidebarItem, inline = true) {+ function openRenameChat(item: SidebarItem, inline = true, rowScope?: string) {setRenameDraft(item.title);- setRenamingTarget({ kind: "chat", item, current: item.title, inline });+ setRenamingTarget({+ kind: "chat",+ item,+ current: item.title,+ inline,+ rowScope,+ });}function openRenameRun(run: TrainingRunSummary) {const current = getTrainingRunDisplayTitle(run);@@ -2275,16 +2358,6 @@ export function AppSidebar() {}return;}- if (target.kind === "project") {- try {- await renameChatProject(target.project.id, renameTrimmed);- } catch (err) {- toast.error("Failed to rename project", {- description: err instanceof Error ? err.message : undefined,- });- }- return;- }try {const updated = await renameTrainingRun(target.run.id, nextRunDisplayName);emitTrainingRunUpdated(updated);@@ -3038,14 +3111,14 @@ export function AppSidebar() {variant === "project"? showWorkSpinner? undefined- : // Room for the hover pin quick-action plus the kebab.- "group-hover/project-chat-item:pr-14 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:pr-8 [@media(pointer:coarse)]:pr-14"+ : // Room for the pin quick-action plus the kebab, and the same room with the menu open:+ // a narrower gutter there let the title run under them.+ "group-hover/project-chat-item:pr-14 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:pr-14 [@media(pointer:coarse)]:pr-14": isPinned? showWorkSpinner? undefined- : // Pinned rows show an extra unpin button on hover, so reserve more room- // (pr-8 when the menu is open keeps the unpin button clear of the title).- "group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8 [@media(pointer:coarse)]:pr-16"+ : // Pinned rows add an unpin button, so reserve the room on hover and while open.+ "group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-16 [@media(pointer:coarse)]:pr-16": showWorkSpinner? // A spinner glyph cannot truncate, so clear the kebab's 30px inset (pr-1.5 + size-6)."group-hover/recent-item:pr-8 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8 [@media(pointer:coarse)]:pr-10"@@ -3062,7 +3135,9 @@ export function AppSidebar() {const isRenamingThis =renamingTarget?.kind === "chat" &&renamingTarget.inline &&- renamingTarget.item.id === item.id;+ renamingTarget.item.id === item.id &&+ // The same chat can be on screen twice; only the row the menu was opened from edits.+ renamingTarget.rowScope === list?.scope;// Inline rename edits the title in place as a rounded pill, no dialog.if (isRenamingThis) {@@ -3156,7 +3231,10 @@ export function AppSidebar() {togglePinnedChat(item.id);}}aria-label={isPinned ? "Unpin chat" : "Pin chat"}- className="sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/project-chat-item:opacity-100 group-hover/project-chat-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"+ className={cn(+ "sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/project-chat-item:opacity-100 group-hover/project-chat-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",+ REVEAL_WITH_OPEN_MENU_PROJECT_CHAT,+ )}><span className="sidebar-row-action-glyph"><HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />@@ -3171,7 +3249,10 @@ export function AppSidebar() {togglePinnedChat(item.id);}}aria-label="Unpin chat"- className="sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"+ className={cn(+ "sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",+ REVEAL_WITH_OPEN_MENU_RECENT,+ )}><span className="sidebar-row-action-glyph"><HugeiconsIcon icon={PinOffIcon} strokeWidth={1.75} className="size-icon" />@@ -3197,7 +3278,9 @@ export function AppSidebar() {</button>)}>- <DropdownMenuItem onSelect={() => openRenameChat(item)}>+ <DropdownMenuItem+ onSelect={() => openRenameChat(item, true, list?.scope)}+ ><HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" /><span>Rename</span></DropdownMenuItem>@@ -3254,13 +3337,14 @@ export function AppSidebar() {<DropdownMenuSub><DropdownMenuSubTrigger><HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />- <span>Move to project</span>+ <span>Project</span></DropdownMenuSubTrigger><DropdownMenuSubContentsideOffset={0}alignOffset={-4}className="unsloth-plus-menu w-52">+ {/* Actions above the rule, destinations below it. */}<DropdownMenuItemonSelect={() => {setProjectCreateMoveTarget(item);@@ -3270,6 +3354,33 @@ export function AppSidebar() {<HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" /><span>New project</span></DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon icon={FolderAttachmentIcon} strokeWidth={1.75} className="size-icon" />+ <span>Project sources</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">+ {projects.length === 0 && (+ <DropdownMenuItem disabled>No projects yet</DropdownMenuItem>+ )}+ {projects.map((project) => (+ <DropdownMenuItem+ key={project.id}+ onSelect={async () => {+ try {+ await saveChatToProjectSources(item, project.id);+ } catch {+ toast.error("Failed to save to project sources.");+ }+ }}+ >+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ <span className="truncate">{project.name}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSeparator /><DropdownMenuItemdisabled={!item.projectId}onSelect={() => void moveChatToProject(item, null)}@@ -3326,32 +3437,6 @@ export function AppSidebar() {</DropdownMenuItem></DropdownMenuSubContent></DropdownMenuSub>- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <HugeiconsIcon icon={BookOpen01Icon} strokeWidth={1.75} className="size-icon" />- <span>Save to project sources</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent sideOffset={8} alignOffset={-4} className="unsloth-plus-menu w-52">- {projects.length === 0 && (- <DropdownMenuItem disabled>No projects yet</DropdownMenuItem>- )}- {projects.map((project) => (- <DropdownMenuItem- key={project.id}- onSelect={async () => {- try {- await saveChatToProjectSources(item, project.id);- } catch {- toast.error("Failed to save to project sources.");- }- }}- >- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />- <span className="truncate">{project.name}</span>- </DropdownMenuItem>- ))}- </DropdownMenuSubContent>- </DropdownMenuSub><DropdownMenuSeparator /><DropdownMenuItem onSelect={() => void handleArchiveThread(item)}><HugeiconsIcon icon={Archive03Icon} strokeWidth={1.75} className="size-icon" />@@ -3378,6 +3463,199 @@ export function AppSidebar() {);}+ /** One folder row and the chats under it. `order` is the list it drags within: Projects for an+ * unpinned folder, Pinned for a pinned one, so neither renumbers the other. */+ function renderProjectFolderRow(+ project: ProjectRecord,+ index: number,+ order: { scope: string; orderedIds: string[] },+ ) {+ const projectChats =+ sortedChatsByProjectId.get(project.id) ?? [];+ const projectChatIds =+ projectChatRowIds.get(project.id) ?? [];+ const expanded = !collapsedProjectIds.has(project.id);+ const showAll = expandedChatProjectIds.has(project.id);+ const visibleChats =+ expanded && !showAll+ ? projectChats.slice(0, PROJECT_CHAT_LIMIT)+ : projectChats;+ const isProjectPinned = pinnedProjectIdSet.has(+ project.id,+ );+ return (+ <Fragment key={project.id}>+ {/* Folders drag to reorder whatever the chat sort is. */}+ <ContextMenu>+ <ContextMenuTrigger asChild>+ <SidebarMenuItem+ className={cn(+ "group/recent-item relative",+ draggingRow?.id === project.id && "opacity-50",+ dropCueClass(+ order.scope,+ order.orderedIds,+ project.id,+ ),+ )}+ onContextMenu={() =>+ selectProjectForContextMenu(project.id)+ }+ {...rowDragProps(+ order.scope,+ order.orderedIds,+ project.id,+ )}+ >+ <SidebarMenuButton+ // Highlight the folder only on the project home; with a chat open, only that row is active.+ isActive={activeProjectId === project.id && !activeThreadId}+ data-selected={+ selectedProjectIds.has(project.id)+ ? "true"+ : undefined+ }+ onClick={(event) => {+ if (+ handleProjectSelectionClick(event, project.id, order.orderedIds)+ )+ return;+ clearSelection();+ toggleProjectCollapsed(project.id);+ }}+ // Same gutter whether hover or this row's menu revealed the actions.+ className="sidebar-nav-btn h-[33px] rounded-full gap-[8.5px] pl-3 pr-2.5 font-medium group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-16 [@media(pointer:coarse)]:pr-16"+ >+ {/* The folder says whether its chats are showing. */}+ <HugeiconsIcon+ icon={expanded ? Folder02Icon : Folder01Icon}+ strokeWidth={1.75}+ className="size-icon! shrink-0"+ />+ <span className="truncate text-ui-14p5 leading-ui-19 tracking-nav">{project.name}</span>+ </SidebarMenuButton>+ {/* New chat in this project */}+ <button+ type="button"+ aria-label="New chat"+ onClick={(e) => {+ e.stopPropagation();+ openNewChat(project.id);+ }}+ className={cn(+ "sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",+ REVEAL_WITH_OPEN_MENU_RECENT,+ )}+ >+ <span className="sidebar-row-action-glyph">+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />+ </span>+ </button>+ {/* Project options */}+ <NonModalDropdownMenu+ side="bottom"+ align="start"+ sideOffset={0}+ className="unsloth-plus-menu menu-flat-destructive w-56"+ trigger={(triggerRef) => (+ <button+ ref={triggerRef}+ type="button"+ onClick={(e) => e.stopPropagation()}+ aria-label="Project options"+ className="sidebar-row-action sidebar-touch-reveal group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"+ >+ <span className="sidebar-row-action-glyph">+ <HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" />+ </span>+ </button>+ )}+ >+ <DropdownMenuItem onSelect={() => openProject(project.id)}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ <span>Project home</span>+ </DropdownMenuItem>+ {/* No "New chat" here: the row's own pencil does it. */}+ <DropdownMenuItem onSelect={() => toggleProjectPin(project.id)}>+ <HugeiconsIcon icon={isProjectPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />+ <span>{isProjectPinned ? "Unpin project" : "Pin project"}</span>+ </DropdownMenuItem>+ {/* Name, instructions and folders are one dialog, so Edit rather than Rename. */}+ <DropdownMenuItem onSelect={() => setEditingProject(project)}>+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />+ <span>Edit</span>+ </DropdownMenuItem>+ {renderMoveRowItems(+ order.scope,+ order.orderedIds,+ project.id,+ index,+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => {+ // Start each delete with the file toggle off: Cancel closes programmatically and skips the+ openDeleteDialog({ kind: "project", project });+ }}+ >+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />+ <span>Delete project</span>+ </DropdownMenuItem>+ </NonModalDropdownMenu>+ </SidebarMenuItem>+ </ContextMenuTrigger>+ {renderProjectContextMenu()}+ </ContextMenu>+ {expanded &&+ visibleChats.map((chat, index) =>+ renderChatSidebarItem(+ chat,+ "project",+ manualDragEnabled+ ? {+ scope: projectOrderScope(project.id),+ orderedIds: projectChatIds,+ index,+ }+ : undefined,+ {+ scope: projectOrderScope(project.id),+ ids: projectChatIds,+ },+ ),+ )}+ {/* An open folder with nothing in it says so. Muted and static: nothing here to click. */}+ {expanded && projectChats.length === 0 && (+ <SidebarMenuItem>+ <p className="flex h-[30px] items-center pl-9 pr-4 text-ui-13 leading-ui-18 tracking-nav text-nav-fg-muted">+ {t("shell.navigation.noChats")}+ </p>+ </SidebarMenuItem>+ )}+ {expanded &&+ projectChats.length > PROJECT_CHAT_LIMIT && (+ <SidebarMenuItem>+ <SidebarMenuButton+ onClick={() => toggleProjectShowAll(project.id)}+ // Force the muted token: .sidebar-nav-btn's own color rule outweighs a plain text utility,+ // so Show more would otherwise match the chat rows.+ className="sidebar-nav-btn h-[30px] rounded-full pl-9 pr-4 font-medium text-nav-fg-muted!"+ >+ <span className="text-ui-13 leading-ui-18 tracking-nav">+ {t(+ showAll+ ? "shell.navigation.showLess"+ : "shell.navigation.showMore",+ )}+ </span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ )}+ </Fragment>+ );+ }+return (<>{slotShortcuts}@@ -3792,8 +4070,11 @@ export function AppSidebar() {</SidebarGroupContent></SidebarGroup>- {/* Pinned chats */}- {!isStudioRoute && !showTrainingRecents && pinnedChatItems.length > 0 && (+ {/* Pinned: the folders pinned to it, then the pinned chats */}+ {!isStudioRoute &&+ !showTrainingRecents &&+ (pinnedChatItems.length > 0 ||+ (organizeBy === "project" && pinnedProjectRecords.length > 0)) && (<Collapsible open={pinnedOpen} onOpenChange={setPinnedOpen} asChild><SidebarGroup className="group-data-[collapsible=icon]:hidden px-0 py-0"><SidebarGroupLabel className={cn("sidebar-sticky-label sidebar-sticky-label-following group/sidebar-header gap-1", headerRightPadding, scrolled && "is-scrolled")}>@@ -3812,6 +4093,14 @@ export function AppSidebar() {<CollapsibleContent><SidebarGroupContent className={unrailedRowPadding}><SidebarMenu>+ {/* Folders first: a folder carries its own chats. */}+ {organizeBy === "project" &&+ pinnedProjectRecords.map((project, projectIndex) =>+ renderProjectFolderRow(project, projectIndex, {+ scope: PINNED_PROJECT_ORDER_SCOPE,+ orderedIds: pinnedProjectRowIds,+ }),+ )}{sortedPinnedChatItems.map((item, index) =>renderChatSidebarItem(item,@@ -3833,11 +4122,9 @@ export function AppSidebar() {</Collapsible>)}- {/* Projects: one folder per project, its chats nested underneath */}- {!isStudioRoute &&- !showTrainingRecents &&- organizeBy === "project" &&- sidebarProjectRecords.length > 0 && (+ {/* One folder per unpinned project. The header owns "New project", so the section stays+ even when every project is pinned. */}+ {projectsSectionRendered && (<Collapsibleopen={projectsOpen}onOpenChange={setProjectsOpen}@@ -3872,187 +4159,12 @@ export function AppSidebar() {<CollapsibleContent><SidebarGroupContent className={unrailedRowPadding}><SidebarMenu>- {visibleProjectRecords.map((project, projectIndex) => {- const projectChats =- sortedChatsByProjectId.get(project.id) ?? [];- const projectChatIds =- projectChatRowIds.get(project.id) ?? [];- const expanded = !collapsedProjectIds.has(project.id);- const showAll = expandedChatProjectIds.has(project.id);- const visibleChats =- expanded && !showAll- ? projectChats.slice(0, PROJECT_CHAT_LIMIT)- : projectChats;- const isProjectPinned = pinnedProjectIdSet.has(- project.id,- );- return (- <Fragment key={project.id}>- {/* Folders drag to reorder whatever the chat sort is. */}- <ContextMenu>- <ContextMenuTrigger asChild>- <SidebarMenuItem- className={cn(- "group/recent-item relative",- draggingRow?.id === project.id && "opacity-50",- dropCueClass(- PROJECT_ORDER_SCOPE,- projectRowIds,- project.id,- ),- )}- onContextMenu={() =>- selectProjectForContextMenu(project.id)- }- {...rowDragProps(- PROJECT_ORDER_SCOPE,- projectRowIds,- project.id,- )}- >- <SidebarMenuButton- // Highlight the folder only on the project home; with a chat open, only that row is active.- isActive={activeProjectId === project.id && !activeThreadId}- data-selected={- selectedProjectIds.has(project.id)- ? "true"- : undefined- }- onClick={(event) => {- if (- handleProjectSelectionClick(event, project.id)- )- return;- clearSelection();- toggleProjectCollapsed(project.id);- }}- className="sidebar-nav-btn h-[33px] rounded-full gap-[8.5px] pl-3 pr-2.5 font-medium group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8 [@media(pointer:coarse)]:pr-16"- >- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon! shrink-0" />- <span className="truncate text-ui-14p5 leading-ui-19 tracking-nav">{project.name}</span>- </SidebarMenuButton>- {/* New chat in this project */}- <button- type="button"- aria-label="New chat"- onClick={(e) => {- e.stopPropagation();- openNewChat(project.id);- }}- className="sidebar-row-action sidebar-touch-reveal is-unpin-action group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"- >- <span className="sidebar-row-action-glyph">- <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />- </span>- </button>- {/* Project options */}- <NonModalDropdownMenu- side="bottom"- align="start"- sideOffset={0}- className="unsloth-plus-menu menu-flat-destructive w-56"- trigger={(triggerRef) => (- <button- ref={triggerRef}- type="button"- onClick={(e) => e.stopPropagation()}- aria-label="Project options"- className="sidebar-row-action sidebar-touch-reveal group-hover/recent-item:opacity-100 group-hover/recent-item:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto"- >- <span className="sidebar-row-action-glyph">- <HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={1.75} className="size-icon" />- </span>- </button>- )}- >- <DropdownMenuItem onSelect={() => openProject(project.id)}>- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />- <span>Project home</span>- </DropdownMenuItem>- <DropdownMenuItem onSelect={() => openNewChat(project.id)}>- <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-icon" />- <span>New chat</span>- </DropdownMenuItem>- <DropdownMenuItem- onSelect={() => {- // Seed the shared draft so the dialog opens with the current name, not stale text.- setRenameDraft(project.name);- setRenamingTarget({- kind: "project",- project,- current: project.name,- });- }}- >- <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />- <span>Rename project</span>- </DropdownMenuItem>- {renderMoveRowItems(- PROJECT_ORDER_SCOPE,- projectRowIds,- project.id,- projectIndex,- )}- <DropdownMenuItem onSelect={() => toggleProjectPin(project.id)}>- <HugeiconsIcon icon={isProjectPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />- <span>{isProjectPinned ? "Unpin project" : "Pin project"}</span>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- onSelect={() => {- // Start each delete with the file toggle off: Cancel closes programmatically and skips the- openDeleteDialog({ kind: "project", project });- }}- >- <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />- <span>Delete project</span>- </DropdownMenuItem>- </NonModalDropdownMenu>- </SidebarMenuItem>- </ContextMenuTrigger>- {renderProjectContextMenu()}- </ContextMenu>- {expanded &&- visibleChats.map((chat, index) =>- renderChatSidebarItem(- chat,- "project",- manualDragEnabled- ? {- scope: projectOrderScope(project.id),- orderedIds: projectChatIds,- index,- }- : undefined,- {- scope: projectOrderScope(project.id),- ids: projectChatIds,- },- ),- )}- {expanded &&- projectChats.length > PROJECT_CHAT_LIMIT && (- <SidebarMenuItem>- <SidebarMenuButton- onClick={() => toggleProjectShowAll(project.id)}- // Force the muted token: .sidebar-nav-btn's own color rule outweighs a plain text utility,- // so Show more would otherwise match the chat rows.- className="sidebar-nav-btn h-[30px] rounded-full pl-9 pr-4 font-medium text-nav-fg-muted!"- >- <span className="text-ui-13 leading-ui-18 tracking-nav">- {t(- showAll- ? "shell.navigation.showLess"- : "shell.navigation.showMore",- )}- </span>- </SidebarMenuButton>- </SidebarMenuItem>- )}- </Fragment>- );- })}+ {visibleProjectRecords.map((project, projectIndex) =>+ renderProjectFolderRow(project, projectIndex, {+ scope: PROJECT_ORDER_SCOPE,+ orderedIds: projectRowIds,+ }),+ )}{/* Long project lists stay one row deep until asked. */}{sidebarProjectRecords.length > SIDEBAR_PROJECT_LIMIT && (<SidebarMenuItem>@@ -4604,9 +4716,7 @@ export function AppSidebar() {<DialogTitle>{renamingTarget?.kind === "run"? t("shell.dialog.renameRun.title")- : renamingTarget?.kind === "project"- ? "Rename project"- : t("shell.dialog.renameChat.title")}+ : t("shell.dialog.renameChat.title")}</DialogTitle></DialogHeader><Input@@ -4623,16 +4733,12 @@ export function AppSidebar() {placeholder={renamingTarget?.kind === "run"? t("shell.dialog.renameRun.placeholder")- : renamingTarget?.kind === "project"- ? "Project name"- : t("shell.dialog.renameChat.placeholder")+ : t("shell.dialog.renameChat.placeholder")}aria-label={renamingTarget?.kind === "run"? t("shell.dialog.renameRun.placeholder")- : renamingTarget?.kind === "project"- ? "Project name"- : t("shell.dialog.renameChat.placeholder")+ : t("shell.dialog.renameChat.placeholder")}className="focus-visible:border-input focus-visible:ring-0"/>@@ -4666,6 +4772,14 @@ export function AppSidebar() {submitLabel={projectCreateMoveTarget ? "Create and move" : "Create project"}onCreated={afterCreateProject}/>+ <EditProjectDialog+ project={editingProject}+ onOpenChange={(open) => {+ if (!open) setEditingProject(null);+ }}+ // Delete keeps its own confirmation, with the "delete its files too" switch.+ onDelete={(project) => openDeleteDialog({ kind: "project", project })}+ /></>);}diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 1ba3c4868b3..727c5ba1e64 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -309,6 +309,7 @@ import {Download01Icon,Edit03Icon,FileDatabaseIcon,+ FolderAttachmentIcon,Folder01Icon,FolderAddIcon,HelpCircleIcon,@@ -8372,7 +8373,7 @@ const AssistantActionBar: FC = () => {className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-[12px] px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"><HugeiconsIcon- icon={BookOpen01Icon}+ icon={FolderAttachmentIcon}strokeWidth={1.75}className="size-icon"/>diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 2ae839a7058..a1d77648be7 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -99,11 +99,11 @@ import {} from "./utils/conversation-markdown";import {Archive03Icon,- BookOpen01Icon,BubbleChatTemporaryIcon,Delete02Icon,Download01Icon,Edit03Icon,+ FolderAttachmentIcon,Folder01Icon,Folder02Icon,FolderExportIcon,@@ -1967,7 +1967,8 @@ function ProjectLanding({strokeWidth={1.75}className="size-icon"/>- <span>Move to project</span>+ {/* Same label the sidebar row menu uses. */}+ <span>Project</span></DropdownMenuSubTrigger><DropdownMenuSubContent className="unsloth-plus-menu w-52"><DropdownMenuItem@@ -2024,11 +2025,11 @@ function ProjectLanding({onSelect={() => void handleSaveAsSource(item)}><HugeiconsIcon- icon={BookOpen01Icon}+ icon={FolderAttachmentIcon}strokeWidth={1.75}className="size-icon"/>- <span>Save to project sources</span>+ <span>Project sources</span></DropdownMenuItem><DropdownMenuSeparator /><DropdownMenuItemdiff --git a/studio/frontend/src/features/chat/components/edit-project-dialog.tsx b/studio/frontend/src/features/chat/components/edit-project-dialog.tsxnew file mode 100644index 00000000000..59245a2f6dc--- /dev/null+++ b/studio/frontend/src/features/chat/components/edit-project-dialog.tsx@@ -0,0 +1,195 @@+// 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 { Textarea } from "@/components/ui/textarea";+import { LinkedFoldersManager } from "@/features/rag";+import { toast } from "@/lib/toast";+import { Folder02Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";++import {+ renameChatProject,+ updateChatProjectInstructions,+} from "../hooks/use-chat-projects";+import type { ProjectRecord } from "../types";++/** Name, instructions and linked folders for one project. Opened from the folder row's "Edit".+ * Deleting hands back to the caller, which owns the confirmation. */+export function EditProjectDialog({+ project,+ onOpenChange,+ onDelete,+}: {+ /** The project being edited, or null while the dialog is closed. */+ project: ProjectRecord | null;+ onOpenChange: (open: boolean) => void;+ onDelete: (project: ProjectRecord) => void;+}) {+ const [name, setName] = useState(project?.name ?? "");+ const [instructions, setInstructions] = useState(project?.instructions ?? "");+ const [busy, setBusy] = useState(false);+ // Reseed on render, not in an effect: the fields are drafts of whichever project is open, and+ // a stale one would save the last project's text over this one.+ const [seededFor, setSeededFor] = useState(project?.id ?? null);+ if ((project?.id ?? null) !== seededFor) {+ setSeededFor(project?.id ?? null);+ setName(project?.name ?? "");+ setInstructions(project?.instructions ?? "");+ setBusy(false);+ }++ if (!project) return null;+ // Captured once: save() reads it after an await, where the prop may have changed.+ const target = project;++ const trimmedName = name.trim();+ const trimmedInstructions = instructions.trim();+ const nameChanged = trimmedName.length > 0 && trimmedName !== project.name;+ const instructionsChanged =+ trimmedInstructions !== (project.instructions ?? "").trim();+ const dirty = nameChanged || instructionsChanged;++ function close() {+ if (busy) return;+ onOpenChange(false);+ }++ async function save() {+ if (busy || !trimmedName) return;+ if (!dirty) {+ onOpenChange(false);+ return;+ }+ setBusy(true);+ try {+ // Separate writes: a failed rename must not drop the instructions with it.+ if (nameChanged) await renameChatProject(target.id, trimmedName);+ if (instructionsChanged) {+ await updateChatProjectInstructions(target.id, trimmedInstructions);+ }+ onOpenChange(false);+ } catch (err) {+ toast.error("Failed to save project", {+ description: err instanceof Error ? err.message : undefined,+ });+ } finally {+ setBusy(false);+ }+ }++ return (+ <Dialog+ open={true}+ onOpenChange={(next) => {+ if (next) return;+ close();+ }}+ >+ <DialogContent className="corner-squircle dialog-soft-surface gap-5 sm:max-w-lg">+ <DialogHeader>+ <DialogTitle className="text-ui-21">Edit project</DialogTitle>+ <DialogDescription className="sr-only">+ Rename this project, set the instructions its chats follow, and manage the local+ folders it indexes.+ </DialogDescription>+ </DialogHeader>+ {/* The same name field the create dialog uses. */}+ <div className="flex items-stretch overflow-hidden rounded-[16px] border border-border bg-background transition-colors focus-within:border-ring has-[input:disabled]:opacity-50 dark:border-transparent dark:bg-white/[0.06]">+ <span className="flex w-10 shrink-0 items-center justify-center pl-1 text-muted-foreground">+ <HugeiconsIcon+ icon={Folder02Icon}+ strokeWidth={1.75}+ className="size-5"+ />+ </span>+ <span aria-hidden="true" className="my-3 w-px bg-border" />+ <input+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ void save();+ }+ }}+ autoFocus={true}+ disabled={busy}+ maxLength={120}+ placeholder="Project name"+ aria-label="Project name"+ className="min-w-0 flex-1 bg-transparent py-4 pr-4 pl-2.5 text-base outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"+ />+ </div>+ <div className="flex flex-col gap-2">+ <label+ htmlFor="edit-project-instructions"+ className="text-ui-15 font-medium text-foreground"+ >+ Instructions+ </label>+ <p className="text-ui-13 text-muted-foreground">+ Sent with every chat in this project, ahead of the conversation.+ </p>+ <Textarea+ id="edit-project-instructions"+ value={instructions}+ onChange={(e) => setInstructions(e.target.value)}+ disabled={busy}+ rows={4}+ placeholder="How should the model answer in this project?"+ className="resize-none rounded-[16px]"+ />+ </div>+ {/* The Sources tab's own manager, so a folder linked here is linked there. */}+ <div className="rounded-[18px] bg-muted/30 px-4 py-3.5">+ <LinkedFoldersManager+ scope={{ type: "project", id: project.id }}+ compact={true}+ />+ </div>+ <DialogFooter className="flex-wrap gap-2 sm:justify-between">+ <Button+ type="button"+ variant="ghost"+ disabled={busy}+ onClick={() => {+ onOpenChange(false);+ onDelete(project);+ }}+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"+ >+ Delete project+ </Button>+ <span className="flex flex-wrap gap-2">+ <Button+ type="button"+ variant="ghost"+ disabled={busy}+ onClick={close}+ >+ Cancel+ </Button>+ <Button+ type="button"+ onClick={() => void save()}+ disabled={busy || !trimmedName}+ >+ {busy ? "Saving…" : "Save"}+ </Button>+ </span>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/studio/frontend/src/features/chat/components/new-project-dialog.tsx b/studio/frontend/src/features/chat/components/new-project-dialog.tsxindex e3eb4260b58..d621fcf3ea0 100644--- a/studio/frontend/src/features/chat/components/new-project-dialog.tsx+++ b/studio/frontend/src/features/chat/components/new-project-dialog.tsx@@ -131,7 +131,7 @@ export function NewProjectDialog({</DialogHeader>{/* Name field: folder glyph in its own cell, divided from the input. */}<div className="flex items-stretch overflow-hidden rounded-[16px] border border-border bg-background transition-colors focus-within:border-ring has-[input:disabled]:opacity-50 dark:border-transparent dark:bg-white/[0.06]">- <span className="flex w-9 shrink-0 items-center justify-center text-muted-foreground">+ <span className="flex w-10 shrink-0 items-center justify-center pl-1 text-muted-foreground"><HugeiconsIconicon={Folder02Icon}strokeWidth={1.75}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 5cea8f5cffd..71edac18717 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -105,6 +105,7 @@ export {moveIdBy,showsInRecents,PINNED_ORDER_SCOPE,+ PINNED_PROJECT_ORDER_SCOPE,PROJECT_ORDER_SCOPE,projectOrderScope,RECENTS_ORDER_SCOPE,@@ -227,6 +228,7 @@ export { ChatSearchDialog } from "./components/chat-search-dialog";export { StopRunningChatsDialog } from "./components/stop-running-chats-dialog";export { setTrainingCompareHandoff } from "./lib/training-compare-handoff";export type { ProjectRecord } from "./types";+export { EditProjectDialog } from "./components/edit-project-dialog";export { clearAllChats, countAllChats } from "./utils/clear-all-chats";export { offerToDeleteKeptSandboxes } from "./utils/offer-kept-sandbox-files";export { pasteClipboardFiles } from "./utils/clipboard-files";diff --git a/studio/frontend/src/features/chat/stores/chat-navigation-store.ts b/studio/frontend/src/features/chat/stores/chat-navigation-store.tsindex d702c5b61a9..c68a70b7e3b 100644--- a/studio/frontend/src/features/chat/stores/chat-navigation-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-navigation-store.ts@@ -12,10 +12,11 @@ import type { SidebarItem } from "../hooks/use-chat-sidebar-items";const RECENTLY_VIEWED_LIMIT = 24;export interface ChatNavigationState {- /** The pinned block, in the order the sidebar draws it. */+ /** The pinned block, in the order the sidebar draws it: the pinned folders' chats, then the+ * pinned chats. */pinnedItems: SidebarItem[];- /** Project chats on screen. Empty when the sidebar is organized as one list, where those chats- * are in Recents instead. */+ /** The Projects section's chats on screen, the pinned folders' excepted. Empty when the sidebar+ * is organized as one list, where those chats are in Recents instead. */projectItems: SidebarItem[];/** Recents, likewise. ⌥⌘1-6 indexes into this list alone. */recentItems: SidebarItem[];@@ -231,9 +232,9 @@ export const useChatNavigationStore = create<ChatNavigationState>(}),);-/** Every chat row the sidebar shows, in draw order: pinned, then project folders, then Recents.- * A pinned project chat is drawn twice, so the first of the pair wins and the walk does not- * stop on it again. */+/** Every chat row the sidebar shows, in draw order: the Pinned block, then the Projects section's+ * folders, then Recents. A pinned project chat is drawn twice, so the first of the pair wins and+ * the walk does not stop on it again. */export function visibleChatItems(state: ChatNavigationState): SidebarItem[] {const seen = new Set<string>();const out: SidebarItem[] = [];diff --git a/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts b/studio/frontend/src/features/chat/stores/sidebar-organization-store.tsindex 48f55e8e613..67a76ff1fea 100644--- a/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts+++ b/studio/frontend/src/features/chat/stores/sidebar-organization-store.ts@@ -21,6 +21,8 @@ export const RECENTS_ORDER_SCOPE = "recents";export const PINNED_ORDER_SCOPE = "pinned";// The project folders themselves, which drag regardless of the chat sort.export const PROJECT_ORDER_SCOPE = "projects";+// Pinned folders reorder among themselves: one list's drag must not renumber the other's.+export const PINNED_PROJECT_ORDER_SCOPE = "pinned-projects";export function projectOrderScope(projectId: string): string {return `project:${projectId}`;diff --git a/studio/frontend/src/features/rag/components/linked-folders-manager.tsx b/studio/frontend/src/features/rag/components/linked-folders-manager.tsxindex 420cdd1ea08..9e8fd817eae 100644--- a/studio/frontend/src/features/rag/components/linked-folders-manager.tsx+++ b/studio/frontend/src/features/rag/components/linked-folders-manager.tsx@@ -22,7 +22,9 @@ import {import { Progress } from "@/components/ui/progress";import { Spinner } from "@/components/ui/spinner";import { cn } from "@/lib/utils";-import { FolderSyncIcon, MoreHorizontalIcon, RotateCwIcon } from "lucide-react";+import { FolderSyncIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { MoreHorizontalIcon, RotateCwIcon } from "lucide-react";import { useState } from "react";import type { FolderSyncJob, LinkedFolderScope } from "../types/rag";import { useLinkedFolders } from "./use-linked-folders";@@ -92,7 +94,7 @@ export function LinkedFoldersManager({{manager.mutating ? (<Spinner className="size-3.5" />) : (- <FolderSyncIcon className="size-3.5" />+ <HugeiconsIcon icon={FolderSyncIcon} strokeWidth={1.75} className="size-3.5" />)}Link folder</Button>@@ -119,7 +121,7 @@ export function LinkedFoldersManager({key={folder.id}className="flex min-w-0 items-start gap-3 rounded-xl border border-border/70 bg-background px-3 py-2.5">- <FolderSyncIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <HugeiconsIcon icon={FolderSyncIcon} strokeWidth={1.75} className="mt-0.5 size-4 shrink-0 text-muted-foreground" /><div className="min-w-0 flex-1"><div className="flex items-baseline gap-2"><span@@ -184,7 +186,7 @@ export function LinkedFoldersManager({disabled={running}onSelect={() => void manager.sync(folder.id)}>- <FolderSyncIcon className="size-3.5" /> Sync changes+ <HugeiconsIcon icon={FolderSyncIcon} strokeWidth={1.75} className="size-3.5" /> Sync changes</DropdownMenuItem><DropdownMenuItemdisabled={running}diff --git a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx b/studio/frontend/src/features/rag/components/thread-documents-bar.tsxindex b4c2d2b19c1..505f8251d07 100644--- a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx+++ b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx@@ -6,6 +6,7 @@ import { HugeiconsIcon } from "@hugeicons/react";import {AttachmentIcon,FileDatabaseIcon,+ FolderAttachmentIcon,Folder02Icon,} from "@hugeicons/core-free-icons";import { Tick02Icon } from "@/lib/tick-icon";@@ -133,7 +134,7 @@ function InheritedProjectSources({className="composer-pill-btn shrink-0 cursor-default !text-foreground/60"title="This chat retrieves from its project's sources. Manage them in the project's Sources tab.">- <HugeiconsIcon icon={Folder02Icon} strokeWidth={2} className="size-3.5" />+ <HugeiconsIcon icon={FolderAttachmentIcon} strokeWidth={2} className="size-3.5" /><span>Project sources</span></span>{/* Same cap as the editable list: a linked folder can carry hundreds ofdiff --git a/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx b/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsxindex 19f26805b10..fd4b58ed638 100644--- a/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx+++ b/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx@@ -22,7 +22,13 @@ import { useT } from "@/i18n";import type { TranslationKey } from "@/i18n";import type { IconSvgElement } from "@hugeicons/react";import type { SidebarNavItemPref } from "../stores/appearance-custom-store";-import { useAppearanceCustomStore } from "../stores/appearance-custom-store";+import {+ sidebarNavAutoAfterChoice,+ sidebarNavRowPinned,+ useAppearanceCustomStore,+} from "../stores/appearance-custom-store";+import { useChatProjects } from "@/features/chat";+import { useSidebarOrganizationStore } from "@/features/chat";const ITEM_META: Record<SidebarNavItemPref["id"],@@ -50,12 +56,26 @@ function FixedRow({ icon, label }: { icon: IconSvgElement; label: string }) {);}-function MovableRow({ item }: { item: SidebarNavItemPref }) {+function MovableRow({+ item,+ projectsSectionShowing,+}: {+ item: SidebarNavItemPref;+ projectsSectionShowing: boolean;+}) {const t = useT();const controls = useDragControls();const patch = useAppearanceCustomStore((s) => s.patch);const sidebarNav = useAppearanceCustomStore((s) => s.customization.sidebarNav);+ const sidebarNavAuto = useAppearanceCustomStore(+ (s) => s.customization.sidebarNavAuto,+ );const meta = ITEM_META[item.id];+ // What the sidebar is doing now, which for a row on its rule is not what `pinned` says.+ // Flipping the switch is a decision, so the rule is dropped.+ const pinned = sidebarNavRowPinned(item, sidebarNavAuto, {+ projectsSectionShowing,+ });return (<Reorder.Itemvalue={item.id}@@ -96,12 +116,13 @@ function MovableRow({ item }: { item: SidebarNavItemPref }) {aria-label={t("settings.appearance.sidebarNav.pinToSidebar", {name: t(meta.labelKey),})}- checked={item.pinned}- onCheckedChange={(pinned) =>+ checked={pinned}+ onCheckedChange={(next) =>patch({sidebarNav: sidebarNav.map((entry) =>- entry.id === item.id ? { ...entry, pinned } : entry,+ entry.id === item.id ? { ...entry, pinned: next } : entry,),+ sidebarNavAuto: sidebarNavAutoAfterChoice(sidebarNavAuto, item.id),})}/>@@ -113,8 +134,19 @@ function MovableRow({ item }: { item: SidebarNavItemPref }) {export function SidebarNavCustomizer() {const t = useT();const sidebarNav = useAppearanceCustomStore((s) => s.customization.sidebarNav);+ const sidebarNavAuto = useAppearanceCustomStore(+ (s) => s.customization.sidebarNavAuto,+ );const patch = useAppearanceCustomStore((s) => s.patch);- const unpinnedCount = sidebarNav.filter((item) => !item.pinned).length;+ // The sidebar's inputs minus the route: this panel describes the sidebar in general.+ const organizeBy = useSidebarOrganizationStore((s) => s.organizeBy);+ const { projects } = useChatProjects();+ const projectsSectionShowing =+ organizeBy === "project" && projects.length > 0;+ const unpinnedCount = sidebarNav.filter(+ (item) =>+ !sidebarNavRowPinned(item, sidebarNavAuto, { projectsSectionShowing }),+ ).length;return (<div className="flex flex-col rounded-xl border border-border/70 p-1.5"><FixedRow icon={PencilEdit02Icon} label={t("shell.navigation.newChat")} />@@ -131,7 +163,11 @@ export function SidebarNavCustomizer() {className="flex flex-col">{sidebarNav.map((item) => (- <MovableRow key={item.id} item={item} />+ <MovableRow+ key={item.id}+ item={item}+ projectsSectionShowing={projectsSectionShowing}+ />))}</Reorder.Group>{/* Mirrors the sidebar: More only exists at two or more. */}diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.tsindex 80f9b38db74..0b52a045a21 100644--- a/studio/frontend/src/features/settings/index.ts+++ b/studio/frontend/src/features/settings/index.ts@@ -41,6 +41,8 @@ export {migrateShippedSidebarNavDefault,prefersReducedMotion,sanitizeCustomization,+ sidebarNavAutoAfterChoice,+ sidebarNavRowPinned,useAppearanceCustomStore,} from "./stores/appearance-custom-store";export type {diff --git a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts b/studio/frontend/src/features/settings/stores/appearance-custom-store.tsindex 53a71aff023..da0e0e29d56 100644--- a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts+++ b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts@@ -110,6 +110,32 @@ export type SidebarNavItemPref = {pinned: boolean;};+/** Rows whose placement follows the sidebar's own state until the user decides for them. */+export const SIDEBAR_NAV_AUTO_ITEM_IDS = ["projects"] as const satisfies+ readonly SidebarNavItemId[];++/** Where a nav row goes. Projects repeats the Projects section, so while that section lists the+ * folders the row steps aside into "More". A toggle in Customize sidebar drops it from `auto`+ * and wins from then on. */+export function sidebarNavRowPinned(+ item: SidebarNavItemPref,+ auto: readonly SidebarNavItemId[],+ context: { projectsSectionShowing: boolean },+): boolean {+ if (item.id === "projects" && auto.includes("projects")) {+ return !context.projectsSectionShowing;+ }+ return item.pinned;+}++/** The list after the user has decided a row's placement themselves. */+export function sidebarNavAutoAfterChoice(+ auto: readonly SidebarNavItemId[],+ id: SidebarNavItemId,+): SidebarNavItemId[] {+ return auto.filter((entry) => entry !== id);+}+// Matches the shipped layout, so an untouched install looks unchanged.export const SIDEBAR_NAV_DEFAULT_PINNED: Record<SidebarNavItemId, boolean> = {hub: true,@@ -213,6 +239,9 @@ export type AppearanceCustomization = {sidebarMenu: SidebarMenuItemPref[];/** Order of the sidebar nav rows, and which are pinned vs. under "More". */sidebarNav: SidebarNavItemPref[];+ /** Rows still following their automatic rule instead of a choice made in Customize sidebar.+ * Only Projects has one. */+ sidebarNavAuto: SidebarNavItemId[];};const EMPTY_MODE_COLORS: CustomModeColors = {@@ -243,6 +272,7 @@ export const DEFAULT_CUSTOMIZATION: AppearanceCustomization = {id,pinned: SIDEBAR_NAV_DEFAULT_PINNED[id],})),+ sidebarNavAuto: [...SIDEBAR_NAV_AUTO_ITEM_IDS],};export const UI_FONT_SIZE_RANGE = { min: 12, max: 20, default: 15 } as const;@@ -350,6 +380,28 @@ function sanitizeSidebarNav(value: unknown): SidebarNavItemPref[] {return items;}+/** `undefined` is a payload written before this field. Only an untouched layout never chose a+ * placement for Projects, so an arranged one keeps the pin it already carries. */+function sanitizeSidebarNavAuto(+ value: unknown,+ nav: SidebarNavItemPref[],+): SidebarNavItemId[] {+ if (value === undefined || value === null) {+ return isUntouchedSidebarNav(nav) ? [...SIDEBAR_NAV_AUTO_ITEM_IDS] : [];+ }+ const seen = new Set<SidebarNavItemId>();+ for (const entry of Array.isArray(value) ? value : []) {+ // Only rows that have a rule: anything else would silently pin itself.+ if (+ isSidebarNavItemId(entry) &&+ (SIDEBAR_NAV_AUTO_ITEM_IDS as readonly string[]).includes(entry)+ ) {+ seen.add(entry);+ }+ }+ return [...seen];+}+function sanitizeSidebarMenu(value: unknown): SidebarMenuItemPref[] {const items: SidebarMenuItemPref[] = [];const seen = new Set<SidebarMenuItemId>();@@ -380,6 +432,7 @@ export function sanitizeCustomization(value: unknown): AppearanceCustomization {typeof source.contrast === "number" && Number.isFinite(source.contrast)? Math.min(100, Math.max(0, Math.round(source.contrast))): DEFAULT_CUSTOMIZATION.contrast;+ const sidebarNav = sanitizeSidebarNav(source.sidebarNav);return {colors: {light: sanitizeModeColors(source.colors?.light),@@ -404,10 +457,22 @@ export function sanitizeCustomization(value: unknown): AppearanceCustomization {: "system",fontSmoothing: source.fontSmoothing !== false,sidebarMenu: sanitizeSidebarMenu(source.sidebarMenu),- sidebarNav: sanitizeSidebarNav(source.sidebarNav),+ sidebarNav,+ sidebarNavAuto: sanitizeSidebarNavAuto(source.sidebarNavAuto, sidebarNav),};}+/** Whether a nav layout is still one we shipped, rather than one the user arranged. */+function isUntouchedSidebarNav(nav: SidebarNavItemPref[]): boolean {+ const stored = JSON.stringify(nav);+ if (stored === JSON.stringify(DEFAULT_CUSTOMIZATION.sidebarNav)) return true;+ // Sanitize each layout too: the stored one has since gained any ids added after it was+ // written, so a raw compare would never match.+ return SHIPPED_SIDEBAR_NAV_DEFAULTS.some(+ (layout) => JSON.stringify(sanitizeSidebarNav(layout)) === stored,+ );+}+/** Adopt the latest default only when the sidebar still matches one we shipped. */export function migrateShippedSidebarNavDefault(customization: AppearanceCustomization,@@ -417,13 +482,7 @@ export function migrateShippedSidebarNavDefault(// Once this migration version has been persisted, the same layout may be a// deliberate user choice and must never be adopted again.if (storedVersion >= migrationVersion) return customization;- const stored = JSON.stringify(customization.sidebarNav);- // Sanitize each layout too: the stored one has since gained any ids added- // after it was written, so a raw compare would never match.- const untouched = SHIPPED_SIDEBAR_NAV_DEFAULTS.some(- (layout) => JSON.stringify(sanitizeSidebarNav(layout)) === stored,- );- return untouched+ return isUntouchedSidebarNav(customization.sidebarNav)? {...customization,sidebarNav: [...DEFAULT_CUSTOMIZATION.sidebarNav],diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex eb18fae26e2..02d2f8c1008 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -162,6 +162,8 @@ export const ar = {export: "تصدير",recents: "العناصر الأخيرة",noChatsYet: "لا توجد محادثات بعد",+ // Shown under an empty project folder in the sidebar.+ noChats: "لا توجد محادثات",showMore: "عرض المزيد",showLess: "عرض أقل",settings: "الإعدادات",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 993a48fca9a..2ba3d9243fa 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -165,6 +165,8 @@ export const de = {export: "Exportieren",recents: "Zuletzt verwendet",noChatsYet: "Noch keine Chats",+ // Shown under an empty project folder in the sidebar.+ noChats: "Keine Chats",showMore: "Mehr anzeigen",showLess: "Weniger anzeigen",settings: "Einstellungen",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 78fc235dc50..af60d2943cc 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -165,6 +165,8 @@ export const en = {export: "Export",recents: "Recents",noChatsYet: "No chats yet",+ // Shown under an empty project folder in the sidebar.+ noChats: "No chats",showMore: "Show more",showLess: "Show less",settings: "Settings",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex b9ccb641b07..735d52db464 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -164,6 +164,8 @@ export const es = {export: "Exportar",recents: "Recientes",noChatsYet: "Aún no hay chats",+ // Shown under an empty project folder in the sidebar.+ noChats: "Sin chats",showMore: "Mostrar más",showLess: "Mostrar menos",settings: "Configuración",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex b254bb0de13..85882feeba4 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -165,6 +165,8 @@ export const fr = {export: "Exporter",recents: "Discussions récentes",noChatsYet: "Aucune discussion pour le moment",+ // Shown under an empty project folder in the sidebar.+ noChats: "Aucune discussion",showMore: "Afficher plus",showLess: "Afficher moins",settings: "Paramètres",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 1bb6869fa1c..ac40e2c47a2 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -165,6 +165,8 @@ export const hi = {export: "एक्सपोर्ट",recents: "हाल के",noChatsYet: "अभी तक कोई चैट नहीं",+ // Shown under an empty project folder in the sidebar.+ noChats: "कोई चैट नहीं",showMore: "और दिखाएं",showLess: "कम दिखाएं",settings: "सेटिंग्स",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex e3cc8f00731..d0f4a0b024c 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -129,6 +129,8 @@ export const it = {export: "Esporta",recents: "Recenti",noChatsYet: "Ancora nessuna chat",+ // Shown under an empty project folder in the sidebar.+ noChats: "Nessuna chat",showMore: "Mostra altro",showLess: "Mostra meno",settings: "Impostazioni",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex a527067f5b3..8d9594fbf05 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -164,6 +164,8 @@ export const ja = {export: "エクスポート",recents: "履歴",noChatsYet: "チャットがまだありません",+ // Shown under an empty project folder in the sidebar.+ noChats: "チャットなし",showMore: "もっと見る",showLess: "表示を減らす",settings: "設定",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex f3a54274e75..143da8dd525 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -162,6 +162,8 @@ export const ko = {export: "내보내기",recents: "최근 항목",noChatsYet: "아직 채팅이 없습니다",+ // Shown under an empty project folder in the sidebar.+ noChats: "채팅 없음",showMore: "더 보기",showLess: "간략히 보기",settings: "설정",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex cc4440819a0..6a189732735 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -164,6 +164,8 @@ export const ptBR = {export: "Exportar",recents: "Recentes",noChatsYet: "Nenhum chat ainda",+ // Shown under an empty project folder in the sidebar.+ noChats: "Nenhum chat",showMore: "Mostrar mais",showLess: "Mostrar menos",settings: "Configurações",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 8bb318cc6b3..0cee8991bae 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -164,6 +164,8 @@ export const ru = {export: "Экспорт",recents: "Недавние",noChatsYet: "Пока нет чатов",+ // Shown under an empty project folder in the sidebar.+ noChats: "Нет чатов",showMore: "Показать больше",showLess: "Показать меньше",settings: "Настройки",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 7962c4279a0..2e169259b80 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -160,6 +160,8 @@ export const zhCN = {export: "导出",recents: "最近",noChatsYet: "暂无对话",+ // Shown under an empty project folder in the sidebar.+ noChats: "无对话",showMore: "显示更多",showLess: "显示更少",settings: "设置",diff --git a/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.tsindex 500b0258af4..4d6493497a7 100644--- a/studio/frontend/tests/keyboard-shortcuts.test.ts+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts@@ -1159,10 +1159,15 @@ test("the rename chord does not land in a surface only a row can show", async ()APP_SIDEBAR,/useShortcut\("renameChat", \(\) => \{[\s\S]*?withActiveChat\(\(item\) => openRenameChat\(item, false\)\);/,);- assert.match(APP_SIDEBAR, /onSelect=\{\(\) => openRenameChat\(item\)\}/);+ // The menu names the list its row is in, so a chat on screen twice renames in the row the+ // user opened, not in both at once.assert.match(APP_SIDEBAR,- /function openRenameChat\(item: SidebarItem, inline = true\)/,+ /onSelect=\{\(\) => openRenameChat\(item, true, list\?\.scope\)\}/,+ );+ assert.match(+ APP_SIDEBAR,+ /function openRenameChat\(item: SidebarItem, inline = true, rowScope\?: string\)/,);// The pill is gated on it, so a dialog rename cannot also arm a row that is@@ -1263,9 +1268,19 @@ test("a collapsed sidebar section is not published for the chords", async () =>APP_SIDEBAR,/chatListsOnScreen && chatOpen \? sortedRecentChatItems/,);- assert.match(APP_SIDEBAR, /organizeBy !== "project" \|\| !projectsOpen/);+ // Folders follow the section they render in: the pinned ones close with Pinned, the rest+ // with Projects, so neither disclosure speaks for the other's rows.+ assert.match(+ APP_SIDEBAR,+ /folderChatItems\(pinnedOpen, pinnedProjectRecords\)/,+ );+ assert.match(+ APP_SIDEBAR,+ /folderChatItems\(projectsOpen, visibleProjectRecords\)/,+ );+ assert.match(APP_SIDEBAR, /if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !open\)/);// And the published lists are the filtered ones.- assert.match(APP_SIDEBAR, /pinnedItems: visiblePinnedItems,/);+ assert.match(APP_SIDEBAR, /pinnedItems: pinnedSectionChatItems,/);assert.match(APP_SIDEBAR, /recentItems: visibleRecentItems,/);});@@ -1582,26 +1597,31 @@ test("the published chat lists stop where the sidebar stops", async () => {/const chatListsOnScreen =\n\s*!isStudioRoute &&\n\s*!showTrainingRecents &&\n\s*\(isMobile \|\| sidebarState !== "collapsed"\);/,);for (const group of [- /if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !projectsOpen\)/,+ /if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !open\) return \[\];/,/\(chatListsOnScreen && pinnedOpen \? sortedPinnedChatItems : \[\]\)/,/\(chatListsOnScreen && chatOpen \? sortedRecentChatItems : \[\]\)/,]) {assert.match(APP_SIDEBAR, group);}- // Select All reads the same three arrays, so it cannot reach further than- // the walk does.+ // Select All reads the same rows the walk does, so it cannot reach further.const selectAll = APP_SIDEBAR.indexOf("const selectAllChats = useCallback(");assert.ok(selectAll !== -1, "selectAllChats moved");assert.match(APP_SIDEBAR.slice(selectAll, APP_SIDEBAR.indexOf("\n }, [", selectAll)),- /\.\.\.visiblePinnedItems,\n\s*\.\.\.renderedProjectChatItems,\n\s*\.\.\.visibleRecentItems,/,+ /const ids = renderedChatItems\.map\(\(item\) => item\.id\);/,+ );+ assert.match(+ APP_SIDEBAR,+ /const renderedChatItems = useMemo\(\n\s*\(\) => \[\n\s*\.\.\.pinnedSectionChatItems,\n\s*\.\.\.sectionProjectChatItems,\n\s*\.\.\.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 ["visiblePinnedItems","visibleRecentItems",- "renderedProjectChatItems",+ "renderedChatItems",+ "pinnedProjectChatItems",+ "sectionProjectChatItems",]) {assert.ok(!rendered.includes(name), `${name} is read by the JSX too`);}@@ -1658,21 +1678,30 @@ test("a selection does not outlive the rows it was made on", async () => {APP_SIDEBAR,/if \(projectAnchor && !renderedProjectIds\.has\(projectAnchor\)\) \{\n\s*projectAnchorRef\.current = null;/,);- // The three ways a folder row leaves without the sidebar going with it.+ // The ways a folder row leaves without the sidebar going with it — including its section+ // closing, which for a pinned folder is Pinned, not Projects.+ assert.match(+ APP_SIDEBAR,+ /const renderedProjectIds = useMemo\(\(\) => \{\n\s*if \(!chatListsOnScreen \|\| organizeBy !== "project"\) \{\n\s*return new Set<string>\(\);\n\s*\}/,+ );+ assert.match(+ APP_SIDEBAR,+ /if \(pinnedOpen\) \{\n\s*for \(const project of pinnedProjectRecords\) ids\.add\(project\.id\);/,+ );assert.match(APP_SIDEBAR,- /const renderedProjectIds = useMemo\(\(\) => \{\n\s*if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !projectsOpen\) \{\n\s*return new Set<string>\(\);\n\s*\}\n\s*return new Set\(visibleProjectRecords\.map\(\(project\) => project\.id\)\);/,+ /if \(projectsOpen\) \{\n\s*for \(const project of visibleProjectRecords\) ids\.add\(project\.id\);/,);// Both counts feed the flag, which is why both have to be pruned.assert.match(APP_SIDEBAR,/const selectionActive =\n?\s*selectionCount > 0 \|\| projectSelectionCount > 0;/,);- // Built from the three arrays that already carry every disclosure state, so+ // Built from the draw-order list, which already carries every disclosure state, so// a collapse or a "show less" needs nothing restated here.assert.match(APP_SIDEBAR,- /const renderedChatIds = useMemo\(\(\) => \{[\s\S]*?visiblePinnedItems[\s\S]*?renderedProjectChatItems[\s\S]*?visibleRecentItems/,+ /const renderedChatIds = useMemo\(\n\s*\(\) => new Set\(renderedChatItems\.map\(\(item\) => item\.id\)\),/,);// Which is what makes the four bulk branches safe to leave as they are.for (const id of [@@ -1795,7 +1824,10 @@ test("the rows the selection guard reads keep their identity", async () => {"visibleProjectRecords","visiblePinnedItems","visibleRecentItems",- "renderedProjectChatItems",+ "pinnedProjectChatItems",+ "sectionProjectChatItems",+ "pinnedSectionChatItems",+ "renderedChatItems","renderedChatIds",]) {const at = APP_SIDEBAR.indexOf(`const ${name} = `);@@ -1806,6 +1838,10 @@ test("the rows the selection guard reads keep their identity", async () => {`${name} is rebuilt every render and feeds a selection effect`,);}+ // The builder those lists memoise on has to hold its identity too, or they rebuild with it.+ const builder = APP_SIDEBAR.indexOf("const folderChatItems = ");+ assert.notEqual(builder, -1, "folderChatItems is gone");+ assert.match(APP_SIDEBAR.slice(builder, builder + 64), /= useCallback\(/);});// The root of the chain the test above pins. groupThreads returns a freshdiff --git a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts b/studio/frontend/tests/sidebar-nav-backend-parity.test.tsindex 8a1f074a99b..71414bbc582 100644--- a/studio/frontend/tests/sidebar-nav-backend-parity.test.ts+++ b/studio/frontend/tests/sidebar-nav-backend-parity.test.ts@@ -23,6 +23,32 @@ test("the backend sidebar nav defaults match the frontend", async () => {assert.deepEqual(backend, DEFAULT_CUSTOMIZATION.sidebarNav);});+// PersonalizationCustomization ignores unknown keys, so a field this side sends and that one+// never declared is dropped on every save and rebuilt from defaults on the next load, quietly+// undoing whatever the user set.+test("the backend stores every customization field the frontend sends", () => {+ const source = readText("../../backend/routes/settings.py");+ const model = /class PersonalizationCustomization\(BaseModel\):([\s\S]*?)\nclass /.exec(+ source,+ );+ assert.ok(model, "could not find PersonalizationCustomization in settings.py");+ const fields = new Set(+ [...model[1].matchAll(/^ {4}(\w+):/gm)]+ .map((m) => m[1])+ .filter((name) => name !== "model_config"),+ );+ for (const key of Object.keys(DEFAULT_CUSTOMIZATION)) {+ assert.ok(fields.has(key), `the backend drops "${key}" on every save`);+ }+ // And this one defaults to None rather than a list: the client tells a record written before+ // the field apart from one whose user chose an empty list, and a filled-in default would+ // reapply a rule the user had already overruled.+ assert.match(+ model[1],+ /sidebarNavAuto: Optional\[list\[SidebarNavItemId\]\] = Field\(\n\s*None,/,+ );+});+// The two capability-gated rows. They are the ones that can render disabled without the user// having done anything, so they are also the ones a rename would silently un-gate: navRows is// keyed by SidebarNavItemId, so a dropped `pending` there just stops spinning, it does notdiff --git a/studio/frontend/tests/sidebar-projects-nav-auto.test.ts b/studio/frontend/tests/sidebar-projects-nav-auto.test.tsnew file mode 100644index 00000000000..e6531a825d1--- /dev/null+++ b/studio/frontend/tests/sidebar-projects-nav-auto.test.ts@@ -0,0 +1,167 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The Projects nav row repeats the Projects section, so it steps aside while that section is on+// screen, until the user decides its place in Customize sidebar.++import assert from "node:assert/strict";+import test from "node:test";+import { installLocalStorageFake, readSrcAsync } from "./helpers/kit.ts";++installLocalStorageFake();++const {+ DEFAULT_CUSTOMIZATION,+ sanitizeCustomization,+ sidebarNavAutoAfterChoice,+ sidebarNavRowPinned,+} = await import("../src/features/settings/stores/appearance-custom-store.ts");++const PROJECTS = { id: "projects", pinned: true } as const;++test("the row stands down only while the section is showing", () => {+ const auto = ["projects"] as const;+ assert.equal(+ sidebarNavRowPinned(PROJECTS, auto, { projectsSectionShowing: true }),+ false,+ "the row is still pinned beside the section that repeats it",+ );+ // No projects left, or the sidebar organised as one list, and the section is gone with them.+ assert.equal(+ sidebarNavRowPinned(PROJECTS, auto, { projectsSectionShowing: false }),+ true,+ );+});++test("a choice in Customize sidebar outlives the rule", () => {+ const decided = sidebarNavAutoAfterChoice(["projects"], "projects");+ assert.deepEqual(decided, []);+ // Pinned stays pinned beside the section…+ assert.equal(+ sidebarNavRowPinned(PROJECTS, decided, { projectsSectionShowing: true }),+ true,+ );+ // …and off stays off once every project is deleted.+ assert.equal(+ sidebarNavRowPinned({ id: "projects", pinned: false }, decided, {+ projectsSectionShowing: false,+ }),+ false,+ );+});++test("only Projects has a rule; every other row reads its own pref", () => {+ for (const id of ["hub", "images", "train", "api"] as const) {+ for (const showing of [true, false]) {+ assert.equal(+ sidebarNavRowPinned({ id, pinned: true }, ["projects"], {+ projectsSectionShowing: showing,+ }),+ true,+ );+ }+ }+ // And a stored list cannot smuggle another id into the rule.+ const sanitized = sanitizeCustomization({+ sidebarNavAuto: ["projects", "train", "nonsense"],+ });+ assert.deepEqual(sanitized.sidebarNavAuto, ["projects"]);+});++test("an install that never chose gets the rule, one that chose keeps its choice", () => {+ // Written before the field existed, with a layout we shipped: no choice was ever made.+ assert.deepEqual(sanitizeCustomization({}).sidebarNavAuto, ["projects"]);+ assert.deepEqual(DEFAULT_CUSTOMIZATION.sidebarNavAuto, ["projects"]);+ assert.deepEqual(+ sanitizeCustomization({ sidebarNav: [...DEFAULT_CUSTOMIZATION.sidebarNav] })+ .sidebarNavAuto,+ ["projects"],+ );+ // An arranged layout already carries a Projects choice, so the rule must not overrule it.+ const unpinned = sanitizeCustomization({+ sidebarNav: DEFAULT_CUSTOMIZATION.sidebarNav.map((entry) =>+ entry.id === "projects" ? { ...entry, pinned: false } : entry,+ ),+ });+ assert.deepEqual(unpinned.sidebarNavAuto, []);+ assert.equal(+ sidebarNavRowPinned(+ unpinned.sidebarNav.find((entry) => entry.id === "projects")!,+ unpinned.sidebarNavAuto,+ { projectsSectionShowing: false },+ ),+ false,+ "an upgrade pinned a row the user had put away",+ );+ // Reordering counts as arranging too, even with Projects left where it was.+ const reordered = sanitizeCustomization({+ sidebarNav: [+ { id: "train", pinned: true },+ ...DEFAULT_CUSTOMIZATION.sidebarNav.filter((entry) => entry.id !== "train"),+ ],+ });+ assert.deepEqual(reordered.sidebarNavAuto, []);+ // An explicit empty list is a decision, and survives the round trip.+ assert.deepEqual(sanitizeCustomization({ sidebarNavAuto: [] }).sidebarNavAuto, []);+});++// The rail hides both folder sections in CSS without unmounting them, so the row has to stay on+// it: standing down there would bury the only way to reach projects behind More.+test("the rail keeps the Projects row, since the section is hidden there", async () => {+ const sidebar = await readSrcAsync("components/app-sidebar.tsx");+ assert.match(+ sidebar,+ /const projectsSectionShowing =\n\s*projectsSectionRendered && \(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,+ /\{projectsSectionRendered && \(\n[\s\S]{0,400}?group-data-\[collapsible=icon\]:hidden/,+ );+});++// Pinned folders are rows of Pinned, whose ids are not the Projects list's, so a Shift-click+// that read the Projects list found neither endpoint and cleared the selection.+test("folders range-select within the list the row is in", async () => {+ const sidebar = await readSrcAsync("components/app-sidebar.tsx");+ assert.match(+ sidebar,+ /function handleProjectSelectionClick\(\n\s*event: React\.MouseEvent,\n\s*projectId: string,\n(?:\s*\/\/[^\n]*\n)*\s*orderedIds: string\[\],/,+ );+ assert.match(+ sidebar,+ /const sameList = anchorId !== null && orderedIds\.includes\(anchorId\);/,+ );+ assert.match(sidebar, /rangeBetween\(orderedIds, anchorId, projectId\)/);+ assert.match(+ sidebar,+ /handleProjectSelectionClick\(event, project\.id, order\.orderedIds\)/,+ );+ // Nothing reaches for the Projects list from inside the handler any more.+ const handler = sidebar.slice(+ sidebar.indexOf("function handleProjectSelectionClick("),+ sidebar.indexOf("function selectProjectForContextMenu("),+ );+ assert.ok(!handler.includes("projectRowIds"), "the handler still reads projectRowIds");+});++test("the sidebar and the customizer resolve the row the same way", async () => {+ const sidebar = await readSrcAsync("components/app-sidebar.tsx");+ const customizer = await readSrcAsync(+ "features/settings/components/sidebar-nav-customizer.tsx",+ );+ // Both split their rows with the shared resolver rather than reading `pinned` directly.+ assert.match(+ sidebar,+ /sidebarNavRowPinned\(item, sidebarNavAuto, \{ projectsSectionShowing \}\)/,+ );+ assert.match(sidebar, /\.filter\(\(item\) => !navRowPinned\(item\)\)/);+ assert.match(sidebar, /\.filter\(\(item\) => navRowPinned\(item\)\)/);+ assert.match(customizer, /checked=\{pinned\}/);+ // And the switch records the decision alongside the new placement.+ assert.match(+ customizer,+ /sidebarNavAuto: sidebarNavAutoAfterChoice\(sidebarNavAuto, item\.id\)/,+ );+});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.tsnew file mode 100644index 00000000000..97b46f681a7--- /dev/null+++ b/studio/frontend/tests/sidebar-row-menu-and-pinned-folders.test.ts@@ -0,0 +1,255 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// What a sidebar row gets wrong when the same chat or folder is on screen twice, or when its+// menu is open rather than merely hovered.++import assert from "node:assert/strict";+import test from "node:test";+import {+ useChatNavigationStore,+ visibleChatItems,+} from "../src/features/chat/stores/chat-navigation-store.ts";+import { applyManualOrder } from "../src/features/chat/stores/sidebar-organization-store.ts";+import type { SidebarItem } from "../src/features/chat/hooks/use-chat-sidebar-items.ts";+import { readSrcAsync } from "./helpers/kit.ts";++const APP_SIDEBAR = await readSrcAsync("components/app-sidebar.tsx");++// The open-state gutter rule is more specific than the hover one, so it wins when both match:+// a hovered row with its menu open laid out with the narrower gutter while hover had revealed+// every action. Measured in a browser: the old pr-8 left the title 36px past the secondary+// action's left edge, pr-16 leaves it 4px clear.+test("an open row menu reserves the same gutter hover does", () => {+ const pattern =+ /group-hover\/([a-z-]+):pr-(\d+)[^"]*group-has-\[\.sidebar-row-action\[data-state=open\]\]\/([a-z-]+):pr-(\d+)/g;+ const seen: string[] = [];+ for (const [, hoverGroup, hoverPad, openGroup, openPad] of APP_SIDEBAR.matchAll(+ pattern,+ )) {+ assert.equal(+ hoverGroup,+ openGroup,+ "the hover and open-state gutters are written for different rows",+ );+ assert.equal(+ openPad,+ hoverPad,+ `${openGroup} reserves pr-${hoverPad} on hover but pr-${openPad} with its menu open, so the title runs under the actions`,+ );+ seen.push(`${openGroup}:${openPad}`);+ }+ // Project chat, pinned chat, spinner, plain recents and folder rows.+ assert.ok(seen.length >= 5, `only ${seen.length} rows carry both gutters`);+});++// The kebab reveals itself while its menu is open, but the quick-action beside it was+// hover-only, so it slid in over the title even once the gutter was right.+test("the quick-action beside an open menu is revealed with it", () => {+ for (const group of ["project-chat-item", "recent-item"]) {+ const reveal = new RegExp(+ `group-has-\\[\\.sidebar-row-action\\[data-state=open\\]\\]/${group}:opacity-100 group-has-\\[\\.sidebar-row-action\\[data-state=open\\]\\]/${group}:pointer-events-auto`,+ );+ assert.match(APP_SIDEBAR, reveal, `${group} has no open-menu reveal`);+ }+ // Every secondary action carries it: the pin, the unpin and the folder's New chat.+ const secondaries = APP_SIDEBAR.match(/is-unpin-action/g) ?? [];+ assert.equal(secondaries.length, 3, "a secondary row action came or went");+ assert.equal(+ (APP_SIDEBAR.match(/REVEAL_WITH_OPEN_MENU_(PROJECT_CHAT|RECENT),/g) ?? [])+ .length,+ 3,+ "a secondary row action is not revealed with its row's menu",+ );+});++// A pinned project chat is two rows at once. Both matched on the chat id, so both mounted an+// autofocused input: the second stole focus and the first's blur cancelled the rename.+test("the rename pill belongs to the row its menu was opened from", () => {+ assert.match(+ APP_SIDEBAR,+ /renamingTarget\.item\.id === item\.id &&\n(?:\s*\/\/[^\n]*\n)*\s*renamingTarget\.rowScope === list\?\.scope;/,+ );+ assert.match(+ APP_SIDEBAR,+ /function openRenameChat\(item: SidebarItem, inline = true, rowScope\?: string\)/,+ );+ assert.match(+ APP_SIDEBAR,+ /onSelect=\{\(\) => openRenameChat\(item, true, list\?\.scope\)\}/,+ );+ // The chord has no row under the cursor, so it opens the dialog and names no scope.+ assert.match(APP_SIDEBAR, /openRenameChat\(item, false\)/);+});++// The row toggles its chats, so the folder says which way it is.+test("a folder row's icon follows its disclosure", () => {+ assert.match(APP_SIDEBAR, /icon=\{expanded \? Folder02Icon : Folder01Icon\}/);+});++// An open folder with no chats reads as one that failed to expand, so it says so.+test("an empty open folder says it is empty", () => {+ assert.match(+ APP_SIDEBAR,+ /\{expanded && projectChats\.length === 0 && \(\n\s*<SidebarMenuItem>\n\s*<p className="[^"]*text-nav-fg-muted">\n\s*\{t\("shell\.navigation\.noChats"\)\}/,+ );+ // And it is a row, so the bottom fade has to count it like the "Show more" one.+ 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", () => {+ const sub = APP_SIDEBAR.slice(+ APP_SIDEBAR.indexOf("<span>Project</span>"),+ 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("<DropdownMenuSeparator />");+ 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(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>"));+});++// The folder menu: pin beside Project home, Edit for the dialog that owns the name, and no+// New chat, which the row's own pencil already does.+test("the folder menu leads with where to go, then what to change", async () => {+ const menu = APP_SIDEBAR.slice(+ APP_SIDEBAR.indexOf("<span>Project home</span>"),+ APP_SIDEBAR.indexOf("<span>Delete project</span>"),+ );+ assert.ok(menu.length > 0, "the folder menu moved");+ const pin = menu.indexOf('{isProjectPinned ? "Unpin project" : "Pin project"}');+ const edit = menu.indexOf("<span>Edit</span>");+ assert.notEqual(pin, -1, "Pin project left the folder menu");+ assert.notEqual(edit, -1, "Edit is not in the folder menu");+ assert.ok(pin < edit, "Pin project is not directly under Project home");+ assert.ok(+ !menu.includes("<span>New chat</span>"),+ "New chat is still in the folder menu",+ );+ assert.ok(!APP_SIDEBAR.includes("<span>Rename project</span>"));+ // Edit opens the dialog, and the dialog is mounted with a delete that reuses the confirmation.+ assert.match(APP_SIDEBAR, /onSelect=\{\(\) => setEditingProject\(project\)\}/);+ assert.match(+ APP_SIDEBAR,+ /<EditProjectDialog\n\s*project=\{editingProject\}/,+ );+ assert.match(+ APP_SIDEBAR,+ /onDelete=\{\(project\) => openDeleteDialog\(\{ kind: "project", project \}\)\}/,+ );+ // And the rename dialog no longer carries a project branch nothing can reach.+ assert.ok(!APP_SIDEBAR.includes('renamingTarget?.kind === "project"'));++ const dialog = await readSrcAsync(+ "features/chat/components/edit-project-dialog.tsx",+ );+ // Name, instructions and the linked folders, each writing through its own call.+ assert.match(dialog, /renameChatProject\(target\.id, trimmedName\)/);+ assert.match(+ dialog,+ /updateChatProjectInstructions\(target\.id, trimmedInstructions\)/,+ );+ assert.match(dialog, /scope=\{\{ type: "project", id: project\.id \}\}/);+});++// Pinning a folder used to sort it to the top of Projects, beside a Pinned section of chats.+test("a pinned folder is a row of Pinned, not of Projects", () => {+ // Pinned renders the folders, in the Pinned section's own order scope.+ assert.match(+ APP_SIDEBAR,+ /pinnedProjectRecords\.map\(\(project, projectIndex\) =>\n\s*renderProjectFolderRow\(project, projectIndex, \{\n\s*scope: PINNED_PROJECT_ORDER_SCOPE,\n\s*orderedIds: pinnedProjectRowIds,/,+ );+ // Projects renders what is left, in its own.+ assert.match(+ APP_SIDEBAR,+ /visibleProjectRecords\.map\(\(project, projectIndex\) =>\n\s*renderProjectFolderRow\(project, projectIndex, \{\n\s*scope: PROJECT_ORDER_SCOPE,\n\s*orderedIds: projectRowIds,/,+ );+ // And the Projects list no longer carries them, so a folder is never in both sections.+ const records = APP_SIDEBAR.slice(+ APP_SIDEBAR.indexOf("const sidebarProjectRecords = useMemo("),+ APP_SIDEBAR.indexOf("const visibleProjectRecords"),+ );+ assert.match(records, /\.filter\(\(p\) => !pinnedProjectIdSet\.has\(p\.id\)\)/);+ assert.ok(+ !records.includes("pinnedProjectIds"),+ "the Projects list still folds the pinned folders in",+ );+ // The header owns "New project", so its test counts every project, pinned or not.+ assert.match(+ APP_SIDEBAR,+ /const projectsSectionRendered =\n[\s\S]{0,200}?organizeBy === "project" &&\n\s*projects\.length > 0;/,+ );+ assert.match(APP_SIDEBAR, /\{projectsSectionRendered && \(/);+});++// Moving a folder into Pinned must not undo an order the user had already dragged it into: the+// Pinned scope is empty on the first run, while the Projects one still holds that order.+test("a pinned folder keeps the order it was dragged into", () => {+ const projects = [{ id: "a" }, { id: "b" }, { id: "c" }];+ const byId = new Map(projects.map((p) => [p.id, p]));+ // Pinned b first, so pin order alone would draw b above a.+ const pinned = ["b", "a"].map((id) => byId.get(id)!);+ const draggedInProjects = ["c", "a", "b"];+ const order = (pinnedScope: string[] | undefined) =>+ applyManualOrder(+ pinned,+ pinnedScope?.length ? pinnedScope : draggedInProjects,+ (project) => project.id,+ ).map((project) => project.id);+ assert.deepEqual(order(undefined), ["a", "b"]);+ // And a drop in Pinned takes over from then on.+ assert.deepEqual(order(["b", "a"]), ["b", "a"]);+ assert.match(+ APP_SIDEBAR,+ /manualOrder\[PINNED_PROJECT_ORDER_SCOPE\]\?\.length\n\s*\? manualOrder\[PINNED_PROJECT_ORDER_SCOPE\]\n\s*: manualOrder\[PROJECT_ORDER_SCOPE\],/,+ );+});++// Pinned draws its folders above its chats, and the chords walk what the store was handed.+test("the walk reads the rows in the order Pinned draws them", () => {+ const item = (id: string): SidebarItem => ({+ type: "single",+ id,+ title: id,+ createdAt: 0,+ updatedAt: 0,+ });+ const folderChats = [item("folder-1"), item("folder-2")];+ // folder-2 is pinned as well as being in a pinned folder, so it is drawn twice.+ const pinnedChats = [item("pin-1"), item("folder-2")];+ useChatNavigationStore.getState().publishLists({+ pinnedItems: [...folderChats, ...pinnedChats],+ projectItems: [item("proj-1")],+ recentItems: [item("recent-1")],+ attentionItemIds: [],+ activeItemId: null,+ });+ assert.deepEqual(+ visibleChatItems(useChatNavigationStore.getState()).map((i) => i.id),+ ["folder-1", "folder-2", "pin-1", "proj-1", "recent-1"],+ );+ // The sidebar publishes that block whole, and leaves the section's own chats to projectItems.+ assert.match(+ APP_SIDEBAR,+ /const pinnedSectionChatItems = useMemo\(\n\s*\(\) => \[\.\.\.pinnedProjectChatItems, \.\.\.visiblePinnedItems\],/,+ );+ assert.match(+ APP_SIDEBAR,+ /pinnedItems: pinnedSectionChatItems,\n\s*projectItems: sectionProjectChatItems,/,+ );+});diff --git a/studio/frontend/tests/sidebar-selection-coverage.test.ts b/studio/frontend/tests/sidebar-selection-coverage.test.tsindex 7beb10121de..4a871a4e511 100644--- a/studio/frontend/tests/sidebar-selection-coverage.test.ts+++ b/studio/frontend/tests/sidebar-selection-coverage.test.ts@@ -25,7 +25,11 @@ test("every chat list hands its rows a selection list", async () => {test("folder rows select too, and open their own bulk menu", async () => {const source = APP_SIDEBAR;- assert.match(source, /handleProjectSelectionClick\(event, project\.id\)/);+ // The row hands in its own list: Pinned holds folders too, with ids of its own.+ assert.match(+ source,+ /handleProjectSelectionClick\(event, project\.id, order\.orderedIds\)/,+ );assert.match(source, /selectProjectForContextMenu\(project\.id\)/);assert.match(source, /\{renderProjectContextMenu\(\)\}/);assert.match(source, /selectedProjectIds\.has\(project\.id\)/);