Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📌 feat: Unified Pinned Section With Sidebar Drag Interactions (#15057)

Marco Berettae75835e32788
diff --git a/api/server/routes/settings.js b/api/server/routes/settings.js
index 38b353d560..dd36144cb9 100644
--- a/api/server/routes/settings.js
+++ b/api/server/routes/settings.js
@@ -1,5 +1,10 @@
const express = require('express');
-const { createToolFavoritesHandlers } = require('@librechat/api');
+const { CacheKeys } = require('librechat-data-provider');
+const {
+ createToolFavoritesHandlers,
+ createPinnedOrderHandlers,
+ invalidateCachedAuthUserDoc,
+} = require('@librechat/api');
const {
updateFavoritesController,
getFavoritesController,
@@ -9,7 +14,14 @@ const {
updateSkillStatesController,
} = require('~/server/controllers/SkillStatesController');
const { requireJwtAuth } = require('~/server/middleware');
-const { getToolFavorites, addToolFavorite, removeToolFavorite } = require('~/models');
+const { getLogStores } = require('~/cache');
+const {
+ getToolFavorites,
+ addToolFavorite,
+ removeToolFavorite,
+ getUserById,
+ updateUser,
+} = require('~/models');
const router = express.Router();
@@ -19,6 +31,14 @@ const toolFavorites = createToolFavoritesHandlers({
removeToolFavorite,
});
+const authUserDocCacheStore = getLogStores(CacheKeys.AUTH_USER_DOC);
+const pinnedOrder = createPinnedOrderHandlers({
+ getUserById,
+ updateUser,
+ invalidateCachedAuthUserDoc: (userId) =>
+ invalidateCachedAuthUserDoc(authUserDocCacheStore, { userId }),
+});
+
router.get('/favorites/tools', requireJwtAuth, toolFavorites.listToolFavorites);
router.put('/favorites/tools/:itemType/:itemId', requireJwtAuth, toolFavorites.addToolFavorite);
router.delete(
@@ -28,6 +48,8 @@ router.delete(
);
router.get('/favorites', requireJwtAuth, getFavoritesController);
router.post('/favorites', requireJwtAuth, updateFavoritesController);
+router.get('/pinned-order', requireJwtAuth, pinnedOrder.getPinnedOrder);
+router.post('/pinned-order', requireJwtAuth, pinnedOrder.updatePinnedOrder);
router.get('/skills/active', requireJwtAuth, getSkillStatesController);
router.post('/skills/active', requireJwtAuth, updateSkillStatesController);
diff --git a/client/src/components/Conversations/Conversations.tsx b/client/src/components/Conversations/Conversations.tsx
index ff0a0879b0..c6feda3b87 100644
--- a/client/src/components/Conversations/Conversations.tsx
+++ b/client/src/components/Conversations/Conversations.tsx
@@ -1,19 +1,20 @@
import { useMemo, memo, type FC, useCallback, useEffect, useRef } from 'react';
+import { useDrop } from 'react-dnd';
import throttle from 'lodash/throttle';
import { useRecoilValue } from 'recoil';
import { ChevronDown } from 'lucide-react';
-import { Spinner, useMediaQuery } from '@librechat/client';
import { List, CellMeasurer, CellMeasurerCache } from 'react-virtualized';
+import { Spinner, useMediaQuery, buttonVariants } from '@librechat/client';
import type { TConversation } from 'librechat-data-provider';
import type { ReactNode } from 'react';
+import type { ConversationDragItem } from './dnd';
import {
- useLocalize,
- TranslationKeys,
- useFavorites,
- useShowMarketplace,
- useElementSize,
-} from '~/hooks';
-import FavoritesList from '~/components/Nav/Favorites/FavoritesList';
+ CONVERSATION_DRAG_TYPE,
+ markExternalHover,
+ useAssignDroppedConversation,
+ useEffectiveProjectId,
+} from './dnd';
+import { useLocalize, TranslationKeys, useElementSize } from '~/hooks';
import { groupConversationsByDate, cn } from '~/utils';
import { useActiveJobs } from '~/data-provider';
import Convo from './Convo';
@@ -39,7 +40,6 @@ interface ConversationsProps {
isSearchLoading: boolean;
isChatsExpanded: boolean;
setIsChatsExpanded: (expanded: boolean) => void;
- showFavorites?: boolean;
/** Actions for the Chats header, alongside the Projects header's own. */
chatsHeaderTrailing?: ReactNode;
}
@@ -94,17 +94,24 @@ interface ChatsHeaderProps {
onToggle: () => void;
/** Section-scoped actions, mirroring the Projects header. */
trailing?: ReactNode;
+ /** Drop-target affordance while a project conversation is dragged over the section. */
+ highlight?: boolean;
}
/** Collapsible header for the Chats section */
-const ChatsHeader: FC<ChatsHeaderProps> = memo(({ isExpanded, onToggle, trailing }) => {
+const ChatsHeader: FC<ChatsHeaderProps> = memo(({ isExpanded, onToggle, trailing, highlight }) => {
const localize = useLocalize();
return (
- <div className="flex h-8 w-full items-center pr-2">
+ <div
+ className={cn(
+ 'flex h-8 w-full items-center pr-2',
+ highlight && 'rounded-lg bg-surface-active-alt',
+ )}
+ >
<button
onClick={onToggle}
- className="group flex min-w-0 flex-1 items-center gap-1 rounded-lg px-1 py-2 text-xs font-bold text-text-secondary outline-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary"
+ className={cn(buttonVariants({ variant: 'section-header' }), 'group min-w-0 flex-1')}
type="button"
aria-expanded={isExpanded}
>
@@ -142,7 +149,6 @@ const DateLabel: FC<{ groupName: string; isFirst?: boolean }> = memo(({ groupNam
DateLabel.displayName = 'DateLabel';
type FlattenedItem =
- | { type: 'favorites' }
| { type: 'header'; groupName: string }
| { type: 'convo'; convo: TConversation }
| { type: 'loading' };
@@ -157,23 +163,37 @@ const Conversations: FC<ConversationsProps> = ({
isSearchLoading,
isChatsExpanded,
setIsChatsExpanded,
- showFavorites = true,
chatsHeaderTrailing,
}) => {
const localize = useLocalize();
const search = useRecoilValue(store.search);
- const { favorites, isLoading: isFavoritesLoading } = useFavorites();
const isSmallScreen = useMediaQuery('(max-width: 768px)');
+ /* Dropping a project conversation on the Chats section files it back out of
+ * its project. Root-list chats already live here, so they are rejected. */
+ const assignDropped = useAssignDroppedConversation();
+ const effectiveProjectId = useEffectiveProjectId();
+ const chatsRegionRef = useRef<HTMLDivElement>(null);
+ const [{ isDropOver, canDrop }, dropRef] = useDrop<
+ ConversationDragItem,
+ unknown,
+ { isDropOver: boolean; canDrop: boolean }
+ >({
+ accept: CONVERSATION_DRAG_TYPE,
+ canDrop: (item) => effectiveProjectId(item) != null,
+ /* Reported even when refused, so a root chat dropped back on Chats does not
+ * save the shift its pointer caused on the way out of the pinned list. */
+ hover: () => markExternalHover(),
+ drop: (item) => assignDropped(item, null),
+ collect: (monitor) => ({ isDropOver: monitor.isOver(), canDrop: monitor.canDrop() }),
+ });
+ dropRef(chatsRegionRef);
const convoHeight = isSmallScreen ? 44 : 34;
- const showAgentMarketplace = useShowMarketplace();
const {
ref: listContainerRef,
width: listWidth,
height: listHeight,
} = useElementSize<HTMLDivElement>();
- const favoritesContentKeyRef = useRef('');
-
// Fetch active job IDs for showing generation indicators
const { data: activeJobsData } = useActiveJobs();
const activeJobIds = useMemo(
@@ -181,14 +201,6 @@ const Conversations: FC<ConversationsProps> = ({
[activeJobsData?.activeJobIds],
);
- // Determine if FavoritesList will render content
- const shouldShowFavorites =
- showFavorites &&
- !search.query &&
- (isFavoritesLoading || favorites.length > 0 || showAgentMarketplace);
-
- favoritesContentKeyRef.current = `${favorites.length}-${showAgentMarketplace ? 1 : 0}-${isFavoritesLoading ? 1 : 0}`;
-
const filteredConversations = useMemo(
() => rawConversations.filter(Boolean) as TConversation[],
[rawConversations],
@@ -205,6 +217,18 @@ const Conversations: FC<ConversationsProps> = ({
conversations input actually changes; a failed fetchNextPage leaves
the same array and must not loop. */
const paginatedFromRef = useRef<Array<TConversation | null> | null>(null);
+
+ /* A drain that exhausted its retries leaves that array unchanged, so the
+ guard above would bar every later attempt and the remaining chats would
+ stay unreachable for the rest of the session. Collapsing the section is a
+ deliberate act, so reopening it is allowed to try once more, which is a
+ retry path rather than a loop. */
+ useEffect(() => {
+ if (!isChatsExpanded) {
+ paginatedFromRef.current = null;
+ }
+ }, [isChatsExpanded]);
+
useEffect(() => {
if (!isChatsExpanded || isLoading || isSearchLoading || groupedConversations.length > 0) {
return;
@@ -225,11 +249,6 @@ const Conversations: FC<ConversationsProps> = ({
const flattenedItems = useMemo(() => {
const items: FlattenedItem[] = [];
- // Only include favorites row if FavoritesList will render content
- if (shouldShowFavorites) {
- items.push({ type: 'favorites' });
- }
-
if (isChatsExpanded) {
groupedConversations.forEach(([groupName, convos]) => {
items.push({ type: 'header', groupName });
@@ -241,7 +260,7 @@ const Conversations: FC<ConversationsProps> = ({
}
}
return items;
- }, [groupedConversations, isLoading, isChatsExpanded, shouldShowFavorites]);
+ }, [groupedConversations, isLoading, isChatsExpanded]);
// Store flattenedItems in a ref for keyMapper to access without recreating cache
const flattenedItemsRef = useRef(flattenedItems);
@@ -258,12 +277,8 @@ const Conversations: FC<ConversationsProps> = ({
if (!item) {
return `unknown-${index}`;
}
- if (item.type === 'favorites') {
- return `favorites-${favoritesContentKeyRef.current}`;
- }
if (item.type === 'header') {
- const firstHeaderIndex = flattenedItemsRef.current[0]?.type === 'favorites' ? 1 : 0;
- return `header-${item.groupName}-${index === firstHeaderIndex ? 'first' : 'sub'}`;
+ return `header-${item.groupName}-${index === 0 ? 'first' : 'sub'}`;
}
if (item.type === 'convo') {
return `convo-${item.convo.conversationId}`;
@@ -277,22 +292,6 @@ const Conversations: FC<ConversationsProps> = ({
[convoHeight],
);
- const clearFavoritesCache = useCallback(() => {
- if (cache) {
- cache.clear(0, 0);
- if (containerRef.current && 'recomputeRowHeights' in containerRef.current) {
- containerRef.current.recomputeRowHeights(0);
- }
- }
- }, [cache, containerRef]);
-
- useEffect(() => {
- const frameId = requestAnimationFrame(() => {
- clearFavoritesCache();
- });
- return () => cancelAnimationFrame(frameId);
- }, [favorites.length, isFavoritesLoading, showAgentMarketplace, clearFavoritesCache]);
-
useEffect(() => {
const frameId = requestAnimationFrame(() => {
cache.clearAll();
@@ -345,19 +344,10 @@ const Conversations: FC<ConversationsProps> = ({
);
}
- if (item.type === 'favorites') {
- return (
- <MeasuredRow key={key} {...rowProps}>
- <FavoritesList isSmallScreen={isSmallScreen} toggleNav={toggleNav} />
- </MeasuredRow>
- );
- }
-
if (item.type === 'header') {
- const firstHeaderIndex = flattenedItems[0]?.type === 'favorites' ? 1 : 0;
return (
<MeasuredRow key={key} {...rowProps}>
- <DateLabel groupName={item.groupName} isFirst={index === firstHeaderIndex} />
+ <DateLabel groupName={item.groupName} isFirst={index === 0} />
</MeasuredRow>
);
}
@@ -371,6 +361,7 @@ const Conversations: FC<ConversationsProps> = ({
retainView={moveToTop}
toggleNav={toggleNav}
isGenerating={isGenerating}
+ draggable
/>
</MeasuredRow>
);
@@ -378,7 +369,7 @@ const Conversations: FC<ConversationsProps> = ({
return null;
},
- [cache, flattenedItems, moveToTop, toggleNav, isSmallScreen, activeJobIds],
+ [cache, flattenedItems, moveToTop, toggleNav, activeJobIds],
);
const getRowHeight = useCallback(
@@ -401,12 +392,16 @@ const Conversations: FC<ConversationsProps> = ({
);
return (
- <div className="relative flex h-full min-h-0 flex-col pb-2 text-sm text-text-primary">
+ <div
+ ref={chatsRegionRef}
+ className="relative flex h-full min-h-0 flex-col pb-2 text-sm text-text-primary"
+ >
<div className="px-3">
<ChatsHeader
isExpanded={isChatsExpanded}
onToggle={() => setIsChatsExpanded(!isChatsExpanded)}
trailing={chatsHeaderTrailing}
+ highlight={isDropOver && canDrop}
/>
</div>
{isSearchLoading ? (
diff --git a/client/src/components/Conversations/Convo.tsx b/client/src/components/Conversations/Convo.tsx
index fc92d4a6e3..59329f9ae3 100644
--- a/client/src/components/Conversations/Convo.tsx
+++ b/client/src/components/Conversations/Convo.tsx
@@ -1,16 +1,24 @@
import React, { memo, useState, useEffect, useRef, useMemo, useCallback } from 'react';
+import { useDrag } from 'react-dnd';
import { useRecoilValue } from 'recoil';
-import { Link2, Pin } from 'lucide-react';
+import { Link2, PinOff } from 'lucide-react';
import { useParams } from 'react-router-dom';
import { Constants } from 'librechat-data-provider';
-import { Spinner, useToastContext, useMediaQuery } from '@librechat/client';
+import { Button, Spinner, TooltipAnchor, useToastContext, useMediaQuery } from '@librechat/client';
import type { TConversation } from 'librechat-data-provider';
-import { useGetStartupConfig, useUpdateConversationMutation } from '~/data-provider';
+import type { ConversationDragItem } from './dnd';
+import {
+ useGetStartupConfig,
+ usePinConversationMutation,
+ useUpdateConversationMutation,
+} from '~/data-provider';
import { useNavigateToConvo, useLocalize, useShiftKey } from '~/hooks';
import ConversationEndpointIcon from './ConversationEndpointIcon';
+import { focusableInRow, resolveRowBeside } from './focus';
import { areConversationRenderPropsEqual } from './utils';
import { cn, logger, setDocumentTitle } from '~/utils';
import { NotificationSeverity } from '~/common';
+import { CONVERSATION_DRAG_TYPE } from './dnd';
import ConvoActions from './ConvoActions';
import RenameForm from './RenameForm';
import ConvoLink from './ConvoLink';
@@ -21,6 +29,15 @@ interface ConversationProps {
retainView: () => void;
toggleNav: (afterSlide?: () => void) => void;
isGenerating?: boolean;
+ /** Sidebar rows double as drag sources for filing the chat into a project;
+ * other surfaces leave this off. */
+ draggable?: boolean;
+ /** Lets a wrapper that owns its own drag source release it while the title is
+ * being edited, the way this row releases its own. */
+ onRenamingChange?: (renaming: boolean) => void;
+ /** Shortcuts an owning list handles for this row, declared on its focusable
+ * element so they are announced rather than left to be discovered. */
+ keyShortcuts?: string;
}
function Conversation({
@@ -28,6 +45,9 @@ function Conversation({
retainView,
toggleNav,
isGenerating = false,
+ draggable = false,
+ onRenamingChange,
+ keyShortcuts,
}: ConversationProps) {
const params = useParams();
const localize = useLocalize();
@@ -35,6 +55,7 @@ function Conversation({
const { navigateToConvo } = useNavigateToConvo();
const currentConvoId = useMemo(() => params.conversationId, [params.conversationId]);
const updateConvoMutation = useUpdateConversationMutation(currentConvoId ?? '');
+ const unpinMutation = usePinConversationMutation();
const activeConvos = useRecoilValue(store.allConversationsSelector);
const isSmallScreen = useMediaQuery('(max-width: 768px)');
/* A deployment with shared links off leaves existing links in the database but stops
@@ -46,7 +67,7 @@ function Conversation({
const { conversationId, title = '' } = conversation;
const [titleInput, setTitleInput] = useState(title || '');
- const [renaming, setRenaming] = useState(false);
+ const [renaming, setRenamingState] = useState(false);
const [isPopoverActive, setIsPopoverActive] = useState(false);
const [isHovered, setIsHovered] = useState(false);
// Lazy-load ConvoOptions to avoid running heavy hooks for all conversations
@@ -55,6 +76,41 @@ function Conversation({
const previousTitle = useRef(title);
const containerRef = useRef<HTMLDivElement>(null);
+ const onRenamingChangeRef = useRef(onRenamingChange);
+ onRenamingChangeRef.current = onRenamingChange;
+
+ const setRenaming = useCallback((next: boolean) => {
+ setRenamingState(next);
+ onRenamingChangeRef.current?.(next);
+ }, []);
+
+ /* A row can be removed mid-rename, for instance by unpinning the same chat
+ * from the project list that renders it too. Without this the owner would
+ * keep treating the row as renaming and, once it came back, leave its drag
+ * source released for the rest of the section's life. */
+ useEffect(
+ () => () => {
+ onRenamingChangeRef.current?.(false);
+ },
+ [],
+ );
+
+ /* HTML5 drag needs a hover-capable pointer: connecting the source on touch
+ * stamps `draggable="true"` on the row, and iOS Safari then hands taps to the
+ * drag recognizer instead of synthesizing a click, so the row would only
+ * select on the second tap. A `draggable` ancestor also swallows drag-select
+ * inside the rename input, so the source is released while renaming. */
+ const canHoverPointer = useMediaQuery('(hover: hover)');
+ const [, dragConnector] = useDrag<ConversationDragItem, unknown, unknown>({
+ type: CONVERSATION_DRAG_TYPE,
+ item: () => ({
+ conversationId: conversationId ?? '',
+ chatProjectId: conversation.chatProjectId ?? null,
+ pinned: conversation.pinned === true,
+ }),
+ });
+ dragConnector(draggable && canHoverPointer && !renaming ? containerRef : null);
+
useEffect(() => {
if (title !== previousTitle.current) {
setTitleInput(title as string);
@@ -116,6 +172,47 @@ function Conversation({
}
}, [hasInteracted]);
+ /* Matches the favorites' row-level unpin: one click on the pin badge, no
+ * menu digging. The row unmounts once the pinned refetch lands, so focus is
+ * handed to a neighbouring row first. Where that row is has to be resolved
+ * before the mutation, not in its callback: by then the refetch may already
+ * have unmounted this row and cleared the ref the search starts from. */
+ const unpinConvo = useCallback(() => {
+ if (!conversationId) {
+ return;
+ }
+ const row = containerRef.current;
+ /* Outside the pinned list there is no successor, because the row stays put.
+ * The pin badge that had focus does not, though, so focus moves to the
+ * row's own link rather than falling to the document. */
+ const successor =
+ row?.contains(document.activeElement) === true
+ ? (resolveRowBeside(row) ?? focusableInRow(row))
+ : null;
+ unpinMutation.mutate(
+ { conversationId, pinned: false },
+ {
+ onSuccess: () => {
+ const activeElement = document.activeElement;
+ const focusInRow = row?.contains(activeElement) === true;
+ const rowRemovedFocus =
+ row?.isConnected === false &&
+ (activeElement === document.body || activeElement === document.documentElement);
+ if (successor?.isConnected && (focusInRow || rowRemovedFocus)) {
+ successor.focus();
+ }
+ },
+ onError: () => {
+ showToast({
+ message: localize('com_ui_unpin_error'),
+ severity: NotificationSeverity.ERROR,
+ showIcon: true,
+ });
+ },
+ },
+ );
+ }, [conversationId, unpinMutation, showToast, localize]);
+
const handleMouseLeave = useCallback(() => {
if (!isPopoverActive) {
setHasInteracted(false);
@@ -263,6 +360,7 @@ function Conversation({
onRename={handleRename}
isSmallScreen={isSmallScreen}
localize={localize}
+ keyShortcuts={keyShortcuts}
>
<ConversationEndpointIcon conversation={conversation} size={20} context="menu-item" />
</ConvoLink>
@@ -271,7 +369,25 @@ function Conversation({
<Link2 className="icon-sm mr-1 shrink-0 text-text-secondary" aria-hidden="true" />
)}
{conversation.pinned === true && (
- <Pin className="icon-sm mr-1 shrink-0 text-text-primary" aria-hidden="true" />
+ <TooltipAnchor
+ description={localize('com_ui_unpin')}
+ side="top"
+ render={
+ <Button
+ variant="row-action"
+ size="icon-xs"
+ aria-label={localize('com_ui_unpin')}
+ data-testid="convo-unpin-button"
+ onClick={(e) => {
+ e.stopPropagation();
+ unpinConvo();
+ }}
+ className="mr-1 shrink-0 text-text-primary"
+ >
+ <PinOff className="size-4" aria-hidden="true" />
+ </Button>
+ }
+ />
)}
<div
className={cn(
diff --git a/client/src/components/Conversations/ConvoLink.tsx b/client/src/components/Conversations/ConvoLink.tsx
index cad28376f3..17fdd0a5e3 100644
--- a/client/src/components/Conversations/ConvoLink.tsx
+++ b/client/src/components/Conversations/ConvoLink.tsx
@@ -12,6 +12,9 @@ interface ConvoLinkProps {
onRename: () => void;
isSmallScreen: boolean;
localize: (key: TranslationKeys, options?: TOptions) => string;
+ /** Shortcuts the row responds to, declared on the element that takes focus so
+ * assistive tech announces them when the user arrives here. */
+ keyShortcuts?: string;
children: React.ReactNode;
}
@@ -39,6 +42,7 @@ const ConvoLink: React.FC<ConvoLinkProps> = ({
onRename,
isSmallScreen,
localize,
+ keyShortcuts,
children,
}) => {
const [isOverflowing, setIsOverflowing] = useState(false);
@@ -126,6 +130,7 @@ const ConvoLink: React.FC<ConvoLinkProps> = ({
isActiveConvo || isPopoverActive ? 'bg-surface-active-alt' : '',
)}
aria-current={isActiveConvo ? 'page' : undefined}
+ aria-keyshortcuts={keyShortcuts}
aria-label={
isSharedBadgeVisible
? localize('com_ui_conversation_label_shared', {
diff --git a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
index 7781367d20..fce713aaa8 100644
--- a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
+++ b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
@@ -3,7 +3,6 @@ import * as Ariakit from '@ariakit/react';
import { useQueryClient } from '@tanstack/react-query';
import { useParams, useNavigate } from 'react-router-dom';
import { QueryKeys, PermissionTypes, Permissions } from 'librechat-data-provider';
-import { DropdownPopup, Spinner, useToastContext, useMediaQuery } from '@librechat/client';
import {
Ellipsis,
Share2,
@@ -15,6 +14,13 @@ import {
Pin,
Trash,
} from 'lucide-react';
+import {
+ DropdownPopup,
+ Spinner,
+ buttonVariants,
+ useToastContext,
+ useMediaQuery,
+} from '@librechat/client';
import type { TMessage } from 'librechat-data-provider';
import type { MouseEvent } from 'react';
import {
@@ -367,7 +373,10 @@ function ConvoOptions({
);
const buttonClassName = cn(
- 'inline-flex h-7 w-7 items-center justify-center rounded-md border-none p-0 text-sm font-medium ring-ring-primary transition-all duration-200 ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:opacity-50',
+ /** The same shared row action the unpin badge beside it uses, rather than a
+ * second copy of that recipe. */
+ buttonVariants({ variant: 'row-action', size: 'icon-xs' }),
+ 'text-text-secondary',
/** Touch has no hover, so a reveal-on-hover trigger is simply invisible there. */
isActiveConvo === true || isPopoverActive || isSmallScreen
? 'opacity-100'
@@ -433,7 +442,13 @@ function ConvoOptions({
aria-label={localize('com_nav_convo_menu_options')}
aria-expanded={isPopoverActive}
/** Shared with the shift-held variant so both obey the same reveal rules. */
- className={cn(buttonClassName, 'gap-2')}
+ className={cn(
+ buttonClassName,
+ 'gap-2',
+ /** The hover fill persists while the menu is open, even once the
+ * pointer moves into the dropdown. */
+ isPopoverActive && 'bg-surface-active text-text-primary',
+ )}
onClick={(e: MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
}}
@@ -443,7 +458,7 @@ function ConvoOptions({
}
}}
>
- <Ellipsis className="icon-md text-text-secondary" aria-hidden={true} />
+ <Ellipsis className="icon-md" aria-hidden={true} />
</Ariakit.MenuButton>
}
items={dropdownItems}
diff --git a/client/src/components/Conversations/PinnedSection.tsx b/client/src/components/Conversations/PinnedSection.tsx
index 0bdcb95f69..e4d7563b72 100644
--- a/client/src/components/Conversations/PinnedSection.tsx
+++ b/client/src/components/Conversations/PinnedSection.tsx
@@ -1,42 +1,695 @@
-import { memo, useMemo } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ChevronDown } from 'lucide-react';
-import type { TConversation } from 'librechat-data-provider';
+import { useDrag, useDragLayer, useDrop } from 'react-dnd';
+import { Skeleton, useMediaQuery, useToastContext, buttonVariants } from '@librechat/client';
+import type { TConversation, TEndpointsConfig } from 'librechat-data-provider';
+import type {
+ SelectEndpointHandler,
+ SelectSpecHandler,
+} from '~/components/Nav/Favorites/useFavoritesData';
+import type { ConversationDragItem } from './dnd';
+import type { Favorite } from '~/store/favorites';
+import {
+ CONVERSATION_DRAG_TYPE,
+ beginPinnedDrag,
+ endedOverExternalTarget,
+ markPinnedHover,
+ mergeVisibleOrder,
+ shouldSwapOnHover,
+} from './dnd';
+import {
+ useActiveJobs,
+ useGetPinnedOrderQuery,
+ usePinConversationMutation,
+ useUpdatePinnedOrderMutation,
+} from '~/data-provider';
+import useFavoritesData from '~/components/Nav/Favorites/useFavoritesData';
+import FavoriteItem from '~/components/Nav/Favorites/FavoriteItem';
import { useLocalize, useLocalStorage } from '~/hooks';
-import { useActiveJobs } from '~/data-provider';
+import { getSpecAgentAvatarURL, cn } from '~/utils';
+import { NotificationSeverity } from '~/common';
import { Collapse } from '~/components/ui';
-import { cn } from '~/utils';
+import { focusFirstRow } from './focus';
import Convo from './Convo';
+const FAVORITE_ROW_DRAG_TYPE = 'favorite-item';
+
+/** Declared on each row's focus target: a screen-reader user tabbing straight
+ * to a row would otherwise never meet the section's written hint, leaving the
+ * only non-pointer way to reorder undiscoverable. */
+const REORDER_SHORTCUTS = 'Alt+ArrowUp Alt+ArrowDown';
+/** A pinned row accepts both: favorites reorder here only, while a dragged
+ * conversation reorders here but can also be dropped on a project row or the
+ * Chats section to be filed or unfiled. */
+const PINNED_ROW_ACCEPTS = [CONVERSATION_DRAG_TYPE, FAVORITE_ROW_DRAG_TYPE];
+
const noop = () => {};
+/** A key identifies a row everywhere in this section, so the encoding has to be
+ * injective. The favorites API accepts any string for an endpoint or a model,
+ * so a plain `endpoint::model` join collides: `a::b` + `c` and `a` + `b::c`
+ * both read back as `a::b::c`, and the dedupe below would then hide one of two
+ * distinct favorites. Length-prefixing the endpoint makes the split exact. */
+export const favoriteEntryKey = (favorite: Favorite): string => {
+ if (favorite.agentId) {
+ return `agent:${favorite.agentId}`;
+ }
+ if (favorite.spec) {
+ return `spec:${favorite.spec}`;
+ }
+ const endpoint = favorite.endpoint ?? '';
+ return `model:${endpoint.length}:${endpoint}:${favorite.model ?? ''}`;
+};
+
+const convoEntryKey = (conversationId: string): string => `convo:${conversationId}`;
+
+type PinnedEntry =
+ | { key: string; kind: 'favorite'; favorite: Favorite }
+ | { key: string; kind: 'convo'; conversationId: string };
+
+type PinnedRowDragItem = ConversationDragItem & { key: string };
+
+/** Mirrors a favorite row (h-9, icon, title) so the loading swap keeps height. */
+const FavoriteRowSkeleton = () => (
+ <div className="flex w-full items-center rounded-lg p-2" aria-hidden="true">
+ <Skeleton className="mr-2 h-5 w-5 rounded-full" />
+ <Skeleton className="h-4 w-24" />
+ </div>
+);
+
+interface DraggablePinnedRowProps {
+ entry: PinnedEntry;
+ conversation?: TConversation;
+ indexOfKey: (key: string) => number;
+ moveEntry: (dragKey: string, hoverKey: string) => void;
+ moveEntryBy: (key: string, delta: number) => void;
+ onDrop: (handledElsewhere: boolean) => void;
+ /** Released while the row's title is being edited, so a drag-select inside
+ * the rename input is not swallowed by the drag source. */
+ canDrag?: boolean;
+ children: React.ReactNode;
+}
+
+/** Hover-reorder wrapper for the unified pinned list, following the favorites
+ * pattern: rows shift as the drag passes them and the order commits on drop.
+ * Touch pointers are excluded, matching every other drag source here, so the
+ * Alt+Arrow shortcut below is the only way to reorder without a mouse. */
+const DraggablePinnedRow = ({
+ entry,
+ conversation,
+ indexOfKey,
+ moveEntry,
+ moveEntryBy,
+ onDrop,
+ canDrag = true,
+ children,
+}: DraggablePinnedRowProps) => {
+ const ref = useRef<HTMLDivElement>(null);
+ const hasHoverPointer = useMediaQuery('(hover: hover)');
+ const [{ handlerId }, drop] = useDrop<PinnedRowDragItem, unknown, { handlerId: unknown }>({
+ accept: PINNED_ROW_ACCEPTS,
+ collect(monitor) {
+ return { handlerId: monitor.getHandlerId() };
+ },
+ hover(item, monitor) {
+ /* Recorded before any of the guards below, including the one for hovering
+ * the dragged row itself. Returning early there would leave an earlier
+ * external hover standing, and a drag that wandered onto a project and
+ * came back to its own position would be discarded as a filing action. */
+ markPinnedHover();
+ if (!item.key || item.key === entry.key || !ref.current) {
+ return;
+ }
+ const clientOffset = monitor.getClientOffset();
+ if (!clientOffset) {
+ return;
+ }
+ const rect = ref.current.getBoundingClientRect();
+ const swap = shouldSwapOnHover({
+ dragIndex: indexOfKey(item.key),
+ hoverIndex: indexOfKey(entry.key),
+ pointerY: clientOffset.y,
+ hoverTop: rect.top,
+ hoverBottom: rect.bottom,
+ });
+ if (!swap) {
+ return;
+ }
+ moveEntry(item.key, entry.key);
+ },
+ });
+
+ const [{ isDragging }, drag] = useDrag<PinnedRowDragItem, unknown, { isDragging: boolean }>({
+ type: entry.kind === 'convo' ? CONVERSATION_DRAG_TYPE : FAVORITE_ROW_DRAG_TYPE,
+ item: (): PinnedRowDragItem => {
+ beginPinnedDrag();
+ return entry.kind === 'convo'
+ ? {
+ key: entry.key,
+ conversationId: entry.conversationId,
+ chatProjectId: conversation?.chatProjectId ?? null,
+ pinned: conversation?.pinned === true,
+ }
+ : { key: entry.key, conversationId: '', chatProjectId: null, pinned: false };
+ },
+ collect: (monitor) => ({ isDragging: monitor.isDragging() }),
+ /* Rows carry no drop handler of their own, so an unhandled drop usually
+ * means a reorder. A refused external target also reports none, though, so
+ * the last thing under the pointer settles it. */
+ end: (_item, monitor) => {
+ onDrop(monitor.didDrop() || endedOverExternalTarget());
+ },
+ });
+
+ drop(ref);
+ drag(hasHoverPointer && canDrag ? ref : null);
+
+ /* Keyboard equivalent of the drag: the shortcut is caught as it bubbles from
+ * whichever element inside the row holds focus, so the row keeps that focus
+ * across the move. It obeys the same gate as the pointer drag, which also
+ * keeps Alt/Option+Arrow doing its usual word-wise caret movement inside an
+ * open rename input rather than moving the row out from under it. */
+ const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (!canDrag) {
+ return;
+ }
+ if (!event.altKey || event.ctrlKey || event.metaKey) {
+ return;
+ }
+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ moveEntryBy(entry.key, event.key === 'ArrowUp' ? -1 : 1);
+ };
+
+ return (
+ <div
+ ref={ref}
+ style={{ opacity: isDragging ? 0 : 1 }}
+ data-handler-id={handlerId}
+ onKeyDown={handleKeyDown}
+ >
+ {children}
+ </div>
+ );
+};
+
+interface FavoriteRowProps {
+ favorite: Favorite;
+ agentsMap: ReturnType<typeof useFavoritesData>['agentsMap'];
+ specsMap: ReturnType<typeof useFavoritesData>['specsMap'];
+ endpointsConfig: TEndpointsConfig;
+ isAgentsLoading: boolean;
+ onSelectEndpoint: SelectEndpointHandler;
+ onSelectSpec: SelectSpecHandler;
+ onRemoveFocus: () => void;
+ keyShortcuts?: string;
+}
+
+/** One favorite rendered for the unified list; skeleton while its agent is
+ * still resolving, nothing if the agent or spec is gone (cleanup handles the
+ * latter asynchronously). */
+const FavoriteRow = ({
+ favorite,
+ agentsMap,
+ specsMap,
+ endpointsConfig,
+ isAgentsLoading,
+ onSelectEndpoint,
+ onSelectSpec,
+ onRemoveFocus,
+ keyShortcuts,
+}: FavoriteRowProps) => {
+ if (favorite.agentId) {
+ const agent = agentsMap[favorite.agentId];
+ if (!agent) {
+ if (isAgentsLoading) {
+ return <FavoriteRowSkeleton />;
+ }
+ return null;
+ }
+ return (
+ <FavoriteItem
+ item={agent}
+ type="agent"
+ onSelectEndpoint={onSelectEndpoint}
+ onRemoveFocus={onRemoveFocus}
+ keyShortcuts={keyShortcuts}
+ />
+ );
+ }
+ if (favorite.spec) {
+ const spec = specsMap[favorite.spec];
+ if (!spec) {
+ return null;
+ }
+ return (
+ <FavoriteItem
+ item={spec}
+ type="spec"
+ onSelectSpec={onSelectSpec}
+ endpointsConfig={endpointsConfig}
+ agentAvatarURL={getSpecAgentAvatarURL(spec, agentsMap)}
+ onRemoveFocus={onRemoveFocus}
+ keyShortcuts={keyShortcuts}
+ />
+ );
+ }
+ if (favorite.model && favorite.endpoint) {
+ return (
+ <FavoriteItem
+ item={{ model: favorite.model, endpoint: favorite.endpoint }}
+ type="model"
+ onSelectEndpoint={onSelectEndpoint}
+ onRemoveFocus={onRemoveFocus}
+ keyShortcuts={keyShortcuts}
+ />
+ );
+ }
+ return null;
+};
+
interface PinnedSectionProps {
conversations: TConversation[];
toggleNav: () => void;
+ isSmallScreen?: boolean;
+ /** True when this list is the whole pinned list: no bookmark filter, and the
+ * pinned query has finished draining. Only then can keys the section cannot
+ * resolve be treated as gone rather than merely unseen. */
+ membershipComplete?: boolean;
+ /** When the pinned query last delivered, compared against the stored order's
+ * own fetch time to tell membership that reconciled with it from membership
+ * that is merely still inside its own freshness window. */
+ membershipUpdatedAt?: number;
}
-const PinnedSection = ({ conversations, toggleNav }: PinnedSectionProps) => {
+/** Pinned chats and pinned agents/models/specs (favorites) render as ONE
+ * reorderable list: favorites and conversations interleave freely, the order
+ * persists per user, and the section opens with the same collapse motion as
+ * the Projects section above it. */
+const PinnedSection = ({
+ conversations,
+ toggleNav,
+ isSmallScreen,
+ membershipComplete = false,
+ membershipUpdatedAt = 0,
+}: PinnedSectionProps) => {
const localize = useLocalize();
const [isExpanded, setIsExpanded] = useLocalStorage('pinnedSectionExpanded', true);
const { data: activeJobsData } = useActiveJobs();
+ const favoritesData = useFavoritesData();
+ /* Gated on success, not on the fetch having been attempted: a failed GET
+ * still reports as fetched while leaving the order undefined, and merging
+ * against that `?? []` then cancelling the retry would post only the visible
+ * keys and discard saved positions for good. A reconciling refetch counts as
+ * not ready either: returning to this tab after another changed the order
+ * would otherwise let a reorder cancel that refetch and post the stale
+ * arrangement straight back over it. */
+ const {
+ data: storedOrder,
+ isSuccess: orderFetched,
+ isFetching: orderFetching,
+ dataUpdatedAt: orderUpdatedAt,
+ } = useGetPinnedOrderQuery();
+ const orderLoaded = orderFetched && !orderFetching;
+ const updatePinnedOrder = useUpdatePinnedOrderMutation();
+ const pinMutation = usePinConversationMutation();
+ const { showToast } = useToastContext();
+ const sectionRef = useRef<HTMLDivElement | null>(null);
const activeJobIds = useMemo(
() => new Set(activeJobsData?.activeJobIds ?? []),
[activeJobsData?.activeJobIds],
);
- if (conversations.length === 0) {
+ /* Dropping an unpinned conversation anywhere on the section pins it. Row
+ * drops reorder instead (their targets carry no drop handler, so a drop that
+ * misses them bubbles here), and already-pinned rows are refused so an
+ * aborted reorder never re-pins anything. */
+ const [{ isPinOver, canPin }, pinDropRef] = useDrop<
+ ConversationDragItem,
+ unknown,
+ { isPinOver: boolean; canPin: boolean }
+ >({
+ accept: PINNED_ROW_ACCEPTS,
+ canDrop: (item, monitor) =>
+ monitor.getItemType() === CONVERSATION_DRAG_TYPE && item.pinned !== true,
+ /* The header and the padding around the rows are part of this list too, so
+ * a drag that wandered onto a project and came back to rest on one of them
+ * is still a reorder even though no row hover ran. */
+ hover: () => markPinnedHover(),
+ drop: (item, monitor) => {
+ if (monitor.getItemType() !== CONVERSATION_DRAG_TYPE) {
+ return;
+ }
+ if (!item.conversationId) {
+ return;
+ }
+ pinMutation.mutate(
+ { conversationId: item.conversationId, pinned: true },
+ {
+ onError: () => {
+ showToast({
+ message: localize('com_ui_pin_error'),
+ severity: NotificationSeverity.ERROR,
+ showIcon: true,
+ });
+ },
+ },
+ );
+ },
+ collect: (monitor) => ({ isPinOver: monitor.isOver(), canPin: monitor.canDrop() }),
+ });
+
+ /* An empty section still needs to receive the drop, so it materializes as a
+ * drop zone while a conversation is being dragged. */
+ const draggingConversation = useDragLayer(
+ (monitor) => monitor.isDragging() && monitor.getItemType() === CONVERSATION_DRAG_TYPE,
+ );
+
+ /** Natural order: favorites in their stored order, then pinned chats. Keys
+ * identify a row everywhere here, so a repeat has to be dropped rather than
+ * rendered: the `/favorites` payload validator accepts a duplicate entry,
+ * and one would give two rows the same React key, point every drag at the
+ * first copy, and make the order endpoint reject the write outright. */
+ const naturalEntries = useMemo<PinnedEntry[]>(() => {
+ const entries: PinnedEntry[] = [];
+ const seen = new Set<string>();
+ for (const favorite of favoritesData.favorites) {
+ const key = favoriteEntryKey(favorite);
+ if (seen.has(key)) {
+ continue;
+ }
+ seen.add(key);
+ entries.push({ key, kind: 'favorite', favorite });
+ }
+ for (const convo of conversations) {
+ const conversationId = convo.conversationId;
+ if (!conversationId) {
+ continue;
+ }
+ const key = convoEntryKey(conversationId);
+ if (seen.has(key)) {
+ continue;
+ }
+ seen.add(key);
+ entries.push({ key, kind: 'convo', conversationId });
+ }
+ return entries;
+ }, [favoritesData.favorites, conversations]);
+
+ /** Stored keys order the entries they still resolve to; the rest append in
+ * natural order, so a stale order never hides an item. */
+ const orderedEntries = useMemo<PinnedEntry[]>(() => {
+ if (!storedOrder || storedOrder.length === 0) {
+ return naturalEntries;
+ }
+ const byKey = new Map(naturalEntries.map((entry) => [entry.key, entry]));
+ const ordered: PinnedEntry[] = [];
+ const placed = new Set<string>();
+ for (const key of storedOrder) {
+ const entry = byKey.get(key);
+ if (entry) {
+ ordered.push(entry);
+ placed.add(key);
+ }
+ }
+ for (const entry of naturalEntries) {
+ if (!placed.has(entry.key)) {
+ ordered.push(entry);
+ }
+ }
+ return ordered;
+ }, [storedOrder, naturalEntries]);
+
+ /* The live list the drag mutates; keyed ordering only, so a refetch under a
+ * drag cannot clobber the in-flight arrangement. */
+ const dragEntriesRef = useRef<PinnedEntry[]>(orderedEntries);
+ const dragMembershipRef = useRef(naturalEntries);
+ const [liveEntries, setLiveEntries] = useState<PinnedEntry[] | null>(null);
+ const [announcement, setAnnouncement] = useState('');
+ /** `RenameForm` has no blur cancellation, so a second row's form can open
+ * while the first is still mounted. Every renaming row has to keep its drag
+ * source released, not just the most recent one. */
+ const [renamingKeys, setRenamingKeys] = useState<ReadonlySet<string>>(() => new Set());
+
+ const setRowRenaming = useCallback((key: string, renaming: boolean) => {
+ setRenamingKeys((previous) => {
+ if (previous.has(key) === renaming) {
+ return previous;
+ }
+ const next = new Set(previous);
+ if (renaming) {
+ next.add(key);
+ } else {
+ next.delete(key);
+ }
+ return next;
+ });
+ }, []);
+
+ if (orderedEntries !== dragEntriesRef.current && liveEntries === null) {
+ dragEntriesRef.current = orderedEntries;
+ dragMembershipRef.current = naturalEntries;
+ }
+
+ const displayEntries = liveEntries ?? orderedEntries;
+
+ /** Live index of a key in the list the drag is mutating, so a hover can tell
+ * which side of the hovered row the drag is coming from. */
+ /* Read inside callbacks that outlive the render they were created in. */
+ const orderLoadedRef = useRef(orderLoaded);
+ orderLoadedRef.current = orderLoaded;
+
+ const indexOfKey = useCallback(
+ (key: string) => dragEntriesRef.current.findIndex((entry) => entry.key === key),
+ [],
+ );
+
+ /* Every drag end runs the commit, including drags that only filed a chat
+ * into a project and drags that were abandoned without passing a row. Only a
+ * drag that actually reordered something is worth a write. */
+ const hasReorderedRef = useRef(false);
+ /* Bumped by every move. A write that settles after the user has already
+ * arranged the list again must not clear the snapshot showing that newer
+ * arrangement, or the rows would snap back to the older order while the drag
+ * still holds, and releasing would save something no longer on screen. */
+ const arrangementRef = useRef(0);
+
+ const moveEntry = useCallback((dragKey: string, hoverKey: string) => {
+ const list = [...dragEntriesRef.current];
+ const from = list.findIndex((entry) => entry.key === dragKey);
+ const to = list.findIndex((entry) => entry.key === hoverKey);
+ if (from < 0 || to < 0 || from === to) {
+ return;
+ }
+ const [moved] = list.splice(from, 1);
+ list.splice(to, 0, moved);
+ dragEntriesRef.current = list;
+ hasReorderedRef.current = true;
+ arrangementRef.current += 1;
+ setLiveEntries(list);
+ }, []);
+
+ /** Keyboard reorder: one step per keypress, persisted immediately, with the
+ * new position announced because nothing visual conveys it to a screen
+ * reader. */
+ const moveEntryBy = useCallback(
+ (key: string, delta: number) => {
+ if (!orderLoadedRef.current) {
+ return;
+ }
+ const list = [...dragEntriesRef.current];
+ const from = list.findIndex((entry) => entry.key === key);
+ const to = from + delta;
+ if (from < 0 || to < 0 || to >= list.length) {
+ return;
+ }
+ const [moved] = list.splice(from, 1);
+ list.splice(to, 0, moved);
+ dragEntriesRef.current = list;
+ hasReorderedRef.current = true;
+ arrangementRef.current += 1;
+ setLiveEntries(list);
+ setAnnouncement(
+ localize('com_ui_moved_to_position', { 0: `${to + 1}`, 1: `${list.length}` }),
+ );
+ commitOrderRef.current();
+ },
+ [localize],
+ );
+
+ const commitOrder = useCallback(
+ (handledElsewhere = false) => {
+ if (!hasReorderedRef.current) {
+ return;
+ }
+ /* A reconciling refetch is in flight. `canDrag` only disconnects the
+ * source for drags that have not started, so one already under the
+ * pointer still lands here, and the array built now would be merged onto
+ * the order that refetch is about to replace. The arrangement is kept
+ * and written once the fresh order arrives, below. */
+ if (!handledElsewhere && !orderLoadedRef.current) {
+ return;
+ }
+ hasReorderedRef.current = false;
+ const arrangement = arrangementRef.current;
+ if (handledElsewhere) {
+ /* The drop filed the chat into a project or back into Chats. The rows
+ * the pointer crossed on the way shifted only incidentally, so that
+ * movement is discarded rather than saved as a deliberate reorder. */
+ setLiveEntries(null);
+ return;
+ }
+ const entries = dragEntriesRef.current;
+ const visibleKeys = entries.map((entry) => entry.key);
+ /* Merging keeps keys the section cannot currently see, which is right
+ * while a bookmark filter hides rows or the pinned query is still
+ * draining. Once the visible list is known to be the whole list, those
+ * keys really are gone and replacing prunes them: merging forever would
+ * grow the array until the endpoint's size guard rejected every write. */
+ /* Every membership source has to have actually delivered, not merely
+ * stopped loading: a favorites fetch that exhausted its retries leaves
+ * the list empty, and pruning against that would drop every favorite key
+ * from the stored order. */
+ /* Current enough, too, and not merely settled: the pinned query holds its
+ * data for five minutes while the order has no such window, so focusing a
+ * tab reconciles the order on its own. Pruning that newer order against
+ * the older membership beside it would drop the position of a favorite
+ * or conversation another tab pinned in between. Until both membership
+ * sources catch up, merging keeps those keys. */
+ const membershipCurrent = membershipComplete && membershipUpdatedAt >= orderUpdatedAt;
+ /* Reconciled membership can arrive while the live arrangement is frozen.
+ * Its keys are not necessarily represented by that older snapshot. */
+ const canPrune =
+ membershipCurrent &&
+ favoritesData.isLoaded &&
+ favoritesData.dataUpdatedAt >= orderUpdatedAt &&
+ dragMembershipRef.current === naturalEntries;
+ const nextOrder = canPrune ? visibleKeys : mergeVisibleOrder(storedOrder ?? [], visibleKeys);
+
+ updatePinnedOrder.mutate(nextOrder, {
+ /* `pinnedOrder` is the only ordering the section reads: no consumer of
+ * the favorites array depends on its order, so writing the arrangement
+ * back there a second time bought nothing and raced the membership
+ * mutations that share that array. */
+ onError: () => {
+ showToast({
+ message: localize('com_ui_reorder_error'),
+ severity: NotificationSeverity.ERROR,
+ showIcon: true,
+ });
+ },
+ /* Release the local arrangement once the write resolves either way: by
+ * then the optimistic cache carries it, or the rollback has replaced it
+ * with what the server actually holds. */
+ onSettled: () => {
+ if (arrangementRef.current !== arrangement) {
+ return;
+ }
+ setLiveEntries(null);
+ },
+ });
+ },
+ [
+ updatePinnedOrder,
+ storedOrder,
+ membershipComplete,
+ membershipUpdatedAt,
+ orderUpdatedAt,
+ naturalEntries,
+ favoritesData.isLoaded,
+ favoritesData.dataUpdatedAt,
+ showToast,
+ localize,
+ ],
+ );
+
+ /* `moveEntryBy` is declared above `commitOrder` and both are stable across a
+ * drag, so the commit is reached through a ref rather than reordering them
+ * into a dependency cycle. */
+ const commitOrderRef = useRef(commitOrder);
+ commitOrderRef.current = commitOrder;
+
+ /* Flushes an arrangement that arrived while the order was reconciling. The
+ * query settling is the external event being waited on, and `commitOrder`
+ * returns immediately unless one is actually held. */
+ useEffect(() => {
+ if (orderLoaded) {
+ commitOrderRef.current();
+ }
+ }, [orderLoaded]);
+
+ /* `FavoriteItem` reports the removal only once its row is already gone, so
+ * there is no position left to search around: focus goes to the first
+ * surviving row, matching what the favorites list did before this merge. */
+ const handleRemoveFocus = useCallback(() => {
+ focusFirstRow(sectionRef.current);
+ }, []);
+
+ const handleSelectEndpoint = useCallback<SelectEndpointHandler>(
+ (...args) => {
+ favoritesData.onSelectEndpoint?.(...args);
+ if (isSmallScreen) {
+ toggleNav();
+ }
+ },
+ [favoritesData, isSmallScreen, toggleNav],
+ );
+
+ const handleSelectSpec = useCallback<SelectSpecHandler>(
+ (...args) => {
+ favoritesData.onSelectSpec?.(...args);
+ if (isSmallScreen) {
+ toggleNav();
+ }
+ },
+ [favoritesData, isSmallScreen, toggleNav],
+ );
+
+ const conversationByKey = useMemo(
+ () => new Map(conversations.map((convo) => [convo.conversationId ?? '', convo])),
+ [conversations],
+ );
+
+ /** The section root is both the pin drop target and the scope focus falls
+ * back into when a row is removed. */
+ const setSectionRef = useCallback(
+ (node: HTMLDivElement | null) => {
+ sectionRef.current = node;
+ pinDropRef(node);
+ },
+ [pinDropRef],
+ );
+
+ /* The section renders while either half is present or still resolving, and
+ * drops out only once both are definitively empty. A live conversation drag
+ * keeps it mounted as a drop target even when empty. */
+ if (naturalEntries.length === 0 && !favoritesData.isLoading && !draggingConversation) {
return null;
}
return (
<div
+ ref={setSectionRef}
className="flex flex-col px-3 text-sm"
role="region"
+ /** The focus handoff after an unpin must act only on rows in this list:
+ * `ConversationsSection` is also a labelled region and an ancestor of
+ * the project rows, which render the same `Convo` and survive unpinning. */
+ data-pinned-section=""
aria-label={localize('com_ui_pinned')}
>
- <div className="flex h-8 w-full items-center pr-2">
+ <div
+ className={cn(
+ 'flex h-8 w-full items-center pr-2',
+ isPinOver && canPin && 'rounded-lg bg-surface-active-alt',
+ )}
+ >
<button
onClick={() => setIsExpanded(!isExpanded)}
- className="group flex min-w-0 flex-1 items-center gap-1 rounded-lg px-1 py-2 text-xs font-bold text-text-secondary outline-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary"
+ className={cn(buttonVariants({ variant: 'section-header' }), 'group min-w-0 flex-1')}
type="button"
aria-expanded={isExpanded}
>
@@ -52,18 +705,87 @@ const PinnedSection = ({ conversations, toggleNav }: PinnedSectionProps) => {
</div>
<Collapse open={isExpanded}>
- <div className="scrollbar-gutter-stable max-h-[30vh] overflow-y-auto">
+ {/* Projects above already claims up to 42vh; matching it here starved the
+ flex-growing Chats region on short viewports, so this keeps the
+ pre-existing budget. */}
+ <div className="scrollbar-gutter-stable max-h-[30vh] overflow-y-auto pt-0.5">
+ {displayEntries.length === 0 && draggingConversation && (
+ <div
+ className={cn(
+ 'flex h-9 items-center justify-center rounded-lg border border-dashed text-xs text-text-secondary',
+ isPinOver && canPin
+ ? 'border-border-medium bg-surface-active-alt text-text-primary'
+ : 'border-border-light',
+ )}
+ aria-hidden="true"
+ >
+ {localize('com_ui_drop_to_pin')}
+ </div>
+ )}
+ <p className="sr-only">{localize('com_ui_pinned_reorder_hint')}</p>
+ <p className="sr-only" role="status" aria-live="polite">
+ {announcement}
+ </p>
<ul className="m-0 list-none p-0">
- {conversations.map((convo) => (
- <li key={convo.conversationId} className="list-none">
- <Convo
- conversation={convo}
- retainView={noop}
- toggleNav={toggleNav}
- isGenerating={activeJobIds.has(convo.conversationId ?? '')}
- />
+ {favoritesData.isLoading && favoritesData.favorites.length === 0 && (
+ <li className="list-none">
+ <FavoriteRowSkeleton />
</li>
- ))}
+ )}
+ {displayEntries.map((entry) => {
+ if (entry.kind === 'convo') {
+ const convo = conversationByKey.get(entry.conversationId);
+ if (!convo) {
+ return null;
+ }
+ return (
+ <li key={entry.key} className="list-none">
+ <DraggablePinnedRow
+ entry={entry}
+ conversation={convo}
+ indexOfKey={indexOfKey}
+ moveEntry={moveEntry}
+ moveEntryBy={moveEntryBy}
+ onDrop={commitOrder}
+ canDrag={orderLoaded && !renamingKeys.has(entry.key)}
+ >
+ <Convo
+ conversation={convo}
+ retainView={noop}
+ toggleNav={toggleNav}
+ isGenerating={activeJobIds.has(convo.conversationId ?? '')}
+ keyShortcuts={orderLoaded ? REORDER_SHORTCUTS : undefined}
+ onRenamingChange={(renaming) => setRowRenaming(entry.key, renaming)}
+ />
+ </DraggablePinnedRow>
+ </li>
+ );
+ }
+ return (
+ <li key={entry.key} className="list-none">
+ <DraggablePinnedRow
+ entry={entry}
+ indexOfKey={indexOfKey}
+ moveEntry={moveEntry}
+ moveEntryBy={moveEntryBy}
+ onDrop={commitOrder}
+ canDrag={orderLoaded}
+ >
+ <FavoriteRow
+ favorite={entry.favorite}
+ agentsMap={favoritesData.agentsMap}
+ specsMap={favoritesData.specsMap}
+ endpointsConfig={favoritesData.endpointsConfig}
+ isAgentsLoading={favoritesData.isAgentsLoading}
+ onSelectEndpoint={handleSelectEndpoint}
+ onSelectSpec={handleSelectSpec}
+ onRemoveFocus={handleRemoveFocus}
+ keyShortcuts={orderLoaded ? REORDER_SHORTCUTS : undefined}
+ />
+ </DraggablePinnedRow>
+ </li>
+ );
+ })}
</ul>
</div>
</Collapse>
diff --git a/client/src/components/Conversations/ProjectsSection.tsx b/client/src/components/Conversations/ProjectsSection.tsx
index ac80420535..345f479180 100644
--- a/client/src/components/Conversations/ProjectsSection.tsx
+++ b/client/src/components/Conversations/ProjectsSection.tsx
@@ -1,17 +1,10 @@
-import { memo, useCallback, useId, useMemo, useState } from 'react';
+import { memo, useCallback, useId, useMemo, useRef, useState } from 'react';
+import { useDrop } from 'react-dnd';
import { useRecoilValue } from 'recoil';
import * as Ariakit from '@ariakit/react';
import { useQueryClient } from '@tanstack/react-query';
import { Constants, QueryKeys } from 'librechat-data-provider';
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom';
-import {
- Button,
- Spinner,
- TooltipAnchor,
- DropdownPopup,
- NewChatIcon,
- buttonVariants,
-} from '@librechat/client';
import {
ChevronDown,
ChevronRight,
@@ -22,9 +15,25 @@ import {
Pencil,
Trash2,
} from 'lucide-react';
+import {
+ Button,
+ Skeleton,
+ Spinner,
+ TooltipAnchor,
+ DropdownPopup,
+ NewChatIcon,
+ buttonVariants,
+} from '@librechat/client';
import type { TChatProject, TConversation } from 'librechat-data-provider';
import type { MouseEvent } from 'react';
+import type { ConversationDragItem } from './dnd';
import type { MenuItemProps } from '~/common';
+import {
+ CONVERSATION_DRAG_TYPE,
+ markExternalHover,
+ useAssignDroppedConversation,
+ useEffectiveProjectId,
+} from './dnd';
import {
useProjectsInfiniteQuery,
useActiveJobs,
@@ -56,6 +65,16 @@ type ProjectChatsInlineProps = {
onShowAll: () => void;
};
+/** Mirrors a Convo row (h-9, endpoint dot, title) so the swap from skeletons to
+ * rows doesn't shift height, and an opening project reads as loading its chats
+ * rather than as an empty strip with a lone spinner. */
+const ProjectChatSkeleton = () => (
+ <div className="flex h-9 w-full items-center gap-2 px-1.5" aria-hidden="true">
+ <Skeleton className="h-5 w-5 shrink-0 rounded-full" />
+ <Skeleton className="h-3.5 w-24" />
+ </div>
+);
+
const ProjectChatsInline = memo(function ProjectChatsInline({
projectId,
expanded,
@@ -87,8 +106,11 @@ const ProjectChatsInline = memo(function ProjectChatsInline({
if (isLoading && conversations.length === 0) {
return (
- <div className="flex justify-start py-1.5 pl-2">
- <Spinner className="h-4 w-4 text-text-secondary" />
+ <div data-testid={`project-chats-loading-${projectId}`} aria-busy="true">
+ <span className="sr-only">{localize('com_ui_loading')}</span>
+ {Array.from({ length: 3 }, (_, index) => (
+ <ProjectChatSkeleton key={index} />
+ ))}
</div>
);
}
@@ -110,6 +132,7 @@ const ProjectChatsInline = memo(function ProjectChatsInline({
retainView={noop}
toggleNav={toggleNav}
isGenerating={activeJobIds.has(convo.conversationId ?? '')}
+ draggable
/>
))}
{hasMore && (
@@ -152,6 +175,29 @@ const ProjectItem = memo(
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
const projectChatPath = `/c/${Constants.NEW_CONVO}?projectId=${encodeURIComponent(project._id)}`;
+ /* The whole item, header plus its expanded chats, is the drop target for
+ * filing a dragged conversation into this project; the project's own chats
+ * read as already-filed and are rejected. The highlight lands on the header
+ * row so the affordance reads as the project, not the row under it. */
+ const assignDropped = useAssignDroppedConversation();
+ const effectiveProjectId = useEffectiveProjectId();
+ const projectRowRef = useRef<HTMLLIElement>(null);
+ const [{ isDropOver, canDrop }, dropRef] = useDrop<
+ ConversationDragItem,
+ unknown,
+ { isDropOver: boolean; canDrop: boolean }
+ >({
+ accept: CONVERSATION_DRAG_TYPE,
+ canDrop: (item) => effectiveProjectId(item) !== project._id,
+ /* Reported even when the drop is refused: a pinned row dragged onto the
+ * project it already belongs to still left the pinned list, and the rows
+ * it crossed must not be saved in their shifted order. */
+ hover: () => markExternalHover(),
+ drop: (item) => assignDropped(item, project._id),
+ collect: (monitor) => ({ isDropOver: monitor.isOver(), canDrop: monitor.canDrop() }),
+ });
+ dropRef(projectRowRef);
+
const openProject = useCallback(() => {
navigate(`/projects/${project._id}`);
toggleNav();
@@ -217,12 +263,13 @@ const ProjectItem = memo(
);
return (
- <li className="list-none">
+ <li className="list-none" ref={projectRowRef}>
<div
className={cn(
'group/project-row relative flex h-9 items-center rounded-lg text-sm text-text-primary hover:bg-surface-hover',
isActive && 'bg-surface-active-alt hover:bg-surface-active-alt',
!isActive && isMenuOpen && 'bg-surface-hover',
+ isDropOver && canDrop && 'bg-surface-active-alt ring-1 ring-inset ring-border-medium',
)}
>
<button
@@ -421,7 +468,7 @@ const ProjectsSection = ({ toggleNav, isAuthenticated }: ProjectsSectionProps) =
setStoredExpanded(!isExpanded);
setHasToggledSection(true);
}}
- className="group flex min-w-0 flex-1 items-center gap-1 rounded-lg px-1 py-2 text-xs font-bold text-text-secondary outline-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary"
+ className={cn(buttonVariants({ variant: 'section-header' }), 'group min-w-0 flex-1')}
aria-expanded={isExpanded}
>
<span className="select-none truncate">{localize('com_ui_projects')}</span>
diff --git a/client/src/components/Conversations/__tests__/Conversations.test.tsx b/client/src/components/Conversations/__tests__/Conversations.test.tsx
index 86486db9d5..f60ec5548b 100644
--- a/client/src/components/Conversations/__tests__/Conversations.test.tsx
+++ b/client/src/components/Conversations/__tests__/Conversations.test.tsx
@@ -2,12 +2,17 @@ import React, { createRef } from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { RecoilRoot } from 'recoil';
+import { DndProvider } from 'react-dnd';
+import { HTML5Backend } from 'react-dnd-html5-backend';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { CellMeasurerCache, List } from 'react-virtualized';
import type { TConversation } from 'librechat-data-provider';
import Conversations from '../Conversations';
import store from '~/store';
-let mockCapturedCache: CellMeasurerCache | null = null;
+/* The section resolves a conversation's project from the query cache, so the
+ * tree needs a client even though the data hooks themselves are mocked. */
+const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
jest.mock('react-virtualized', () => {
const actual = jest.requireActual('react-virtualized');
@@ -21,7 +26,7 @@ jest.mock('react-virtualized', () => {
List: ({
rowRenderer,
rowCount,
- deferredMeasurementCache,
+ _deferredMeasurementCache,
}: {
rowRenderer: (opts: {
index: number;
@@ -33,7 +38,6 @@ jest.mock('react-virtualized', () => {
deferredMeasurementCache: CellMeasurerCache;
[key: string]: unknown;
}) => {
- mockCapturedCache = deferredMeasurementCache;
return (
<div data-testid="virtual-list" data-row-count={rowCount}>
{Array.from({ length: Math.min(rowCount, 10) }, (_, i) =>
@@ -55,30 +59,23 @@ jest.mock('~/store', () => {
};
});
-type FavoriteEntry = { agentId?: string; model?: string; endpoint?: string };
-
-const mockFavoritesState: { favorites: FavoriteEntry[]; isLoading: boolean } = {
- favorites: [],
- isLoading: false,
-};
-
-let mockShowMarketplace = true;
-
jest.mock('~/hooks', () => ({
- useFavorites: () => mockFavoritesState,
useLocalize: () => (key: string) => key,
- useShowMarketplace: () => mockShowMarketplace,
useElementSize: () => ({ ref: jest.fn(), width: 300, height: 600 }),
TranslationKeys: {},
}));
jest.mock('@librechat/client', () => ({
+ /* The section headers compose through the shared variant recipe. */
+ buttonVariants: () => '',
Spinner: () => <div data-testid="spinner" />,
useMediaQuery: () => false,
+ useToastContext: () => ({ showToast: jest.fn() }),
}));
jest.mock('~/data-provider', () => ({
useActiveJobs: () => ({ data: undefined }),
+ useAssignConversationToProjectMutation: () => ({ mutate: jest.fn() }),
}));
jest.mock('~/utils', () => ({
@@ -86,101 +83,11 @@ jest.mock('~/utils', () => ({
cn: (...args: unknown[]) => args.filter(Boolean).join(' '),
}));
-jest.mock('~/components/Nav/Favorites/FavoritesList', () => ({
- __esModule: true,
- default: () => <div data-testid="favorites-list" />,
-}));
-
jest.mock('../Convo', () => ({
__esModule: true,
default: () => <div data-testid="convo" />,
}));
-describe('Conversations – favorites CellMeasurerCache key invalidation', () => {
- const containerRef = createRef<List>();
-
- beforeEach(() => {
- mockCapturedCache = null;
- mockFavoritesState.favorites = [];
- mockFavoritesState.isLoading = false;
- mockShowMarketplace = true;
- });
-
- const Wrapper = () => (
- <RecoilRoot>
- <Conversations
- conversations={[]}
- moveToTop={jest.fn()}
- toggleNav={jest.fn()}
- containerRef={containerRef}
- loadMoreConversations={jest.fn()}
- isLoading={false}
- isSearchLoading={false}
- isChatsExpanded={true}
- setIsChatsExpanded={jest.fn()}
- />
- </RecoilRoot>
- );
-
- it('should invalidate the cached favorites height when favorites count changes', () => {
- const { rerender } = render(<Wrapper />);
- const cache = mockCapturedCache!;
- expect(cache).toBeDefined();
-
- cache.set(0, 0, 300, 48);
- expect(cache.has(0, 0)).toBe(true);
- expect(cache.getHeight(0, 0)).toBe(48);
-
- mockFavoritesState.favorites = [{ model: 'gpt-4', endpoint: 'openAI' }];
- rerender(<Wrapper />);
-
- expect(cache.has(0, 0)).toBe(false);
- });
-
- it('should invalidate the cached favorites height when loading state transitions', () => {
- mockFavoritesState.isLoading = true;
- const { rerender } = render(<Wrapper />);
- const cache = mockCapturedCache!;
-
- cache.set(0, 0, 300, 80);
- expect(cache.has(0, 0)).toBe(true);
-
- mockFavoritesState.isLoading = false;
- rerender(<Wrapper />);
-
- expect(cache.has(0, 0)).toBe(false);
- });
-
- it('should invalidate the cached favorites height when marketplace visibility changes', () => {
- mockFavoritesState.favorites = [{ model: 'gpt-4', endpoint: 'openAI' }];
- const { rerender } = render(<Wrapper />);
- const cache = mockCapturedCache!;
-
- cache.set(0, 0, 300, 48);
- expect(cache.has(0, 0)).toBe(true);
-
- mockShowMarketplace = false;
- rerender(<Wrapper />);
-
- expect(cache.has(0, 0)).toBe(false);
- });
-
- it('should retain the cached favorites height when content state is unchanged', () => {
- mockFavoritesState.favorites = [{ model: 'gpt-4', endpoint: 'openAI' }];
- const { rerender } = render(<Wrapper />);
- const cache = mockCapturedCache!;
-
- cache.set(0, 0, 300, 88);
- expect(cache.has(0, 0)).toBe(true);
- expect(cache.getHeight(0, 0)).toBe(88);
-
- rerender(<Wrapper />);
-
- expect(cache.has(0, 0)).toBe(true);
- expect(cache.getHeight(0, 0)).toBe(88);
- });
-});
-
const pinnedConvo = {
conversationId: 'pinned-1',
title: 'Pinned Chat',
@@ -193,38 +100,35 @@ const pinnedConvo = {
describe('Conversations: pinned chats live in PinnedSection', () => {
const containerRef = createRef<List>();
- beforeEach(() => {
- mockCapturedCache = null;
- mockFavoritesState.favorites = [];
- mockFavoritesState.isLoading = false;
- mockShowMarketplace = false;
- });
-
const renderConversations = (conversations: TConversation[], searchQuery = '') =>
render(
- <RecoilRoot
- initializeState={({ set }) => {
- set(store.search, {
- query: searchQuery,
- enabled: true,
- debouncedQuery: searchQuery,
- isSearching: true,
- isTyping: false,
- });
- }}
- >
- <Conversations
- conversations={conversations}
- moveToTop={jest.fn()}
- toggleNav={jest.fn()}
- containerRef={containerRef}
- loadMoreConversations={jest.fn()}
- isLoading={false}
- isSearchLoading={false}
- isChatsExpanded={true}
- setIsChatsExpanded={jest.fn()}
- />
- </RecoilRoot>,
+ <QueryClientProvider client={queryClient}>
+ <DndProvider backend={HTML5Backend}>
+ <RecoilRoot
+ initializeState={({ set }) => {
+ set(store.search, {
+ query: searchQuery,
+ enabled: true,
+ debouncedQuery: searchQuery,
+ isSearching: true,
+ isTyping: false,
+ });
+ }}
+ >
+ <Conversations
+ conversations={conversations}
+ moveToTop={jest.fn()}
+ toggleNav={jest.fn()}
+ containerRef={containerRef}
+ loadMoreConversations={jest.fn()}
+ isLoading={false}
+ isSearchLoading={false}
+ isChatsExpanded={true}
+ setIsChatsExpanded={jest.fn()}
+ />
+ </RecoilRoot>
+ </DndProvider>
+ </QueryClientProvider>,
);
it('does not render a pinned header inside the chats list', () => {
@@ -241,13 +145,6 @@ describe('Conversations: pinned chats live in PinnedSection', () => {
describe('Conversations: all-pin pages still paginate', () => {
const containerRef = createRef<List>();
- beforeEach(() => {
- mockCapturedCache = null;
- mockFavoritesState.favorites = [];
- mockFavoritesState.isLoading = false;
- mockShowMarketplace = false;
- });
-
const renderList = ({
conversations,
loadMoreConversations,
@@ -260,20 +157,23 @@ describe('Conversations: all-pin pages still paginate', () => {
isLoading?: boolean;
}) =>
render(
- <RecoilRoot>
- <Conversations
- conversations={conversations}
- moveToTop={jest.fn()}
- toggleNav={jest.fn()}
- containerRef={containerRef}
- loadMoreConversations={loadMoreConversations}
- isLoading={isLoading}
- isSearchLoading={false}
- isChatsExpanded={isChatsExpanded}
- setIsChatsExpanded={jest.fn()}
- showFavorites={false}
- />
- </RecoilRoot>,
+ <QueryClientProvider client={queryClient}>
+ <DndProvider backend={HTML5Backend}>
+ <RecoilRoot>
+ <Conversations
+ conversations={conversations}
+ moveToTop={jest.fn()}
+ toggleNav={jest.fn()}
+ containerRef={containerRef}
+ loadMoreConversations={loadMoreConversations}
+ isLoading={isLoading}
+ isSearchLoading={false}
+ isChatsExpanded={isChatsExpanded}
+ setIsChatsExpanded={jest.fn()}
+ />
+ </RecoilRoot>
+ </DndProvider>
+ </QueryClientProvider>,
);
it('requests another page when grouping leaves the chats list empty', () => {
@@ -309,36 +209,42 @@ describe('Conversations: all-pin pages still paginate', () => {
expect(loadMoreConversations).toHaveBeenCalledTimes(1);
rerender(
- <RecoilRoot>
- <Conversations
- conversations={conversations}
- moveToTop={jest.fn()}
- toggleNav={jest.fn()}
- containerRef={containerRef}
- loadMoreConversations={loadMoreConversations}
- isLoading={true}
- isSearchLoading={false}
- isChatsExpanded={true}
- setIsChatsExpanded={jest.fn()}
- showFavorites={false}
- />
- </RecoilRoot>,
+ <QueryClientProvider client={queryClient}>
+ <DndProvider backend={HTML5Backend}>
+ <RecoilRoot>
+ <Conversations
+ conversations={conversations}
+ moveToTop={jest.fn()}
+ toggleNav={jest.fn()}
+ containerRef={containerRef}
+ loadMoreConversations={loadMoreConversations}
+ isLoading={true}
+ isSearchLoading={false}
+ isChatsExpanded={true}
+ setIsChatsExpanded={jest.fn()}
+ />
+ </RecoilRoot>
+ </DndProvider>
+ </QueryClientProvider>,
);
rerender(
- <RecoilRoot>
- <Conversations
- conversations={conversations}
- moveToTop={jest.fn()}
- toggleNav={jest.fn()}
- containerRef={containerRef}
- loadMoreConversations={loadMoreConversations}
- isLoading={false}
- isSearchLoading={false}
- isChatsExpanded={true}
- setIsChatsExpanded={jest.fn()}
- showFavorites={false}
- />
- </RecoilRoot>,
+ <QueryClientProvider client={queryClient}>
+ <DndProvider backend={HTML5Backend}>
+ <RecoilRoot>
+ <Conversations
+ conversations={conversations}
+ moveToTop={jest.fn()}
+ toggleNav={jest.fn()}
+ containerRef={containerRef}
+ loadMoreConversations={loadMoreConversations}
+ isLoading={false}
+ isSearchLoading={false}
+ isChatsExpanded={true}
+ setIsChatsExpanded={jest.fn()}
+ />
+ </RecoilRoot>
+ </DndProvider>
+ </QueryClientProvider>,
);
expect(loadMoreConversations).toHaveBeenCalledTimes(1);
diff --git a/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx b/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx
index 72c959aaf1..72b8703012 100644
--- a/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx
+++ b/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx
@@ -1,3 +1,5 @@
+import { DndProvider } from 'react-dnd';
+import { HTML5Backend } from 'react-dnd-html5-backend';
import { render, screen, fireEvent, act } from '@testing-library/react';
import type { TConversation } from 'librechat-data-provider';
@@ -23,6 +25,7 @@ jest.mock('~/hooks', () => ({
jest.mock('~/data-provider', () => ({
useGetStartupConfig: () => ({ data: { sharedLinksEnabled: false } }),
useUpdateConversationMutation: () => ({ mutateAsync: jest.fn() }),
+ usePinConversationMutation: () => ({ mutate: jest.fn() }),
}));
jest.mock('react-router-dom', () => ({
@@ -74,7 +77,11 @@ const conversation = {
} as TConversation;
const renderRow = () =>
- render(<Conversation conversation={conversation} retainView={jest.fn()} toggleNav={jest.fn()} />);
+ render(
+ <DndProvider backend={HTML5Backend}>
+ <Conversation conversation={conversation} retainView={jest.fn()} toggleNav={jest.fn()} />
+ </DndProvider>,
+ );
describe('Conversation row on touch', () => {
beforeEach(() => {
diff --git a/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx b/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx
new file mode 100644
index 0000000000..af24941d98
--- /dev/null
+++ b/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx
@@ -0,0 +1,285 @@
+import { DndProvider } from 'react-dnd';
+import { HTML5Backend } from 'react-dnd-html5-backend';
+import { render, screen, fireEvent, act } from '@testing-library/react';
+import type { TConversation } from 'librechat-data-provider';
+
+type PinVariables = { conversationId: string; pinned: boolean };
+type PinOptions = { onSuccess?: () => void; onError?: () => void };
+
+const pinCalls: Array<{ variables: PinVariables; options?: PinOptions }> = [];
+
+jest.mock('@librechat/client', () => ({
+ useMediaQuery: () => false,
+ useToastContext: () => ({ showToast: jest.fn() }),
+ Spinner: () => <div data-testid="spinner" />,
+ TooltipAnchor: ({ render: trigger }: { render: React.ReactNode }) => trigger,
+ /* Stands in for the shared primitive: the row's actions compose through it,
+ * so it has to pass its props to a real button for these assertions. */
+ Button: ({
+ children,
+ variant: _variant,
+ size: _size,
+ ...props
+ }: React.ComponentProps<'button'> & { variant?: string; size?: string }) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+ useNavigateToConvo: () => ({ navigateToConvo: jest.fn() }),
+ useShiftKey: () => false,
+}));
+
+jest.mock('~/data-provider', () => ({
+ useGetStartupConfig: () => ({ data: { sharedLinksEnabled: false } }),
+ useUpdateConversationMutation: () => ({ mutateAsync: jest.fn() }),
+ usePinConversationMutation: () => ({
+ mutate: (variables: PinVariables, options?: PinOptions) => {
+ pinCalls.push({ variables, options });
+ },
+ }),
+}));
+
+jest.mock('react-router-dom', () => ({
+ useParams: () => ({ conversationId: 'other-convo' }),
+}));
+
+jest.mock('recoil', () => ({
+ useRecoilValue: () => [],
+}));
+
+jest.mock('~/store', () => ({
+ __esModule: true,
+ default: { allConversationsSelector: 'allConversationsSelector' },
+}));
+
+jest.mock('~/utils', () => ({
+ cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),
+ logger: { error: jest.fn() },
+ setDocumentTitle: jest.fn(),
+}));
+
+jest.mock('../ConvoOptions', () => ({
+ ConvoOptions: () => <div data-testid="convo-options" />,
+}));
+
+jest.mock('../ConversationEndpointIcon', () => ({
+ __esModule: true,
+ default: () => <div data-testid="convo-icon" />,
+}));
+
+/** The real row's only focusable element is the link button inside it; the row
+ * element itself is a plain div, so a focus target has to be found in here. */
+jest.mock('../ConvoLink', () => ({
+ __esModule: true,
+ default: ({ title }: { title: string }) => (
+ <button type="button" aria-label={`open ${title}`}>
+ {title}
+ </button>
+ ),
+}));
+
+jest.mock('../RenameForm', () => ({
+ __esModule: true,
+ default: () => <form data-testid="rename-form" />,
+}));
+
+import Conversation from '../Convo';
+
+const pinned = (id: string, title: string) =>
+ ({ conversationId: id, title, pinned: true }) as unknown as TConversation;
+
+const renderPinnedSection = (conversations: TConversation[]) =>
+ render(
+ <DndProvider backend={HTML5Backend}>
+ <div role="region" data-pinned-section="" aria-label="com_ui_pinned">
+ {conversations.map((conversation) => (
+ <Conversation
+ key={conversation.conversationId}
+ conversation={conversation}
+ retainView={jest.fn()}
+ toggleNav={jest.fn()}
+ />
+ ))}
+ </div>
+ </DndProvider>,
+ );
+
+describe('pinned conversation row unpin', () => {
+ beforeEach(() => {
+ pinCalls.length = 0;
+ });
+
+ it('unpins from the row badge without opening the options menu', () => {
+ renderPinnedSection([pinned('c1', 'First'), pinned('c2', 'Second')]);
+
+ fireEvent.click(screen.getAllByTestId('convo-unpin-button')[0]);
+
+ expect(pinCalls).toHaveLength(1);
+ expect(pinCalls[0].variables).toEqual({ conversationId: 'c1', pinned: false });
+ });
+
+ /** Activating the badge focuses it, by click or by keyboard; the focus
+ * handoff only applies when the row that is going away actually held it. */
+ const activateUnpin = (index: number) => {
+ const button = screen.getAllByTestId('convo-unpin-button')[index];
+ button.focus();
+ fireEvent.click(button);
+ };
+
+ it('hands focus to a neighbouring row, not the row that is going away', () => {
+ renderPinnedSection([pinned('c1', 'First'), pinned('c2', 'Second')]);
+
+ activateUnpin(0);
+ act(() => {
+ pinCalls[0].options?.onSuccess?.();
+ });
+
+ /* The unpinned row is still mounted at this point: focus has to skip it,
+ * and land on something actually focusable rather than the row div. */
+ expect(document.activeElement).toBe(screen.getByLabelText('open Second'));
+ });
+ it('does not steal focus when focus moves away before deferred success', () => {
+ const elsewhere = document.createElement('button');
+ document.body.appendChild(elsewhere);
+ renderPinnedSection([pinned('c1', 'First'), pinned('c2', 'Second')]);
+
+ activateUnpin(0);
+ elsewhere.focus();
+ act(() => {
+ pinCalls[0].options?.onSuccess?.();
+ });
+
+ expect(document.activeElement).toBe(elsewhere);
+ elsewhere.remove();
+ });
+
+ it('restores focus when the focused row is removed before deferred success', () => {
+ const first = pinned('c1', 'First');
+ const second = pinned('c2', 'Second');
+ const { rerender } = renderPinnedSection([first, second]);
+
+ activateUnpin(0);
+ rerender(
+ <DndProvider backend={HTML5Backend}>
+ <div role="region" data-pinned-section="" aria-label="com_ui_pinned">
+ <Conversation
+ key={second.conversationId}
+ conversation={second}
+ retainView={jest.fn()}
+ toggleNav={jest.fn()}
+ />
+ </div>
+ </DndProvider>,
+ );
+ act(() => {
+ pinCalls[0].options?.onSuccess?.();
+ });
+
+ expect(document.activeElement).toBe(screen.getByLabelText('open Second'));
+ });
+
+ it('falls back to the row above when the last row is unpinned', () => {
+ renderPinnedSection([pinned('c1', 'First'), pinned('c2', 'Second')]);
+
+ activateUnpin(1);
+ act(() => {
+ pinCalls[0].options?.onSuccess?.();
+ });
+
+ expect(document.activeElement).toBe(screen.getByLabelText('open First'));
+ });
+
+ it('falls back to New Chat when no other row survives', () => {
+ /* The id has to be one a real control carries: the expanded panel's New
+ * Chat button. A made-up one would let this pass while focus fell to the
+ * document in the app. */
+ const newChat = document.createElement('button');
+ newChat.setAttribute('data-testid', 'new-chat-button');
+ document.body.appendChild(newChat);
+
+ renderPinnedSection([pinned('c1', 'Only')]);
+
+ activateUnpin(0);
+ act(() => {
+ pinCalls[0].options?.onSuccess?.();
+ });
+
+ expect(document.activeElement).toBe(newChat);
+ newChat.remove();
+ });
+
+ it('does not steal focus when the removed row never had it', () => {
+ renderPinnedSection([pinned('c1', 'First'), pinned('c2', 'Second')]);
+
+ /* A pointer user unpinning a row they were not keyboard-focused on should
+ * keep whatever they had focused, not be yanked into the sidebar. */
+ fireEvent.click(screen.getAllByTestId('convo-unpin-button')[0]);
+ act(() => {
+ pinCalls[0].options?.onSuccess?.();
+ });
+
+ expect(document.activeElement).not.toBe(screen.getByLabelText('open Second'));
+ });
+
+ it('keeps focus on the surviving row when it is outside the pinned section', () => {
+ /* The same row renders inside an expanded project, where unpinning only
+ * clears the flag and the row stays put. The pin badge that had focus does
+ * not survive though, so focus moves to the row's own link rather than
+ * being left on a removed control or dropped to the document. */
+ render(
+ <DndProvider backend={HTML5Backend}>
+ <div role="region" aria-label="chats">
+ <Conversation
+ conversation={pinned('c1', 'Project Chat')}
+ retainView={jest.fn()}
+ toggleNav={jest.fn()}
+ />
+ <Conversation
+ conversation={pinned('c2', 'Other')}
+ retainView={jest.fn()}
+ toggleNav={jest.fn()}
+ />
+ </div>
+ </DndProvider>,
+ );
+
+ const button = screen.getAllByTestId('convo-unpin-button')[0];
+ button.focus();
+ fireEvent.click(button);
+ act(() => {
+ pinCalls[0].options?.onSuccess?.();
+ });
+
+ /* Its own row, not the neighbour: this row is not going anywhere. */
+ expect(document.activeElement).toBe(screen.getByLabelText('open Project Chat'));
+ });
+
+ it('reports the rename ending when the row is removed mid-rename', () => {
+ /* The owner releases a renaming row's drag source. A row taken away while
+ * renaming, for instance by unpinning it from the project list that also
+ * renders it, would otherwise never report the rename ending and stay
+ * undraggable once it came back. */
+ const onRenamingChange = jest.fn();
+ const { unmount } = render(
+ <DndProvider backend={HTML5Backend}>
+ <div role="region" data-pinned-section="" aria-label="com_ui_pinned">
+ <Conversation
+ conversation={pinned('c1', 'Renaming')}
+ retainView={jest.fn()}
+ toggleNav={jest.fn()}
+ onRenamingChange={onRenamingChange}
+ />
+ </div>
+ </DndProvider>,
+ );
+
+ onRenamingChange.mockClear();
+ unmount();
+
+ expect(onRenamingChange).toHaveBeenCalledWith(false);
+ });
+});
diff --git a/client/src/components/Conversations/__tests__/PinnedSection.spec.tsx b/client/src/components/Conversations/__tests__/PinnedSection.spec.tsx
index 304bd18377..b7e728b03f 100644
--- a/client/src/components/Conversations/__tests__/PinnedSection.spec.tsx
+++ b/client/src/components/Conversations/__tests__/PinnedSection.spec.tsx
@@ -1,11 +1,37 @@
import React from 'react';
-import { fireEvent, render, screen } from '@testing-library/react';
+import { render, screen, fireEvent, act } from '@testing-library/react';
import '@testing-library/jest-dom';
+import { DndProvider } from 'react-dnd';
+import { HTML5Backend } from 'react-dnd-html5-backend';
import type { TConversation } from 'librechat-data-provider';
import PinnedSection from '../PinnedSection';
const mockSetExpanded = jest.fn();
let mockIsExpanded = true;
+let mockPinnedOrder: string[] | undefined;
+let mockOrderFetched = true;
+let mockOrderFetching = false;
+/** When each side of the pruning decision was fetched. Membership later than
+ * the order is the ordinary case: the order is one small record while the
+ * pinned list drains page by page. */
+let mockOrderUpdatedAt = 1000;
+const MEMBERSHIP_FETCHED_AT = 2000;
+const mockReorderFavorites = jest.fn();
+const mockUpdatePinnedOrder = jest.fn();
+
+const mockFavoritesData = {
+ favorites: [] as Array<Record<string, string>>,
+ isLoading: false,
+ isLoaded: true,
+ dataUpdatedAt: MEMBERSHIP_FETCHED_AT,
+ isAgentsLoading: false,
+ agentsMap: {} as Record<string, unknown>,
+ specsMap: {} as Record<string, unknown>,
+ endpointsConfig: {},
+ reorderFavorites: mockReorderFavorites,
+ onSelectEndpoint: jest.fn(),
+ onSelectSpec: jest.fn(),
+};
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
@@ -14,74 +40,583 @@ jest.mock('~/hooks', () => ({
jest.mock('~/utils', () => ({
cn: (...args: unknown[]) => args.filter(Boolean).join(' '),
+ getSpecAgentAvatarURL: () => null,
}));
jest.mock('~/data-provider', () => ({
useActiveJobs: () => ({ data: undefined }),
+ useGetPinnedOrderQuery: () => ({
+ data: mockPinnedOrder,
+ isSuccess: mockOrderFetched,
+ isFetching: mockOrderFetching,
+ dataUpdatedAt: mockOrderUpdatedAt,
+ }),
+ useUpdatePinnedOrderMutation: () => ({ mutate: mockUpdatePinnedOrder }),
+ usePinConversationMutation: () => ({ mutate: jest.fn() }),
+}));
+
+jest.mock('@librechat/client', () => ({
+ /* The section headers compose through the shared variant recipe. */
+ buttonVariants: () => '',
+ Skeleton: () => <div data-testid="favorite-skeleton" />,
+ useMediaQuery: () => true,
+ useToastContext: () => ({ showToast: jest.fn() }),
+}));
+
+jest.mock('~/components/Nav/Favorites/useFavoritesData', () => ({
+ __esModule: true,
+ default: () => mockFavoritesData,
}));
-jest.mock('../Convo', () => ({
+jest.mock('../Convo', () => {
+ /* A mock factory cannot close over imports, so React is required in here. */
+ const { useEffect, useRef } = jest.requireActual<typeof import('react')>('react');
+ function MockConvo({
+ conversation,
+ onRenamingChange,
+ }: {
+ conversation: { title: string };
+ onRenamingChange?: (renaming: boolean) => void;
+ }) {
+ /* Mirrors the real row's contract: a row removed mid-rename reports the
+ * rename ending on its way out. */
+ const report = useRef(onRenamingChange);
+ report.current = onRenamingChange;
+ useEffect(
+ () => () => {
+ report.current?.(false);
+ },
+ [],
+ );
+ return (
+ <div data-testid="pinned-convo">
+ <button type="button">{conversation.title}</button>
+ {/* No text content: `itemLabels` reads the row's text to assert order. */}
+ <button
+ type="button"
+ aria-label="rename"
+ data-testid={`rename-${conversation.title}`}
+ onClick={() => onRenamingChange?.(true)}
+ />
+ </div>
+ );
+ }
+ return { __esModule: true, default: MockConvo };
+});
+
+jest.mock('~/components/Nav/Favorites/FavoriteItem', () => ({
__esModule: true,
- default: ({ conversation }: { conversation: TConversation }) => (
- <div data-testid="pinned-convo">{conversation.title}</div>
- ),
+ default: ({
+ item,
+ type,
+ keyShortcuts,
+ }: {
+ item: { model?: string; id?: string; label?: string };
+ type: string;
+ keyShortcuts?: string;
+ }) => {
+ const label = item.id ?? item.label ?? item.model ?? '';
+ return (
+ <div data-testid="favorite-item" data-type={type} aria-keyshortcuts={keyShortcuts}>
+ {label}
+ </div>
+ );
+ },
}));
-const pinnedConvo = {
- conversationId: 'pinned-1',
- title: 'Pinned Chat',
- pinned: true,
- endpoint: 'openAI',
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
-} as TConversation;
-
-const anotherPinnedConvo = {
- ...pinnedConvo,
- conversationId: 'pinned-2',
- title: 'Another Pin',
-} as TConversation;
-
-describe('PinnedSection', () => {
+const pinnedConvo = (id: string, title: string) =>
+ ({ conversationId: id, title, pinned: true }) as unknown as TConversation;
+
+const renderTree = (conversations: TConversation[]) => (
+ <DndProvider backend={HTML5Backend}>
+ <PinnedSection conversations={conversations} toggleNav={jest.fn()} />
+ </DndProvider>
+);
+
+const renderSection = (conversations: TConversation[]) => render(renderTree(conversations));
+
+const itemLabels = () =>
+ Array.from(
+ screen
+ .getAllByTestId(/pinned-convo|favorite-item|favorite-skeleton/)
+ .map((el) => el.textContent?.trim()),
+ );
+
+describe('PinnedSection unified list', () => {
beforeEach(() => {
mockIsExpanded = true;
+ mockPinnedOrder = undefined;
+ mockOrderFetched = true;
+ mockOrderFetching = false;
+ mockOrderUpdatedAt = 1000;
mockSetExpanded.mockReset();
+ mockReorderFavorites.mockReset();
+ mockUpdatePinnedOrder.mockReset();
+ mockFavoritesData.favorites = [];
+ mockFavoritesData.isLoading = false;
+ mockFavoritesData.isLoaded = true;
+ mockFavoritesData.dataUpdatedAt = MEMBERSHIP_FETCHED_AT;
+ mockFavoritesData.isAgentsLoading = false;
+ mockFavoritesData.agentsMap = {};
+ mockFavoritesData.specsMap = {};
});
- it('renders nothing when there are no pinned conversations', () => {
- const { container } = render(<PinnedSection conversations={[]} toggleNav={jest.fn()} />);
+ it('renders nothing when there are no favorites or pinned conversations', () => {
+ const { container } = renderSection([]);
expect(container).toBeEmptyDOMElement();
});
- it('renders a collapsible Pinned header matching Chats and Projects', () => {
- render(<PinnedSection conversations={[pinnedConvo]} toggleNav={jest.fn()} />);
- const toggle = screen.getByRole('button', { name: 'com_ui_pinned' });
- expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ it('renders favorites followed by pinned conversations in natural order', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat'), pinnedConvo('c2', 'Another Pin')]);
+ expect(itemLabels()).toEqual(['gpt-4o', 'Pinned Chat', 'Another Pin']);
+ });
+
+ it('interleaves favorites and conversations by the stored order', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }, { agentId: 'agent-1' }];
+ mockFavoritesData.agentsMap = { 'agent-1': { id: 'agent-1' } };
+ mockPinnedOrder = ['convo:c1', 'agent:agent-1', 'model:6:openAI:gpt-4o'];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+ expect(itemLabels()).toEqual(['Pinned Chat', 'agent-1', 'gpt-4o']);
+ });
+
+ it('appends items missing from the stored order and ignores stale keys', () => {
+ mockFavoritesData.favorites = [{ spec: 'fast' }];
+ mockFavoritesData.specsMap = { fast: { name: 'fast', label: 'Fast' } };
+ mockPinnedOrder = ['convo:gone', 'model:6:openAI:removed'];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+ expect(itemLabels()).toEqual(['Fast', 'Pinned Chat']);
+ });
+
+ it('shows a skeleton row while favorites are still loading', () => {
+ mockFavoritesData.isLoading = true;
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+ expect(screen.getAllByTestId('favorite-skeleton').length).toBeGreaterThan(0);
+ expect(screen.getByText('Pinned Chat')).toBeInTheDocument();
+ });
+
+ it('hides an unresolved agent favorite once agents are loaded', () => {
+ mockFavoritesData.favorites = [{ agentId: 'agent-gone' }];
+ mockFavoritesData.isAgentsLoading = false;
+ renderSection([]);
+ expect(screen.queryAllByTestId('favorite-item')).toHaveLength(0);
+ });
+
+ it('renders the section for favorites alone', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ const { container } = renderSection([]);
+ expect(screen.getByTestId('favorite-item')).toBeInTheDocument();
+ expect(container).not.toBeEmptyDOMElement();
+ });
+
+ describe('keyboard reordering', () => {
+ const moveFocusedRow = (label: string, key: 'ArrowUp' | 'ArrowDown') =>
+ fireEvent.keyDown(screen.getByText(label), { key, altKey: true });
+
+ it('moves a row down with Alt+ArrowDown and persists the new order', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+ expect(itemLabels()).toEqual(['gpt-4o', 'Pinned Chat']);
+
+ moveFocusedRow('gpt-4o', 'ArrowDown');
+
+ expect(itemLabels()).toEqual(['Pinned Chat', 'gpt-4o']);
+ expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
+ ['convo:c1', 'model:6:openAI:gpt-4o'],
+ expect.anything(),
+ );
+ });
+
+ it('moves a row up with Alt+ArrowUp', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ moveFocusedRow('Pinned Chat', 'ArrowUp');
+
+ expect(itemLabels()).toEqual(['Pinned Chat', 'gpt-4o']);
+ });
+
+ /* Reordering against an order that has not arrived yet would merge into
+ * `[]` and, since `onMutate` cancels that GET, post only what is on screen,
+ * discarding the saved positions of everything else. */
+ /* A write that settles after the user has arranged the list again must not
+ * clear the snapshot showing that newer arrangement. */
+ it('keeps a newer arrangement when an older write settles', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'First'), pinnedConvo('c2', 'Second')]);
+
+ moveFocusedRow('gpt-4o', 'ArrowDown');
+ const firstSettle = mockUpdatePinnedOrder.mock.calls[0][1].onSettled;
+
+ moveFocusedRow('gpt-4o', 'ArrowDown');
+ const arranged = itemLabels();
+
+ act(() => firstSettle());
+
+ /* Releasing after this would otherwise save an order no longer on screen. */
+ expect(itemLabels()).toEqual(arranged);
+ });
+
+ /* Alt/Option+Arrow moves the caret word-wise inside a text field, so the
+ * shortcut has to stand down wherever the drag source does. */
+ it('leaves Alt+Arrow to the rename input while a row title is being edited', () => {
+ renderSection([pinnedConvo('c1', 'Pinned Chat'), pinnedConvo('c2', 'Second')]);
+
+ fireEvent.click(screen.getByTestId('rename-Pinned Chat'));
+ moveFocusedRow('Pinned Chat', 'ArrowDown');
+
+ expect(itemLabels()).toEqual(['Pinned Chat', 'Second']);
+ expect(mockUpdatePinnedOrder).not.toHaveBeenCalled();
+ });
+
+ /* A failed GET still reports as fetched, so the gate is on success. */
+ it('refuses to reorder until the stored order was fetched successfully', () => {
+ mockOrderFetched = false;
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ moveFocusedRow('gpt-4o', 'ArrowDown');
+
+ expect(itemLabels()).toEqual(['gpt-4o', 'Pinned Chat']);
+ expect(mockUpdatePinnedOrder).not.toHaveBeenCalled();
+ });
+
+ /* A favorites fetch that exhausted its retries stops loading with nothing
+ * to show, and pruning against that empty list would drop every favorite
+ * key from the stored order. */
+ it('keeps merging when the favorites fetch never delivered', () => {
+ mockFavoritesData.isLoaded = false;
+ mockPinnedOrder = ['convo:gone', 'convo:c1'];
+ render(
+ <DndProvider backend={HTML5Backend}>
+ <PinnedSection
+ conversations={[pinnedConvo('c1', 'Pinned Chat'), pinnedConvo('c2', 'Second')]}
+ toggleNav={jest.fn()}
+ membershipComplete
+ membershipUpdatedAt={MEMBERSHIP_FETCHED_AT}
+ />
+ </DndProvider>,
+ );
+
+ moveFocusedRow('Pinned Chat', 'ArrowDown');
+
+ expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
+ ['convo:gone', 'convo:c2', 'convo:c1'],
+ expect.anything(),
+ );
+ });
+
+ it('prunes keys that are gone once the whole list is known', () => {
+ mockPinnedOrder = ['convo:gone', 'model:6:openAI:gpt-4o', 'convo:c1'];
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ render(
+ <DndProvider backend={HTML5Backend}>
+ <PinnedSection
+ conversations={[pinnedConvo('c1', 'Pinned Chat')]}
+ toggleNav={jest.fn()}
+ membershipComplete
+ membershipUpdatedAt={MEMBERSHIP_FETCHED_AT}
+ />
+ </DndProvider>,
+ );
+
+ moveFocusedRow('gpt-4o', 'ArrowDown');
+
+ /* Merging forever would grow the array until the size guard rejected
+ * every write, so a complete membership load compacts it. */
+ expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
+ ['convo:c1', 'model:6:openAI:gpt-4o'],
+ expect.anything(),
+ );
+ });
+
+ it('does nothing at the ends of the list', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ moveFocusedRow('gpt-4o', 'ArrowUp');
+
+ expect(itemLabels()).toEqual(['gpt-4o', 'Pinned Chat']);
+ expect(mockUpdatePinnedOrder).not.toHaveBeenCalled();
+ });
+
+ it('ignores a bare arrow key so list navigation still works', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ fireEvent.keyDown(screen.getByText('gpt-4o'), { key: 'ArrowDown' });
+
+ expect(itemLabels()).toEqual(['gpt-4o', 'Pinned Chat']);
+ expect(mockUpdatePinnedOrder).not.toHaveBeenCalled();
+ });
+
+ it('announces the new position', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ moveFocusedRow('gpt-4o', 'ArrowDown');
+
+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_moved_to_position');
+ });
+
+ /* Rows can be missing from view for reasons the section cannot tell apart:
+ * a bookmark filter hides them, or the pinned query is still draining its
+ * cursor. Persisting only what is on screen would drop those keys and lose
+ * their positions, so the order is always merged, never replaced. */
+ it('keeps keys it cannot see in the stored order', () => {
+ mockPinnedOrder = ['convo:hidden', 'model:6:openAI:gpt-4o', 'convo:c1'];
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ moveFocusedRow('gpt-4o', 'ArrowDown');
+
+ expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
+ ['convo:hidden', 'convo:c1', 'model:6:openAI:gpt-4o'],
+ expect.anything(),
+ );
+ });
+
+ it('does not write the favorites array a second time', () => {
+ mockPinnedOrder = ['model:6:openAI:gpt-4o', 'convo:c1'];
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ moveFocusedRow('gpt-4o', 'ArrowDown');
+
+ /* `pinnedOrder` is the only ordering the section reads, and a second
+ * whole-array write would race the favorites membership mutations. */
+ expect(mockReorderFavorites).not.toHaveBeenCalled();
+ });
+ });
+
+ it('renders one row per favorite even when the stored list repeats one', () => {
+ /* The `/favorites` payload validator accepts a duplicate entry. Two rows
+ * keyed the same would collide in React and make every reorder POST fail
+ * the endpoint's uniqueness check. */
+ mockFavoritesData.favorites = [
+ { model: 'gpt-4o', endpoint: 'openAI' },
+ { model: 'gpt-4o', endpoint: 'openAI' },
+ ];
+ renderSection([]);
+
+ expect(screen.getAllByTestId('favorite-item')).toHaveLength(1);
+ });
+
+ /* A row removed mid-rename never reports the rename ending, so the owner
+ * would keep its drag source released even after it came back. */
+ it('reconnects the drag source when a renaming row is removed and returns', () => {
+ const { rerender } = renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ fireEvent.click(screen.getByTestId('rename-Pinned Chat'));
+ expect(screen.getByTestId('pinned-convo').parentElement).not.toHaveAttribute(
+ 'draggable',
+ 'true',
+ );
+
+ rerender(
+ <DndProvider backend={HTML5Backend}>
+ <PinnedSection conversations={[]} toggleNav={jest.fn()} />
+ </DndProvider>,
+ );
+ rerender(
+ <DndProvider backend={HTML5Backend}>
+ <PinnedSection conversations={[pinnedConvo('c1', 'Pinned Chat')]} toggleNav={jest.fn()} />
+ </DndProvider>,
+ );
+
+ expect(screen.getByTestId('pinned-convo').parentElement).toHaveAttribute('draggable', 'true');
});
- it('renders pinned conversations when expanded', () => {
+ it('releases the drag source while a row title is being edited', () => {
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ const row = screen.getByTestId('pinned-convo').parentElement as HTMLElement;
+ expect(row).toHaveAttribute('draggable', 'true');
+
+ fireEvent.click(screen.getByTestId('rename-Pinned Chat'));
+
+ /* A `draggable` ancestor swallows drag-select inside the rename input. */
+ expect(row).not.toHaveAttribute('draggable', 'true');
+ });
+
+ /* Dragging a pin onto a project row above the section, or onto Chats below
+ * it, sweeps the pointer across sibling rows whose hover handlers shift the
+ * order. That movement is incidental to a filing action, not a reorder. */
+ it('writes nothing when a drag ends without a reorder', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ const row = screen.getByTestId('pinned-convo').parentElement as HTMLElement;
+ fireEvent.dragStart(row);
+ fireEvent.dragEnd(row);
+
+ expect(mockUpdatePinnedOrder).not.toHaveBeenCalled();
+ });
+
+ /* An arrangement that arrives while the order is reconciling is held and
+ * written when the fresh order lands. The flush runs on every settle, so it
+ * has to stay quiet when there is nothing being held: reposting a committed
+ * arrangement would undo whatever that reconciliation just brought in. */
+ it('does not repost an arrangement that was already written', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ const view = renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ fireEvent.keyDown(screen.getByText('gpt-4o'), { key: 'ArrowDown', altKey: true });
+ expect(mockUpdatePinnedOrder).toHaveBeenCalledTimes(1);
+
+ mockOrderFetching = true;
+ view.rerender(renderTree([pinnedConvo('c1', 'Pinned Chat')]));
+ mockOrderFetching = false;
+ view.rerender(renderTree([pinnedConvo('c1', 'Pinned Chat')]));
+
+ expect(mockUpdatePinnedOrder).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps two model favorites distinct when a component contains the delimiter', () => {
+ /* The favorites API accepts any string for either half, so joining them on
+ * `::` collides: `a::b` + `c` and `a` + `b::c` would key the same and the
+ * dedupe would hide one of two genuinely different favorites. */
+ mockFavoritesData.favorites = [
+ { endpoint: 'a::b', model: 'c' },
+ { endpoint: 'a', model: 'b::c' },
+ ];
+ renderSection([]);
+
+ expect(screen.getAllByTestId('favorite-item')).toHaveLength(2);
+ });
+
+ /* A screen-reader user tabbing straight to a row never meets the section's
+ * written hint, so the shortcut has to be declared where focus lands. */
+ it('declares the reorder shortcut on the rows that take focus', () => {
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([pinnedConvo('c1', 'Pinned Chat')]);
+
+ expect(screen.getByTestId('favorite-item')).toHaveAttribute(
+ 'aria-keyshortcuts',
+ 'Alt+ArrowUp Alt+ArrowDown',
+ );
+ });
+
+ it('does not advertise the shortcut before reordering is possible', () => {
+ mockOrderFetched = false;
+ mockFavoritesData.favorites = [{ model: 'gpt-4o', endpoint: 'openAI' }];
+ renderSection([]);
+
+ expect(screen.getByTestId('favorite-item')).not.toHaveAttribute('aria-keyshortcuts');
+ });
+
+ /* The pinned query holds its data for five minutes while the order has none,
+ * so focusing a tab reconciles the order on its own. Pruning the newer order
+ * against the membership beside it would drop the key of a conversation
+ * another tab pinned in between, which no later fetch can bring back. */
+ it('keeps merging when the order reconciled more recently than membership', () => {
+ mockPinnedOrder = ['convo:unseen', 'convo:c1'];
+ mockOrderUpdatedAt = MEMBERSHIP_FETCHED_AT + 1;
render(
- <PinnedSection conversations={[pinnedConvo, anotherPinnedConvo]} toggleNav={jest.fn()} />,
+ <DndProvider backend={HTML5Backend}>
+ <PinnedSection
+ conversations={[pinnedConvo('c1', 'Pinned Chat'), pinnedConvo('c2', 'Second')]}
+ toggleNav={jest.fn()}
+ membershipComplete
+ membershipUpdatedAt={MEMBERSHIP_FETCHED_AT}
+ />
+ </DndProvider>,
+ );
+
+ fireEvent.keyDown(screen.getByText('Pinned Chat'), { key: 'ArrowDown', altKey: true });
+
+ expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
+ ['convo:unseen', 'convo:c2', 'convo:c1'],
+ expect.anything(),
+ );
+ });
+
+ it('preserves unseen favorite positions until favorites catch up with the order', () => {
+ mockPinnedOrder = ['model:6:openAI:unseen', 'convo:c1'];
+ mockFavoritesData.dataUpdatedAt = mockOrderUpdatedAt - 1;
+ const tree = (
+ <DndProvider backend={HTML5Backend}>
+ <PinnedSection
+ conversations={[pinnedConvo('c1', 'Pinned Chat'), pinnedConvo('c2', 'Second')]}
+ toggleNav={jest.fn()}
+ membershipComplete
+ membershipUpdatedAt={MEMBERSHIP_FETCHED_AT}
+ />
+ </DndProvider>
+ );
+ const { rerender } = render(tree);
+
+ fireEvent.keyDown(screen.getByText('Pinned Chat'), { key: 'ArrowDown', altKey: true });
+
+ expect(mockUpdatePinnedOrder).toHaveBeenLastCalledWith(
+ ['model:6:openAI:unseen', 'convo:c2', 'convo:c1'],
+ expect.anything(),
+ );
+
+ mockFavoritesData.dataUpdatedAt = mockOrderUpdatedAt;
+ act(() => mockUpdatePinnedOrder.mock.calls[0][1].onSettled());
+ rerender(tree);
+ fireEvent.keyDown(screen.getByText('Pinned Chat'), { key: 'ArrowDown', altKey: true });
+
+ expect(mockUpdatePinnedOrder).toHaveBeenLastCalledWith(
+ ['convo:c2', 'convo:c1'],
+ expect.anything(),
);
- expect(screen.getByText('Pinned Chat')).toBeInTheDocument();
- expect(screen.getByText('Another Pin')).toBeInTheDocument();
});
- it('hides pinned conversations when collapsed', () => {
- mockIsExpanded = false;
- render(<PinnedSection conversations={[pinnedConvo]} toggleNav={jest.fn()} />);
- expect(screen.getByRole('button', { name: 'com_ui_pinned' })).toHaveAttribute(
- 'aria-expanded',
- 'false',
+ it('preserves newly reconciled keys while an older arrangement remains active', () => {
+ mockPinnedOrder = ['model:6:openAI:new-favorite', 'convo:c1', 'convo:c2'];
+ mockFavoritesData.isLoaded = false;
+ const conversations = [pinnedConvo('c1', 'First'), pinnedConvo('c2', 'Second')];
+ const tree = () => (
+ <DndProvider backend={HTML5Backend}>
+ <PinnedSection
+ conversations={conversations}
+ toggleNav={jest.fn()}
+ membershipComplete
+ membershipUpdatedAt={MEMBERSHIP_FETCHED_AT}
+ />
+ </DndProvider>
);
- /** Collapse keeps children mounted so the height can tween, and hides them
- * from assistive tech instead, the same as ProjectsSection above it. */
- expect(screen.getByText('Pinned Chat').closest('[aria-hidden="true"]')).not.toBeNull();
+ const { rerender } = render(tree());
+ fireEvent.keyDown(screen.getByText('First'), { key: 'ArrowDown', altKey: true });
+
+ mockFavoritesData.favorites = [{ model: 'new-favorite', endpoint: 'openAI' }];
+ mockFavoritesData.isLoaded = true;
+ mockFavoritesData.dataUpdatedAt = MEMBERSHIP_FETCHED_AT;
+ rerender(tree());
+ fireEvent.keyDown(screen.getByText('First'), { key: 'ArrowUp', altKey: true });
+
+ expect(mockUpdatePinnedOrder).toHaveBeenLastCalledWith(
+ ['model:6:openAI:new-favorite', 'convo:c1', 'convo:c2'],
+ expect.anything(),
+ );
+ act(() => mockUpdatePinnedOrder.mock.calls[1][1].onSettled());
+ expect(itemLabels()).toEqual(['new-favorite', 'First', 'Second']);
});
- it('toggles the section when the header is clicked', () => {
- render(<PinnedSection conversations={[pinnedConvo]} toggleNav={jest.fn()} />);
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_pinned' }));
- expect(mockSetExpanded).toHaveBeenCalledWith(false);
+ /* An optimistic favorite removal leaves the earlier GET's success standing,
+ * so pruning then would drop the ordering key of a write that has not landed
+ * and cannot be recovered if it fails. */
+ it('keeps merging while a favorites write is in flight', () => {
+ mockFavoritesData.isLoaded = false;
+ mockPinnedOrder = ['convo:gone', 'convo:c1'];
+ render(
+ <DndProvider backend={HTML5Backend}>
+ <PinnedSection
+ conversations={[pinnedConvo('c1', 'Pinned Chat'), pinnedConvo('c2', 'Second')]}
+ toggleNav={jest.fn()}
+ membershipComplete
+ membershipUpdatedAt={MEMBERSHIP_FETCHED_AT}
+ />
+ </DndProvider>,
+ );
+
+ fireEvent.keyDown(screen.getByText('Pinned Chat'), { key: 'ArrowDown', altKey: true });
+
+ expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
+ ['convo:gone', 'convo:c2', 'convo:c1'],
+ expect.anything(),
+ );
});
});
diff --git a/client/src/components/Conversations/__tests__/assignDestination.spec.tsx b/client/src/components/Conversations/__tests__/assignDestination.spec.tsx
new file mode 100644
index 0000000000..450220cf47
--- /dev/null
+++ b/client/src/components/Conversations/__tests__/assignDestination.spec.tsx
@@ -0,0 +1,94 @@
+import { QueryKeys } from 'librechat-data-provider';
+import { renderHook } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { ReactNode } from 'react';
+import type { ConversationDragItem } from '../dnd';
+import { useEffectiveProjectId } from '../dnd';
+
+type PendingAssignment = { token: number; projectId: string | null } | undefined;
+
+let mockPending: PendingAssignment;
+
+jest.mock('~/data-provider/Projects/mutations', () => ({
+ getPendingAssignment: () => mockPending,
+}));
+
+jest.mock('@librechat/client', () => ({
+ useToastContext: () => ({ showToast: jest.fn() }),
+}));
+
+jest.mock('~/data-provider', () => ({
+ useAssignConversationToProjectMutation: () => ({ mutateAsync: jest.fn() }),
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+/** A drag item as the row reports it: `chatProjectId` is whatever the list that
+ * rendered the row believed when the drag began. */
+const item = (conversationId: string, chatProjectId: string | null): ConversationDragItem => ({
+ conversationId,
+ chatProjectId,
+ pinned: false,
+});
+
+const setup = () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ const { result } = renderHook(() => useEffectiveProjectId(), { wrapper });
+ return { queryClient, effectiveProjectId: result.current };
+};
+
+describe('useEffectiveProjectId', () => {
+ beforeEach(() => {
+ mockPending = undefined;
+ });
+
+ it('falls back to the row when nothing is pending or cached', () => {
+ const { effectiveProjectId } = setup();
+ expect(effectiveProjectId(item('c1', 'project-a'))).toBe('project-a');
+ });
+
+ it('prefers a pending write over everything else', () => {
+ mockPending = { token: 1, projectId: 'project-b' };
+ const { queryClient, effectiveProjectId } = setup();
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], { chatProjectId: 'project-a' });
+
+ expect(effectiveProjectId(item('c1', 'project-a'))).toBe('project-b');
+ });
+
+ it('honours a pending move back to the root list', () => {
+ mockPending = { token: 1, projectId: null };
+ const { effectiveProjectId } = setup();
+ expect(effectiveProjectId(item('c1', 'project-a'))).toBe(null);
+ });
+
+ /* The mutation writes this cache synchronously on success, so it is right the
+ * moment the write lands rather than once the lists refresh. */
+ it('uses the conversation cache once nothing is pending', () => {
+ const { queryClient, effectiveProjectId } = setup();
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], { chatProjectId: 'project-b' });
+
+ /* Two lists render this conversation and refresh independently, so a stale
+ * row must not be believed over what the write already confirmed. */
+ expect(effectiveProjectId(item('c1', 'project-a'))).toBe('project-b');
+ expect(effectiveProjectId(item('c1', null))).toBe('project-b');
+ });
+
+ it('reports the root list from the cache as a real value, not a miss', () => {
+ const { queryClient, effectiveProjectId } = setup();
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], { chatProjectId: null });
+
+ expect(effectiveProjectId(item('c1', 'project-a'))).toBe(null);
+ });
+
+ it('leaves other conversations alone', () => {
+ const { queryClient, effectiveProjectId } = setup();
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], { chatProjectId: 'project-b' });
+
+ expect(effectiveProjectId(item('c2', 'project-a'))).toBe('project-a');
+ });
+});
diff --git a/client/src/components/Conversations/__tests__/dnd.spec.ts b/client/src/components/Conversations/__tests__/dnd.spec.ts
new file mode 100644
index 0000000000..c5554841ad
--- /dev/null
+++ b/client/src/components/Conversations/__tests__/dnd.spec.ts
@@ -0,0 +1,143 @@
+import {
+ beginPinnedDrag,
+ endedOverExternalTarget,
+ markExternalHover,
+ markPinnedHover,
+ mergeVisibleOrder,
+ shouldSwapOnHover,
+} from '../dnd';
+
+/** A 36px favorite row and a 48px chat row, the two heights the pinned list
+ * mixes below the `md` breakpoint. */
+const row = (top: number, height: number) => ({ hoverTop: top, hoverBottom: top + height });
+
+describe('shouldSwapOnHover', () => {
+ it('refuses a hover on the row being dragged', () => {
+ expect(shouldSwapOnHover({ dragIndex: 1, hoverIndex: 1, pointerY: 50, ...row(36, 48) })).toBe(
+ false,
+ );
+ });
+
+ it('refuses a hover on a row the list no longer holds', () => {
+ expect(shouldSwapOnHover({ dragIndex: -1, hoverIndex: 2, pointerY: 50, ...row(36, 48) })).toBe(
+ false,
+ );
+ expect(shouldSwapOnHover({ dragIndex: 0, hoverIndex: -1, pointerY: 50, ...row(36, 48) })).toBe(
+ false,
+ );
+ });
+
+ it('waits for the midpoint when dragging downwards', () => {
+ expect(shouldSwapOnHover({ dragIndex: 0, hoverIndex: 1, pointerY: 40, ...row(36, 48) })).toBe(
+ false,
+ );
+ expect(shouldSwapOnHover({ dragIndex: 0, hoverIndex: 1, pointerY: 62, ...row(36, 48) })).toBe(
+ true,
+ );
+ });
+
+ it('waits for the midpoint when dragging upwards', () => {
+ expect(shouldSwapOnHover({ dragIndex: 2, hoverIndex: 1, pointerY: 80, ...row(36, 48) })).toBe(
+ false,
+ );
+ expect(shouldSwapOnHover({ dragIndex: 2, hoverIndex: 1, pointerY: 40, ...row(36, 48) })).toBe(
+ true,
+ );
+ });
+
+ it('does not oscillate once a shorter row has displaced a taller one', () => {
+ /* A 36px row dragged onto a 48px row below it. Before the swap the rows sit
+ * at 0-36 and 36-84; a pointer at y=40 is inside the taller row's top half,
+ * so nothing moves. Swapping there would put the taller row at 0-48, still
+ * under the same pointer, and the next hover would swap it straight back. */
+ expect(shouldSwapOnHover({ dragIndex: 0, hoverIndex: 1, pointerY: 40, ...row(36, 48) })).toBe(
+ false,
+ );
+ /* After a swap that did clear the midpoint, the displaced row occupies
+ * 0-48 and the pointer that caused it sits past its midpoint, which reads
+ * as "already ahead of this row" rather than as a reason to swap back. */
+ expect(shouldSwapOnHover({ dragIndex: 1, hoverIndex: 0, pointerY: 62, ...row(0, 48) })).toBe(
+ false,
+ );
+ });
+});
+
+describe('mergeVisibleOrder', () => {
+ it('replaces the whole order when everything is visible', () => {
+ expect(mergeVisibleOrder(['a', 'b', 'c'], ['c', 'a', 'b'])).toEqual(['c', 'a', 'b']);
+ });
+
+ it('keeps hidden keys in place when only part of the list is visible', () => {
+ /* `b` and `d` are filtered out of view. Reordering the visible `a`, `c`, `e`
+ * must not drop them, which is what persisting the visible list alone did. */
+ const stored = ['a', 'b', 'c', 'd', 'e'];
+ expect(mergeVisibleOrder(stored, ['e', 'c', 'a'])).toEqual(['e', 'b', 'c', 'd', 'a']);
+ });
+
+ it('appends visible keys the stored order does not know', () => {
+ expect(mergeVisibleOrder(['a', 'b'], ['b', 'a', 'new'])).toEqual(['b', 'a', 'new']);
+ });
+
+ it('drops nothing when the stored order is empty', () => {
+ expect(mergeVisibleOrder([], ['a', 'b'])).toEqual(['a', 'b']);
+ });
+
+ it('keeps every hidden key when only one row is visible', () => {
+ expect(mergeVisibleOrder(['a', 'b', 'c'], ['c'])).toEqual(['a', 'b', 'c']);
+ });
+});
+
+/* `didDrop()` is false both for a drop the pinned rows handled and for one an
+ * external target refused, so the last target under the pointer is what
+ * separates a deliberate reorder from a filing action that merely shifted the
+ * rows it crossed. */
+describe('drag target tracking', () => {
+ beforeEach(() => {
+ beginPinnedDrag();
+ });
+
+ it('treats a drag that never left the pinned rows as a reorder', () => {
+ markPinnedHover();
+ expect(endedOverExternalTarget()).toBe(false);
+ });
+
+ it('treats a drag ending on a project row as external, refused or not', () => {
+ markPinnedHover();
+ markExternalHover();
+ expect(endedOverExternalTarget()).toBe(true);
+ });
+
+ it('treats a drag that strayed out and came back as a reorder', () => {
+ markPinnedHover();
+ markExternalHover();
+ markPinnedHover();
+ expect(endedOverExternalTarget()).toBe(false);
+ });
+
+ /* Hovering the dragged row itself is a no-op for ordering but still says the
+ * pointer is inside the list, so a drag that wandered onto a project and came
+ * back to its own position is a reorder, not a filing action. */
+ it('counts a return to the dragged row as being back inside the list', () => {
+ markPinnedHover();
+ markExternalHover();
+ /* The row's hover fires for its own key too, before the no-op guard. */
+ markPinnedHover();
+ expect(endedOverExternalTarget()).toBe(false);
+ });
+
+ /* The header and the padding around the rows belong to the list too, so
+ * coming to rest on one of them is a return, not a departure. */
+ it('counts a return anywhere inside the section as being back inside', () => {
+ markPinnedHover();
+ markExternalHover();
+ /* The section's own hover fires where no row does. */
+ markPinnedHover();
+ expect(endedOverExternalTarget()).toBe(false);
+ });
+
+ it('starts each drag with no external hover carried over', () => {
+ markExternalHover();
+ beginPinnedDrag();
+ expect(endedOverExternalTarget()).toBe(false);
+ });
+});
diff --git a/client/src/components/Conversations/__tests__/utils.spec.ts b/client/src/components/Conversations/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..0f0d89c6a1
--- /dev/null
+++ b/client/src/components/Conversations/__tests__/utils.spec.ts
@@ -0,0 +1,33 @@
+import type { TConversation } from 'librechat-data-provider';
+import { areConversationRenderPropsEqual } from '../utils';
+
+const convo = { conversationId: 'c1', title: 'Chat' } as TConversation;
+
+describe('areConversationRenderPropsEqual', () => {
+ it('treats identical props as equal', () => {
+ expect(areConversationRenderPropsEqual({ conversation: convo }, { conversation: convo })).toBe(
+ true,
+ );
+ });
+
+ /* The shortcut appears only once the pinned order has loaded, so it changes
+ * without the conversation doing so. Ignoring it here would memo the row and
+ * leave its focusable element permanently unable to announce the shortcut. */
+ it('notices the reorder shortcut appearing on an otherwise unchanged row', () => {
+ expect(
+ areConversationRenderPropsEqual(
+ { conversation: convo },
+ { conversation: convo, keyShortcuts: 'Alt+ArrowUp Alt+ArrowDown' },
+ ),
+ ).toBe(false);
+ });
+
+ it('notices it going away again', () => {
+ expect(
+ areConversationRenderPropsEqual(
+ { conversation: convo, keyShortcuts: 'Alt+ArrowUp Alt+ArrowDown' },
+ { conversation: convo },
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/client/src/components/Conversations/dnd.ts b/client/src/components/Conversations/dnd.ts
new file mode 100644
index 0000000000..95e9c8e1fc
--- /dev/null
+++ b/client/src/components/Conversations/dnd.ts
@@ -0,0 +1,167 @@
+import { useCallback } from 'react';
+import { useToastContext } from '@librechat/client';
+import { QueryKeys } from 'librechat-data-provider';
+import { useQueryClient } from '@tanstack/react-query';
+import type { TConversation } from 'librechat-data-provider';
+import { getPendingAssignment } from '~/data-provider/Projects/mutations';
+import { useAssignConversationToProjectMutation } from '~/data-provider';
+import { NotificationSeverity } from '~/common';
+import { useLocalize } from '~/hooks';
+
+export const CONVERSATION_DRAG_TYPE = 'conversation-item';
+
+/** Which kind of target the pointer was over most recently.
+ *
+ * `monitor.didDrop()` alone cannot tell a reorder from a filing action that
+ * was refused: dropping a chat on the project it already belongs to is
+ * rejected, so no target handles it and the drop looks exactly like one that
+ * landed inside the pinned list, even though the rows it crossed on the way
+ * moved only incidentally. Tracking who was last under the pointer also allows
+ * for a drag that strays over a project and comes back to reorder after all. */
+let lastHoverWasExternal = false;
+
+/** Called by the pinned rows, whose hover is what reorders the list. */
+export const markPinnedHover = (): void => {
+ lastHoverWasExternal = false;
+};
+
+/** Called by the project rows and the Chats section, accepted or refused. */
+export const markExternalHover = (): void => {
+ lastHoverWasExternal = true;
+};
+
+export const beginPinnedDrag = (): void => {
+ lastHoverWasExternal = false;
+};
+
+export const endedOverExternalTarget = (): boolean => lastHoverWasExternal;
+
+export type ConversationDragItem = {
+ conversationId: string;
+ chatProjectId: string | null;
+ pinned: boolean;
+};
+
+/**
+ * The project a conversation belongs to for the purpose of accepting a drop.
+ *
+ * A drag item carries whatever the list that rendered its row believed, which
+ * goes stale the moment an assignment is accepted, and the same conversation
+ * can be rendered by several lists that refresh independently. So the pending
+ * write wins if there is one, then the conversation cache the mutation writes
+ * synchronously on success, and only then the row's own value.
+ */
+export const useEffectiveProjectId = () => {
+ const queryClient = useQueryClient();
+ return useCallback(
+ (item: ConversationDragItem): string | null => {
+ if (!item.conversationId) {
+ return item.chatProjectId;
+ }
+ const pending = getPendingAssignment(item.conversationId);
+ if (pending) {
+ return pending.projectId;
+ }
+ const cached = queryClient.getQueryData<TConversation>([
+ QueryKeys.conversation,
+ item.conversationId,
+ ]);
+ /* A cache miss falls through to the row, but a cached `null` is a real
+ * answer: it means the chat was confirmed out of every project. */
+ if (cached) {
+ return cached.chatProjectId ?? null;
+ }
+ return item.chatProjectId;
+ },
+ [queryClient],
+ );
+};
+
+/** Files a dragged conversation into a project, or back into the root chats
+ * list on `projectId: null`. The mutation owns every cache invalidation
+ * (chats, pinned rows, project stats); this adds the toast feedback the
+ * options-menu path already shows for the same action. */
+export const useAssignDroppedConversation = () => {
+ const localize = useLocalize();
+ const { showToast } = useToastContext();
+ const assignConversation = useAssignConversationToProjectMutation();
+ const effectiveProjectId = useEffectiveProjectId();
+
+ return useCallback(
+ (item: ConversationDragItem, projectId: string | null) => {
+ const conversationId = item.conversationId;
+ if (!conversationId || effectiveProjectId(item) === projectId) {
+ return;
+ }
+ /* The mutation serializes these per conversation and records where each
+ * is headed, so this only has to report the outcome. */
+ void assignConversation.mutateAsync({ conversationId, projectId }).then(
+ () =>
+ showToast({
+ message: localize('com_ui_project_updated'),
+ severity: NotificationSeverity.SUCCESS,
+ showIcon: true,
+ }),
+ () =>
+ showToast({
+ message: localize('com_ui_project_update_error'),
+ severity: NotificationSeverity.ERROR,
+ showIcon: true,
+ }),
+ );
+ },
+ [assignConversation, effectiveProjectId, localize, showToast],
+ );
+};
+
+/** Whether a hover should reorder yet. Rows only swap once the pointer crosses
+ * the hovered row's midpoint: without the threshold a shorter dragged row
+ * keeps re-entering the taller row it just displaced, and the list oscillates
+ * under a cursor that never moved. */
+export const shouldSwapOnHover = ({
+ dragIndex,
+ hoverIndex,
+ pointerY,
+ hoverTop,
+ hoverBottom,
+}: {
+ dragIndex: number;
+ hoverIndex: number;
+ pointerY: number;
+ hoverTop: number;
+ hoverBottom: number;
+}): boolean => {
+ if (dragIndex < 0 || hoverIndex < 0 || dragIndex === hoverIndex) {
+ return false;
+ }
+ const middleY = (hoverBottom - hoverTop) / 2;
+ const offsetY = pointerY - hoverTop;
+ if (dragIndex < hoverIndex) {
+ return offsetY >= middleY;
+ }
+ return offsetY <= middleY;
+};
+
+/** Rewrites only the slots the visible keys occupy in the stored order, so a
+ * reorder performed while a filter hides part of the list keeps every hidden
+ * key exactly where it was instead of dropping it. Visible keys the stored
+ * order does not know about append at the end. */
+export const mergeVisibleOrder = (stored: string[], visible: string[]): string[] => {
+ const visibleSet = new Set(visible);
+ const merged: string[] = [];
+ let next = 0;
+ for (const key of stored) {
+ if (!visibleSet.has(key)) {
+ merged.push(key);
+ continue;
+ }
+ if (next < visible.length) {
+ merged.push(visible[next]);
+ next++;
+ }
+ }
+ for (; next < visible.length; next++) {
+ merged.push(visible[next]);
+ }
+ return merged;
+};
diff --git a/client/src/components/Conversations/focus.ts b/client/src/components/Conversations/focus.ts
new file mode 100644
index 0000000000..408b884f47
--- /dev/null
+++ b/client/src/components/Conversations/focus.ts
@@ -0,0 +1,84 @@
+/** Rows in the sidebar's Pinned section. A favorite row is focusable itself
+ * (`role="button"`), while a chat row is a plain container whose link carries
+ * the focus, so both shapes have to be handled. */
+const PINNED_ROW_SELECTOR = '[data-testid="convo-item"],[data-testid="favorite-item"]';
+
+/** Where focus goes when a removed row has no neighbour left. In sidebar order:
+ * the expanded panel's own control, the mobile drawer's, then the chat
+ * header's. */
+const NEW_CHAT_CONTROLS = [
+ '[data-testid="new-chat-button"]',
+ '[data-testid="nav-new-chat-fab"]',
+ '[data-testid="header-new-chat-button"]',
+];
+
+const findNewChatControl = (): HTMLElement | null => {
+ for (const selector of NEW_CHAT_CONTROLS) {
+ const control = document.querySelector<HTMLElement>(selector);
+ if (control) {
+ return control;
+ }
+ }
+ return null;
+};
+
+const focusableWithin = (row: HTMLElement): HTMLElement | null => {
+ if (row.matches('a[href],button:not([disabled]),[tabindex]:not([tabindex="-1"])')) {
+ return row;
+ }
+ return row.querySelector<HTMLElement>('a[href],button:not([disabled])');
+};
+
+/**
+ * The element that should take focus when `row` is removed: the row below, else
+ * the one above, else the New Chat button. Resolve this *before* starting the
+ * removal: once the row unmounts there is no longer a position to search from.
+ */
+export const resolveRowBeside = (row: HTMLElement | null): HTMLElement | null => {
+ /* Scoped to the Pinned section by its own marker, not by role: the whole
+ * conversations pane is a labelled region too, and the project lists inside
+ * it render this same row. Unpinning a chat there only clears its pinned
+ * flag, so that row stays put and its focus must stay with it. */
+ const scope = row?.closest('[data-pinned-section]');
+ if (row && scope) {
+ const rows = Array.from(scope.querySelectorAll<HTMLElement>(PINNED_ROW_SELECTOR));
+ const current = rows.indexOf(row);
+ const neighbour = rows[current + 1] ?? rows[current - 1];
+ const target = neighbour ? focusableWithin(neighbour) : null;
+ if (target) {
+ return target;
+ }
+ }
+
+ if (!scope) {
+ return null;
+ }
+ return findNewChatControl();
+};
+
+/**
+ * The row's own focusable element, for when the row itself survives but the
+ * control that had focus does not: unpinning from a project list only clears
+ * the flag, and the pin badge that was focused disappears with it.
+ */
+export const focusableInRow = (row: HTMLElement | null): HTMLElement | null =>
+ row ? focusableWithin(row) : null;
+
+/** Resolves and focuses in one step, for removals that happen synchronously. */
+export const focusRowBeside = (row: HTMLElement | null): boolean => {
+ const target = resolveRowBeside(row);
+ target?.focus();
+ return target != null && document.activeElement === target;
+};
+
+/**
+ * Focuses the first surviving row in `scope`, falling back to the New Chat
+ * button. For removals that report back only once the row is already gone, so
+ * there is no longer a position to search around.
+ */
+export const focusFirstRow = (scope: HTMLElement | null): boolean => {
+ const row = scope?.querySelector<HTMLElement>(PINNED_ROW_SELECTOR) ?? null;
+ const target = (row && focusableWithin(row)) ?? findNewChatControl();
+ target?.focus();
+ return target != null && document.activeElement === target;
+};
diff --git a/client/src/components/Conversations/utils.ts b/client/src/components/Conversations/utils.ts
index 4b12d1a009..281acc11bd 100644
--- a/client/src/components/Conversations/utils.ts
+++ b/client/src/components/Conversations/utils.ts
@@ -3,6 +3,9 @@ import type { TConversation } from 'librechat-data-provider';
export type ConversationRenderProps = {
conversation: TConversation;
isGenerating?: boolean;
+ /** Announced on the row's focusable element, and it appears only once the
+ * owning list can act on it, so a change here has to reach the DOM. */
+ keyShortcuts?: string;
};
export function areConversationIconFieldsEqual(
@@ -44,6 +47,7 @@ export function areConversationRenderPropsEqual(
) {
return (
areConversationListItemFieldsEqual(prevProps.conversation, nextProps.conversation) &&
- prevProps.isGenerating === nextProps.isGenerating
+ prevProps.isGenerating === nextProps.isGenerating &&
+ prevProps.keyShortcuts === nextProps.keyShortcuts
);
}
diff --git a/client/src/components/Nav/AgentMarketplaceButton.tsx b/client/src/components/Nav/AgentMarketplaceButton.tsx
index 1caabe9c8f..c7173ee73d 100644
--- a/client/src/components/Nav/AgentMarketplaceButton.tsx
+++ b/client/src/components/Nav/AgentMarketplaceButton.tsx
@@ -1,45 +1,54 @@
-import React, { useCallback } from 'react';
+import { Link } from 'react-router-dom';
import { LayoutGrid } from 'lucide-react';
-import { useNavigate } from 'react-router-dom';
-import { TooltipAnchor, Button } from '@librechat/client';
+import { Button, TooltipAnchor } from '@librechat/client';
import { useLocalize, useShowMarketplace } from '~/hooks';
interface AgentMarketplaceButtonProps {
- isSmallScreen?: boolean;
- toggleNav: () => void;
+ /** Which way the tooltip opens: the desktop rail is a left edge, the mobile
+ * drawer header is a top edge. */
+ side?: 'right' | 'bottom';
+ /** Mobile dismisses the drawer on navigation; the desktop rail stays put. */
+ onNavigate?: () => void;
}
+/** Agent Marketplace entry in the sidebar. Self-gated on marketplace
+ * permissions, so a deployment without access is left with no gap. */
export default function AgentMarketplaceButton({
- isSmallScreen,
- toggleNav,
+ side = 'right',
+ onNavigate,
}: AgentMarketplaceButtonProps) {
- const navigate = useNavigate();
const localize = useLocalize();
const showAgentMarketplace = useShowMarketplace();
- const handleAgentMarketplace = useCallback(() => {
- navigate('/agents');
- if (isSmallScreen) {
- toggleNav();
- }
- }, [navigate, isSmallScreen, toggleNav]);
-
if (!showAgentMarketplace) {
return null;
}
return (
<TooltipAnchor
+ side={side}
description={localize('com_agents_marketplace')}
render={
- <Button
- variant="outline"
- data-testid="nav-agents-marketplace-button"
- aria-label={localize('com_agents_marketplace')}
- className="rounded-full border-none bg-transparent p-2 hover:bg-surface-hover md:rounded-xl"
- onClick={handleAgentMarketplace}
- >
- <LayoutGrid className="icon-lg text-text-primary" aria-hidden="true" />
+ /** Composed through the shared button so the focus ring, hover fill and
+ * theme timing come from the primitive rather than being restated: a
+ * hand-rolled version of this had no focus ring at all. `asChild`
+ * keeps it a router Link, so modifier- and middle-clicks still open
+ * the marketplace in a new tab, and those stay on the current page and
+ * so must not dismiss. */
+ <Button asChild variant="ghost" size="icon" className="h-9 w-9 flex-shrink-0">
+ <Link
+ to="/agents"
+ data-testid="nav-agents-marketplace-button"
+ aria-label={localize('com_agents_marketplace')}
+ onClick={(event) => {
+ if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey) {
+ return;
+ }
+ onNavigate?.();
+ }}
+ >
+ <LayoutGrid className="h-5 w-5 text-text-primary" aria-hidden="true" />
+ </Link>
</Button>
}
/>
diff --git a/client/src/components/Nav/Bookmarks/BookmarkNav.tsx b/client/src/components/Nav/Bookmarks/BookmarkNav.tsx
index 5b1058b548..cb9ec00b8c 100644
--- a/client/src/components/Nav/Bookmarks/BookmarkNav.tsx
+++ b/client/src/components/Nav/Bookmarks/BookmarkNav.tsx
@@ -12,9 +12,12 @@ import { cn } from '~/utils';
type BookmarkNavProps = {
tags: string[];
setTags: (tags: string[]) => void;
+ /** Sizes the trigger to the search bar it shares a row with; otherwise it keeps
+ * the compact section-heading size used beside the Chats heading on mobile. */
+ matchSearchBar?: boolean;
};
-const BookmarkNav: FC<BookmarkNavProps> = ({ tags, setTags }: BookmarkNavProps) => {
+const BookmarkNav: FC<BookmarkNavProps> = ({ tags, setTags, matchSearchBar }: BookmarkNavProps) => {
const localize = useLocalize();
const menuId = useId();
const [isMenuOpen, setIsMenuOpen] = useState(false);
@@ -106,10 +109,14 @@ const BookmarkNav: FC<BookmarkNavProps> = ({ tags, setTags }: BookmarkNavProps)
id="bookmark-nav-menu-button"
aria-label={buttonAriaLabel}
aria-pressed={tags.length > 0}
- /** Matches the Projects heading's actions — it sits beside a section heading too. */
+ /** Matches the Projects heading's actions: it sits beside a section heading too. */
className={cn(
- buttonVariants({ variant: 'section-action', size: 'icon-xs' }),
+ buttonVariants({
+ variant: 'section-action',
+ size: matchSearchBar ? null : 'icon-xs',
+ }),
'shrink-0',
+ matchSearchBar && 'h-9 w-9 rounded-lg',
isMenuOpen && 'bg-surface-active-alt text-text-primary',
)}
data-testid="bookmark-menu"
diff --git a/client/src/components/Nav/Favorites/FavoriteItem.tsx b/client/src/components/Nav/Favorites/FavoriteItem.tsx
index c0a76628a6..ce049bc560 100644
--- a/client/src/components/Nav/Favorites/FavoriteItem.tsx
+++ b/client/src/components/Nav/Favorites/FavoriteItem.tsx
@@ -18,6 +18,9 @@ type Kwargs = {
type FavoriteItemBaseProps = {
onRemoveFocus?: () => void;
+ /** Shortcuts an owning list handles for this row, declared here because this
+ * is the element that takes focus. */
+ keyShortcuts?: string;
};
type AgentFavoriteProps = FavoriteItemBaseProps & {
@@ -44,7 +47,7 @@ type SpecFavoriteProps = FavoriteItemBaseProps & {
type FavoriteItemProps = AgentFavoriteProps | ModelFavoriteProps | SpecFavoriteProps;
export default function FavoriteItem(props: FavoriteItemProps) {
- const { onRemoveFocus } = props;
+ const { onRemoveFocus, keyShortcuts } = props;
const localize = useLocalize();
const { removeFavoriteAgent, removeFavoriteModel, removeFavoriteSpec } = useFavorites();
@@ -127,6 +130,7 @@ export default function FavoriteItem(props: FavoriteItemProps) {
role="button"
tabIndex={0}
aria-label={ariaLabel}
+ aria-keyshortcuts={keyShortcuts}
className="group relative flex w-full cursor-pointer items-center justify-between rounded-lg p-2 text-sm text-text-primary outline-none hover:bg-surface-active-alt focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary"
onClick={handleClick}
onKeyDown={handleKeyDown}
diff --git a/client/src/components/Nav/Favorites/FavoritesList.tsx b/client/src/components/Nav/Favorites/FavoritesList.tsx
deleted file mode 100644
index 889d72a91a..0000000000
--- a/client/src/components/Nav/Favorites/FavoritesList.tsx
+++ /dev/null
@@ -1,495 +0,0 @@
-import React, { useRef, useCallback, useMemo, useEffect, memo } from 'react';
-import { useRecoilValue } from 'recoil';
-import { LayoutGrid } from 'lucide-react';
-import { useDrag, useDrop } from 'react-dnd';
-import { useNavigate } from 'react-router-dom';
-import { useQueries } from '@tanstack/react-query';
-import { Skeleton, useMediaQuery } from '@librechat/client';
-import { QueryKeys, EModelEndpoint, dataService } from 'librechat-data-provider';
-import type { Agent, TEndpointsConfig, TModelSpec } from 'librechat-data-provider';
-import {
- useGetConversation,
- useFavorites,
- useLocalize,
- useShowMarketplace,
- useNewConvo,
-} from '~/hooks';
-import { useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';
-import { useAssistantsMapContext, useAgentsMapContext } from '~/Providers';
-import useSelectMention from '~/hooks/Input/useSelectMention';
-import { getSpecAgentAvatarURL } from '~/utils';
-import FavoriteItem from './FavoriteItem';
-import store from '~/store';
-
-/** A 404/403 from getAgentById means the agent is gone or inaccessible; other errors are transient. */
-const isMissingAgentError = (error: unknown): boolean => {
- if (error && typeof error === 'object' && 'response' in error) {
- const status = (error as { response?: { status?: number } }).response?.status;
- return status === 404 || status === 403;
- }
- return false;
-};
-
-/** Height intentionally matches FavoriteItem (px-3 py-2 + h-5 icon) to keep the CellMeasurerCache valid across the isAgentsLoading transition. */
-const FavoriteItemSkeleton = () => (
- <div
- className="flex w-full items-center rounded-lg px-3 py-2"
- data-testid="favorite-item-skeleton"
- >
- <Skeleton className="mr-2 h-5 w-5 rounded-full" />
- <Skeleton className="h-4 w-24" />
- </div>
-);
-
-const MarketplaceSkeleton = () => (
- <div className="flex w-full items-center rounded-lg px-3 py-2">
- <Skeleton className="mr-2 h-5 w-5" />
- <Skeleton className="h-4 w-28" />
- </div>
-);
-
-interface DraggableFavoriteItemProps {
- id: string;
- index: number;
- moveItem: (dragIndex: number, hoverIndex: number) => void;
- onDrop: () => void;
- children: React.ReactNode;
-}
-
-const DraggableFavoriteItem = ({
- id,
- index,
- moveItem,
- onDrop,
- children,
-}: DraggableFavoriteItemProps) => {
- const ref = useRef<HTMLDivElement>(null);
- /**
- * HTML5 drag needs a hover-capable pointer. Connecting the drag source on touch would
- * stamp `draggable="true"` on this wrapper, and iOS Safari hands a touch on a draggable
- * element to the drag recognizer instead of synthesizing a click, so the row underneath
- * only selects on the second tap.
- */
- const canDrag = useMediaQuery('(hover: hover)');
- const [{ handlerId }, drop] = useDrop<{ index: number; id: string }, unknown, { handlerId: any }>(
- {
- accept: 'favorite-item',
- collect(monitor) {
- return {
- handlerId: monitor.getHandlerId(),
- };
- },
- hover(item, monitor) {
- if (!ref.current) {
- return;
- }
- const dragIndex = item.index;
- const hoverIndex = index;
-
- if (dragIndex === hoverIndex) {
- return;
- }
-
- const hoverBoundingRect = ref.current?.getBoundingClientRect();
- const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
- const clientOffset = monitor.getClientOffset();
- if (!clientOffset) {
- return;
- }
- const hoverClientY = clientOffset.y - hoverBoundingRect.top;
-
- if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
- return;
- }
-
- if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
- return;
- }
-
- moveItem(dragIndex, hoverIndex);
- item.index = hoverIndex;
- },
- },
- );
-
- const [{ isDragging }, drag] = useDrag({
- type: 'favorite-item',
- item: () => {
- return { id, index };
- },
- collect: (monitor) => ({
- isDragging: monitor.isDragging(),
- }),
- end: () => {
- onDrop();
- },
- });
-
- const opacity = isDragging ? 0 : 1;
- drop(ref);
- drag(canDrag ? ref : null);
-
- return (
- <div ref={ref} style={{ opacity }} data-handler-id={handlerId}>
- {children}
- </div>
- );
-};
-
-function FavoritesList({
- isSmallScreen,
- toggleNav,
-}: {
- isSmallScreen?: boolean;
- toggleNav?: () => void;
-}) {
- const navigate = useNavigate();
- const localize = useLocalize();
- const search = useRecoilValue(store.search);
- const getConversation = useGetConversation(0);
- const { favorites, reorderFavorites, isLoading: isFavoritesLoading } = useFavorites();
- const showAgentMarketplace = useShowMarketplace();
-
- const { newConversation } = useNewConvo();
- const assistantsMap = useAssistantsMapContext();
- const agentsMap = useAgentsMapContext();
- const { data: endpointsConfig = {} as TEndpointsConfig, isLoading: isEndpointsLoading } =
- useGetEndpointsQuery();
- const { data: startupConfig } = useGetStartupConfig();
-
- const modelSpecs = useMemo(
- () => startupConfig?.modelSpecs?.list ?? [],
- [startupConfig?.modelSpecs?.list],
- );
-
- const specsMap = useMemo(() => {
- const map: Record<string, TModelSpec> = {};
- for (const spec of modelSpecs) {
- map[spec.name] = spec;
- }
- return map;
- }, [modelSpecs]);
-
- const { onSelectEndpoint: _onSelectEndpoint, onSelectSpec: _onSelectSpec } = useSelectMention({
- modelSpecs,
- assistantsMap,
- endpointsConfig,
- getConversation,
- newConversation,
- returnHandlers: true,
- });
-
- const onSelectEndpoint = useCallback(
- (...args: Parameters<NonNullable<typeof _onSelectEndpoint>>) => {
- _onSelectEndpoint?.(...args);
- if (isSmallScreen && toggleNav) {
- toggleNav();
- }
- },
- [_onSelectEndpoint, isSmallScreen, toggleNav],
- );
-
- const onSelectSpec = useCallback(
- (...args: Parameters<NonNullable<typeof _onSelectSpec>>) => {
- _onSelectSpec?.(...args);
- if (isSmallScreen && toggleNav) {
- toggleNav();
- }
- },
- [_onSelectSpec, isSmallScreen, toggleNav],
- );
-
- const marketplaceRef = useRef<HTMLDivElement>(null);
- const listContainerRef = useRef<HTMLDivElement>(null);
-
- const handleAgentMarketplace = useCallback(() => {
- navigate('/agents');
- if (isSmallScreen && toggleNav) {
- toggleNav();
- }
- }, [navigate, isSmallScreen, toggleNav]);
-
- const handleRemoveFocus = useCallback(() => {
- if (marketplaceRef.current) {
- marketplaceRef.current.focus();
- return;
- }
- const nextFavorite = listContainerRef.current?.querySelector<HTMLElement>(
- '[data-testid="favorite-item"]',
- );
- if (nextFavorite) {
- nextFavorite.focus();
- return;
- }
- const newChatButton = document.querySelector<HTMLElement>(
- '[data-testid="nav-new-chat-button"]',
- );
- newChatButton?.focus();
- }, []);
-
- const safeFavorites = useMemo(() => (Array.isArray(favorites) ? favorites : []), [favorites]);
-
- const allAgentIds = useMemo(
- () => safeFavorites.map((f) => f.agentId).filter(Boolean) as string[],
- [safeFavorites],
- );
-
- const agentsEndpointEnabled = !!endpointsConfig?.[EModelEndpoint.agents];
-
- const agentIdsToFetch = useMemo(() => {
- if (!agentsEndpointEnabled) {
- return [];
- }
- if (agentsMap === undefined) {
- return allAgentIds;
- }
- return allAgentIds.filter((id) => !agentsMap[id]);
- }, [allAgentIds, agentsMap, agentsEndpointEnabled]);
-
- const agentQueries = useQueries({
- queries: agentIdsToFetch.map((agentId) => ({
- queryKey: [QueryKeys.agent, agentId],
- queryFn: (): Promise<Agent> => dataService.getAgentById({ agent_id: agentId }),
- staleTime: 1000 * 60 * 5,
- retry: (failureCount: number, error: unknown) =>
- !isMissingAgentError(error) && failureCount < 3,
- })),
- });
-
- const staleAgentIdsKey = useMemo(() => {
- // Only persist cleanup once the global map has loaded. A revoked AGENTS.USE role
- // makes every getAgentById return a global 403, which must not delete favorites.
- if (agentsMap === undefined) {
- return '';
- }
- const ids: string[] = [];
- for (let i = 0; i < agentIdsToFetch.length; i++) {
- const query = agentQueries[i];
- if (query.isError && isMissingAgentError(query.error)) {
- ids.push(agentIdsToFetch[i]);
- }
- }
- return ids.sort().join(',');
- }, [agentIdsToFetch, agentQueries, agentsMap]);
-
- const cleanupAttemptedRef = useRef('');
-
- useEffect(() => {
- if (!staleAgentIdsKey || cleanupAttemptedRef.current === staleAgentIdsKey) {
- return;
- }
- const staleSet = new Set(staleAgentIdsKey.split(','));
- const cleaned = safeFavorites.filter((f) => !f.agentId || !staleSet.has(f.agentId));
- if (cleaned.length < safeFavorites.length) {
- cleanupAttemptedRef.current = staleAgentIdsKey;
- reorderFavorites(cleaned, true);
- }
- }, [staleAgentIdsKey, safeFavorites, reorderFavorites]);
-
- const staleSpecNamesKey = useMemo(() => {
- if (startupConfig === undefined) {
- return '';
- }
- return safeFavorites
- .filter((f) => f.spec && !specsMap[f.spec])
- .map((f) => f.spec as string)
- .sort()
- .join(',');
- }, [safeFavorites, specsMap, startupConfig]);
-
- const specCleanupAttemptedRef = useRef('');
-
- useEffect(() => {
- if (!staleSpecNamesKey || specCleanupAttemptedRef.current === staleSpecNamesKey) {
- return;
- }
- const staleSet = new Set(staleSpecNamesKey.split(','));
- const cleaned = safeFavorites.filter((f) => !f.spec || !staleSet.has(f.spec));
- if (cleaned.length < safeFavorites.length) {
- specCleanupAttemptedRef.current = staleSpecNamesKey;
- reorderFavorites(cleaned, true);
- }
- }, [staleSpecNamesKey, safeFavorites, reorderFavorites]);
-
- const combinedAgentsMap = useMemo(() => {
- const combined: Record<string, Agent> = {};
- if (agentsMap) {
- for (const [key, value] of Object.entries(agentsMap)) {
- if (value) {
- combined[key] = value;
- }
- }
- }
- agentQueries.forEach((query) => {
- if (query.data) {
- combined[query.data.id] = query.data;
- }
- });
- return combined;
- }, [agentsMap, agentQueries]);
-
- const isAgentsLoading =
- allAgentIds.length > 0 &&
- (isEndpointsLoading ||
- agentQueries.some(
- (q) =>
- q.isLoading || (agentsMap === undefined && q.isError && !isMissingAgentError(q.error)),
- ));
-
- const draggedFavoritesRef = useRef(safeFavorites);
-
- const moveItem = useCallback(
- (dragIndex: number, hoverIndex: number) => {
- const newFavorites = [...draggedFavoritesRef.current];
- const [draggedItem] = newFavorites.splice(dragIndex, 1);
- newFavorites.splice(hoverIndex, 0, draggedItem);
- draggedFavoritesRef.current = newFavorites;
- reorderFavorites(newFavorites, false);
- },
- [reorderFavorites],
- );
-
- const handleDrop = useCallback(() => {
- // Persist the final order using the ref which has the latest state
- reorderFavorites(draggedFavoritesRef.current, true);
- }, [reorderFavorites]);
-
- // Keep ref in sync when favorites change from external sources
- useEffect(() => {
- draggedFavoritesRef.current = safeFavorites;
- }, [safeFavorites]);
-
- if (search.query) {
- return null;
- }
-
- if (!isFavoritesLoading && safeFavorites.length === 0 && !showAgentMarketplace) {
- return null;
- }
-
- if (isFavoritesLoading) {
- return (
- <div className="mb-2 flex flex-col pb-2">
- <div className="mt-1 flex flex-col gap-1">
- {showAgentMarketplace && <MarketplaceSkeleton />}
- <FavoriteItemSkeleton />
- </div>
- </div>
- );
- }
-
- return (
- <div className="mb-2 flex flex-col">
- <div ref={listContainerRef} className="mt-1 flex flex-col gap-1">
- {/* Show skeletons for ALL items while agents are still loading */}
- {isAgentsLoading ? (
- <>
- {/* Marketplace skeleton */}
- {showAgentMarketplace && <MarketplaceSkeleton />}
- {/* Favorite items skeletons */}
- {safeFavorites.map((_, index) => (
- <FavoriteItemSkeleton key={`skeleton-${index}`} />
- ))}
- </>
- ) : (
- <>
- {/* Agent Marketplace button */}
- {showAgentMarketplace && (
- <div
- ref={marketplaceRef}
- role="button"
- tabIndex={0}
- aria-label={localize('com_agents_marketplace')}
- className="group relative flex w-full cursor-pointer items-center justify-between rounded-lg px-3 py-2 text-sm text-text-primary outline-none hover:bg-surface-active-alt focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring-primary"
- onClick={handleAgentMarketplace}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- handleAgentMarketplace();
- }
- }}
- data-testid="nav-agents-marketplace-button"
- >
- <div className="flex flex-1 items-center truncate pr-6">
- <div className="mr-2 h-5 w-5">
- <LayoutGrid className="h-5 w-5 text-text-primary" />
- </div>
- <span className="truncate">{localize('com_agents_marketplace')}</span>
- </div>
- </div>
- )}
- {safeFavorites.map((fav, index) => {
- if (fav.agentId) {
- const agent = combinedAgentsMap?.[fav.agentId];
- if (!agent) {
- return null;
- }
- return (
- <DraggableFavoriteItem
- key={fav.agentId}
- id={fav.agentId}
- index={index}
- moveItem={moveItem}
- onDrop={handleDrop}
- >
- <FavoriteItem
- item={agent}
- type="agent"
- onSelectEndpoint={onSelectEndpoint}
- onRemoveFocus={handleRemoveFocus}
- />
- </DraggableFavoriteItem>
- );
- } else if (fav.spec) {
- const spec = specsMap[fav.spec];
- if (!spec) {
- return null;
- }
- return (
- <DraggableFavoriteItem
- key={`spec-${fav.spec}`}
- id={`spec-${fav.spec}`}
- index={index}
- moveItem={moveItem}
- onDrop={handleDrop}
- >
- <FavoriteItem
- item={spec}
- type="spec"
- onSelectSpec={onSelectSpec}
- onRemoveFocus={handleRemoveFocus}
- endpointsConfig={endpointsConfig}
- agentAvatarURL={getSpecAgentAvatarURL(spec, agentsMap)}
- />
- </DraggableFavoriteItem>
- );
- } else if (fav.model && fav.endpoint) {
- return (
- <DraggableFavoriteItem
- key={`${fav.endpoint}-${fav.model}`}
- id={`${fav.endpoint}-${fav.model}`}
- index={index}
- moveItem={moveItem}
- onDrop={handleDrop}
- >
- <FavoriteItem
- item={{ model: fav.model, endpoint: fav.endpoint }}
- type="model"
- onSelectEndpoint={onSelectEndpoint}
- onRemoveFocus={handleRemoveFocus}
- />
- </DraggableFavoriteItem>
- );
- }
- return null;
- })}
- </>
- )}
- </div>
- </div>
- );
-}
-
-FavoritesList.displayName = 'FavoritesList';
-
-export default memo(FavoritesList);
diff --git a/client/src/components/Nav/Favorites/tests/FavoritesList.spec.tsx b/client/src/components/Nav/Favorites/tests/FavoritesList.spec.tsx
deleted file mode 100644
index 2f1ccab12a..0000000000
--- a/client/src/components/Nav/Favorites/tests/FavoritesList.spec.tsx
+++ /dev/null
@@ -1,569 +0,0 @@
-import React from 'react';
-import { render, waitFor, fireEvent, screen } from '@testing-library/react';
-import '@testing-library/jest-dom';
-import { RecoilRoot } from 'recoil';
-import { DndProvider } from 'react-dnd';
-import { BrowserRouter } from 'react-router-dom';
-import { HTML5Backend } from 'react-dnd-html5-backend';
-import { dataService, EModelEndpoint } from 'librechat-data-provider';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import type { Agent } from 'librechat-data-provider';
-
-// Mock store before importing FavoritesList
-jest.mock('~/store', () => {
- const { atom } = jest.requireActual('recoil');
- return {
- __esModule: true,
- default: {
- search: atom({
- key: 'mock-search-atom',
- default: { query: '' },
- }),
- conversationByIndex: (index: number) =>
- atom({
- key: `mock-conversation-atom-${index}`,
- default: null,
- }),
- },
- };
-});
-import FavoritesList from '../FavoritesList';
-
-type FavoriteItem = {
- agentId?: string;
- model?: string;
- endpoint?: string;
- spec?: string;
-};
-
-// Mock dataService
-jest.mock('librechat-data-provider', () => ({
- ...jest.requireActual('librechat-data-provider'),
- dataService: {
- getAgentById: jest.fn(),
- },
-}));
-
-// Mock hooks
-const mockFavorites: FavoriteItem[] = [];
-const mockUseFavorites = jest.fn(() => ({
- favorites: mockFavorites,
- reorderFavorites: jest.fn(),
- isLoading: false,
-}));
-
-jest.mock('~/hooks', () => ({
- useFavorites: () => mockUseFavorites(),
- useLocalize: () => (key: string) => key,
- useShowMarketplace: () => false,
- useNewConvo: () => ({ newConversation: jest.fn() }),
- useGetConversation: () => () => null,
-}));
-
-const mockUseAgentsMapContext = jest.fn((): Record<string, Agent> | undefined => ({}));
-jest.mock('~/Providers', () => ({
- useAssistantsMapContext: () => ({}),
- useAgentsMapContext: () => mockUseAgentsMapContext(),
-}));
-
-const mockOnSelectSpec = jest.fn();
-jest.mock('~/hooks/Input/useSelectMention', () => () => ({
- onSelectEndpoint: jest.fn(),
- onSelectSpec: mockOnSelectSpec,
-}));
-
-const mockUseGetStartupConfig = jest.fn((): { data?: { modelSpecs: { list: unknown[] } } } => ({
- data: { modelSpecs: { list: [] as unknown[] } },
-}));
-
-const mockUseGetEndpointsQuery = jest.fn(
- (): { data?: Record<string, unknown>; isLoading?: boolean } => ({
- data: { [EModelEndpoint.agents]: { order: 0 } },
- }),
-);
-
-jest.mock('~/data-provider', () => ({
- useGetEndpointsQuery: () => mockUseGetEndpointsQuery(),
- useGetStartupConfig: () => mockUseGetStartupConfig(),
-}));
-
-jest.mock('../FavoriteItem', () => ({
- __esModule: true,
- default: ({ item, type }: { item: any; type: string }) => {
- let label = item.model;
- if (type === 'agent') {
- label = item.name;
- } else if (type === 'spec') {
- label = item.label;
- }
- return (
- <div data-testid="favorite-item" data-type={type}>
- {label}
- </div>
- );
- },
-}));
-
-const createTestQueryClient = () =>
- new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- });
-
-const renderWithProviders = (ui: React.ReactElement) => {
- const queryClient = createTestQueryClient();
- return render(
- <QueryClientProvider client={queryClient}>
- <RecoilRoot>
- <BrowserRouter>
- <DndProvider backend={HTML5Backend}>{ui}</DndProvider>
- </BrowserRouter>
- </RecoilRoot>
- </QueryClientProvider>,
- );
-};
-
-describe('FavoritesList', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- mockFavorites.length = 0;
- mockUseAgentsMapContext.mockImplementation(() => ({}));
- mockUseGetEndpointsQuery.mockImplementation(() => ({
- data: { [EModelEndpoint.agents]: { order: 0 } },
- }));
- mockUseFavorites.mockImplementation(() => ({
- favorites: mockFavorites,
- reorderFavorites: jest.fn(),
- isLoading: false,
- }));
- mockUseGetStartupConfig.mockImplementation(() => ({
- data: { modelSpecs: { list: [] } },
- }));
- });
-
- describe('rendering', () => {
- it('should render nothing when favorites is empty and marketplace is hidden', () => {
- const { container } = renderWithProviders(<FavoritesList />);
- expect(container.firstChild).toBeNull();
- });
-
- it('should render skeleton while loading', () => {
- mockUseFavorites.mockReturnValueOnce({
- favorites: [],
- reorderFavorites: jest.fn(),
- isLoading: true,
- });
-
- const { container } = renderWithProviders(<FavoritesList />);
- // Skeletons should be present during loading - container should have children
- expect(container.firstChild).not.toBeNull();
- // When loading, the component renders skeleton placeholders (check for content, not specific CSS)
- expect(container.innerHTML).toContain('div');
- });
- });
-
- describe('memoization', () => {
- it('does not re-run when the parent re-renders with stable props (insulated from streaming)', () => {
- const stableToggleNav = jest.fn();
- const Parent = () => {
- const [count, setCount] = React.useState(0);
- return (
- <>
- <button data-testid="force-rerender" onClick={() => setCount((c) => c + 1)}>
- {count}
- </button>
- <FavoritesList isSmallScreen={false} toggleNav={stableToggleNav} />
- </>
- );
- };
-
- renderWithProviders(<Parent />);
-
- const callsAfterMount = mockUseFavorites.mock.calls.length;
- expect(callsAfterMount).toBeGreaterThan(0);
-
- fireEvent.click(screen.getByTestId('force-rerender'));
-
- expect(mockUseFavorites).toHaveBeenCalledTimes(callsAfterMount);
- });
- });
-
- describe('missing agent handling', () => {
- it('should exclude missing agents (404) from rendered favorites and render valid agents', async () => {
- const validAgent: Agent = {
- id: 'valid-agent',
- name: 'Valid Agent',
- author: 'test-author',
- } as Agent;
-
- // Set up favorites with both valid and missing agent
- mockFavorites.push({ agentId: 'valid-agent' }, { agentId: 'deleted-agent' });
-
- // Mock getAgentById: valid-agent returns successfully, deleted-agent returns 404
- (dataService.getAgentById as jest.Mock).mockImplementation(
- ({ agent_id }: { agent_id: string }) => {
- if (agent_id === 'valid-agent') {
- return Promise.resolve(validAgent);
- }
- if (agent_id === 'deleted-agent') {
- return Promise.reject({ response: { status: 404 } });
- }
- return Promise.reject(new Error('Unknown agent'));
- },
- );
-
- const { findAllByTestId } = renderWithProviders(<FavoritesList />);
-
- // Wait for queries to resolve
- const favoriteItems = await findAllByTestId('favorite-item');
-
- // Only the valid agent should be rendered
- expect(favoriteItems).toHaveLength(1);
- expect(favoriteItems[0]).toHaveTextContent('Valid Agent');
-
- // The deleted agent should still be requested, but not rendered
- expect(dataService.getAgentById as jest.Mock).toHaveBeenCalledWith({
- agent_id: 'deleted-agent',
- });
- });
-
- it('should not show infinite loading skeleton when agents return 404', async () => {
- // Set up favorites with only a deleted agent
- mockFavorites.push({ agentId: 'deleted-agent' });
-
- // Mock getAgentById to return 404
- (dataService.getAgentById as jest.Mock).mockRejectedValue({ response: { status: 404 } });
-
- const { queryAllByTestId } = renderWithProviders(<FavoritesList />);
-
- // Wait for the loading state to resolve after 404 handling by ensuring the agent request was made
- await waitFor(() => {
- expect(dataService.getAgentById as jest.Mock).toHaveBeenCalledWith({
- agent_id: 'deleted-agent',
- });
- });
-
- // No favorite items should be rendered (deleted agent is filtered out)
- expect(queryAllByTestId('favorite-item')).toHaveLength(0);
- });
-
- it('renders pinned agents via direct fetch while the global agents map is still loading', async () => {
- const validAgent: Agent = {
- id: 'pinned-agent',
- name: 'Pinned Agent',
- author: 'test-author',
- } as Agent;
-
- mockUseAgentsMapContext.mockImplementation(() => undefined);
- mockFavorites.push({ agentId: 'pinned-agent' });
-
- (dataService.getAgentById as jest.Mock).mockResolvedValue(validAgent);
-
- const { findAllByTestId } = renderWithProviders(<FavoritesList />);
-
- const favoriteItems = await findAllByTestId('favorite-item');
- expect(favoriteItems).toHaveLength(1);
- expect(favoriteItems[0]).toHaveTextContent('Pinned Agent');
- expect(dataService.getAgentById as jest.Mock).toHaveBeenCalledWith({
- agent_id: 'pinned-agent',
- });
- });
-
- it('does not fetch or render agents when the agents endpoint is disabled', async () => {
- mockUseGetEndpointsQuery.mockImplementation(() => ({ data: {} }));
- mockUseAgentsMapContext.mockImplementation(() => undefined);
- mockFavorites.push({ agentId: 'pinned-agent' });
-
- const { queryAllByTestId } = renderWithProviders(<FavoritesList />);
-
- await new Promise((r) => setTimeout(r, 50));
- expect(dataService.getAgentById as jest.Mock).not.toHaveBeenCalled();
- expect(queryAllByTestId('favorite-item')).toHaveLength(0);
- });
-
- it('keeps skeletons (not an empty row) while the endpoints config is still loading', async () => {
- mockUseGetEndpointsQuery.mockImplementation(() => ({ data: undefined, isLoading: true }));
- mockUseAgentsMapContext.mockImplementation(() => undefined);
- mockFavorites.push({ agentId: 'pinned-agent' });
-
- const { queryAllByTestId } = renderWithProviders(<FavoritesList />);
-
- await new Promise((r) => setTimeout(r, 50));
- // Endpoint gate is undecided, so no direct fetch yet, but the row stays as a skeleton.
- expect(dataService.getAgentById as jest.Mock).not.toHaveBeenCalled();
- expect(queryAllByTestId('favorite-item-skeleton').length).toBeGreaterThan(0);
- expect(queryAllByTestId('favorite-item')).toHaveLength(0);
- });
-
- it('does not delete favorites on a global 403 while the agents map is unavailable', async () => {
- const mockReorderFavorites = jest.fn();
- // A revoked AGENTS.USE role makes the list query (and thus the map) fail, so the
- // map stays undefined and every getAgentById returns a global 403.
- mockUseAgentsMapContext.mockImplementation(() => undefined);
- mockUseFavorites.mockImplementation(() => ({
- favorites: [{ agentId: 'agent-a' }, { agentId: 'agent-b' }],
- reorderFavorites: mockReorderFavorites,
- isLoading: false,
- }));
-
- (dataService.getAgentById as jest.Mock).mockRejectedValue({ response: { status: 403 } });
-
- const { queryAllByTestId } = renderWithProviders(<FavoritesList />);
-
- await waitFor(() => {
- expect(dataService.getAgentById as jest.Mock).toHaveBeenCalledWith({ agent_id: 'agent-a' });
- });
- await new Promise((r) => setTimeout(r, 50));
-
- expect(mockReorderFavorites).not.toHaveBeenCalled();
- expect(queryAllByTestId('favorite-item')).toHaveLength(0);
- });
-
- it('keeps a pinned agent as a skeleton on a transient error while the map is still loading', async () => {
- const mockReorderFavorites = jest.fn();
- mockUseAgentsMapContext.mockImplementation(() => undefined);
- mockUseFavorites.mockImplementation(() => ({
- favorites: [{ agentId: 'flaky-agent' }],
- reorderFavorites: mockReorderFavorites,
- isLoading: false,
- }));
-
- (dataService.getAgentById as jest.Mock).mockRejectedValue({ response: { status: 500 } });
-
- const { queryAllByTestId } = renderWithProviders(<FavoritesList />);
-
- await waitFor(() => {
- expect(dataService.getAgentById as jest.Mock).toHaveBeenCalledWith({
- agent_id: 'flaky-agent',
- });
- });
-
- // Item is neither rendered nor cleaned up — it stays in the loading skeleton state.
- expect(queryAllByTestId('favorite-item')).toHaveLength(0);
- expect(mockReorderFavorites).not.toHaveBeenCalled();
- });
-
- it('should treat 403 the same as 404 — agent not rendered', async () => {
- const validAgent: Agent = {
- id: 'valid-agent',
- name: 'Valid Agent',
- author: 'test-author',
- } as Agent;
-
- mockFavorites.push({ agentId: 'valid-agent' }, { agentId: 'revoked-agent' });
-
- (dataService.getAgentById as jest.Mock).mockImplementation(
- ({ agent_id }: { agent_id: string }) => {
- if (agent_id === 'valid-agent') {
- return Promise.resolve(validAgent);
- }
- if (agent_id === 'revoked-agent') {
- return Promise.reject({ response: { status: 403 } });
- }
- return Promise.reject(new Error('Unknown agent'));
- },
- );
-
- const { findAllByTestId } = renderWithProviders(<FavoritesList />);
-
- const favoriteItems = await findAllByTestId('favorite-item');
- expect(favoriteItems).toHaveLength(1);
- expect(favoriteItems[0]).toHaveTextContent('Valid Agent');
- });
-
- it('should call reorderFavorites to persist removal of stale agents', async () => {
- const mockReorderFavorites = jest.fn().mockResolvedValue(undefined);
- mockUseFavorites.mockReturnValue({
- favorites: [{ agentId: 'revoked-agent' }],
- reorderFavorites: mockReorderFavorites,
- isLoading: false,
- });
-
- (dataService.getAgentById as jest.Mock).mockRejectedValue({ response: { status: 403 } });
-
- renderWithProviders(<FavoritesList />);
-
- await waitFor(() => {
- expect(mockReorderFavorites).toHaveBeenCalledWith([], true);
- });
- });
-
- it('should only attempt cleanup once even when favorites revert to stale state', async () => {
- const mockReorderFavorites = jest.fn().mockResolvedValue(undefined);
-
- mockUseFavorites.mockReturnValue({
- favorites: [{ agentId: 'revoked-agent' }],
- reorderFavorites: mockReorderFavorites,
- isLoading: false,
- });
-
- (dataService.getAgentById as jest.Mock).mockRejectedValue({ response: { status: 403 } });
-
- const { rerender } = renderWithProviders(<FavoritesList />);
-
- await waitFor(() => {
- expect(mockReorderFavorites).toHaveBeenCalledWith([], true);
- });
-
- expect(mockReorderFavorites).toHaveBeenCalledTimes(1);
-
- rerender(
- <QueryClientProvider client={createTestQueryClient()}>
- <RecoilRoot>
- <BrowserRouter>
- <DndProvider backend={HTML5Backend}>
- <FavoritesList />
- </DndProvider>
- </BrowserRouter>
- </RecoilRoot>
- </QueryClientProvider>,
- );
-
- await new Promise((r) => setTimeout(r, 50));
-
- expect(mockReorderFavorites).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('model spec rendering', () => {
- it('renders a spec favorite when startupConfig has a matching spec', async () => {
- mockUseGetStartupConfig.mockImplementation(() => ({
- data: {
- modelSpecs: {
- list: [
- {
- name: 'fast-spec',
- label: 'Fast Spec',
- preset: { endpoint: 'openai', model: 'gpt-5' },
- },
- ],
- },
- },
- }));
- mockFavorites.push({ spec: 'fast-spec' });
-
- const { findAllByTestId } = renderWithProviders(<FavoritesList />);
- const items = await findAllByTestId('favorite-item');
-
- expect(items).toHaveLength(1);
- expect(items[0]).toHaveAttribute('data-type', 'spec');
- expect(items[0]).toHaveTextContent('Fast Spec');
- });
-
- it('skips a spec favorite when the spec is no longer in startupConfig', () => {
- mockUseGetStartupConfig.mockImplementation(() => ({
- data: { modelSpecs: { list: [] } },
- }));
- mockFavorites.push({ spec: 'stale-spec' });
-
- const { queryAllByTestId } = renderWithProviders(<FavoritesList />);
- expect(queryAllByTestId('favorite-item')).toHaveLength(0);
- });
-
- it('calls reorderFavorites to auto-remove stale spec favorites', async () => {
- const mockReorderFavorites = jest.fn().mockResolvedValue(undefined);
- mockUseFavorites.mockReturnValue({
- favorites: [{ spec: 'stale-spec' }],
- reorderFavorites: mockReorderFavorites,
- isLoading: false,
- });
- mockUseGetStartupConfig.mockReturnValue({
- data: { modelSpecs: { list: [] } },
- });
-
- renderWithProviders(<FavoritesList />);
-
- await waitFor(() => {
- expect(mockReorderFavorites).toHaveBeenCalledWith([], true);
- });
- });
-
- it('does not clean up specs when startupConfig is still loading', async () => {
- const mockReorderFavorites = jest.fn().mockResolvedValue(undefined);
- mockUseFavorites.mockReturnValue({
- favorites: [{ spec: 'valid-spec' }],
- reorderFavorites: mockReorderFavorites,
- isLoading: false,
- });
- mockUseGetStartupConfig.mockReturnValue({ data: undefined });
-
- renderWithProviders(<FavoritesList />);
-
- await new Promise((r) => setTimeout(r, 50));
- expect(mockReorderFavorites).not.toHaveBeenCalled();
- });
-
- it('renders a mix of agents, models, and specs', async () => {
- const validAgent: Agent = {
- id: 'a1',
- name: 'Agent One',
- author: 'me',
- } as Agent;
- mockUseGetStartupConfig.mockImplementation(() => ({
- data: {
- modelSpecs: {
- list: [
- {
- name: 's1',
- label: 'Spec One',
- preset: { endpoint: 'openai', model: 'gpt-5' },
- },
- ],
- },
- },
- }));
- mockFavorites.push({ agentId: 'a1' }, { model: 'gpt-5', endpoint: 'openai' }, { spec: 's1' });
- (dataService.getAgentById as jest.Mock).mockResolvedValue(validAgent);
-
- const { findAllByTestId } = renderWithProviders(<FavoritesList />);
- const items = await findAllByTestId('favorite-item');
-
- expect(items).toHaveLength(3);
- const types = items.map((el) => el.getAttribute('data-type'));
- expect(types).toEqual(['agent', 'model', 'spec']);
- });
- });
-
- describe('drag source by pointer capability', () => {
- const mockHover = (hasHover: boolean) => {
- (window.matchMedia as jest.Mock).mockImplementation((query: string) => ({
- matches: query === '(hover: hover)' ? hasHover : false,
- media: query,
- onchange: null,
- addListener: jest.fn(),
- removeListener: jest.fn(),
- addEventListener: jest.fn(),
- removeEventListener: jest.fn(),
- dispatchEvent: jest.fn(),
- }));
- };
-
- const renderFavoriteWrapper = async () => {
- mockFavorites.push({ model: 'gpt-5', endpoint: 'openai' });
- const { findByTestId } = renderWithProviders(<FavoritesList />);
- const item = await findByTestId('favorite-item');
- return item.closest('[data-handler-id]');
- };
-
- it('connects the drag source on a hover-capable pointer', async () => {
- mockHover(true);
-
- const wrapper = await renderFavoriteWrapper();
-
- await waitFor(() => expect(wrapper).toHaveAttribute('draggable', 'true'));
- });
-
- it('leaves the row undraggable on touch so the first tap selects it', async () => {
- mockHover(false);
-
- const wrapper = await renderFavoriteWrapper();
-
- /** iOS Safari gives a touch on a draggable element to the drag recognizer
- * instead of synthesizing a click, costing the row its first tap. */
- expect(wrapper).not.toHaveAttribute('draggable', 'true');
- });
- });
-});
diff --git a/client/src/components/Nav/Favorites/tests/useFavoritesData.spec.tsx b/client/src/components/Nav/Favorites/tests/useFavoritesData.spec.tsx
new file mode 100644
index 0000000000..8d55f5ea1d
--- /dev/null
+++ b/client/src/components/Nav/Favorites/tests/useFavoritesData.spec.tsx
@@ -0,0 +1,141 @@
+import React from 'react';
+import { render, waitFor } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import useFavoritesData from '../useFavoritesData';
+
+const mockGetAgentById = jest.fn();
+const mockReorderFavorites = jest.fn();
+
+let mockFavorites: Array<Record<string, string>> = [];
+let mockAgentsMap: Record<string, unknown> | undefined = {};
+let mockEndpointsConfig: Record<string, unknown> = { agents: {} };
+let mockStartupConfigData: { modelSpecs: { list: Array<Record<string, unknown>> } } | undefined = {
+ modelSpecs: { list: [] },
+};
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: { getAgentById: (...args: unknown[]) => mockGetAgentById(...args) },
+ };
+});
+
+jest.mock('~/data-provider', () => ({
+ useGetEndpointsQuery: () => ({ data: mockEndpointsConfig, isLoading: false }),
+ useGetStartupConfig: () => ({ data: mockStartupConfigData }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useAssistantsMapContext: () => ({}),
+ useAgentsMapContext: () => mockAgentsMap,
+}));
+
+jest.mock('~/hooks/Input/useSelectMention', () => ({
+ __esModule: true,
+ default: () => ({ onSelectEndpoint: jest.fn(), onSelectSpec: jest.fn() }),
+}));
+
+jest.mock('~/hooks', () => ({
+ useFavorites: () => ({
+ favorites: mockFavorites,
+ reorderFavorites: mockReorderFavorites,
+ isLoading: false,
+ }),
+ useGetConversation: () => jest.fn(() => null),
+ useNewConvo: () => ({ newConversation: jest.fn() }),
+}));
+
+let latest: ReturnType<typeof useFavoritesData> | undefined;
+
+const Probe = () => {
+ latest = useFavoritesData();
+ return null;
+};
+
+const createClient = () => new QueryClient({ defaultOptions: { queries: { retry: false } } });
+
+const renderProbe = () =>
+ render(
+ <QueryClientProvider client={createClient()}>
+ <Probe />
+ </QueryClientProvider>,
+ );
+
+describe('useFavoritesData', () => {
+ beforeEach(() => {
+ mockGetAgentById.mockReset();
+ mockReorderFavorites.mockReset();
+ mockFavorites = [];
+ mockAgentsMap = {};
+ mockEndpointsConfig = { agents: {} };
+ mockStartupConfigData = { modelSpecs: { list: [] } };
+ });
+
+ it('removes favorites whose agent is gone (404/403) once the agents map has loaded', async () => {
+ mockFavorites = [{ agentId: 'agent-gone' }, { model: 'gpt-4o', endpoint: 'openAI' }];
+ mockGetAgentById.mockRejectedValue({ response: { status: 403 } });
+ renderProbe();
+ await waitFor(() => {
+ expect(mockReorderFavorites).toHaveBeenCalledWith(
+ [{ model: 'gpt-4o', endpoint: 'openAI' }],
+ true,
+ );
+ });
+ expect(mockReorderFavorites).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps favorites while the global agents map is still loading', async () => {
+ mockFavorites = [{ agentId: 'agent-gone' }];
+ mockAgentsMap = undefined;
+ mockGetAgentById.mockRejectedValue({ response: { status: 403 } });
+ renderProbe();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(mockReorderFavorites).not.toHaveBeenCalled();
+ });
+
+ it('removes favorites whose spec is no longer in the startup config', async () => {
+ mockFavorites = [{ spec: 'gone-spec' }, { model: 'gpt-4o', endpoint: 'openAI' }];
+ renderProbe();
+ await waitFor(() => {
+ expect(mockReorderFavorites).toHaveBeenCalledWith(
+ [{ model: 'gpt-4o', endpoint: 'openAI' }],
+ true,
+ );
+ });
+ });
+
+ it('merges fetched agents into the resolved agents map', async () => {
+ mockFavorites = [{ agentId: 'agent-live' }];
+ mockGetAgentById.mockResolvedValue({ id: 'agent-live', name: 'Live Agent' });
+ const { rerender } = renderProbe();
+ await waitFor(() => {
+ expect(latest?.agentsMap['agent-live']).toEqual(
+ expect.objectContaining({ id: 'agent-live' }),
+ );
+ });
+ rerender(
+ <QueryClientProvider client={createClient()}>
+ <Probe />
+ </QueryClientProvider>,
+ );
+ });
+
+ it('exposes specs from the startup config', () => {
+ mockFavorites = [];
+ mockStartupConfigData = {
+ modelSpecs: { list: [{ name: 'fast', label: 'Fast', preset: {} }] },
+ };
+ renderProbe();
+ expect(latest?.specsMap['fast']).toEqual(expect.objectContaining({ label: 'Fast' }));
+ });
+
+ it('skips agent fetching when the agents endpoint is disabled', async () => {
+ mockFavorites = [{ agentId: 'agent-live' }];
+ mockEndpointsConfig = {};
+ renderProbe();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(mockGetAgentById).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/Nav/Favorites/useFavoritesData.ts b/client/src/components/Nav/Favorites/useFavoritesData.ts
new file mode 100644
index 0000000000..9b112705f0
--- /dev/null
+++ b/client/src/components/Nav/Favorites/useFavoritesData.ts
@@ -0,0 +1,210 @@
+import { useEffect, useMemo, useRef } from 'react';
+import { useQueries } from '@tanstack/react-query';
+import { QueryKeys, EModelEndpoint, dataService } from 'librechat-data-provider';
+import type { Agent, TEndpointsConfig, TModelSpec } from 'librechat-data-provider';
+import type { Favorite } from '~/store/favorites';
+import { useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';
+import { useAssistantsMapContext, useAgentsMapContext } from '~/Providers';
+import { useFavorites, useGetConversation, useNewConvo } from '~/hooks';
+import useSelectMention from '~/hooks/Input/useSelectMention';
+
+/** A 404/403 from getAgentById means the agent is gone or inaccessible; other errors are transient. */
+export const isMissingAgentError = (error: unknown): boolean => {
+ if (error && typeof error === 'object' && 'response' in error) {
+ const status = (error as { response?: { status?: number } }).response?.status;
+ return status === 404 || status === 403;
+ }
+ return false;
+};
+
+export type FavoriteSelectKwargs = {
+ model?: string;
+ agent_id?: string;
+ assistant_id?: string;
+ spec?: string | null;
+};
+export type SelectEndpointHandler = (
+ endpoint?: EModelEndpoint | string | null,
+ kwargs?: FavoriteSelectKwargs,
+) => void;
+export type SelectSpecHandler = (spec: TModelSpec) => void;
+
+export type FavoritesData = {
+ favorites: Favorite[];
+ isLoading: boolean;
+ /** Whether the atom has absorbed the settled favorites query value. */
+ isLoaded: boolean;
+ dataUpdatedAt: number;
+ isAgentsLoading: boolean;
+ agentsMap: Record<string, Agent>;
+ specsMap: Record<string, TModelSpec>;
+ endpointsConfig: TEndpointsConfig;
+ reorderFavorites: (favorites: Favorite[], persist: boolean) => void;
+ onSelectEndpoint: SelectEndpointHandler | undefined;
+ onSelectSpec: SelectSpecHandler | undefined;
+};
+
+/**
+ * Data layer for the sidebar's favorite models/agents/specs: resolution of
+ * favorites into renderable items, agent fetching past the global map, and
+ * cleanup of favorites whose agent or spec no longer exists. Rendering and
+ * ordering live with the caller (the Pinned section interleaves these rows
+ * with pinned conversations).
+ */
+export default function useFavoritesData(): FavoritesData {
+ const getConversation = useGetConversation(0);
+ const { favorites, reorderFavorites, isLoading, isLoaded, dataUpdatedAt } = useFavorites();
+
+ const { newConversation } = useNewConvo();
+ const assistantsMap = useAssistantsMapContext();
+ const agentsMapContext = useAgentsMapContext();
+ const { data: endpointsConfig = {} as TEndpointsConfig, isLoading: isEndpointsLoading } =
+ useGetEndpointsQuery();
+ const { data: startupConfig } = useGetStartupConfig();
+
+ const modelSpecs = useMemo(
+ () => startupConfig?.modelSpecs?.list ?? [],
+ [startupConfig?.modelSpecs?.list],
+ );
+
+ const specsMap = useMemo(() => {
+ const map: Record<string, TModelSpec> = {};
+ for (const spec of modelSpecs) {
+ map[spec.name] = spec;
+ }
+ return map;
+ }, [modelSpecs]);
+
+ const { onSelectEndpoint, onSelectSpec } = useSelectMention({
+ modelSpecs,
+ assistantsMap,
+ endpointsConfig,
+ getConversation,
+ newConversation,
+ returnHandlers: true,
+ });
+
+ const safeFavorites = useMemo(() => (Array.isArray(favorites) ? favorites : []), [favorites]);
+
+ const allAgentIds = useMemo(
+ () => safeFavorites.map((f) => f.agentId).filter(Boolean) as string[],
+ [safeFavorites],
+ );
+
+ const agentsEndpointEnabled = !!endpointsConfig?.[EModelEndpoint.agents];
+
+ const agentIdsToFetch = useMemo(() => {
+ if (!agentsEndpointEnabled) {
+ return [];
+ }
+ if (agentsMapContext === undefined) {
+ return allAgentIds;
+ }
+ return allAgentIds.filter((id) => !agentsMapContext[id]);
+ }, [allAgentIds, agentsMapContext, agentsEndpointEnabled]);
+
+ const agentQueries = useQueries({
+ queries: agentIdsToFetch.map((agentId) => ({
+ queryKey: [QueryKeys.agent, agentId],
+ queryFn: (): Promise<Agent> => dataService.getAgentById({ agent_id: agentId }),
+ staleTime: 1000 * 60 * 5,
+ retry: (failureCount: number, error: unknown) =>
+ !isMissingAgentError(error) && failureCount < 3,
+ })),
+ });
+
+ const staleAgentIdsKey = useMemo(() => {
+ // Only persist cleanup once the global map has loaded. A revoked AGENTS.USE role
+ // makes every getAgentById return a global 403, which must not delete favorites.
+ if (agentsMapContext === undefined) {
+ return '';
+ }
+ const ids: string[] = [];
+ for (let i = 0; i < agentIdsToFetch.length; i++) {
+ const query = agentQueries[i];
+ if (query.isError && isMissingAgentError(query.error)) {
+ ids.push(agentIdsToFetch[i]);
+ }
+ }
+ return ids.sort().join(',');
+ }, [agentIdsToFetch, agentQueries, agentsMapContext]);
+
+ const cleanupAttemptedRef = useRef('');
+
+ useEffect(() => {
+ if (!staleAgentIdsKey || cleanupAttemptedRef.current === staleAgentIdsKey) {
+ return;
+ }
+ const staleSet = new Set(staleAgentIdsKey.split(','));
+ const cleaned = safeFavorites.filter((f) => !f.agentId || !staleSet.has(f.agentId));
+ if (cleaned.length < safeFavorites.length) {
+ cleanupAttemptedRef.current = staleAgentIdsKey;
+ reorderFavorites(cleaned, true);
+ }
+ }, [staleAgentIdsKey, safeFavorites, reorderFavorites]);
+
+ const staleSpecNamesKey = useMemo(() => {
+ if (startupConfig === undefined) {
+ return '';
+ }
+ return safeFavorites
+ .filter((f) => f.spec && !specsMap[f.spec])
+ .map((f) => f.spec as string)
+ .sort()
+ .join(',');
+ }, [safeFavorites, specsMap, startupConfig]);
+
+ const specCleanupAttemptedRef = useRef('');
+
+ useEffect(() => {
+ if (!staleSpecNamesKey || specCleanupAttemptedRef.current === staleSpecNamesKey) {
+ return;
+ }
+ const staleSet = new Set(staleSpecNamesKey.split(','));
+ const cleaned = safeFavorites.filter((f) => !f.spec || !staleSet.has(f.spec));
+ if (cleaned.length < safeFavorites.length) {
+ specCleanupAttemptedRef.current = staleSpecNamesKey;
+ reorderFavorites(cleaned, true);
+ }
+ }, [staleSpecNamesKey, safeFavorites, reorderFavorites]);
+
+ const combinedAgentsMap = useMemo(() => {
+ const combined: Record<string, Agent> = {};
+ if (agentsMapContext) {
+ for (const [key, value] of Object.entries(agentsMapContext)) {
+ if (value) {
+ combined[key] = value;
+ }
+ }
+ }
+ agentQueries.forEach((query) => {
+ if (query.data) {
+ combined[query.data.id] = query.data;
+ }
+ });
+ return combined;
+ }, [agentsMapContext, agentQueries]);
+
+ const isAgentsLoading =
+ allAgentIds.length > 0 &&
+ (isEndpointsLoading ||
+ agentQueries.some(
+ (q) =>
+ q.isLoading ||
+ (agentsMapContext === undefined && q.isError && !isMissingAgentError(q.error)),
+ ));
+
+ return {
+ favorites: safeFavorites,
+ isLoading,
+ isLoaded,
+ dataUpdatedAt,
+ isAgentsLoading,
+ agentsMap: combinedAgentsMap,
+ specsMap,
+ endpointsConfig,
+ reorderFavorites,
+ onSelectEndpoint,
+ onSelectSpec,
+ };
+}
diff --git a/client/src/components/UnifiedSidebar/ConversationsSection.tsx b/client/src/components/UnifiedSidebar/ConversationsSection.tsx
index 9ef7cb0fa8..7b5f132421 100644
--- a/client/src/components/UnifiedSidebar/ConversationsSection.tsx
+++ b/client/src/components/UnifiedSidebar/ConversationsSection.tsx
@@ -19,7 +19,6 @@ import {
} from '~/hooks';
import ProjectsSection from '~/components/Conversations/ProjectsSection';
import PinnedSection from '~/components/Conversations/PinnedSection';
-import FavoritesList from '~/components/Nav/Favorites/FavoritesList';
import useSidebarToggle from '~/hooks/Nav/useSidebarToggle';
import { Conversations } from '~/components/Conversations';
import { collectPinnedConversations } from '~/utils';
@@ -37,7 +36,6 @@ const ConversationsSection = memo(() => {
const [isChatsExpanded, setIsChatsExpanded] = useLocalStorage('chatsExpanded', true);
const [tags, setTags] = useState<string[]>([]);
-
const hasAccessToBookmarks = useHasAccess({
permissionType: PermissionTypes.BOOKMARKS,
permission: Permissions.USE,
@@ -45,7 +43,7 @@ const ConversationsSection = memo(() => {
const search = useRecoilValue(store.search);
- const { data, fetchNextPage, isFetchingNextPage, isLoading, isFetching } =
+ const { data, fetchNextPage, isFetchingNextPage, isLoading, isFetching, isPreviousData } =
useConversationsInfiniteQuery(
{
tags: tags.length === 0 ? undefined : tags,
@@ -85,10 +83,16 @@ const ConversationsSection = memo(() => {
/** Pins are fetched on their own so one older than the first page of the chats list
* still shows on first paint, instead of appearing only once that list scrolls to it.
* The bookmark filter still applies, matching the chats list beside it. */
- const { data: pinnedData } = usePinnedConversationsQuery(
+ const {
+ data: pinnedData,
+ isSuccess: isPinnedFetched,
+ isFetching: isPinnedFetching,
+ dataUpdatedAt: pinnedUpdatedAt,
+ } = usePinnedConversationsQuery(
{ tags: tags.length === 0 ? undefined : tags },
{ enabled: isAuthenticated },
);
+ const isPinnedComplete = isPinnedFetched && !isPinnedFetching;
/* `groupConversationsByDate` strips pins from the chats groups. A failed
refetch keeps the previous dedicated result, so merge in pins from the
@@ -151,19 +155,26 @@ const ConversationsSection = memo(() => {
<div className="flex items-center gap-0.5 px-3">
{hasAccessToBookmarks && (
<Suspense fallback={null}>
- <BookmarkNav tags={tags} setTags={setTags} />
+ <BookmarkNav tags={tags} setTags={setTags} matchSearchBar />
</Suspense>
)}
{search.enabled && <SearchBar isSmallScreen={isSmallScreen} />}
</div>
)}
+ {!search.query && <ProjectsSection toggleNav={toggleNav} isAuthenticated={isAuthenticated} />}
{!search.query && (
- <div className="px-3">
- <FavoritesList isSmallScreen={isSmallScreen} toggleNav={toggleNav} />
- </div>
+ <PinnedSection
+ conversations={pinnedConversations}
+ toggleNav={toggleNav}
+ isSmallScreen={isSmallScreen}
+ /* Only a successful drain proves the list is whole: a failed later
+ page still publishes partial data and stops fetching. */
+ membershipComplete={tags.length === 0 && isPinnedComplete}
+ /* When that drain last ran, which decides whether it is current
+ enough to prune the stored order against. */
+ membershipUpdatedAt={pinnedUpdatedAt}
+ />
)}
- {!search.query && <ProjectsSection toggleNav={toggleNav} isAuthenticated={isAuthenticated} />}
- {!search.query && <PinnedSection conversations={pinnedConversations} toggleNav={toggleNav} />}
<div className="flex min-h-0 flex-grow flex-col overflow-hidden">
<Conversations
conversations={conversations}
@@ -172,10 +183,9 @@ const ConversationsSection = memo(() => {
containerRef={conversationsRef}
loadMoreConversations={loadMoreConversations}
isLoading={isFetchingNextPage || isLoading}
- isSearchLoading={isSearchLoading}
+ isSearchLoading={isSearchLoading || isPreviousData}
isChatsExpanded={isChatsExpanded}
setIsChatsExpanded={setIsChatsExpanded}
- showFavorites={false}
chatsHeaderTrailing={
isSmallScreen && hasAccessToBookmarks ? (
<Suspense fallback={null}>
diff --git a/client/src/components/UnifiedSidebar/ExpandedPanel.tsx b/client/src/components/UnifiedSidebar/ExpandedPanel.tsx
index ab04ba9ae7..371cb383bd 100644
--- a/client/src/components/UnifiedSidebar/ExpandedPanel.tsx
+++ b/client/src/components/UnifiedSidebar/ExpandedPanel.tsx
@@ -6,6 +6,7 @@ import { Skeleton, Sidebar, Button, TooltipAnchor } from '@librechat/client';
import type { NavLink } from '~/common';
import { useShortcutAriaKey, useShortcutHint } from '~/hooks/useKeyboardShortcuts';
import { useActivePanel, resolveActivePanel, DEFAULT_PANEL } from '~/Providers';
+import AgentMarketplaceButton from '~/components/Nav/AgentMarketplaceButton';
import { CLOSE_SIDEBAR_ID } from '~/components/Chat/Menus/OpenSidebar';
import useNewChat from '~/hooks/Chat/useNewChat';
import { useLocalize } from '~/hooks';
@@ -169,6 +170,7 @@ function ExpandedPanel({
}
/>
<NewChatButton setActive={setActive} />
+ <AgentMarketplaceButton />
<div className="mx-2 border-b border-border-light" />
<div className="flex flex-col gap-1 overflow-y-auto">
{links.map((link) => (
diff --git a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx
index 3cc998129a..71fa22177b 100644
--- a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx
+++ b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx
@@ -30,6 +30,22 @@ const mockUseTitleGeneration = jest.fn(() => {
useRecoilValue(streamTickAtom);
});
+/** One stable identity across renders, like react-query's cached data: the
+ * section's derived `conversations` memo (and so the PinnedSection props)
+ * keeps referential stability mid-stream, which is what the memoized-children
+ * guarantee below depends on. */
+const mockConversationsResult = {
+ data: { pages: [{ conversations: [] as unknown[], nextCursor: null }] },
+ fetchNextPage: jest.fn(),
+ isFetchingNextPage: false,
+ isLoading: false,
+ isFetching: false,
+};
+
+/** Same identity rule as above: a fresh `pinnedData.conversations` array would
+ * rebuild `pinnedConversations` and re-render PinnedSection on every tick. */
+const mockPinnedResult = { data: { conversations: [] as unknown[], nextCursor: null } };
+
jest.mock('~/store', () => {
const { atom: recoilAtom } = jest.requireActual('recoil');
return {
@@ -59,16 +75,8 @@ jest.mock('~/hooks', () => ({
jest.mock('~/data-provider', () => ({
__esModule: true,
- useConversationsInfiniteQuery: () => ({
- data: { pages: [{ conversations: [], nextCursor: null }] },
- fetchNextPage: jest.fn(),
- isFetchingNextPage: false,
- isLoading: false,
- isFetching: false,
- }),
- usePinnedConversationsQuery: () => ({
- data: { conversations: [], nextCursor: null },
- }),
+ useConversationsInfiniteQuery: () => mockConversationsResult,
+ usePinnedConversationsQuery: () => mockPinnedResult,
useTitleGeneration: () => mockUseTitleGeneration(),
useGetEndpointsQuery: () => ({ data: {}, isLoading: false }),
useGetStartupConfig: () => ({ data: { modelSpecs: { list: [] } } }),
@@ -96,10 +104,18 @@ jest.mock('~/components/Conversations/ProjectsSection', () => ({
default: () => <div data-testid="projects-stub" />,
}));
-jest.mock('~/components/Conversations/PinnedSection', () => ({
- __esModule: true,
- default: () => <div data-testid="pinned-stub" />,
-}));
+jest.mock('~/components/Conversations/PinnedSection', () => {
+ const { memo } = jest.requireActual('react');
+ /** Mirrors the real merged section closely enough for the streaming test:
+ * memoized like it, and its first act is the same `useFavorites` call
+ * through the ~/hooks mock, so that hook's call count tracks its renders. */
+ const PinnedSectionStub = memo(function PinnedSectionStub() {
+ mockUseFavorites();
+ return <div data-testid="pinned-stub" />;
+ });
+ PinnedSectionStub.displayName = 'PinnedSectionStub';
+ return { __esModule: true, default: PinnedSectionStub };
+});
jest.mock('~/components/Nav/SearchBar', () => ({
__esModule: true,
diff --git a/client/src/components/UnifiedSidebar/__tests__/ExpandedPanel.spec.tsx b/client/src/components/UnifiedSidebar/__tests__/ExpandedPanel.spec.tsx
index 69656cd85d..feab690f2a 100644
--- a/client/src/components/UnifiedSidebar/__tests__/ExpandedPanel.spec.tsx
+++ b/client/src/components/UnifiedSidebar/__tests__/ExpandedPanel.spec.tsx
@@ -44,6 +44,7 @@ jest.mock('~/store', () => {
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
useNewConvo: () => ({ newConversation: mockNewConversation }),
+ useShowMarketplace: () => false,
}));
/**
diff --git a/client/src/components/UnifiedSidebar/mobile/Header.tsx b/client/src/components/UnifiedSidebar/mobile/Header.tsx
index 6fc226d422..bbaebcb361 100644
--- a/client/src/components/UnifiedSidebar/mobile/Header.tsx
+++ b/client/src/components/UnifiedSidebar/mobile/Header.tsx
@@ -1,6 +1,7 @@
import { memo, lazy, Suspense, useEffect, useRef } from 'react';
import { Button, Sidebar, Skeleton } from '@librechat/client';
import type { NavLink } from '~/common';
+import AgentMarketplaceButton from '~/components/Nav/AgentMarketplaceButton';
import { CLOSE_SIDEBAR_ID } from '~/components/Chat/Menus/OpenSidebar';
import { useShortcutAriaKey } from '~/hooks/useKeyboardShortcuts';
import { useLocalize } from '~/hooks';
@@ -74,6 +75,7 @@ function Header({
onNavigate={onClose}
routeActiveId={routeActiveId}
/>
+ <AgentMarketplaceButton side="bottom" onNavigate={onClose} />
<Suspense fallback={<Skeleton className="size-9 rounded-lg" />}>
<AccountSettings collapsed />
</Suspense>
diff --git a/client/src/components/UnifiedSidebar/mobile/__tests__/Header.spec.tsx b/client/src/components/UnifiedSidebar/mobile/__tests__/Header.spec.tsx
index 9c63b5be0e..0a4cefb7e9 100644
--- a/client/src/components/UnifiedSidebar/mobile/__tests__/Header.spec.tsx
+++ b/client/src/components/UnifiedSidebar/mobile/__tests__/Header.spec.tsx
@@ -1,9 +1,13 @@
import React from 'react';
+import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
import type { NavLink } from '~/common';
+let mockShowMarketplace = true;
+
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
+ useShowMarketplace: () => mockShowMarketplace,
}));
jest.mock('~/hooks/useKeyboardShortcuts', () => ({
@@ -23,6 +27,7 @@ jest.mock('@librechat/client', () => ({
)),
Sidebar: (props: React.ComponentProps<'svg'>) => <svg data-testid="sidebar-icon" {...props} />,
Skeleton: () => <div data-testid="skeleton" />,
+ TooltipAnchor: ({ render: trigger }: { render: React.ReactNode }) => trigger,
}));
jest.mock('../Switcher', () => ({
@@ -45,7 +50,7 @@ const links = [] as NavLink[];
describe('mobile drawer header', () => {
it('claims the close identity while the drawer is open', () => {
- render(<Header links={links} expanded={true} onClose={jest.fn()} />);
+ render(<Header links={links} expanded={true} onClose={jest.fn()} />, { wrapper: MemoryRouter });
const close = screen.getByTestId('close-sidebar-button');
expect(close).toHaveAttribute('id', 'close-sidebar-button');
@@ -58,7 +63,9 @@ describe('mobile drawer header', () => {
* would find one sitting off-viewport and act on it.
*/
it('gives up that identity once closed', () => {
- render(<Header links={links} expanded={false} onClose={jest.fn()} />);
+ render(<Header links={links} expanded={false} onClose={jest.fn()} />, {
+ wrapper: MemoryRouter,
+ });
expect(screen.queryByTestId('close-sidebar-button')).not.toBeInTheDocument();
expect(document.getElementById('close-sidebar-button')).toBeNull();
@@ -66,7 +73,7 @@ describe('mobile drawer header', () => {
/** The only close control while open, so its binding must be discoverable here. */
it('advertises the toggle shortcut on the close control', () => {
- render(<Header links={links} expanded={true} onClose={jest.fn()} />);
+ render(<Header links={links} expanded={true} onClose={jest.fn()} />, { wrapper: MemoryRouter });
expect(screen.getByTestId('close-sidebar-button')).toHaveAttribute(
'aria-keyshortcuts',
@@ -75,7 +82,9 @@ describe('mobile drawer header', () => {
});
it('keeps the closed drawer out of the tab order', () => {
- render(<Header links={links} expanded={false} onClose={jest.fn()} />);
+ render(<Header links={links} expanded={false} onClose={jest.fn()} />, {
+ wrapper: MemoryRouter,
+ });
expect(screen.getByLabelText('com_nav_close_sidebar')).toHaveAttribute('tabindex', '-1');
});
@@ -87,7 +96,9 @@ describe('mobile drawer header', () => {
* outlasts it (the id does not exist until `expanded` commits).
*/
it('moves focus to the toggle when the drawer opens', () => {
- const { rerender } = render(<Header links={links} expanded={false} onClose={jest.fn()} />);
+ const { rerender } = render(<Header links={links} expanded={false} onClose={jest.fn()} />, {
+ wrapper: MemoryRouter,
+ });
expect(document.activeElement).toBe(document.body);
rerender(<Header links={links} expanded={true} onClose={jest.fn()} />);
@@ -96,7 +107,9 @@ describe('mobile drawer header', () => {
});
it('never steals focus while closed', () => {
- render(<Header links={links} expanded={false} onClose={jest.fn()} />);
+ render(<Header links={links} expanded={false} onClose={jest.fn()} />, {
+ wrapper: MemoryRouter,
+ });
expect(document.activeElement).toBe(document.body);
});
@@ -107,11 +120,34 @@ describe('mobile drawer header', () => {
* persistent control flipping state rather than a new X appearing elsewhere.
*/
it('leads the row with the shared header-action toggle', () => {
- const { container } = render(<Header links={links} expanded={true} onClose={jest.fn()} />);
+ const { container } = render(<Header links={links} expanded={true} onClose={jest.fn()} />, {
+ wrapper: MemoryRouter,
+ });
const toggle = screen.getByTestId('close-sidebar-button');
expect(container.firstElementChild?.firstElementChild).toBe(toggle);
expect(toggle).toHaveAttribute('variant', 'header-action');
expect(toggle.querySelector('[data-testid="sidebar-icon"]')).not.toBeNull();
});
+
+ it('keeps an Agent Marketplace entry reachable from the drawer', () => {
+ /* The drawer is the only sidebar surface on small screens, so losing this
+ * entry here leaves marketplace users with no sidebar route to `/agents`. */
+ render(<Header links={links} expanded={true} onClose={jest.fn()} />, {
+ wrapper: MemoryRouter,
+ });
+
+ const marketplace = screen.getByTestId('nav-agents-marketplace-button');
+ expect(marketplace).toHaveAttribute('href', '/agents');
+ });
+
+ it('omits the marketplace entry without marketplace access', () => {
+ mockShowMarketplace = false;
+ render(<Header links={links} expanded={true} onClose={jest.fn()} />, {
+ wrapper: MemoryRouter,
+ });
+
+ expect(screen.queryByTestId('nav-agents-marketplace-button')).not.toBeInTheDocument();
+ mockShowMarketplace = true;
+ });
});
diff --git a/client/src/data-provider/Favorites.ts b/client/src/data-provider/Favorites.ts
index 17b53513b5..de46fc3426 100644
--- a/client/src/data-provider/Favorites.ts
+++ b/client/src/data-provider/Favorites.ts
@@ -1,8 +1,42 @@
-import { dataService, QueryKeys } from 'librechat-data-provider';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
-import type { UseQueryOptions } from '@tanstack/react-query';
+import { dataService, MutationKeys, QueryKeys } from 'librechat-data-provider';
+import type { QueryClient, UseQueryOptions } from '@tanstack/react-query';
import type { TToolFavorite } from 'librechat-data-provider';
import type { FavoritesState } from '~/store/favorites';
+import { getSessionPrincipal } from '~/utils/session';
+import { enqueue } from '~/utils';
+
+/** A background refetch that starts while a write is in flight can read the
+ * pre-write state and land after it, putting the old value back. `onMutate`
+ * cancels what is already running, but nothing stops a later focus or
+ * reconnect from starting a fresh one, so those are held off until the write
+ * settles. The cross-tab reconciliation they provide is kept.
+ *
+ * Mount counts as a reconciliation point too: a sidebar search unmounts the
+ * Pinned section, and a query with no observer never sees the focus event, so
+ * clearing the search would otherwise restore data fetched before another tab
+ * changed it and the next reorder would post it back over that change. */
+/* Asked of the client at the moment the event fires rather than read from a
+ * hook: `useIsMutating` only reaches the query's options on the next render,
+ * which is a race against the very event this is meant to gate. */
+const reconcileWhenIdle = (queryClient: QueryClient, mutationKey: MutationKeys) => {
+ const idle = () => queryClient.isMutating({ mutationKey: [mutationKey] }) === 0;
+ return { refetchOnWindowFocus: idle, refetchOnReconnect: idle, refetchOnMount: idle };
+};
+
+const PINNED_ORDER_QUEUE = 'pinnedOrder';
+
+/**
+ * Whether a write started by `owner` still belongs to the session that is
+ * signed in, which decides both whether it may be sent and whether it may touch
+ * the shared pinned-order cache, since that key is not scoped by user.
+ *
+ * An owner that could not be identified is foreign to everything, itself
+ * included: treating two unidentified sessions as the same one is how a queued
+ * write would reach the next account.
+ */
+const isForeignSession = (owner?: string): boolean =>
+ owner == null || getSessionPrincipal() !== owner;
const sameFavorite = (a: TToolFavorite, b: TToolFavorite) =>
a.itemType === b.itemType && a.itemId === b.itemId;
@@ -10,13 +44,16 @@ const sameFavorite = (a: TToolFavorite, b: TToolFavorite) =>
export const useGetFavoritesQuery = (
config?: Omit<UseQueryOptions<FavoritesState, Error>, 'queryKey' | 'queryFn'>,
) => {
+ /* Membership that never refreshed would let a second tab prune the saved
+ * position of a favorite the first tab had added, and the pruning gate can
+ * only wait for a fetch that actually happens. */
+ const queryClient = useQueryClient();
+ const reconcile = reconcileWhenIdle(queryClient, MutationKeys.updateFavorites);
return useQuery<FavoritesState, Error>(
[QueryKeys.favorites],
() => dataService.getFavorites() as Promise<FavoritesState>,
{
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- refetchOnMount: false,
+ ...reconcile,
...config,
},
);
@@ -28,6 +65,10 @@ export const useUpdateFavoritesMutation = () => {
(favorites: FavoritesState) =>
dataService.updateFavorites(favorites) as Promise<FavoritesState>,
{
+ /* Keyed so the write is observable from other hook instances: a favorite
+ * row runs its own `useFavorites`, so its removal is invisible to the
+ * mutation state the pinned section holds. */
+ mutationKey: [MutationKeys.updateFavorites],
// Optimistic update to prevent UI flickering when toggling favorites
onMutate: async (newFavorites) => {
await queryClient.cancelQueries([QueryKeys.favorites]);
@@ -40,6 +81,131 @@ export const useUpdateFavoritesMutation = () => {
queryClient.setQueryData([QueryKeys.favorites], context.previousFavorites);
}
},
+ onSettled: () => {
+ if (
+ queryClient.isMutating({ mutationKey: [MutationKeys.updateFavorites] }) === 1 &&
+ queryClient.getQueryState([QueryKeys.favorites])?.isInvalidated
+ ) {
+ return queryClient.invalidateQueries([QueryKeys.favorites]);
+ }
+ },
+ },
+ );
+};
+
+export const useGetPinnedOrderQuery = (
+ config?: Omit<UseQueryOptions<string[], Error>, 'queryKey' | 'queryFn'>,
+) => {
+ /* This order is one shared per-user record, so a second tab that never
+ * refetched would both show a stale arrangement and, on its next reorder,
+ * post a full array that undoes whatever the other tab saved. */
+ const queryClient = useQueryClient();
+ const reconcile = reconcileWhenIdle(queryClient, MutationKeys.updatePinnedOrder);
+ return useQuery<string[], Error>([QueryKeys.pinnedOrder], () => dataService.getPinnedOrder(), {
+ ...reconcile,
+ ...config,
+ onSuccess: (order) => {
+ /* Completion timestamps cannot date a server snapshot. Discard reads
+ * that overlapped this order and start membership reconciliation after
+ * it, before a reorder can treat the membership as authoritative. */
+ for (const key of [QueryKeys.favorites, QueryKeys.pinnedConversations]) {
+ void queryClient.cancelQueries([key]);
+ const favoritesWritePending =
+ key === QueryKeys.favorites &&
+ queryClient.isMutating({ mutationKey: [MutationKeys.updateFavorites] }) > 0;
+ void queryClient.invalidateQueries({
+ queryKey: [key],
+ refetchType: favoritesWritePending ? 'none' : 'active',
+ });
+ }
+ config?.onSuccess?.(order);
+ },
+ });
+};
+
+/** The order the user last asked for. Module scope for the same reason the
+ * queue is: the sidebar unmounts whole sections while a search is active, and
+ * a per-instance ref would let a remounted hook forget that an older write is
+ * still in flight. */
+let latestPinnedOrder: string[] | null = null;
+
+/** The account each order was initiated by.
+ *
+ * `onMutate` runs before the mutation function and awaits `cancelQueries`, so
+ * the credentials can turn over in between. Reading the session again in the
+ * mutation function would attribute the write to whoever is signed in by then
+ * and send the previous account's order as them, so the owner is recorded in
+ * `onMutate`'s first synchronous statement and carried on the order itself. */
+const ownerByOrder = new WeakMap<string[], string | undefined>();
+
+export const useUpdatePinnedOrderMutation = () => {
+ const queryClient = useQueryClient();
+ return useMutation(
+ /* Two drags completed inside one round trip would otherwise race, and the
+ * server would keep whichever request happened to land last rather than the
+ * order the user finished on. */
+ (pinnedOrder: string[]) => {
+ const owner = ownerByOrder.get(pinnedOrder);
+ return enqueue(`${PINNED_ORDER_QUEUE}:${owner ?? ''}`, async () => {
+ /* A queued write runs later and carries whatever Authorization header
+ * is current by then. If the session changed while it waited, sending
+ * it would write one account's order into another's document. */
+ if (isForeignSession(owner)) {
+ throw new Error('pinnedOrder write abandoned: the signed-in user changed');
+ }
+ /* Superseded while it waited its turn. Key repeat on the reorder
+ * shortcut asks for one write per intermediate position, and the whole
+ * array is posted each time, so sending every one of them would put
+ * hundreds of writes on a user document to describe a single move. The
+ * newest arrangement is already queued behind this one and is the only
+ * one the server needs. */
+ if (latestPinnedOrder !== pinnedOrder) {
+ return pinnedOrder;
+ }
+ try {
+ return await dataService.updatePinnedOrder(pinnedOrder);
+ } catch (error) {
+ /* Corrected here rather than in `onError` because the section that
+ * owns this hook is unmounted while a search is active, and the
+ * observer callbacks do not run once it is. The cache holds an order
+ * the server never accepted, and this query refetches on nothing, so
+ * leaving it would pass it off as stored for the rest of the session.
+ * Restoring a captured previous value is not safe either: queued
+ * behind another write it may itself be unpersisted, and before the
+ * first fetch resolves there is none. */
+ if (latestPinnedOrder === pinnedOrder && !isForeignSession(owner)) {
+ queryClient.resetQueries([QueryKeys.pinnedOrder]);
+ }
+ throw error;
+ }
+ });
+ },
+ {
+ mutationKey: [MutationKeys.updatePinnedOrder],
+ onMutate: async (newOrder) => {
+ /* First, before the await below can let the session change. */
+ const owner = getSessionPrincipal();
+ ownerByOrder.set(newOrder, owner);
+ latestPinnedOrder = newOrder;
+ await queryClient.cancelQueries([QueryKeys.pinnedOrder]);
+ if (isForeignSession(owner)) {
+ /* The session turned over while that await was outstanding. This
+ * cache is shared, so showing one account's order to the next is the
+ * same mistake as sending it. */
+ return { owner };
+ }
+ queryClient.setQueryData([QueryKeys.pinnedOrder], newOrder);
+ return { owner };
+ },
+ onSuccess: (savedOrder, newOrder, context) => {
+ if (isForeignSession(context?.owner)) {
+ return;
+ }
+ if (latestPinnedOrder !== newOrder) {
+ return;
+ }
+ queryClient.setQueryData([QueryKeys.pinnedOrder], savedOrder);
+ },
},
);
};
diff --git a/client/src/data-provider/Projects/__tests__/assignSerialization.spec.tsx b/client/src/data-provider/Projects/__tests__/assignSerialization.spec.tsx
new file mode 100644
index 0000000000..6b1cde1683
--- /dev/null
+++ b/client/src/data-provider/Projects/__tests__/assignSerialization.spec.tsx
@@ -0,0 +1,301 @@
+import { RecoilRoot } from 'recoil';
+import { renderHook, act, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { dataService, QueryKeys, setTokenHeader } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import { useAssignConversationToProjectMutation, getPendingAssignment } from '../mutations';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: { ...actual.dataService, assignConversationToProject: jest.fn() },
+ };
+});
+
+const assignConversationToProject = dataService.assignConversationToProject as jest.MockedFunction<
+ typeof dataService.assignConversationToProject
+>;
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((res) => {
+ resolve = res;
+ });
+ return { promise, resolve };
+};
+
+const response = (conversationId: string, projectId: string | null) =>
+ ({
+ conversation: { conversationId, chatProjectId: projectId },
+ projectId,
+ previousProjectId: null,
+ }) as never;
+
+let activeQueryClient: QueryClient;
+
+const wrapper = ({ children }: { children: ReactNode }) => {
+ activeQueryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ return (
+ <RecoilRoot>
+ <QueryClientProvider client={activeQueryClient}>{children}</QueryClientProvider>
+ </RecoilRoot>
+ );
+};
+
+/** Assignments are attributed to the account whose credentials they will travel
+ * with, so the tests need a session installed. */
+const signInAs = (userId: string) => {
+ const claims = btoa(JSON.stringify({ id: userId })).replace(/=+$/, '');
+ setTokenHeader(`header.${claims}.signature`);
+};
+
+describe('useAssignConversationToProjectMutation', () => {
+ beforeEach(() => {
+ /* Reset, not clear: clearing leaves an unconsumed `mockResolvedValueOnce`
+ * queued, and the next test's first call would take the previous test's
+ * leftover instead of its own. */
+ jest.resetAllMocks();
+ signInAs('user-a');
+ });
+
+ afterEach(() => {
+ setTokenHeader(undefined);
+ });
+
+ /* The drag targets, the row menu and the project dialog each hold their own
+ * instance of this hook. Serializing inside the mutation is what keeps two of
+ * them from racing, whichever surface the user reached for. */
+ it('serializes writes for one conversation across separate hook instances', async () => {
+ const first = deferred<never>();
+ assignConversationToProject
+ .mockReturnValueOnce(first.promise)
+ .mockResolvedValueOnce(response('c-1', 'project-a'));
+
+ const dragSurface = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+ const menuSurface = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+
+ await act(async () => {
+ dragSurface.result.current.mutate({ conversationId: 'c-1', projectId: 'project-b' });
+ });
+ await act(async () => {
+ menuSurface.result.current.mutate({ conversationId: 'c-1', projectId: 'project-a' });
+ });
+
+ /* The menu write must wait: arriving first would let the older drop land
+ * afterwards and overwrite the destination the user asked for last. */
+ expect(assignConversationToProject).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ first.resolve(response('c-1', 'project-b') as never);
+ });
+
+ await waitFor(() => expect(assignConversationToProject).toHaveBeenCalledTimes(2));
+ expect(assignConversationToProject.mock.calls[0][0]).toMatchObject({ projectId: 'project-b' });
+ expect(assignConversationToProject.mock.calls[1][0]).toMatchObject({ projectId: 'project-a' });
+ });
+
+ it('leaves different conversations independent', async () => {
+ const held = deferred<never>();
+ assignConversationToProject
+ .mockReturnValueOnce(held.promise)
+ .mockResolvedValueOnce(response('c2', 'project-a'));
+
+ const { result } = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+
+ await act(async () => {
+ result.current.mutate({ conversationId: 'c-2', projectId: 'project-b' });
+ });
+ await act(async () => {
+ result.current.mutate({ conversationId: 'c-2b', projectId: 'project-a' });
+ });
+
+ expect(assignConversationToProject).toHaveBeenCalledTimes(2);
+
+ await act(async () => {
+ held.resolve(response('c-2', 'project-b') as never);
+ });
+ });
+
+ /* Navigation invalidates this exact conversation, so a refetch that read the
+ * old project can be in flight when the assignment confirms. Everything now
+ * reads a conversation's project from this cache, so an older fetch landing
+ * after the write would quietly revert the move. */
+ it('cancels an in-flight conversation refetch before writing the result', async () => {
+ assignConversationToProject.mockResolvedValueOnce(response('c-3', 'project-b'));
+
+ const { result } = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+ const cancelQueries = jest.spyOn(activeQueryClient, 'cancelQueries');
+
+ await act(async () => {
+ await result.current.mutateAsync({ conversationId: 'c-3', projectId: 'project-b' });
+ });
+
+ expect(cancelQueries).toHaveBeenCalledWith([QueryKeys.conversation, 'c-3']);
+ expect(
+ activeQueryClient.getQueryData<{ chatProjectId: string | null }>([
+ QueryKeys.conversation,
+ 'c-3',
+ ])?.chatProjectId,
+ ).toBe('project-b');
+ });
+
+ /* Between the request settling and the cache write there must be no moment
+ * where neither the pending entry nor the cache names the new project, or a
+ * drag started right then reads the stale row and refuses a valid drop. */
+ it('writes the conversation cache before releasing the pending destination', async () => {
+ let cachedDuringSettle: unknown = 'not-read';
+ assignConversationToProject.mockResolvedValueOnce(response('c-4', 'project-b'));
+
+ const { result } = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+
+ /* Observe the cache at the moment the cancellation resolves, which is the
+ * last point before the write. */
+ const cancelQueries = jest
+ .spyOn(activeQueryClient, 'cancelQueries')
+ .mockImplementation(async () => undefined);
+
+ await act(async () => {
+ await result.current.mutateAsync({ conversationId: 'c-4', projectId: 'project-b' });
+ });
+
+ cachedDuringSettle = activeQueryClient.getQueryData<{ chatProjectId: string | null }>([
+ QueryKeys.conversation,
+ 'c-4',
+ ])?.chatProjectId;
+
+ expect(cancelQueries).toHaveBeenCalledWith([QueryKeys.conversation, 'c-4']);
+ expect(cachedDuringSettle).toBe('project-b');
+ cancelQueries.mockRestore();
+ });
+
+ /* Conversation ids are per-user, so a queued assignment must not travel with
+ * the next account's credentials and act on whatever that id names there. */
+ it('abandons a queued assignment when the session turns over', async () => {
+ const first = deferred<never>();
+ assignConversationToProject
+ .mockReturnValueOnce(first.promise)
+ .mockResolvedValueOnce(response('c-5', 'project-a'));
+
+ const { result } = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+
+ await act(async () => {
+ result.current.mutate({ conversationId: 'c-5', projectId: 'project-b' });
+ });
+ let queued!: Promise<unknown>;
+ await act(async () => {
+ queued = result.current
+ .mutateAsync({ conversationId: 'c-5', projectId: 'project-a' })
+ .catch(() => 'abandoned');
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ setTokenHeader(undefined);
+
+ await act(async () => {
+ first.resolve(response('c-5', 'project-b') as never);
+ await expect(queued).resolves.toBe('abandoned');
+ });
+
+ expect(assignConversationToProject).toHaveBeenCalledTimes(1);
+ });
+
+ /* An abandoned write still has to give its pending entry back. Kept, it would
+ * describe a destination that was never sent, and `useEffectiveProjectId`
+ * would read it the next time this account signed in and refuse a drop there
+ * as a no-op. */
+ it('releases the pending destination when a queued assignment is abandoned', async () => {
+ const first = deferred<never>();
+ assignConversationToProject.mockReturnValueOnce(first.promise);
+
+ const { result } = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+
+ await act(async () => {
+ result.current.mutate({ conversationId: 'c-6', projectId: 'project-b' });
+ });
+ let queued!: Promise<unknown>;
+ await act(async () => {
+ queued = result.current
+ .mutateAsync({ conversationId: 'c-6', projectId: 'project-c' })
+ .catch(() => 'abandoned');
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ signInAs('user-b');
+
+ await act(async () => {
+ first.resolve(response('c-6', 'project-b') as never);
+ await expect(queued).resolves.toBe('abandoned');
+ });
+
+ signInAs('user-a');
+ expect(getPendingAssignment('c-6')).toBeUndefined();
+ });
+
+ /* An assignment can reach the database before a concurrent rename and still
+ * answer after it, and the conversation it carries predates that rename.
+ * Replacing the cached document with it would put the old title back. */
+ it('merges the project into the cached conversation without restoring stale fields', async () => {
+ assignConversationToProject.mockResolvedValueOnce({
+ conversation: { conversationId: 'c-8', chatProjectId: 'project-b', title: 'Old Title' },
+ projectId: 'project-b',
+ previousProjectId: null,
+ } as never);
+
+ const { result } = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+
+ activeQueryClient.setQueryData([QueryKeys.conversation, 'c-8'], {
+ conversationId: 'c-8',
+ title: 'Renamed While Assigning',
+ chatProjectId: null,
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ conversationId: 'c-8', projectId: 'project-b' });
+ });
+
+ expect(
+ activeQueryClient.getQueryData<{ title: string; chatProjectId: string | null }>([
+ QueryKeys.conversation,
+ 'c-8',
+ ]),
+ ).toMatchObject({ title: 'Renamed While Assigning', chatProjectId: 'project-b' });
+ });
+
+ /* Cancelling waits on whatever fetch is already running, so the session can
+ * turn over inside that await. The write on the far side of it would then
+ * install one account's conversation in the next account's cache and report
+ * success for it. */
+ it('abandons the write when the session turns over while cancelling', async () => {
+ assignConversationToProject.mockResolvedValueOnce(response('c-7', 'project-b'));
+
+ const { result } = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+
+ const cancellation = deferred<undefined>();
+ const cancelQueries = jest
+ .spyOn(activeQueryClient, 'cancelQueries')
+ .mockImplementation(() => cancellation.promise as Promise<void>);
+
+ let settled!: Promise<unknown>;
+ await act(async () => {
+ settled = result.current
+ .mutateAsync({ conversationId: 'c-7', projectId: 'project-b' })
+ .catch(() => 'abandoned');
+ await waitFor(() => expect(cancelQueries).toHaveBeenCalled());
+ });
+
+ signInAs('user-b');
+
+ await act(async () => {
+ cancellation.resolve(undefined);
+ await expect(settled).resolves.toBe('abandoned');
+ });
+
+ expect(activeQueryClient.getQueryData([QueryKeys.conversation, 'c-7'])).toBeUndefined();
+ cancelQueries.mockRestore();
+ });
+});
diff --git a/client/src/data-provider/Projects/mutations.ts b/client/src/data-provider/Projects/mutations.ts
index d301fea848..64f78a5d5c 100644
--- a/client/src/data-provider/Projects/mutations.ts
+++ b/client/src/data-provider/Projects/mutations.ts
@@ -11,6 +11,8 @@ import type {
TAssignConversationToProjectResponse,
} from 'librechat-data-provider';
import type { UseMutationResult } from '@tanstack/react-query';
+import { getSessionPrincipal } from '~/utils/session';
+import { enqueue } from '~/utils';
import store from '~/store';
export const useCreateProjectMutation = (): UseMutationResult<
@@ -80,6 +82,31 @@ export const useDeleteProjectMutation = (): UseMutationResult<
});
};
+/** One queue per conversation: assignments to different chats stay independent. */
+const ASSIGN_CONVERSATION_QUEUE = 'assign-conversation:';
+
+/** Where each conversation is headed while a write for it is still queued or in
+ * flight, recorded here so every assignment path shares one answer: a drag
+ * helper that tracked only its own writes would keep reporting its
+ * destination after a menu action had moved the chat somewhere else. Each
+ * entry is identified by the write that made it, since comparing destinations
+ * alone cannot tell two moves to the same project apart. */
+type PendingAssignment = { token: number; projectId: string | null; owner?: string };
+
+const pendingAssignments = new Map<string, PendingAssignment>();
+let assignmentToken = 0;
+
+/** The destination of the newest write still outstanding, if there is one. */
+export const getPendingAssignment = (conversationId: string): PendingAssignment | undefined => {
+ const pending = pendingAssignments.get(conversationId);
+ /* An entry left by another account describes a conversation this session
+ * cannot see, so it must not answer for one of its own. */
+ return pending && !isForeignSession(pending.owner) ? pending : undefined;
+};
+
+const isForeignSession = (owner?: string): boolean =>
+ owner == null || getSessionPrincipal() !== owner;
+
export const useAssignConversationToProjectMutation = (): UseMutationResult<
TAssignConversationToProjectResponse,
unknown,
@@ -87,30 +114,92 @@ export const useAssignConversationToProjectMutation = (): UseMutationResult<
unknown
> => {
const queryClient = useQueryClient();
+ /* Only the project field is published. `updateConversationSelector` spreads
+ * whatever it is given over the active conversation, so passing the whole
+ * response would also reinstate every other field as the server held it when
+ * the assignment ran, undoing a rename that landed in between. */
const updateActiveConversation = useRecoilCallback(
({ set }) =>
- (conversation: TConversation) => {
- if (!conversation.conversationId) {
- return;
- }
- set(store.updateConversationSelector(conversation.conversationId), {
- ...conversation,
- chatProjectId: conversation.chatProjectId ?? null,
- });
+ (conversationId: string, chatProjectId: string | null) => {
+ set(store.updateConversationSelector(conversationId), { chatProjectId });
},
[],
);
return useMutation(
- (payload: TAssignConversationToProjectRequest) =>
- dataService.assignConversationToProject(payload),
+ /* Serialized per conversation, and here rather than at any one caller: the
+ * drag targets, the row menu and the project dialog each hold their own
+ * mutation instance, and the write is an unconditional update, so two of
+ * them racing let whichever request reached the database last decide the
+ * project regardless of which the user asked for first. */
+ (payload: TAssignConversationToProjectRequest) => {
+ const { conversationId, projectId } = payload;
+ const owner = getSessionPrincipal();
+ const token = ++assignmentToken;
+ pendingAssignments.set(conversationId, { token, projectId: projectId ?? null, owner });
+ return enqueue(`${ASSIGN_CONVERSATION_QUEUE}${owner ?? ''}:${conversationId}`, async () => {
+ /* Inside the `try`, so that abandoning the write still releases its
+ * pending entry: left behind, it would answer for this conversation
+ * again the next time the account signed in, and report a destination
+ * that was never sent. */
+ try {
+ /* A queued write travels with whatever credentials are current when it
+ * finally runs. Conversation ids are per-user, so sending one account's
+ * under another's would act on whatever that id names over there. */
+ if (isForeignSession(owner)) {
+ throw new Error('assignment abandoned: the signed-in user changed');
+ }
+ const result = await dataService.assignConversationToProject(payload);
+ if (isForeignSession(owner)) {
+ /* The session turned over while the request was out. Rejecting
+ * rather than returning, so none of the success path runs: the
+ * caches are not scoped by user and conversation ids repeat across
+ * accounts, so this answer would otherwise describe one account's
+ * conversation to the next, and report success for it. */
+ throw new Error('assignment abandoned: the signed-in user changed');
+ }
+ /* The authoritative cache is written here, before the pending entry is
+ * released, so a drag starting in between still sees the new project
+ * from one of the two. Doing it in `onSuccess` left a gap while that
+ * callback awaited the cancellation, and would not run at all once
+ * the component that owns the mutation had unmounted. */
+ await queryClient.cancelQueries([QueryKeys.conversation, conversationId]);
+ /* Cancelling waits on whatever fetch was already running, so the
+ * session can turn over between the check above and the write below.
+ * Asked again on this side of the await, where the answer is the one
+ * the write is about to act on. */
+ if (isForeignSession(owner)) {
+ throw new Error('assignment abandoned: the signed-in user changed');
+ }
+ /* Merged rather than replaced, for the same reason: an assignment that
+ * reached the database before a concurrent rename can still answer
+ * after it, and its copy of the conversation predates that rename. */
+ queryClient.setQueryData<TConversation>(
+ [QueryKeys.conversation, conversationId],
+ (previous) =>
+ previous
+ ? { ...previous, chatProjectId: result.conversation.chatProjectId ?? null }
+ : result.conversation,
+ );
+ return result;
+ } finally {
+ /* Only the newest write clears the entry; by now the conversation
+ * cache carries the truth, so no list refresh has to be waited on. */
+ if (pendingAssignments.get(conversationId)?.token === token) {
+ pendingAssignments.delete(conversationId);
+ }
+ }
+ });
+ },
{
onSuccess: (result) => {
- updateActiveConversation(result.conversation);
- queryClient.setQueryData(
- [QueryKeys.conversation, result.conversation.conversationId],
- result.conversation,
- );
+ /* The conversation cache is written in the request itself, above. */
+ if (result.conversation.conversationId) {
+ updateActiveConversation(
+ result.conversation.conversationId,
+ result.conversation.chatProjectId ?? null,
+ );
+ }
[result.previousProjectId, result.projectId].forEach((projectId) => {
if (projectId) {
queryClient.invalidateQueries([QueryKeys.project, projectId]);
diff --git a/client/src/data-provider/__tests__/favoritesReconciliation.test.tsx b/client/src/data-provider/__tests__/favoritesReconciliation.test.tsx
new file mode 100644
index 0000000000..080ce9954b
--- /dev/null
+++ b/client/src/data-provider/__tests__/favoritesReconciliation.test.tsx
@@ -0,0 +1,120 @@
+import React from 'react';
+import { Provider, createStore } from 'jotai';
+import { dataService } from 'librechat-data-provider';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { TUserFavorite } from 'librechat-data-provider';
+import useFavoritesData from '~/components/Nav/Favorites/useFavoritesData';
+import useFavorites from '~/hooks/useFavorites';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: {
+ ...actual.dataService,
+ getFavorites: jest.fn(),
+ updateFavorites: jest.fn(),
+ },
+ };
+});
+
+jest.mock('~/data-provider', () => ({
+ ...jest.requireActual('../Favorites'),
+ useGetEndpointsQuery: () => ({ data: {}, isLoading: false }),
+ useGetStartupConfig: () => ({ data: { modelSpecs: { list: [] } } }),
+}));
+
+jest.mock('~/hooks', () => ({
+ useFavorites: jest.requireActual('~/hooks/useFavorites').default,
+ useLocalize: () => (key: string) => key,
+ useGetConversation: () => () => null,
+ useNewConvo: () => ({ newConversation: jest.fn() }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useAssistantsMapContext: () => ({}),
+ useAgentsMapContext: () => ({}),
+}));
+
+jest.mock('~/hooks/Input/useSelectMention', () => ({
+ __esModule: true,
+ default: () => ({}),
+}));
+
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
+ useToastContext: () => ({ showToast: jest.fn() }),
+}));
+
+describe('favorites membership reconciliation', () => {
+ beforeEach(() => localStorage.clear());
+
+ it.each(['sidebar cleanup', 'favorite row removal'])(
+ 'restores a failed %s before allowing pinned-order pruning',
+ async (source) => {
+ const saved: TUserFavorite[] = [
+ { model: 'keep', endpoint: 'openAI' },
+ { model: 'restore', endpoint: 'openAI' },
+ ];
+ const getFavorites = jest.mocked(dataService.getFavorites).mockResolvedValue(saved);
+ const write = Promise.withResolvers<TUserFavorite[]>();
+ const updateFavorites = jest
+ .mocked(dataService.updateFavorites)
+ .mockReturnValue(write.promise);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ logger: { log: console.log, warn: console.warn, error: () => undefined },
+ });
+ const store = createStore();
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={queryClient}>
+ <Provider store={store}>{children}</Provider>
+ </QueryClientProvider>
+ );
+ const readyMemberships: TUserFavorite[][] = [];
+ const { result, unmount } = renderHook(
+ () => {
+ const sidebar = useFavoritesData();
+ if (sidebar.isLoaded) {
+ readyMemberships.push(sidebar.favorites);
+ }
+ return sidebar;
+ },
+ { wrapper },
+ );
+ const row =
+ source === 'favorite row removal'
+ ? renderHook(() => useFavorites(), { wrapper })
+ : undefined;
+ try {
+ await waitFor(() => {
+ expect(result.current.isLoaded).toBe(true);
+ expect(result.current.favorites).toEqual(saved);
+ });
+ readyMemberships.length = 0;
+ act(() => {
+ if (row) {
+ row.result.current.removeFavoriteModel('restore', 'openAI');
+ } else {
+ result.current.reorderFavorites([saved[0]], true);
+ }
+ });
+ await waitFor(() => {
+ expect(updateFavorites).toHaveBeenCalledWith([saved[0]]);
+ expect(result.current.favorites).toEqual([saved[0]]);
+ expect(result.current.isLoaded).toBe(false);
+ });
+ await act(async () => write.reject(new Error('write failed')));
+ await waitFor(() => expect(getFavorites).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(result.current.isLoaded).toBe(true));
+ expect(result.current.favorites).toEqual(saved);
+ expect(readyMemberships).not.toContainEqual([saved[0]]);
+ } finally {
+ unmount();
+ row?.unmount();
+ queryClient.clear();
+ }
+ },
+ );
+});
diff --git a/client/src/data-provider/__tests__/pinnedOrder.test.tsx b/client/src/data-provider/__tests__/pinnedOrder.test.tsx
new file mode 100644
index 0000000000..a39f89b16b
--- /dev/null
+++ b/client/src/data-provider/__tests__/pinnedOrder.test.tsx
@@ -0,0 +1,583 @@
+import { setTokenHeader } from 'librechat-data-provider';
+import { dataService, QueryKeys } from 'librechat-data-provider';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { ConversationListResponse, TUserFavorite } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import {
+ useGetFavoritesQuery,
+ useGetPinnedOrderQuery,
+ useUpdateFavoritesMutation,
+ useUpdatePinnedOrderMutation,
+} from '../Favorites';
+import { usePinnedConversationsQuery } from '../queries';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: {
+ ...actual.dataService,
+ getPinnedOrder: jest.fn(),
+ updatePinnedOrder: jest.fn(),
+ getFavorites: jest.fn(),
+ updateFavorites: jest.fn(),
+ listConversations: jest.fn(),
+ },
+ };
+});
+
+const updatePinnedOrder = dataService.updatePinnedOrder as jest.MockedFunction<
+ typeof dataService.updatePinnedOrder
+>;
+const getPinnedOrder = dataService.getPinnedOrder as jest.MockedFunction<
+ typeof dataService.getPinnedOrder
+>;
+const getFavorites = jest.mocked(dataService.getFavorites);
+const updateFavorites = jest.mocked(dataService.updateFavorites);
+const listConversations = jest.mocked(dataService.listConversations);
+
+/** Resolves/rejects on command so two writes can be held in flight at once. */
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+};
+
+/** A token shaped like the real one: the `id` claim is what attributes a write. */
+const signInAs = (userId: string | undefined) => {
+ if (userId == null) {
+ setTokenHeader(undefined);
+ return;
+ }
+ const claims = btoa(JSON.stringify({ id: userId })).replace(/=+$/, '');
+ setTokenHeader(`header.${claims}.signature`);
+};
+
+const setup = (userId: string | undefined = 'user-a') => {
+ signInAs(userId);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ const { result, unmount } = renderHook(() => useUpdatePinnedOrderMutation(), { wrapper });
+ return { queryClient, result, unmount, signInAs };
+};
+
+const cached = (queryClient: QueryClient) =>
+ queryClient.getQueryData<string[]>([QueryKeys.pinnedOrder]);
+
+describe('useUpdatePinnedOrderMutation', () => {
+ beforeEach(() => {
+ /* `reset`, not `clear`: a queued `mockResolvedValueOnce` that a test never
+ * consumed would otherwise be handed to the next one. */
+ jest.resetAllMocks();
+ getPinnedOrder.mockResolvedValue(['a', 'b', 'c']);
+ });
+
+ it('serializes writes so the server sees them in the order they were made', async () => {
+ const first = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(first.promise).mockResolvedValueOnce(['c', 'b', 'a']);
+
+ const { result } = setup();
+
+ /* `onMutate` awaits `cancelQueries`, so the request leaves in a microtask
+ * rather than inside the `mutate` call itself. */
+ await act(async () => {
+ result.current.mutate(['b', 'a', 'c']);
+ });
+ await act(async () => {
+ result.current.mutate(['c', 'b', 'a']);
+ });
+
+ /* The second request must not be issued until the first settles, or the
+ * server keeps whichever response happens to land last. */
+ expect(updatePinnedOrder).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ first.resolve(['b', 'a', 'c']);
+ });
+
+ await waitFor(() => expect(updatePinnedOrder).toHaveBeenCalledTimes(2));
+ expect(updatePinnedOrder.mock.calls[0][0]).toEqual(['b', 'a', 'c']);
+ expect(updatePinnedOrder.mock.calls[1][0]).toEqual(['c', 'b', 'a']);
+ });
+
+ it('leaves a newer pending order alone when an earlier write fails', async () => {
+ const first = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(first.promise).mockResolvedValueOnce(['c', 'b', 'a']);
+
+ const { queryClient, result } = setup();
+ queryClient.setQueryData([QueryKeys.pinnedOrder], ['a', 'b', 'c']);
+
+ await act(async () => {
+ result.current.mutate(['b', 'a', 'c']);
+ });
+ await act(async () => {
+ result.current.mutate(['c', 'b', 'a']);
+ });
+ expect(cached(queryClient)).toEqual(['c', 'b', 'a']);
+
+ await act(async () => {
+ first.reject(new Error('nope'));
+ await first.promise.catch(() => undefined);
+ });
+
+ /* Rolling back here would put the pre-first-drag order on screen while the
+ * second drag is still in flight and about to be stored. */
+ await waitFor(() => expect(cached(queryClient)).toEqual(['c', 'b', 'a']));
+ });
+
+ it('takes the order the server confirms for the newest write', async () => {
+ updatePinnedOrder.mockResolvedValueOnce(['c', 'b', 'a']);
+
+ const { queryClient, result } = setup();
+
+ await act(async () => {
+ await result.current.mutateAsync(['c', 'b', 'a']);
+ });
+
+ expect(cached(queryClient)).toEqual(['c', 'b', 'a']);
+ });
+
+ it('discards the optimistic order when the newest write fails', async () => {
+ updatePinnedOrder.mockRejectedValueOnce(new Error('rejected'));
+
+ const { queryClient, result } = setup();
+ queryClient.setQueryData([QueryKeys.pinnedOrder], ['a', 'b', 'c']);
+
+ await act(async () => {
+ await result.current.mutateAsync(['b', 'a', 'c']).catch(() => undefined);
+ });
+
+ /* The optimistic value was never accepted, so it must not survive as though
+ * it had been. Every automatic refetch trigger is off on this query, so
+ * leaving it cached would pass it off as server data all session. */
+ await waitFor(() => expect(cached(queryClient)).toBeUndefined());
+ });
+
+ it('abandons a queued write when the signed-in user changed', async () => {
+ const first = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(first.promise).mockResolvedValueOnce(['c', 'b', 'a']);
+
+ const { result, signInAs } = setup('user-a');
+
+ await act(async () => {
+ result.current.mutate(['b', 'a', 'c']);
+ });
+ let queued!: Promise<string[] | string>;
+ await act(async () => {
+ queued = result.current.mutateAsync(['c', 'b', 'a']).catch(() => 'abandoned');
+ /* Let `onMutate` settle so the write is queued and has recorded its owner
+ * before the session turns over. */
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ /* The session turns over while the second write is still waiting its turn:
+ * sending it would put one account's order in the other's document. */
+ signInAs('user-b');
+
+ await act(async () => {
+ first.resolve(['b', 'a', 'c']);
+ await expect(queued).resolves.toBe('abandoned');
+ });
+
+ expect(updatePinnedOrder).toHaveBeenCalledTimes(1);
+ expect(updatePinnedOrder.mock.calls[0][0]).toEqual(['b', 'a', 'c']);
+ });
+
+ it('still sends a queued write when the same user stays signed in', async () => {
+ const first = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(first.promise).mockResolvedValueOnce(['c', 'b', 'a']);
+
+ const { result } = setup('user-a');
+
+ await act(async () => {
+ result.current.mutate(['b', 'a', 'c']);
+ });
+ await act(async () => {
+ result.current.mutate(['c', 'b', 'a']);
+ });
+
+ await act(async () => {
+ first.resolve(['b', 'a', 'c']);
+ });
+
+ await waitFor(() => expect(updatePinnedOrder).toHaveBeenCalledTimes(2));
+ });
+
+ it('does not publish a response that arrives after the account changed', async () => {
+ const inFlight = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(inFlight.promise);
+
+ const { queryClient, result, signInAs } = setup('user-a');
+
+ let write!: Promise<unknown>;
+ await act(async () => {
+ write = result.current.mutateAsync(['b', 'a', 'c']).catch(() => undefined);
+ await Promise.resolve();
+ });
+
+ /* The request had already left, so the pre-send owner check passed. The
+ * cache key is not scoped by user, so publishing this response now would
+ * hand account A's order to account B. */
+ signInAs('user-b');
+ queryClient.setQueryData([QueryKeys.pinnedOrder], ['b-order']);
+
+ await act(async () => {
+ inFlight.resolve(['a-order']);
+ await write;
+ });
+
+ expect(cached(queryClient)).toEqual(['b-order']);
+ });
+
+ /* The sidebar drops the section that owns this hook whenever a search is
+ * active, while its queued writes keep running. Losing the identity there
+ * must not strand work that belongs to the very same account. */
+ it('still sends a queued write after the owning section unmounts', async () => {
+ const first = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(first.promise).mockResolvedValueOnce(['c', 'b', 'a']);
+
+ const { result, unmount } = setup('user-a');
+
+ await act(async () => {
+ result.current.mutate(['b', 'a', 'c']);
+ });
+ await act(async () => {
+ result.current.mutate(['c', 'b', 'a']);
+ });
+
+ unmount();
+
+ await act(async () => {
+ first.resolve(['b', 'a', 'c']);
+ });
+
+ await waitFor(() => expect(updatePinnedOrder).toHaveBeenCalledTimes(2));
+ expect(updatePinnedOrder.mock.calls[1][0]).toEqual(['c', 'b', 'a']);
+ });
+
+ it('rolls back a failed write after the owning section unmounts', async () => {
+ const inFlight = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(inFlight.promise);
+
+ const { queryClient, result, unmount } = setup('user-a');
+ queryClient.setQueryData([QueryKeys.pinnedOrder], ['a', 'b', 'c']);
+
+ let write!: Promise<unknown>;
+ await act(async () => {
+ write = result.current.mutateAsync(['b', 'a', 'c']).catch(() => undefined);
+ await Promise.resolve();
+ });
+ /* The optimistic order is on screen and the request has left. */
+ expect(cached(queryClient)).toEqual(['b', 'a', 'c']);
+
+ unmount();
+
+ await act(async () => {
+ inFlight.reject(new Error('rejected'));
+ await write;
+ });
+
+ /* Observer callbacks no longer run, so the correction has to come from the
+ * request itself; skipping it would leave an order cached that the server
+ * never accepted, on a query that refetches on nothing. */
+ await waitFor(() => expect(cached(queryClient)).toBeUndefined());
+ });
+
+ /* The exact sequence the identity has to survive: the section is unmounted by
+ * a search, then A signs out and B signs in before A's queued write starts.
+ * A tracker fed only by the unmounted hook would still read A here and post
+ * A's order on B's credentials. */
+ it('abandons a queued write across a sign-out while the section is unmounted', async () => {
+ const first = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(first.promise).mockResolvedValueOnce(['c', 'b', 'a']);
+
+ const { result, unmount, signInAs } = setup('user-a');
+
+ await act(async () => {
+ result.current.mutate(['b', 'a', 'c']);
+ });
+ let queued!: Promise<unknown>;
+ await act(async () => {
+ queued = result.current.mutateAsync(['c', 'b', 'a']).catch(() => 'abandoned');
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ unmount();
+ signInAs(undefined);
+ signInAs('user-b');
+
+ await act(async () => {
+ first.resolve(['b', 'a', 'c']);
+ await expect(queued).resolves.toBe('abandoned');
+ });
+
+ expect(updatePinnedOrder).toHaveBeenCalledTimes(1);
+ });
+
+ it('abandons a queued write after a plain sign-out', async () => {
+ const first = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(first.promise).mockResolvedValueOnce(['c', 'b', 'a']);
+
+ const { result, signInAs } = setup('user-a');
+
+ await act(async () => {
+ result.current.mutate(['b', 'a', 'c']);
+ });
+ let queued!: Promise<unknown>;
+ await act(async () => {
+ queued = result.current.mutateAsync(['c', 'b', 'a']).catch(() => 'abandoned');
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ /* Signed out is foreign to every owner: nothing queued should ride out on
+ * whatever credentials arrive next. */
+ signInAs(undefined);
+
+ await act(async () => {
+ first.resolve(['b', 'a', 'c']);
+ await expect(queued).resolves.toBe('abandoned');
+ });
+
+ expect(updatePinnedOrder).toHaveBeenCalledTimes(1);
+ });
+
+ /* `onMutate` awaits `cancelQueries` before the request is built, so the
+ * credentials can turn over inside that gap. The owner has to be the account
+ * that started the reorder, not whoever is signed in once setup finishes. */
+ it('attributes a write to the account that started it, not the one setup ended on', async () => {
+ updatePinnedOrder.mockResolvedValueOnce(['b', 'a', 'c']);
+
+ const { queryClient, result, signInAs } = setup('user-a');
+ queryClient.setQueryData([QueryKeys.pinnedOrder], ['a', 'b', 'c']);
+
+ /* Turn the session over while `onMutate` is still awaiting. */
+ const cancelQueries = jest.spyOn(queryClient, 'cancelQueries').mockImplementation(async () => {
+ signInAs('user-b');
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync(['b', 'a', 'c']).catch(() => undefined);
+ });
+
+ expect(updatePinnedOrder).not.toHaveBeenCalled();
+ /* Nor may the optimistic value be shown to the account that arrived. */
+ expect(cached(queryClient)).toEqual(['a', 'b', 'c']);
+ cancelQueries.mockRestore();
+ });
+
+ it('still sends when the session is unchanged through setup', async () => {
+ updatePinnedOrder.mockResolvedValueOnce(['b', 'a', 'c']);
+
+ const { queryClient, result } = setup('user-a');
+
+ await act(async () => {
+ await result.current.mutateAsync(['b', 'a', 'c']);
+ });
+
+ expect(updatePinnedOrder).toHaveBeenCalledTimes(1);
+ expect(cached(queryClient)).toEqual(['b', 'a', 'c']);
+ });
+
+ /* Focus and reconnect reconcile this order across tabs, but a refetch that
+ * starts after onMutate's one-time cancellation can read the pre-reorder
+ * value and land after the write, putting it back. */
+ it('does not start a focus refetch while a write is in flight', async () => {
+ const inFlight = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(inFlight.promise);
+
+ signInAs('user-a');
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const both = renderHook(
+ () => ({
+ query: useGetPinnedOrderQuery(),
+ write: useUpdatePinnedOrderMutation(),
+ }),
+ {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ ),
+ },
+ );
+
+ await waitFor(() => expect(getPinnedOrder).toHaveBeenCalledTimes(1));
+
+ let write!: Promise<unknown>;
+ await act(async () => {
+ write = both.result.current.write.mutateAsync(['b', 'a', 'c']).catch(() => undefined);
+ await Promise.resolve();
+ });
+
+ const beforeFocus = getPinnedOrder.mock.calls.length;
+
+ await act(async () => {
+ window.dispatchEvent(new Event('visibilitychange'));
+ window.dispatchEvent(new Event('focus'));
+ });
+
+ /* No reconciling GET was allowed to start while the write was out. */
+ expect(getPinnedOrder.mock.calls.length).toBe(beforeFocus);
+
+ await act(async () => {
+ inFlight.resolve(['b', 'a', 'c']);
+ await write;
+ });
+ });
+
+ /* Key repeat on the reorder shortcut asks for a write per intermediate
+ * position, and each one posts the whole array. Sending every superseded one
+ * would put a long run of writes on the user document to describe a single
+ * move, so only the newest arrangement is worth the round trip. */
+ it('skips writes that a newer arrangement has superseded', async () => {
+ const first = deferred<string[]>();
+ updatePinnedOrder.mockReturnValueOnce(first.promise).mockResolvedValue(['d', 'c', 'b', 'a']);
+
+ const { result, queryClient } = setup();
+
+ await act(async () => {
+ result.current.mutate(['b', 'a', 'c']);
+ });
+ for (const order of [
+ ['a', 'c', 'b'],
+ ['c', 'a', 'b'],
+ ['d', 'c', 'b', 'a'],
+ ]) {
+ await act(async () => {
+ result.current.mutate(order);
+ });
+ }
+
+ expect(updatePinnedOrder).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ first.resolve(['b', 'a', 'c']);
+ });
+
+ /* The one in flight, then the newest. The two in between are dropped. */
+ await waitFor(() => expect(updatePinnedOrder).toHaveBeenCalledTimes(2));
+ expect(updatePinnedOrder.mock.calls[1][0]).toEqual(['d', 'c', 'b', 'a']);
+ expect(cached(queryClient)).toEqual(['d', 'c', 'b', 'a']);
+ });
+
+ /* A sidebar search unmounts the Pinned section, and a query with no observer
+ * never sees the focus event. Remounting on cached data would show an order
+ * fetched before another tab changed it, and the next reorder would post
+ * that stale array straight back over the change. */
+ it('reconciles the order when the section mounts again', async () => {
+ signInAs('user-a');
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+
+ const first = renderHook(() => useGetPinnedOrderQuery(), { wrapper });
+ await waitFor(() => expect(getPinnedOrder).toHaveBeenCalledTimes(1));
+ first.unmount();
+
+ getPinnedOrder.mockResolvedValue(['c', 'b', 'a']);
+ const second = renderHook(() => useGetPinnedOrderQuery(), { wrapper });
+
+ await waitFor(() => expect(getPinnedOrder).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(second.result.current.data).toEqual(['c', 'b', 'a']));
+ });
+});
+
+describe('pinned order membership reconciliation', () => {
+ beforeEach(() => jest.resetAllMocks());
+
+ it('discards delayed membership snapshots that began before the order arrived', async () => {
+ const order = deferred<string[]>();
+ const oldFavorites = deferred<TUserFavorite[]>();
+ const oldPins = deferred<ConversationListResponse>();
+ const favorites = [{ model: 'new-favorite', endpoint: 'openAI' }];
+ const pins: ConversationListResponse['conversations'] = [
+ {
+ conversationId: 'new-pin',
+ title: 'New pin',
+ pinned: true,
+ endpoint: null,
+ createdAt: '2026-09-06T00:00:00.000Z',
+ updatedAt: '2026-09-06T00:00:00.000Z',
+ },
+ ];
+ getPinnedOrder.mockReturnValue(order.promise);
+ getFavorites.mockReturnValueOnce(oldFavorites.promise).mockResolvedValue(favorites);
+ listConversations
+ .mockReturnValueOnce(oldPins.promise)
+ .mockResolvedValue({ conversations: pins, nextCursor: null });
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const { result } = renderHook(
+ () => ({
+ favorites: useGetFavoritesQuery(),
+ pins: usePinnedConversationsQuery(),
+ order: useGetPinnedOrderQuery(),
+ }),
+ {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ ),
+ },
+ );
+ await waitFor(() => expect(getFavorites).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(listConversations).toHaveBeenCalledTimes(1));
+
+ await act(async () => order.resolve(['model:6:openAI:new-favorite', 'convo:new-pin']));
+ await waitFor(() => expect(result.current.favorites.data).toEqual(favorites));
+ await waitFor(() => expect(result.current.pins.data?.conversations).toEqual(pins));
+
+ await act(async () => {
+ oldFavorites.resolve([]);
+ oldPins.resolve({ conversations: [], nextCursor: null });
+ });
+ expect(result.current.favorites.data).toEqual(favorites);
+ expect(result.current.pins.data?.conversations).toEqual(pins);
+ });
+
+ it('defers favorites reconciliation until a pending membership write settles', async () => {
+ const order = deferred<string[]>();
+ const write = deferred<TUserFavorite[]>();
+ const favorites = [{ model: 'new-favorite', endpoint: 'openAI' }];
+ getPinnedOrder.mockReturnValue(order.promise);
+ getFavorites.mockResolvedValueOnce([]).mockResolvedValue(favorites);
+ updateFavorites.mockReturnValue(write.promise);
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const { result } = renderHook(
+ () => ({
+ favorites: useGetFavoritesQuery(),
+ order: useGetPinnedOrderQuery(),
+ write: useUpdateFavoritesMutation(),
+ }),
+ {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ ),
+ },
+ );
+ await waitFor(() => expect(result.current.favorites.isSuccess).toBe(true));
+ await act(async () => result.current.write.mutate(favorites));
+ await act(async () => order.resolve(['model:6:openAI:new-favorite']));
+ await waitFor(() => expect(result.current.order.isSuccess).toBe(true));
+ expect(getFavorites).toHaveBeenCalledTimes(1);
+ expect(result.current.favorites.data).toEqual(favorites);
+
+ await act(async () => write.resolve(favorites));
+ await waitFor(() => expect(result.current.write.isSuccess).toBe(true));
+ expect(getFavorites).toHaveBeenCalledTimes(2);
+ expect(result.current.favorites.data).toEqual(favorites);
+ });
+});
diff --git a/client/src/data-provider/__tests__/renameConversation.spec.tsx b/client/src/data-provider/__tests__/renameConversation.spec.tsx
new file mode 100644
index 0000000000..d4bb1d3e58
--- /dev/null
+++ b/client/src/data-provider/__tests__/renameConversation.spec.tsx
@@ -0,0 +1,85 @@
+import { RecoilRoot } from 'recoil';
+import { renderHook, act } from '@testing-library/react';
+import { QueryKeys, dataService } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { TConversation } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import { useUpdateConversationMutation } from '../mutations';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: { ...actual.dataService, updateConversation: jest.fn() },
+ };
+});
+
+const updateConversation = dataService.updateConversation as jest.MockedFunction<
+ typeof dataService.updateConversation
+>;
+
+let activeQueryClient: QueryClient;
+
+const wrapper = ({ children }: { children: ReactNode }) => {
+ activeQueryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ return (
+ <RecoilRoot>
+ <QueryClientProvider client={activeQueryClient}>{children}</QueryClientProvider>
+ </RecoilRoot>
+ );
+};
+
+describe('useUpdateConversationMutation', () => {
+ beforeEach(() => {
+ jest.resetAllMocks();
+ });
+
+ /* A rename request carries only a title. Its response is a whole
+ * conversation as it stood when the server handled it, so writing all of it
+ * back would restore the pre-request value of every other field. */
+ it('does not undo a project assignment that landed while the rename was in flight', async () => {
+ const { result } = renderHook(() => useUpdateConversationMutation('c1'), { wrapper });
+
+ /* The assignment has already been confirmed and cached. */
+ activeQueryClient.setQueryData<TConversation>([QueryKeys.conversation, 'c1'], {
+ conversationId: 'c1',
+ title: 'Old title',
+ chatProjectId: 'project-b',
+ } as TConversation);
+
+ /* The rename's response still shows the chat where it was beforehand. */
+ updateConversation.mockResolvedValueOnce({
+ conversationId: 'c1',
+ title: 'New title',
+ chatProjectId: null,
+ } as TConversation);
+
+ await act(async () => {
+ await result.current.mutateAsync({ conversationId: 'c1', title: 'New title' });
+ });
+
+ const cached = activeQueryClient.getQueryData<TConversation>([QueryKeys.conversation, 'c1']);
+ expect(cached?.title).toBe('New title');
+ expect(cached?.chatProjectId).toBe('project-b');
+ });
+
+ it('writes the response through when nothing is cached yet', async () => {
+ const { result } = renderHook(() => useUpdateConversationMutation('c2'), { wrapper });
+
+ updateConversation.mockResolvedValueOnce({
+ conversationId: 'c2',
+ title: 'Fresh',
+ chatProjectId: 'project-a',
+ } as TConversation);
+
+ await act(async () => {
+ await result.current.mutateAsync({ conversationId: 'c2', title: 'Fresh' });
+ });
+
+ const cached = activeQueryClient.getQueryData<TConversation>([QueryKeys.conversation, 'c2']);
+ expect(cached?.title).toBe('Fresh');
+ expect(cached?.chatProjectId).toBe('project-a');
+ });
+});
diff --git a/client/src/data-provider/mutations.ts b/client/src/data-provider/mutations.ts
index cb7e14f2d2..60d54ba4c8 100644
--- a/client/src/data-provider/mutations.ts
+++ b/client/src/data-provider/mutations.ts
@@ -36,8 +36,17 @@ export const useUpdateConversationMutation = (
{
onSuccess: (updatedConvo, payload) => {
const targetId = payload.conversationId || id;
- queryClient.setQueryData([QueryKeys.conversation, targetId], updatedConvo);
- updateConvoInAllQueries(queryClient, targetId, () => updatedConvo);
+ /* A rename carries only a title, so only the title is taken from its
+ * response. Writing the whole conversation would also restore its
+ * pre-request copy of every other field, undoing a concurrent change
+ * whose response happened to land first: an assignment moving the chat
+ * to another project would silently revert here. */
+ const applyRename = (previous?: t.TConversation): t.TConversation =>
+ previous
+ ? { ...previous, title: updatedConvo.title, updatedAt: updatedConvo.updatedAt }
+ : updatedConvo;
+ queryClient.setQueryData<t.TConversation>([QueryKeys.conversation, targetId], applyRename);
+ updateConvoInAllQueries(queryClient, targetId, applyRename);
queryClient.invalidateQueries([QueryKeys.projectConversations]);
},
},
diff --git a/client/src/data-provider/queries.ts b/client/src/data-provider/queries.ts
index 52ec916547..b343421357 100644
--- a/client/src/data-provider/queries.ts
+++ b/client/src/data-provider/queries.ts
@@ -131,7 +131,7 @@ export const usePinnedConversationsQuery = (
return useQuery<ConversationListResponse>(
queryKey,
- async () => {
+ async ({ signal }) => {
const conversations: ConversationListResponse['conversations'] = [];
let cursor: string | undefined;
@@ -145,6 +145,7 @@ export const usePinnedConversationsQuery = (
cursor,
});
} catch (error) {
+ signal?.throwIfAborted();
/** A page failing partway through the drain must not throw away the pins
* already loaded: publish them so the retry, which starts the drain over,
* renders against the partial set instead of an empty section. */
@@ -156,6 +157,7 @@ export const usePinnedConversationsQuery = (
}
throw error;
}
+ signal?.throwIfAborted();
conversations.push(...page.conversations);
cursor = page.nextCursor ?? undefined;
} while (cursor);
diff --git a/client/src/hooks/useFavorites.ts b/client/src/hooks/useFavorites.ts
index 8f8d2f1fe8..06dfa1ebcd 100644
--- a/client/src/hooks/useFavorites.ts
+++ b/client/src/hooks/useFavorites.ts
@@ -1,6 +1,8 @@
-import { useEffect, useCallback, useRef } from 'react';
+import { useEffect, useCallback } from 'react';
import { useAtom } from 'jotai';
import { useToastContext } from '@librechat/client';
+import { useIsMutating } from '@tanstack/react-query';
+import { MutationKeys } from 'librechat-data-provider';
import type { Favorite } from '~/store/favorites';
import { useGetFavoritesQuery, useUpdateFavoritesMutation } from '~/data-provider';
import { favoritesAtom } from '~/store';
@@ -53,12 +55,10 @@ export default function useFavorites() {
const getFavoritesQuery = useGetFavoritesQuery();
const updateFavoritesMutation = useUpdateFavoritesMutation();
- const isMutatingRef = useRef(false);
+ const writesInFlight = useIsMutating([MutationKeys.updateFavorites]);
useEffect(() => {
- // Skip updating local state if a mutation is in progress or just completed
- // The local state is already optimistically updated by saveFavorites
- if (isMutatingRef.current || updateFavoritesMutation.isLoading) {
+ if (writesInFlight > 0) {
return;
}
if (getFavoritesQuery.data) {
@@ -68,7 +68,7 @@ export default function useFavorites() {
setFavorites([]);
}
}
- }, [getFavoritesQuery.data, setFavorites, updateFavoritesMutation.isLoading]);
+ }, [getFavoritesQuery.data, setFavorites, writesInFlight]);
const getErrorMessage = useCallback(
(error: unknown): string => {
@@ -91,20 +91,12 @@ export default function useFavorites() {
async (newFavorites: typeof favorites) => {
const cleaned = cleanFavorites(newFavorites);
setFavorites(cleaned);
- isMutatingRef.current = true;
try {
await updateFavoritesMutation.mutateAsync(cleaned);
} catch (error) {
logger.error('Error updating favorites:', error);
showToast({ message: getErrorMessage(error), status: 'error' });
- // Refetch to resync state with server
- getFavoritesQuery.refetch();
- } finally {
- // Use a small delay to prevent the useEffect from triggering immediately
- // after the mutation completes but before React has finished processing
- setTimeout(() => {
- isMutatingRef.current = false;
- }, 100);
+ void getFavoritesQuery.refetch();
}
},
[setFavorites, updateFavoritesMutation, showToast, getErrorMessage, getFavoritesQuery],
@@ -194,25 +186,13 @@ export default function useFavorites() {
*/
const reorderFavorites = useCallback(
async (newFavorites: typeof favorites, persist = false) => {
- const cleaned = cleanFavorites(newFavorites);
- setFavorites(cleaned);
if (persist) {
- isMutatingRef.current = true;
- try {
- await updateFavoritesMutation.mutateAsync(cleaned);
- } catch (error) {
- logger.error('Error reordering favorites:', error);
- showToast({ message: getErrorMessage(error), status: 'error' });
- // Refetch to resync state with server
- getFavoritesQuery.refetch();
- } finally {
- setTimeout(() => {
- isMutatingRef.current = false;
- }, 100);
- }
+ await saveFavorites(newFavorites);
+ } else {
+ setFavorites(cleanFavorites(newFavorites));
}
},
- [setFavorites, updateFavoritesMutation, showToast, getErrorMessage, getFavoritesQuery],
+ [setFavorites, saveFavorites],
);
return {
@@ -232,6 +212,20 @@ export default function useFavorites() {
reorderFavorites,
/** Whether the favorites query is currently loading */
isLoading: getFavoritesQuery.isLoading,
+ /** Whether the favorites list was actually retrieved. Not the inverse of
+ * `isLoading`: an exhausted retry leaves loading false with no data. */
+ isSuccess: getFavoritesQuery.isSuccess,
+ /** Ready for membership-based pruning only after the atom absorbs the
+ * settled query value, including a rollback with structurally shared data. */
+ isLoaded:
+ getFavoritesQuery.isSuccess &&
+ writesInFlight === 0 &&
+ !getFavoritesQuery.isFetching &&
+ favorites === getFavoritesQuery.data,
+ /** True while the list is being refetched, including the refetch that
+ * recovers from a failed write. */
+ isFetching: getFavoritesQuery.isFetching,
+ dataUpdatedAt: getFavoritesQuery.dataUpdatedAt,
/** Whether there was an error fetching favorites */
isError: getFavoritesQuery.isError,
/** Whether the update mutation is in progress */
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 9f703294a1..03581e6469 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1264,6 +1264,7 @@
"com_ui_download_error_logs": "Download error logs",
"com_ui_downloaded": "Downloaded!",
"com_ui_drag_drop": "Drop any file here to add it to the conversation",
+ "com_ui_drop_to_pin": "Drop to pin",
"com_ui_dropdown_variables": "Dropdown variables:",
"com_ui_duplicate": "Duplicate",
"com_ui_duplicate_agent": "Duplicate Agent",
@@ -1682,6 +1683,7 @@
"com_ui_more_count": "{{0}} more",
"com_ui_more_info": "More info",
"com_ui_more_options": "More options",
+ "com_ui_moved_to_position": "Moved to position {{0}} of {{1}}",
"com_ui_my_prompts": "My Prompts",
"com_ui_my_skills": "My Skills",
"com_ui_n_actions_cancelled": "{{0}} cancelled",
@@ -1791,6 +1793,7 @@
"com_ui_pin": "Pin",
"com_ui_pin_error": "Failed to pin conversation",
"com_ui_pinned": "Pinned",
+ "com_ui_pinned_reorder_hint": "Press Alt plus the up or down arrow key on a pinned item to move it.",
"com_ui_plus_n_more": "+{{0}} more",
"com_ui_preferences": "Preferences",
"com_ui_preferences_updated": "Preferences updated successfully",
@@ -1920,6 +1923,7 @@
"com_ui_rename": "Rename",
"com_ui_rename_conversation": "Rename Conversation",
"com_ui_rename_failed": "Failed to rename conversation",
+ "com_ui_reorder_error": "Failed to save the new order",
"com_ui_requires_auth": "Requires Authentication",
"com_ui_rerun": "Rerun",
"com_ui_rerun_discards_changes": "Rerunning discards these changes and generates a new response. Save to keep them.",
diff --git a/client/src/utils/__tests__/queue.spec.ts b/client/src/utils/__tests__/queue.spec.ts
new file mode 100644
index 0000000000..c0e34564b5
--- /dev/null
+++ b/client/src/utils/__tests__/queue.spec.ts
@@ -0,0 +1,100 @@
+import { enqueue } from '../queue';
+
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+};
+
+/** The queue is module state keyed by string, so every test uses its own key
+ * rather than leaking a pending chain into the next one. */
+let keySeq = 0;
+const freshKey = () => `key-${++keySeq}`;
+
+/** Tasks start on a microtask, never synchronously inside `enqueue`. */
+const flush = () => Promise.resolve();
+
+describe('enqueue', () => {
+ it('runs tasks on one key strictly in order', async () => {
+ const key = freshKey();
+ const started: string[] = [];
+ const first = deferred<void>();
+
+ const a = enqueue(key, () => {
+ started.push('a');
+ return first.promise;
+ });
+ const b = enqueue(key, async () => {
+ started.push('b');
+ });
+
+ await flush();
+ expect(started).toEqual(['a']);
+
+ first.resolve();
+ await Promise.all([a, b]);
+ expect(started).toEqual(['a', 'b']);
+ });
+
+ it('keeps different keys independent', async () => {
+ const started: string[] = [];
+ const held = deferred<void>();
+
+ const a = enqueue(freshKey(), () => {
+ started.push('one');
+ return held.promise;
+ });
+ await enqueue(freshKey(), async () => {
+ started.push('two');
+ });
+
+ /* `two` must not wait behind an unrelated key's in-flight task. */
+ expect(started).toEqual(['one', 'two']);
+ held.resolve();
+ await a;
+ });
+
+ it('does not let a failed task block the queue behind it', async () => {
+ const ran: string[] = [];
+
+ const key = freshKey();
+ const failing = enqueue(key, async () => {
+ ran.push('failing');
+ throw new Error('nope');
+ });
+ const after = enqueue(key, async () => {
+ ran.push('after');
+ });
+
+ await expect(failing).rejects.toThrow('nope');
+ await after;
+ expect(ran).toEqual(['failing', 'after']);
+ });
+
+ it('rejects only for the caller whose task failed', async () => {
+ const key = freshKey();
+ const failing = enqueue(key, async () => {
+ throw new Error('mine');
+ });
+ const ok = enqueue(key, async () => 'value');
+
+ await expect(failing).rejects.toThrow('mine');
+ await expect(ok).resolves.toBe('value');
+ });
+
+ it('releases a key once its queue drains', async () => {
+ const key = freshKey();
+ await enqueue(key, async () => undefined);
+ const started: string[] = [];
+
+ /* A retained tail would leak one map entry per key ever used. */
+ await enqueue(key, async () => {
+ started.push('fresh');
+ });
+ expect(started).toEqual(['fresh']);
+ });
+});
diff --git a/client/src/utils/__tests__/session.spec.ts b/client/src/utils/__tests__/session.spec.ts
new file mode 100644
index 0000000000..e1a9764183
--- /dev/null
+++ b/client/src/utils/__tests__/session.spec.ts
@@ -0,0 +1,101 @@
+import { setTokenHeader } from 'librechat-data-provider';
+import { getSessionPrincipal } from '../session';
+
+/** Shaped like the real access token, whose payload carries an `id` claim. */
+const jwtWith = (claims: Record<string, unknown>) =>
+ `header.${btoa(JSON.stringify(claims)).replace(/=+$/, '')}.signature`;
+
+/** A LibreChat access token, whose payload carries `id`. */
+const tokenFor = (userId: string, issuedAt = 1) => jwtWith({ id: userId, iat: issuedAt });
+
+/** An OpenID `id_token`, which names its subject as `sub` under an issuer. */
+const openIdTokenFor = (subject: string, issuer = 'https://idp.example.com') =>
+ jwtWith({ sub: subject, iss: issuer });
+
+describe('getSessionPrincipal', () => {
+ afterEach(() => {
+ setTokenHeader(undefined);
+ });
+
+ it('reads the account from the installed credentials', () => {
+ setTokenHeader(tokenFor('user-a'));
+ expect(getSessionPrincipal()).toBe('user:user-a');
+ });
+
+ /* `setUserContext` installs the header in one synchronous call while React
+ * state catches up later, so this has to change with the header, not after. */
+ it('changes in the same turn as the header', () => {
+ setTokenHeader(tokenFor('user-a'));
+ setTokenHeader(tokenFor('user-b'));
+ expect(getSessionPrincipal()).toBe('user:user-b');
+ });
+
+ it('reports no account once signed out', () => {
+ setTokenHeader(tokenFor('user-a'));
+ setTokenHeader(undefined);
+ expect(getSessionPrincipal()).toBeUndefined();
+ });
+
+ /* A silent refresh rotates the token for the same account. Comparing tokens
+ * would read that as a different session and throw away queued work the user
+ * is still entitled to, so the claim is what matters. */
+ it('sees a refreshed token as the same account', () => {
+ setTokenHeader(tokenFor('user-a', 1));
+ const before = getSessionPrincipal();
+ setTokenHeader(tokenFor('user-a', 2));
+
+ expect(getSessionPrincipal()).toBe(before);
+ expect(getSessionPrincipal()).toBe('user:user-a');
+ });
+
+ /* With OpenID token reuse the bearer is the provider's own id_token, which
+ * has no LibreChat `id`. Reading those as "nobody" would make two different
+ * accounts compare equal, which is exactly how a queued write reaches the
+ * wrong one. */
+ it('identifies an OpenID session by its subject and issuer', () => {
+ setTokenHeader(openIdTokenFor('subject-a'));
+ expect(getSessionPrincipal()).toBe('oidc:https://idp.example.com:subject-a');
+ });
+
+ it('keeps two OpenID accounts distinct', () => {
+ setTokenHeader(openIdTokenFor('subject-a'));
+ const first = getSessionPrincipal();
+ setTokenHeader(openIdTokenFor('subject-b'));
+
+ expect(getSessionPrincipal()).not.toBe(first);
+ expect(getSessionPrincipal()).toBeDefined();
+ });
+
+ it('keeps the same subject from different issuers distinct', () => {
+ setTokenHeader(openIdTokenFor('shared', 'https://one.example.com'));
+ const first = getSessionPrincipal();
+ setTokenHeader(openIdTokenFor('shared', 'https://two.example.com'));
+
+ expect(getSessionPrincipal()).not.toBe(first);
+ });
+
+ /* An opaque token names no one, so the credential itself has to separate the
+ * sessions rather than both reading as nobody. */
+ it('keeps two opaque sessions distinct', () => {
+ setTokenHeader('opaque-token-a');
+ const first = getSessionPrincipal();
+ setTokenHeader('opaque-token-b');
+
+ expect(first).toBeDefined();
+ expect(getSessionPrincipal()).not.toBe(first);
+ });
+
+ it('falls back to the credential when the payload carries no subject', () => {
+ setTokenHeader(jwtWith({ email: '[email protected]' }));
+ expect(getSessionPrincipal()).toBeDefined();
+ expect(getSessionPrincipal()).not.toBe('user:undefined');
+ });
+
+ it('decodes a payload whose length needs base64 padding restored', () => {
+ /* Ids vary in length, so the dropped `=` padding has to be put back. */
+ for (const id of ['a', 'ab', 'abc', 'abcd', '6a89f66dd0b2baf4d4b02917']) {
+ setTokenHeader(tokenFor(id));
+ expect(getSessionPrincipal()).toBe(`user:${id}`);
+ }
+ });
+});
diff --git a/client/src/utils/index.ts b/client/src/utils/index.ts
index cc2ddd1ae7..30e13a2994 100644
--- a/client/src/utils/index.ts
+++ b/client/src/utils/index.ts
@@ -21,6 +21,7 @@ export * from './errors';
export * from './agents';
export * from './drafts';
export * from './convos';
+export * from './queue';
export * from './routes';
export * from './presets';
export * from './prompts';
diff --git a/client/src/utils/queue.ts b/client/src/utils/queue.ts
new file mode 100644
index 0000000000..5bea8b01fc
--- /dev/null
+++ b/client/src/utils/queue.ts
@@ -0,0 +1,31 @@
+/** Tails of the per-key chains. Module scope on purpose: a component-local ref
+ * is discarded when its owner unmounts (the sidebar drops whole sections while
+ * a search is active), which would start a second queue alongside a request
+ * that is still running. */
+const tails = new Map<string, Promise<unknown>>();
+
+/**
+ * Runs `task` after every task already queued under `key`, so concurrent writes
+ * to one server-side resource arrive in the order the user asked for them
+ * rather than in whatever order the network settles them.
+ *
+ * A failed task does not block the ones behind it; the returned promise still
+ * rejects for that caller.
+ */
+export const enqueue = <T>(key: string, task: () => Promise<T>): Promise<T> => {
+ const previous = tails.get(key) ?? Promise.resolve();
+ const next = previous.then(task, task);
+ tails.set(key, next);
+ void next.then(
+ () => releaseTail(key, next),
+ () => releaseTail(key, next),
+ );
+ return next;
+};
+
+/** Keeps the map from growing one permanent entry per key ever queued. */
+const releaseTail = (key: string, settled: Promise<unknown>): void => {
+ if (tails.get(key) === settled) {
+ tails.delete(key);
+ }
+};
diff --git a/client/src/utils/session.ts b/client/src/utils/session.ts
new file mode 100644
index 0000000000..4a53b7f454
--- /dev/null
+++ b/client/src/utils/session.ts
@@ -0,0 +1,57 @@
+import { getTokenHeader } from 'librechat-data-provider';
+
+/**
+ * Who the requests going out right now belong to.
+ *
+ * Read from the Authorization header rather than from React state, because the
+ * two do not change together: `setUserContext` installs the new header in one
+ * synchronous call, while a Recoil set or an effect publishes the user later.
+ * Work queued by one account and sent during that gap would be attributed to
+ * the previous user while travelling as the new one.
+ *
+ * Not always a LibreChat user id. With OpenID token reuse the bearer is the
+ * provider's own `id_token`, which identifies its subject as `sub` under an
+ * issuer and carries no `id`. What matters is only that one account is never
+ * mistaken for another, so any stable identifier the credential offers will do.
+ */
+export const getSessionPrincipal = (): string | undefined => {
+ const header = getTokenHeader();
+ if (header == null) {
+ return undefined;
+ }
+
+ const token = header.replace(/^Bearer /, '');
+ const claims = decodeClaims(token);
+
+ if (typeof claims?.id === 'string') {
+ return `user:${claims.id}`;
+ }
+ if (typeof claims?.sub === 'string') {
+ /* Scoped by issuer, since subjects are only unique within one. */
+ const issuer = typeof claims.iss === 'string' ? claims.iss : '';
+ return `oidc:${issuer}:${claims.sub}`;
+ }
+
+ /* An opaque token names no one, and two unnamed sessions must not read as the
+ * same person. The credential itself is what distinguishes them; the cost is
+ * that a refresh looks like a new session and abandons whatever it had
+ * queued, which is the safe direction to fail in. */
+ return `token:${token}`;
+};
+
+const decodeClaims = (
+ token: string,
+): { id?: unknown; sub?: unknown; iss?: unknown } | undefined => {
+ const payload = token.split('.')[1];
+ if (payload == null) {
+ return undefined;
+ }
+ try {
+ /* base64url, so the alphabet differs and the padding is dropped. */
+ const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
+ const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=');
+ return JSON.parse(atob(padded));
+ } catch {
+ return undefined;
+ }
+};
diff --git a/packages/api/src/favorites/index.ts b/packages/api/src/favorites/index.ts
index 6c6f862d01..58c5737c6e 100644
--- a/packages/api/src/favorites/index.ts
+++ b/packages/api/src/favorites/index.ts
@@ -1 +1,2 @@
export * from './handlers';
+export * from './pinned';
diff --git a/packages/api/src/favorites/pinned.spec.ts b/packages/api/src/favorites/pinned.spec.ts
new file mode 100644
index 0000000000..26e298db6e
--- /dev/null
+++ b/packages/api/src/favorites/pinned.spec.ts
@@ -0,0 +1,284 @@
+import type { IUser } from '@librechat/data-schemas';
+import type { Response } from 'express';
+import type { AuthUserDocCacheStore } from '~/auth/userDocCache';
+import type { PinnedOrderHandlersDeps } from './pinned';
+import type { ServerRequest } from '~/types';
+import {
+ getCachedAuthUserDoc,
+ invalidateCachedAuthUserDoc,
+ setCachedAuthUserDoc,
+} from '~/auth/userDocCache';
+import { createPinnedOrderHandlers } from './pinned';
+
+jest.mock('@librechat/data-schemas', () => ({
+ logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() },
+}));
+
+const makeRes = (onJson?: () => void) => {
+ const res = {
+ statusCode: 0,
+ body: undefined as unknown,
+ status(code: number) {
+ res.statusCode = code;
+ return res;
+ },
+ json(payload: unknown) {
+ onJson?.();
+ res.body = payload;
+ return res;
+ },
+ };
+ return res as unknown as Response & { statusCode: number; body: unknown };
+};
+
+const ANONYMOUS = Symbol('anonymous');
+
+const makeReq = (body: unknown, userId: string | typeof ANONYMOUS = 'user-1') =>
+ ({
+ body,
+ user: userId === ANONYMOUS ? undefined : ({ id: userId } as IUser),
+ }) as unknown as ServerRequest;
+
+const makeAuthUserDocCacheStore = () => {
+ const values = new Map<string, unknown>();
+ const store: AuthUserDocCacheStore & { values: Map<string, unknown> } = {
+ values,
+ get: async <T>(key: string) => values.get(key) as T | undefined,
+ set: async (key: string, value: unknown) => {
+ values.set(key, value);
+ },
+ delete: async (key: string) => {
+ values.delete(key);
+ },
+ };
+ return store;
+};
+
+const setup = (overrides: Partial<PinnedOrderHandlersDeps> = {}) => {
+ const stored: Record<string, string[]> = { 'user-1': ['convo:a', 'agent:b'] };
+ const deps: PinnedOrderHandlersDeps = {
+ getUserById: jest.fn(async (userId: string) =>
+ stored[userId] ? ({ pinnedOrder: stored[userId] } as IUser) : null,
+ ),
+ updateUser: jest.fn(async (userId: string, updateData: Partial<IUser>) => {
+ if (!stored[userId]) {
+ return null;
+ }
+ stored[userId] = updateData.pinnedOrder ?? stored[userId];
+ return { pinnedOrder: stored[userId] } as IUser;
+ }),
+ invalidateCachedAuthUserDoc: jest.fn(async (_userId: string) => undefined),
+ ...overrides,
+ };
+ return { deps, handlers: createPinnedOrderHandlers(deps), stored };
+};
+
+describe('createPinnedOrderHandlers', () => {
+ describe('getPinnedOrder', () => {
+ it('returns the stored order', async () => {
+ const { handlers, deps } = setup();
+ const res = makeRes();
+ await handlers.getPinnedOrder(makeReq(undefined), res);
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual(['convo:a', 'agent:b']);
+ /* The schema deselects the field, so it has to be asked for by name. */
+ expect(deps.getUserById).toHaveBeenCalledWith('user-1', '+pinnedOrder');
+ });
+
+ it('returns an empty array when the user has no order yet', async () => {
+ const { handlers } = setup({ getUserById: async () => ({}) as IUser });
+ const res = makeRes();
+ await handlers.getPinnedOrder(makeReq(undefined), res);
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual([]);
+ });
+
+ it('rejects an unauthenticated request', async () => {
+ const { handlers } = setup();
+ const res = makeRes();
+ await handlers.getPinnedOrder(makeReq(undefined, ANONYMOUS), res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('returns 404 when the user is gone', async () => {
+ const { handlers } = setup({ getUserById: async () => null });
+ const res = makeRes();
+ await handlers.getPinnedOrder(makeReq(undefined), res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('returns 500 when the read throws', async () => {
+ const { handlers } = setup({
+ getUserById: async () => {
+ throw new Error('boom');
+ },
+ });
+ const res = makeRes();
+ await handlers.getPinnedOrder(makeReq(undefined), res);
+ expect(res.statusCode).toBe(500);
+ });
+ });
+
+ describe('updatePinnedOrder', () => {
+ it('persists a valid order', async () => {
+ const { handlers, stored } = setup();
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: ['agent:b', 'convo:a'] }), res);
+ expect(res.statusCode).toBe(200);
+ expect(stored['user-1']).toEqual(['agent:b', 'convo:a']);
+ expect(res.body).toEqual(['agent:b', 'convo:a']);
+ });
+
+ it('invalidates cached auth user state after persisting a new order', async () => {
+ const store = makeAuthUserDocCacheStore();
+ await setCachedAuthUserDoc(store, 'auth-user-doc-key', {
+ id: 'user-1',
+ pinnedOrder: ['convo:stale'],
+ });
+ expect(await getCachedAuthUserDoc(store, 'auth-user-doc-key')).toEqual(
+ expect.objectContaining({ pinnedOrder: ['convo:stale'] }),
+ );
+
+ const { handlers } = setup({
+ invalidateCachedAuthUserDoc: (userId) => invalidateCachedAuthUserDoc(store, { userId }),
+ });
+ const res = makeRes(() => {
+ expect(store.values.has('auth-user-doc-key')).toBe(false);
+ });
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: ['convo:fresh'] }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual(['convo:fresh']);
+ expect(await getCachedAuthUserDoc(store, 'auth-user-doc-key')).toBeUndefined();
+ });
+
+ /* `updateUser` returns a document without the deselected field, so the
+ * answer has to come from what was validated rather than from the doc. */
+ it('answers with the stored order even when the document omits the field', async () => {
+ const { handlers } = setup({ updateUser: async () => ({}) as IUser });
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: ['convo:x', 'convo:y'] }), res);
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual(['convo:x', 'convo:y']);
+ });
+
+ it('accepts an empty order', async () => {
+ const { handlers } = setup();
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: [] }), res);
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('rejects a non-array body', async () => {
+ const { handlers, deps } = setup();
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: 'convo:a' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(deps.updateUser).not.toHaveBeenCalled();
+ });
+
+ it('rejects empty and non-string entries', async () => {
+ const { handlers } = setup();
+ for (const pinnedOrder of [[''], [42], [null]]) {
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder }), res);
+ expect(res.statusCode).toBe(400);
+ }
+ });
+
+ it('rejects duplicate entries', async () => {
+ const { handlers } = setup();
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: ['convo:a', 'convo:a'] }), res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ /* A model favorite keys as `model:${endpoint.length}:${endpoint}:${model}`
+ * and the favorites endpoint accepts 256 characters for each half, so the
+ * longest key a valid favorite can produce has to survive this validator. */
+ it('accepts the longest key a valid model favorite can produce', async () => {
+ const { handlers } = setup();
+ const res = makeRes();
+ const endpoint = 'e'.repeat(256);
+ const longest = `model:${endpoint.length}:${endpoint}:${'m'.repeat(256)}`;
+ expect(longest.length).toBeLessThanOrEqual(560);
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: [longest] }), res);
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('rejects a key past the per-key cap', async () => {
+ const { handlers } = setup();
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: ['x'.repeat(561)] }), res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ /* Pinning has no membership cap and the sidebar query drains every cursor,
+ * so any count limit would reject a legitimate list. Only the size of the
+ * document being written is bounded. */
+ it('accepts an order with more entries than any count cap would allow', async () => {
+ const { handlers, stored } = setup();
+ const res = makeRes();
+ const order = Array.from({ length: 5000 }, (_, index) => `convo:${index}`);
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: order }), res);
+ expect(res.statusCode).toBe(200);
+ expect(stored['user-1']).toHaveLength(5000);
+ });
+
+ it('rejects a payload past the total size guard', async () => {
+ const { handlers } = setup();
+ const res = makeRes();
+ /* 512 keys of 512 bytes each is 256KB, one past the budget. */
+ const order = Array.from({ length: 600 }, (_, index) => `convo:${index}:${'x'.repeat(500)}`);
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: order }), res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('rejects an unauthenticated request', async () => {
+ const { handlers, deps } = setup();
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: [] }, ANONYMOUS), res);
+ expect(res.statusCode).toBe(401);
+ expect(deps.updateUser).not.toHaveBeenCalled();
+ });
+
+ it('returns 404 when the user is gone', async () => {
+ const { handlers, deps } = setup({ updateUser: async () => null });
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: ['convo:a'] }), res);
+ expect(res.statusCode).toBe(404);
+ expect(deps.invalidateCachedAuthUserDoc).not.toHaveBeenCalled();
+ });
+
+ it('returns 500 when the write throws', async () => {
+ const { handlers, deps } = setup({
+ updateUser: async () => {
+ throw new Error('boom');
+ },
+ });
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({ pinnedOrder: ['convo:a'] }), res);
+ expect(res.statusCode).toBe(500);
+ expect(deps.invalidateCachedAuthUserDoc).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('malformed bodies', () => {
+ /* Express leaves `req.body` nullish for a request with no JSON body, and a
+ * throw here would escape the handler into the generic error path. */
+ it.each([[undefined], [null]])('answers 400 for a %p body', async (body) => {
+ const { handlers, deps } = setup();
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq(body), res);
+ expect(res.statusCode).toBe(400);
+ expect(deps.updateUser).not.toHaveBeenCalled();
+ });
+
+ it('answers 400 when the body carries no pinnedOrder', async () => {
+ const { handlers } = setup();
+ const res = makeRes();
+ await handlers.updatePinnedOrder(makeReq({}), res);
+ expect(res.statusCode).toBe(400);
+ });
+ });
+});
diff --git a/packages/api/src/favorites/pinned.ts b/packages/api/src/favorites/pinned.ts
new file mode 100644
index 0000000000..ac96ca8e87
--- /dev/null
+++ b/packages/api/src/favorites/pinned.ts
@@ -0,0 +1,115 @@
+import { logger } from '@librechat/data-schemas';
+import type { IUser } from '@librechat/data-schemas';
+import type { Response } from 'express';
+import type { ServerRequest } from '~/types';
+
+/** Pinning a conversation has no membership cap and the sidebar query drains
+ * every cursor, so an account can legitimately present any number of keys: a
+ * count limit would reject a valid sidebar rather than bound anything. What
+ * needs bounding is the user document this is stored in, so the guard is on
+ * total size, which only an abusive payload reaches. */
+const MAX_PINNED_ORDER_BYTES = 256 * 1024;
+
+/** The longest key a valid entry can produce is a model favorite's
+ * `model:${endpoint.length}:${endpoint}:${model}`: the favorites endpoint
+ * accepts 256 characters for each half, so 6 + 3 + 1 + 256 + 1 + 256, plus
+ * headroom. */
+const MAX_PINNED_ORDER_KEY_LENGTH = 560;
+
+export interface PinnedOrderHandlersDeps {
+ /** User read/write — from `@librechat/data-schemas` `createMethods` output. */
+ getUserById: (userId: string, fieldsToSelect?: string) => Promise<IUser | null>;
+ updateUser: (userId: string, updateData: Partial<IUser>) => Promise<IUser | null>;
+ invalidateCachedAuthUserDoc: (userId: string) => Promise<void>;
+}
+
+function validatePinnedOrder(pinnedOrder: unknown, res: Response): string[] | null {
+ if (!Array.isArray(pinnedOrder)) {
+ res.status(400).json({ message: 'pinnedOrder must be an array' });
+ return null;
+ }
+
+ let totalBytes = 0;
+ for (const key of pinnedOrder) {
+ if (typeof key !== 'string' || key.length === 0) {
+ res.status(400).json({ message: 'Each pinnedOrder entry must be a non-empty string' });
+ return null;
+ }
+ if (key.length > MAX_PINNED_ORDER_KEY_LENGTH) {
+ res.status(400).json({
+ message: `pinnedOrder entry exceeds maximum length of ${MAX_PINNED_ORDER_KEY_LENGTH}`,
+ });
+ return null;
+ }
+ totalBytes += Buffer.byteLength(key, 'utf8');
+ if (totalBytes > MAX_PINNED_ORDER_BYTES) {
+ res
+ .status(400)
+ .json({ message: `pinnedOrder exceeds maximum size of ${MAX_PINNED_ORDER_BYTES} bytes` });
+ return null;
+ }
+ }
+
+ if (new Set(pinnedOrder).size !== pinnedOrder.length) {
+ res.status(400).json({ message: 'pinnedOrder entries must be unique' });
+ return null;
+ }
+
+ return pinnedOrder as string[];
+}
+
+/** Combined display order for the sidebar's Pinned section. Keys interleave
+ * favorites and pinned chats (`agent:`, `spec:`, `model:`, `convo:`), so the
+ * two systems keep their own membership while sharing one ordering. */
+export function createPinnedOrderHandlers(deps: PinnedOrderHandlersDeps): {
+ getPinnedOrder: (req: ServerRequest, res: Response) => Promise<Response>;
+ updatePinnedOrder: (req: ServerRequest, res: Response) => Promise<Response>;
+} {
+ async function getPinnedOrder(req: ServerRequest, res: Response): Promise<Response> {
+ const userId = req.user?.id;
+ if (!userId) {
+ return res.status(401).json({ message: 'Unauthorized' });
+ }
+ try {
+ const user = await deps.getUserById(userId, '+pinnedOrder');
+ if (!user) {
+ return res.status(404).json({ message: 'User not found' });
+ }
+ return res.status(200).json(user.pinnedOrder ?? []);
+ } catch (error) {
+ logger.error('[PinnedOrder] Error fetching pinned order:', error);
+ return res.status(500).json({ message: 'Internal server error' });
+ }
+ }
+
+ async function updatePinnedOrder(req: ServerRequest, res: Response): Promise<Response> {
+ const userId = req.user?.id;
+ if (!userId) {
+ return res.status(401).json({ message: 'Unauthorized' });
+ }
+
+ /* A request with no JSON body, or a literal `null` one, leaves `req.body`
+ * nullish. Destructuring it would throw past this handler and answer with
+ * Express's generic error page instead of the 400 the validator gives. */
+ const pinnedOrder = (req.body as { pinnedOrder?: unknown } | null | undefined)?.pinnedOrder;
+ const validated = validatePinnedOrder(pinnedOrder, res);
+ if (validated == null) {
+ return res;
+ }
+ try {
+ const user = await deps.updateUser(userId, { pinnedOrder: validated });
+ if (!user) {
+ return res.status(404).json({ message: 'User not found' });
+ }
+ await deps.invalidateCachedAuthUserDoc(userId);
+ /* The field is deselected at schema level, so the updated document does
+ * not carry it back. What was just stored is what to answer with. */
+ return res.status(200).json(validated);
+ } catch (error) {
+ logger.error('[PinnedOrder] Error updating pinned order:', error);
+ return res.status(500).json({ message: 'Internal server error' });
+ }
+ }
+
+ return { getPinnedOrder, updatePinnedOrder };
+}
diff --git a/packages/client/src/components/Button.spec.tsx b/packages/client/src/components/Button.spec.tsx
index ca5825a06e..3f5aeefd60 100644
--- a/packages/client/src/components/Button.spec.tsx
+++ b/packages/client/src/components/Button.spec.tsx
@@ -116,4 +116,23 @@ describe('Button', () => {
expect(sectionAction).toContain('rounded-lg');
expect(cn(sectionAction)).not.toContain('rounded-lg');
});
+
+ /**
+ * Every other variant is given a size by its call sites, but a section
+ * heading is sized by its own text and all three headers ask for the recipe
+ * alone. The default size recipe is emitted after the variant, so without an
+ * opt out it wins the merge and puts a 40px control in a 32px header row.
+ */
+ it('keeps section headers out of the default size recipe', () => {
+ const header = cn(buttonVariants({ variant: 'section-header' }));
+
+ expect(header).toContain('px-1');
+ expect(header).toContain('h-auto');
+ expect(header).not.toContain('h-10');
+ expect(header).not.toContain('px-4');
+ });
+
+ it('still takes a size when a caller asks for one', () => {
+ expect(cn(buttonVariants({ variant: 'section-header', size: 'sm' }))).toContain('h-9');
+ });
});
diff --git a/packages/client/src/components/Button.tsx b/packages/client/src/components/Button.tsx
index f3d6f0f1ba..4516f20104 100644
--- a/packages/client/src/components/Button.tsx
+++ b/packages/client/src/components/Button.tsx
@@ -17,6 +17,7 @@ type ButtonVariantOptions =
| 'secondary'
| 'ghost'
| 'row-action'
+ | 'section-header'
| 'section-action'
| 'header-action'
| null
@@ -63,6 +64,15 @@ const buttonVariantRecipe = cva(
'row-action': 'hover:bg-surface-hover-alt hover:text-text-primary',
link: 'text-text-primary underline-offset-4 hover:underline',
submit: 'bg-surface-submit text-text-on-status hover:bg-surface-submit-hover',
+ /**
+ * The toggle that heads a collapsible sidebar section, such as Chats,
+ * Projects and Pinned. It reads as a quiet label rather than a control
+ * until focused, and keeps its ring inset because these sit flush
+ * against the section body. It carries its own metrics through the
+ * compound below, since a section heading is sized by its text.
+ */
+ 'section-header':
+ 'justify-start gap-1 rounded-lg px-1 py-2 text-xs font-bold text-text-secondary focus-visible:ring-inset focus-visible:ring-offset-0',
/**
* A quiet icon action sitting beside a section heading in the sidebar.
* Unlike `row-action`, it recedes until hovered so the heading stays
@@ -110,6 +120,15 @@ const buttonVariantRecipe = cva(
shape: 'unset',
class: 'rounded-xl',
},
+ /* A section heading is sized by its own text, so it opts out of the
+ * default size recipe that every other caller supplies explicitly.
+ * Without this the default `h-10 px-4` is emitted after the variant and
+ * wins the merge, giving a 40px control in a 32px header row. */
+ {
+ variant: 'section-header',
+ size: 'default',
+ class: 'h-auto px-1 py-2',
+ },
],
defaultVariants: {
variant: 'default',
diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts
index 3a0d1b08bb..7c41728256 100644
--- a/packages/data-provider/src/api-endpoints.ts
+++ b/packages/data-provider/src/api-endpoints.ts
@@ -495,6 +495,9 @@ export const adminLangfuseConnectionTest = () => `${adminLangfuseConnection()}/t
export const adminLangfuseSessionLink = (conversationId: string) =>
`${adminLangfuseConnection()}/session/${encodeURIComponent(conversationId)}`;
+/* Combined Pinned-section display order: favorite and pinned-chat entry keys interleaved. */
+export const pinnedOrder = () => `${BASE_URL}/api/user/settings/pinned-order`;
+
/* Tool favorites (starred marketplace items) */
export const toolFavorites = () => `${BASE_URL}/api/user/settings/favorites/tools`;
export const toolFavorite = (itemType: string, itemId: string) =>
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index 2c24a51a0f..feaeb68c11 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -111,6 +111,15 @@ export function updateFavorites(favorites: q.TUserFavorite[]): Promise<q.TUserFa
});
}
+/** Combined Pinned-section display order: favorite and pinned-chat entry keys interleaved. */
+export function getPinnedOrder(): Promise<string[]> {
+ return request.get(endpoints.pinnedOrder());
+}
+
+export function updatePinnedOrder(pinnedOrder: string[]): Promise<string[]> {
+ return request.post(endpoints.pinnedOrder(), { pinnedOrder });
+}
+
/** Tool favorites — starred marketplace items (builtins, tools, MCP servers, skills). */
export function getToolFavorites(): Promise<q.TToolFavorite[]> {
return request.get(endpoints.toolFavorites());
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index 5cdfd3397c..456efb8574 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -97,6 +97,8 @@ export enum QueryKeys {
subagentThread = 'subagentThread',
codeEnvironments = 'codeEnvironments',
agentQueuedTurns = 'agentQueuedTurns',
+ /* Combined Pinned-section display order (favorites + pinned chats) */
+ pinnedOrder = 'pinnedOrder',
}
// Dynamic query keys that require parameters
@@ -109,6 +111,11 @@ export enum MutationKeys {
subagentControl = 'subagentControl',
enqueueAgentQueuedTurn = 'enqueueAgentQueuedTurn',
cancelAgentQueuedTurn = 'cancelAgentQueuedTurn',
+ /** Whole-array favorites write, keyed so every hook instance's write is
+ * visible to the others through the query client. */
+ updateFavorites = 'updateFavorites',
+ /** Pinned-section display order write, keyed for the same reason. */
+ updatePinnedOrder = 'updatePinnedOrder',
updateLangfuseConnection = 'updateLangfuseConnection',
testLangfuseConnection = 'testLangfuseConnection',
createAgentApiKey = 'createAgentApiKey',
diff --git a/packages/data-schemas/src/schema/user.ts b/packages/data-schemas/src/schema/user.ts
index 8d13c1ec79..1a5ffe1d69 100644
--- a/packages/data-schemas/src/schema/user.ts
+++ b/packages/data-schemas/src/schema/user.ts
@@ -172,6 +172,19 @@ const userSchema: Schema<IUser> = new Schema<IUser>(
],
default: [],
},
+ /** Display order for the sidebar's Pinned section: favorite and pinned-chat
+ * entry keys interleaved (`agent:`, `spec:`, `model:`, `convo:` prefixes).
+ * Keys whose item no longer exists are ignored; unlisted items keep their
+ * natural order after the listed ones. */
+ pinnedOrder: {
+ type: [String],
+ default: [],
+ /** Display-only, and allowed to grow large. Every authentication request
+ * loads the user document, so leaving this selected would put hundreds
+ * of kilobytes on paths that never read it. The pinned-order handler
+ * asks for it explicitly with `+pinnedOrder`. */
+ select: false,
+ },
skillStates: {
type: Map,
of: Boolean,
diff --git a/packages/data-schemas/src/types/user.ts b/packages/data-schemas/src/types/user.ts
index 8370fb63b6..251e0ff122 100644
--- a/packages/data-schemas/src/types/user.ts
+++ b/packages/data-schemas/src/types/user.ts
@@ -65,6 +65,9 @@ export interface IUser extends Document {
statefulCodeEnvironment?: StatefulCodeEnvironment;
};
favorites?: TUserFavorite[];
+ /** Display order for the sidebar's Pinned section: favorite and pinned-chat
+ * entry keys interleaved (`agent:`, `spec:`, `model:`, `convo:` prefixes). */
+ pinnedOrder?: string[];
/** Per-skill active/inactive overrides. Key = skillId, value = active state. */
skillStates?: Record<string, boolean>;
createdAt?: Date;