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: Filter and Sort the Sidebar Chats List (#15842)

Marco Beretta5b4ec6bfe21f
diff --git a/api/server/routes/__test-utils__/convos-route-mocks.js b/api/server/routes/__test-utils__/convos-route-mocks.js
index b4e9270f61..0fdb419324 100644
--- a/api/server/routes/__test-utils__/convos-route-mocks.js
+++ b/api/server/routes/__test-utils__/convos-route-mocks.js
@@ -90,6 +90,21 @@ module.exports = {
}
return Math.min(Math.max(limit, 1), max);
}),
+ /** Mirrors the real whitelist and helpers so the route's sort normalization is exercised. */
+ CONVERSATION_SORT_FIELDS: {
+ title: true,
+ createdAt: true,
+ updatedAt: true,
+ archivedAt: true,
+ },
+ normalizeSortField: jest.fn((value, { fields, fallback }) => {
+ const raw = Array.isArray(value) ? value[0] : value;
+ return typeof raw === 'string' && fields[raw] === true ? raw : fallback;
+ }),
+ normalizeSortDirection: jest.fn((value, { fallback = 'desc' } = {}) => {
+ const raw = Array.isArray(value) ? value[0] : value;
+ return raw === 'asc' || raw === 'desc' ? raw : fallback;
+ }),
resolveImportMaxFileSize: jest.fn(() => 262144000),
createAxiosInstance: jest.fn(() => ({
get: jest.fn(),
diff --git a/api/server/routes/__tests__/convos.spec.js b/api/server/routes/__tests__/convos.spec.js
index 535e5cd440..b03940381b 100644
--- a/api/server/routes/__tests__/convos.spec.js
+++ b/api/server/routes/__tests__/convos.spec.js
@@ -1872,6 +1872,40 @@ describe('Convos Routes', () => {
});
});
+ describe('GET / sort normalization', () => {
+ const { getConvosByCursor } = require('~/models');
+
+ beforeEach(() => {
+ getConvosByCursor.mockResolvedValue({ conversations: [], nextCursor: null });
+ });
+
+ it('forwards a whitelisted sort field and direction', async () => {
+ const response = await request(app)
+ .get('/api/convos')
+ .query({ sortBy: 'title', sortDirection: 'asc' });
+
+ expect(response.status).toBe(200);
+ expect(getConvosByCursor).toHaveBeenCalledWith(
+ 'test-user-123',
+ expect.objectContaining({ sortBy: 'title', sortDirection: 'asc' }),
+ );
+ });
+
+ /** An unknown field reaches `getConvosByCursor`, which throws on it, so forwarding
+ * a stale or hand-edited value would answer 500 instead of listing anything. */
+ it('falls back to the default ordering for values it does not recognize', async () => {
+ const response = await request(app)
+ .get('/api/convos')
+ .query({ sortBy: 'DROP TABLE', sortDirection: 'sideways' });
+
+ expect(response.status).toBe(200);
+ expect(getConvosByCursor).toHaveBeenCalledWith(
+ 'test-user-123',
+ expect.objectContaining({ sortBy: 'updatedAt', sortDirection: 'desc' }),
+ );
+ });
+ });
+
describe('POST /archive', () => {
it('should archive a conversation successfully', async () => {
const mockConversationId = 'conv-123';
diff --git a/api/server/routes/convos.js b/api/server/routes/convos.js
index 04c9ec5d99..dc45fd6a3b 100644
--- a/api/server/routes/convos.js
+++ b/api/server/routes/convos.js
@@ -5,6 +5,9 @@ const {
reportLocatorTraversalFailure,
isEnabled,
normalizeLimit,
+ normalizeSortDirection,
+ normalizeSortField,
+ CONVERSATION_SORT_FIELDS,
openCheckpointDeletion,
waitForGenerationPersistence,
createArchiveAllHandler,
@@ -153,8 +156,11 @@ router.get('/', async (req, res) => {
const pinned = isEnabled(req.query.pinned);
const search =
typeof req.query.search === 'string' ? req.query.search.trim() || undefined : undefined;
- const sortBy = req.query.sortBy || 'updatedAt';
- const sortDirection = req.query.sortDirection || 'desc';
+ const sortBy = normalizeSortField(req.query.sortBy, {
+ fields: CONVERSATION_SORT_FIELDS,
+ fallback: 'updatedAt',
+ });
+ const sortDirection = normalizeSortDirection(req.query.sortDirection);
const projectId = Array.isArray(req.query.projectId)
? req.query.projectId[0]
: req.query.projectId;
diff --git a/client/src/components/Conversations/ChatFilterMenu.tsx b/client/src/components/Conversations/ChatFilterMenu.tsx
new file mode 100644
index 0000000000..26a19da484
--- /dev/null
+++ b/client/src/components/Conversations/ChatFilterMenu.tsx
@@ -0,0 +1,321 @@
+import { memo, useCallback, useId, useMemo, useState } from 'react';
+import * as Ariakit from '@ariakit/react';
+import { useAtomValue, useSetAtom } from 'jotai';
+import { PermissionTypes, Permissions } from 'librechat-data-provider';
+import { BookmarkFilledIcon, BookmarkIcon } from '@radix-ui/react-icons';
+import { TooltipAnchor, buttonVariants, usePopoverZIndex } from '@librechat/client';
+import {
+ Archive,
+ ArrowDownAZ,
+ CalendarPlus,
+ Check,
+ Clock,
+ ListFilter,
+ MessagesSquare,
+ RotateCcw,
+} from 'lucide-react';
+import type { ReactNode } from 'react';
+import type { ChatFilterStatus, ChatSortDirection, ChatSortField } from './chatFilters';
+import type { TranslationKeys } from '~/hooks';
+import {
+ chatFilterCountAtom,
+ chatFilterStatusAtom,
+ chatFilterTagsAtom,
+ chatSortAtom,
+ isAlphabeticalSort,
+ resetChatFiltersAtom,
+ setChatFilterStatusAtom,
+ sortFieldsFor,
+ toggleChatFilterTagAtom,
+} from './chatFilters';
+import { useGetConversationTags } from '~/data-provider';
+import { useHasAccess, useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+const itemClassName =
+ 'flex w-full cursor-pointer select-none items-center gap-2 rounded-lg px-2 py-2 text-sm text-text-primary outline-none data-[active-item]:bg-surface-hover md:py-1.5';
+
+const groupLabelClassName = 'px-2 pb-1 pt-1.5 text-xs font-medium text-text-secondary';
+
+/** Keeps every row's label on the same x, checked or not. */
+const CheckSlot = ({ checked }: { checked: boolean }) =>
+ checked ? (
+ <Check className="ml-auto size-4 shrink-0 text-text-primary" aria-hidden="true" />
+ ) : (
+ <span className="ml-auto size-4 shrink-0" aria-hidden="true" />
+ );
+
+type ChoiceProps = {
+ label: string;
+ icon: ReactNode;
+ checked: boolean;
+ onSelect: () => void;
+};
+
+/** One exclusive choice. `hideOnClick` stays off: adjusting two facets in a row is
+ * the common case, and a menu that closes on the first click makes that four clicks. */
+const Choice = ({ label, icon, checked, onSelect }: ChoiceProps) => (
+ <Ariakit.MenuItem
+ role="menuitemradio"
+ aria-checked={checked}
+ hideOnClick={false}
+ onClick={onSelect}
+ className={itemClassName}
+ >
+ <span className="shrink-0 text-text-secondary" aria-hidden="true">
+ {icon}
+ </span>
+ <span className="truncate">{label}</span>
+ <CheckSlot checked={checked} />
+ </Ariakit.MenuItem>
+);
+
+const STATUS_OPTIONS: Array<{ value: ChatFilterStatus; label: TranslationKeys; icon: ReactNode }> =
+ [
+ {
+ value: 'active',
+ label: 'com_ui_active_chats',
+ icon: <MessagesSquare className="size-4" />,
+ },
+ { value: 'archived', label: 'com_nav_archived_chats', icon: <Archive className="size-4" /> },
+ ];
+
+const SORT_OPTIONS: Record<ChatSortField, { label: TranslationKeys; icon: ReactNode }> = {
+ updatedAt: { label: 'com_ui_sort_updated', icon: <Clock className="size-4" /> },
+ createdAt: { label: 'com_ui_sort_created', icon: <CalendarPlus className="size-4" /> },
+ title: { label: 'com_ui_sort_title', icon: <ArrowDownAZ className="size-4" /> },
+ archivedAt: { label: 'com_nav_archive_created_at', icon: <Archive className="size-4" /> },
+};
+
+/** Bookmarks are their own query and their own permission, so they mount with the
+ * open menu rather than with the sidebar. */
+const BookmarkChoices = memo(() => {
+ const localize = useLocalize();
+ const tags = useAtomValue(chatFilterTagsAtom);
+ const toggleTag = useSetAtom(toggleChatFilterTagAtom);
+ const { data } = useGetConversationTags();
+
+ /** A bookmark no chat carries filters the list down to nothing. */
+ const bookmarks = useMemo(() => data?.filter((tag) => tag.count > 0) ?? [], [data]);
+
+ if (bookmarks.length === 0) {
+ return (
+ <Ariakit.MenuItem
+ disabled={true}
+ className={cn(itemClassName, 'cursor-default text-text-secondary')}
+ >
+ <span className="truncate text-xs">{localize('com_ui_no_bookmarks_title')}</span>
+ </Ariakit.MenuItem>
+ );
+ }
+
+ return (
+ <>
+ {bookmarks.map((bookmark) => {
+ const checked = tags.includes(bookmark.tag);
+ return (
+ <Ariakit.MenuItem
+ key={bookmark.tag}
+ role="menuitemcheckbox"
+ aria-checked={checked}
+ hideOnClick={false}
+ onClick={() => toggleTag(bookmark.tag)}
+ className={itemClassName}
+ >
+ <span className="shrink-0 text-text-secondary" aria-hidden="true">
+ {checked ? (
+ <BookmarkFilledIcon className="size-4" />
+ ) : (
+ <BookmarkIcon className="size-4" />
+ )}
+ </span>
+ <span className="truncate">{bookmark.tag}</span>
+ <span className="ml-auto shrink-0 text-xs tabular-nums text-text-tertiary">
+ {bookmark.count}
+ </span>
+ </Ariakit.MenuItem>
+ );
+ })}
+ </>
+ );
+});
+
+BookmarkChoices.displayName = 'BookmarkChoices';
+
+/**
+ * Every way the chats list can be narrowed or reordered, in one menu beside the
+ * Chats heading: which chats (active or archived), what orders them, and which
+ * bookmarks they must carry. It replaces the bookmark-only control that used to sit
+ * next to the search field, so filtering lives where the list it filters is labelled.
+ */
+const ChatFilterMenu = () => {
+ const localize = useLocalize();
+ const menuId = useId();
+ const zIndex = usePopoverZIndex();
+ const [isOpen, setIsOpen] = useState(false);
+
+ const status = useAtomValue(chatFilterStatusAtom);
+ const sort = useAtomValue(chatSortAtom);
+ const activeCount = useAtomValue(chatFilterCountAtom);
+ const setStatus = useSetAtom(setChatFilterStatusAtom);
+ const setSort = useSetAtom(chatSortAtom);
+ const resetFilters = useSetAtom(resetChatFiltersAtom);
+
+ const hasAccessToBookmarks = useHasAccess({
+ permissionType: PermissionTypes.BOOKMARKS,
+ permission: Permissions.USE,
+ });
+
+ const alphabetical = isAlphabeticalSort(sort.field);
+
+ /** Ascending means A first for titles and oldest first for instants, so the same
+ * two values need two different pairs of labels. */
+ const directionOptions = useMemo<Array<{ value: ChatSortDirection; label: string }>>(
+ () =>
+ alphabetical
+ ? [
+ { value: 'asc', label: localize('com_ui_sort_a_z') },
+ { value: 'desc', label: localize('com_ui_sort_z_a') },
+ ]
+ : [
+ { value: 'desc', label: localize('com_ui_sort_newest') },
+ { value: 'asc', label: localize('com_ui_sort_oldest') },
+ ],
+ [alphabetical, localize],
+ );
+
+ const selectField = useCallback(
+ (field: ChatSortField) => {
+ /** Switching between an instant and a title keeps the direction's meaning rather
+ * than its value: newest-first reads as Z→A otherwise. */
+ const keepsMeaning = isAlphabeticalSort(field) === isAlphabeticalSort(sort.field);
+ const flipped = sort.direction === 'desc' ? 'asc' : 'desc';
+ const direction = keepsMeaning ? sort.direction : flipped;
+ setSort({ field, direction });
+ },
+ [setSort, sort.direction, sort.field],
+ );
+
+ const triggerLabel =
+ activeCount > 0
+ ? localize('com_ui_filters_active', { count: activeCount })
+ : localize('com_ui_filter_and_sort_chats');
+
+ return (
+ <Ariakit.MenuProvider open={isOpen} setOpen={setIsOpen} placement="bottom-end" focusLoop={true}>
+ <TooltipAnchor
+ description={localize('com_ui_filter_and_sort_chats')}
+ render={
+ <Ariakit.MenuButton
+ id="chat-filter-menu-button"
+ aria-label={triggerLabel}
+ aria-pressed={activeCount > 0}
+ data-testid="chat-filter-menu"
+ /** Matches the Projects heading's actions — it sits beside a section heading too. */
+ className={cn(
+ buttonVariants({ variant: 'section-action', size: 'icon-xs' }),
+ 'relative shrink-0',
+ (isOpen || activeCount > 0) && 'bg-surface-active-alt text-text-primary',
+ )}
+ >
+ <ListFilter aria-hidden="true" className="size-4" />
+ {activeCount > 0 && (
+ <span
+ className="absolute right-0.5 top-0.5 size-1.5 rounded-full bg-text-primary"
+ aria-hidden="true"
+ />
+ )}
+ </Ariakit.MenuButton>
+ }
+ />
+ <Ariakit.Menu
+ id={menuId}
+ portal={true}
+ gutter={8}
+ unmountOnHide={true}
+ className="popover-ui min-w-56 max-w-72"
+ /** Portaled beside modal dialog layers, which disable pointer events on body. */
+ style={{ zIndex, pointerEvents: 'auto' }}
+ >
+ <Ariakit.MenuGroup>
+ <Ariakit.MenuGroupLabel className={groupLabelClassName}>
+ {localize('com_ui_show')}
+ </Ariakit.MenuGroupLabel>
+ {STATUS_OPTIONS.map((option) => (
+ <Choice
+ key={option.value}
+ label={localize(option.label)}
+ icon={option.icon}
+ checked={status === option.value}
+ onSelect={() => setStatus(option.value)}
+ />
+ ))}
+ </Ariakit.MenuGroup>
+
+ <Ariakit.MenuSeparator className="my-1 h-px border-border-medium" />
+
+ <Ariakit.MenuGroup>
+ <Ariakit.MenuGroupLabel className={groupLabelClassName}>
+ {localize('com_ui_sort_chats_by')}
+ </Ariakit.MenuGroupLabel>
+ {sortFieldsFor(status).map((field) => (
+ <Choice
+ key={field}
+ label={localize(SORT_OPTIONS[field].label)}
+ icon={SORT_OPTIONS[field].icon}
+ checked={sort.field === field}
+ onSelect={() => selectField(field)}
+ />
+ ))}
+ </Ariakit.MenuGroup>
+
+ <Ariakit.MenuSeparator className="my-1 h-px border-border-medium" />
+
+ <Ariakit.MenuGroup>
+ <Ariakit.MenuGroupLabel className={groupLabelClassName}>
+ {localize('com_ui_sort_order')}
+ </Ariakit.MenuGroupLabel>
+ {directionOptions.map((option) => (
+ <Choice
+ key={option.value}
+ label={option.label}
+ icon={
+ <span className="flex size-4 items-center justify-center text-xs tabular-nums">
+ {option.value === 'asc' ? '↑' : '↓'}
+ </span>
+ }
+ checked={sort.direction === option.value}
+ onSelect={() => setSort({ field: sort.field, direction: option.value })}
+ />
+ ))}
+ </Ariakit.MenuGroup>
+
+ {hasAccessToBookmarks && (
+ <>
+ <Ariakit.MenuSeparator className="my-1 h-px border-border-medium" />
+ <Ariakit.MenuGroup>
+ <Ariakit.MenuGroupLabel className={groupLabelClassName}>
+ {localize('com_ui_bookmarks')}
+ </Ariakit.MenuGroupLabel>
+ <BookmarkChoices />
+ </Ariakit.MenuGroup>
+ </>
+ )}
+
+ <Ariakit.MenuSeparator className="my-1 h-px border-border-medium" />
+ <Ariakit.MenuItem
+ hideOnClick={false}
+ disabled={activeCount === 0}
+ onClick={() => resetFilters()}
+ className={cn(itemClassName, 'text-text-secondary aria-disabled:opacity-50')}
+ data-testid="chat-filter-reset"
+ >
+ <RotateCcw className="size-4 shrink-0" aria-hidden="true" />
+ <span className="truncate">{localize('com_ui_clear_filters')}</span>
+ </Ariakit.MenuItem>
+ </Ariakit.Menu>
+ </Ariakit.MenuProvider>
+ );
+};
+
+export default memo(ChatFilterMenu);
diff --git a/client/src/components/Conversations/Conversations.tsx b/client/src/components/Conversations/Conversations.tsx
index c6feda3b87..0bf3e1a3ac 100644
--- a/client/src/components/Conversations/Conversations.tsx
+++ b/client/src/components/Conversations/Conversations.tsx
@@ -3,11 +3,20 @@ import { useDrop } from 'react-dnd';
import throttle from 'lodash/throttle';
import { useRecoilValue } from 'recoil';
import { ChevronDown } from 'lucide-react';
+import { useAtomValue, useSetAtom } from 'jotai';
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 {
+ chatFilterCountAtom,
+ chatFilterTagsAtom,
+ chatSortAtom,
+ isAlphabeticalSort,
+ isArchivedChatViewAtom,
+ resetChatFiltersAtom,
+} from './chatFilters';
import {
CONVERSATION_DRAG_TYPE,
markExternalHover,
@@ -15,7 +24,7 @@ import {
useEffectiveProjectId,
} from './dnd';
import { useLocalize, TranslationKeys, useElementSize } from '~/hooks';
-import { groupConversationsByDate, cn } from '~/utils';
+import { groupConversations, cn } from '~/utils';
import { useActiveJobs } from '~/data-provider';
import Convo from './Convo';
import store from '~/store';
@@ -42,6 +51,12 @@ interface ConversationsProps {
setIsChatsExpanded: (expanded: boolean) => void;
/** Actions for the Chats header, alongside the Projects header's own. */
chatsHeaderTrailing?: ReactNode;
+ /** Whether another page exists, so an empty list can be told apart from an unpaged one. */
+ hasNextPage?: boolean;
+ /** Whether the initial conversations request failed without usable rows. */
+ isError?: boolean;
+ /** Re-run the conversations request from the error state. */
+ onRetry?: () => void;
}
interface MeasuredRowProps {
@@ -131,20 +146,24 @@ const ChatsHeader: FC<ChatsHeaderProps> = memo(({ isExpanded, onToggle, trailing
ChatsHeader.displayName = 'ChatsHeader';
-const DateLabel: FC<{ groupName: string; isFirst?: boolean }> = memo(({ groupName, isFirst }) => {
- const localize = useLocalize();
- return (
- <h2
- aria-label={localize('com_a11y_chats_date_section', {
- date: localize(groupName as TranslationKeys) || groupName,
- })}
- className={cn('pl-1 pt-1 text-text-secondary', isFirst === true ? 'mt-0' : 'mt-2')}
- style={{ fontSize: '0.7rem' }}
- >
- {localize(groupName as TranslationKeys) || groupName}
- </h2>
- );
-});
+const DateLabel: FC<{ groupName: string; isFirst?: boolean; isAlphabetical?: boolean }> = memo(
+ ({ groupName, isFirst, isAlphabetical = false }) => {
+ const localize = useLocalize();
+ const displayName = localize(groupName as TranslationKeys) || groupName;
+ return (
+ <h2
+ aria-label={localize(
+ isAlphabetical ? 'com_a11y_chats_alpha_section' : 'com_a11y_chats_date_section',
+ isAlphabetical ? { letter: displayName } : { date: displayName },
+ )}
+ className={cn('pl-1 pt-1 text-text-secondary', isFirst === true ? 'mt-0' : 'mt-2')}
+ style={{ fontSize: '0.7rem' }}
+ >
+ {displayName}
+ </h2>
+ );
+ },
+);
DateLabel.displayName = 'DateLabel';
@@ -164,9 +183,17 @@ const Conversations: FC<ConversationsProps> = ({
isChatsExpanded,
setIsChatsExpanded,
chatsHeaderTrailing,
+ hasNextPage = false,
+ isError = false,
+ onRetry,
}) => {
const localize = useLocalize();
const search = useRecoilValue(store.search);
+ const sort = useAtomValue(chatSortAtom);
+ const isArchivedView = useAtomValue(isArchivedChatViewAtom);
+ const activeFilterCount = useAtomValue(chatFilterCountAtom);
+ const filterTags = useAtomValue(chatFilterTagsAtom);
+ const resetFilters = useSetAtom(resetChatFiltersAtom);
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. */
@@ -206,9 +233,17 @@ const Conversations: FC<ConversationsProps> = ({
[rawConversations],
);
+ /** The pinned section above carries pins, so they stay out of these groups — except in
+ * the archive, which that section does not cover: an archived pin would otherwise be
+ * absent from the sidebar entirely rather than merely further down it. */
const groupedConversations = useMemo(
- () => groupConversationsByDate(filteredConversations),
- [filteredConversations],
+ () =>
+ groupConversations(filteredConversations, {
+ field: sort.field,
+ direction: sort.direction,
+ includePinned: isArchivedView,
+ }),
+ [filteredConversations, isArchivedView, sort.direction, sort.field],
);
/* Pins are stripped from the date groups. An all-pin page leaves the
@@ -347,7 +382,11 @@ const Conversations: FC<ConversationsProps> = ({
if (item.type === 'header') {
return (
<MeasuredRow key={key} {...rowProps}>
- <DateLabel groupName={item.groupName} isFirst={index === 0} />
+ <DateLabel
+ groupName={item.groupName}
+ isFirst={index === 0}
+ isAlphabetical={isAlphabeticalSort(sort.field)}
+ />
</MeasuredRow>
);
}
@@ -369,7 +408,7 @@ const Conversations: FC<ConversationsProps> = ({
return null;
},
- [cache, flattenedItems, moveToTop, toggleNav, activeJobIds],
+ [cache, flattenedItems, moveToTop, toggleNav, activeJobIds, sort.field],
);
const getRowHeight = useCallback(
@@ -390,6 +429,102 @@ const Conversations: FC<ConversationsProps> = ({
},
[flattenedItems.length, throttledLoadMore],
);
+ const isListError =
+ isChatsExpanded &&
+ isError &&
+ !isLoading &&
+ !isSearchLoading &&
+ filteredConversations.length === 0;
+
+ /** A list that came back empty is a dead end the user has to be able to leave: say why
+ * it is empty and offer the way back. A drained page can still contain only pinned rows,
+ * which render in PinnedSection and do not make the account empty. */
+ const hasUnfilteredRows =
+ !search.query && filterTags.length === 0 && !isArchivedView && filteredConversations.length > 0;
+ const isEmpty =
+ isChatsExpanded &&
+ !isLoading &&
+ !isSearchLoading &&
+ !isListError &&
+ !hasNextPage &&
+ groupedConversations.length === 0 &&
+ !hasUnfilteredRows;
+
+ let emptyLabel: TranslationKeys = 'com_ui_no_chats';
+ if (search.query) {
+ emptyLabel = 'com_ui_no_search_results';
+ } else if (filterTags.length > 0) {
+ emptyLabel = 'com_ui_no_chats_match_filters';
+ } else if (isArchivedView) {
+ emptyLabel = 'com_ui_no_archived_chats';
+ }
+
+ let body: ReactNode = (
+ <div ref={listContainerRef} className="min-h-0 flex-1 overflow-hidden">
+ <List
+ ref={containerRef}
+ width={listWidth}
+ height={listHeight}
+ deferredMeasurementCache={cache}
+ rowCount={flattenedItems.length}
+ rowHeight={getRowHeight}
+ rowRenderer={rowRenderer}
+ overscanRowCount={10}
+ aria-readonly={false}
+ className="outline-none"
+ aria-label="Conversations"
+ onRowsRendered={handleRowsRendered}
+ tabIndex={-1}
+ style={{ outline: 'none' }}
+ containerRole="rowgroup"
+ />
+ </div>
+ );
+ if (isSearchLoading) {
+ body = (
+ <div className="flex flex-1 items-center justify-center">
+ <Spinner className="text-text-primary" />
+ <span className="ml-2 text-text-primary">{localize('com_ui_loading')}</span>
+ </div>
+ );
+ } else if (isListError) {
+ body = (
+ <div
+ className="flex flex-1 flex-col items-center justify-center gap-2 px-6 text-center"
+ data-testid="convo-list-error"
+ role="alert"
+ >
+ <span className="text-sm text-text-secondary">{localize('com_ui_chats_load_error')}</span>
+ {onRetry && (
+ <button
+ type="button"
+ onClick={onRetry}
+ className="rounded-lg px-2 py-1 text-sm text-text-primary underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary"
+ >
+ {localize('com_ui_retry')}
+ </button>
+ )}
+ </div>
+ );
+ } else if (isEmpty) {
+ body = (
+ <div
+ className="flex flex-1 flex-col items-center justify-center gap-2 px-6 text-center"
+ data-testid="convo-list-empty"
+ >
+ <span className="text-sm text-text-secondary">{localize(emptyLabel)}</span>
+ {activeFilterCount > 0 && (
+ <button
+ type="button"
+ onClick={() => resetFilters()}
+ className="rounded-lg px-2 py-1 text-sm text-text-primary underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary"
+ >
+ {localize('com_ui_clear_filters')}
+ </button>
+ )}
+ </div>
+ );
+ }
return (
<div
@@ -404,32 +539,7 @@ const Conversations: FC<ConversationsProps> = ({
highlight={isDropOver && canDrop}
/>
</div>
- {isSearchLoading ? (
- <div className="flex flex-1 items-center justify-center">
- <Spinner className="text-text-primary" />
- <span className="ml-2 text-text-primary">{localize('com_ui_loading')}</span>
- </div>
- ) : (
- <div ref={listContainerRef} className="min-h-0 flex-1 overflow-hidden">
- <List
- ref={containerRef}
- width={listWidth}
- height={listHeight}
- deferredMeasurementCache={cache}
- rowCount={flattenedItems.length}
- rowHeight={getRowHeight}
- rowRenderer={rowRenderer}
- overscanRowCount={10}
- aria-readonly={false}
- className="outline-none"
- aria-label="Conversations"
- onRowsRendered={handleRowsRendered}
- tabIndex={-1}
- style={{ outline: 'none' }}
- containerRole="rowgroup"
- />
- </div>
- )}
+ {body}
</div>
);
};
diff --git a/client/src/components/Conversations/Convo.tsx b/client/src/components/Conversations/Convo.tsx
index 59329f9ae3..1dfbb4fc08 100644
--- a/client/src/components/Conversations/Convo.tsx
+++ b/client/src/components/Conversations/Convo.tsx
@@ -272,6 +272,9 @@ function Conversation({
const convoOptionsProps = {
title,
isPinned: conversation.pinned,
+ /* The row's own state, not the list's: the sidebar shows unarchived pins beside an
+ archived list, and the previous page's rows stay on screen while the next loads. */
+ isArchived: conversation.isArchived === true,
retainView,
renameHandler: handleRename,
isActiveConvo,
diff --git a/client/src/components/Conversations/ConvoActions.tsx b/client/src/components/Conversations/ConvoActions.tsx
index b4578bc3a6..9c1131e600 100644
--- a/client/src/components/Conversations/ConvoActions.tsx
+++ b/client/src/components/Conversations/ConvoActions.tsx
@@ -10,6 +10,7 @@ export type ConvoActionsProps = {
chatProjectId?: string | null;
title: string | null;
isPinned?: boolean;
+ isArchived?: boolean;
isActiveConvo: boolean;
isShiftHeld?: boolean;
isPopoverActive: boolean;
diff --git a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
index fce713aaa8..b0d4951f6c 100644
--- a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
+++ b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
@@ -3,24 +3,25 @@ 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,
+ buttonVariants,
+ useToastContext,
+ useMediaQuery,
+} from '@librechat/client';
import {
Ellipsis,
Share2,
CopyPlus,
Archive,
+ ArchiveRestore,
FolderInput,
FolderX,
Pen,
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 {
@@ -32,18 +33,30 @@ import {
usePinConversationMutation,
} from '~/data-provider';
import { useHasAccess, useLocalize, useNavigateToConvo, useNewConvo } from '~/hooks';
+import { useChatContext, useLiveAnnouncer } from '~/Providers';
import { NotificationSeverity } from '~/common';
-import { useChatContext } from '~/Providers';
import ProjectButton from './ProjectButton';
import DeleteButton from './DeleteButton';
import ShareButton from './ShareButton';
import { cn } from '~/utils';
+/** The overflow menu and the shift-held quick action show the same archive control in two
+ * sizes, and must never disagree about which direction it moves the conversation. */
+function renderArchiveIcon(isLoading: boolean, isArchived: boolean, className: string) {
+ if (isLoading) {
+ return <Spinner className="size-4" />;
+ }
+ if (isArchived) {
+ return <ArchiveRestore className={className} aria-hidden="true" />;
+ }
+ return <Archive className={className} aria-hidden="true" />;
+}
function ConvoOptions({
conversationId,
chatProjectId,
title,
isPinned = false,
+ isArchived = false,
retainView,
renameHandler,
isPopoverActive,
@@ -55,6 +68,8 @@ function ConvoOptions({
chatProjectId?: string | null;
title: string | null;
isPinned?: boolean;
+ /** This row's own archive state, which the sidebar filter does not stand in for. */
+ isArchived?: boolean;
retainView: () => void;
renameHandler: (e: MouseEvent) => void;
isPopoverActive: boolean;
@@ -65,13 +80,21 @@ function ConvoOptions({
const localize = useLocalize();
const queryClient = useQueryClient();
const isSmallScreen = useMediaQuery('(max-width: 768px)');
- const { index } = useChatContext();
+ const { index, setConversation } = useChatContext();
const { data: startupConfig } = useGetStartupConfig();
const { navigateToConvo } = useNavigateToConvo(index);
const { showToast } = useToastContext();
+ /* Archiving or restoring removes the row from the list that held it, unmounting this
+ menu: the announcement has to come from a live region that outlives the row. */
+ const { announcePolite } = useLiveAnnouncer();
const navigate = useNavigate();
const { conversationId: currentConvoId } = useParams();
+ /* A mutation callback outlives the click that made it: the route it should compare
+ against is whichever chat is open when the request resolves, not the one that was
+ open when the menu item was pressed. */
+ const openConvoIdRef = useRef(currentConvoId);
+ openConvoIdRef.current = currentConvoId;
const { newConversation } = useNewConvo();
const menuId = useId();
@@ -82,7 +105,6 @@ function ConvoOptions({
const [showShareDialog, setShowShareDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [showProjectDialog, setShowProjectDialog] = useState(false);
- const [announcement, setAnnouncement] = useState('');
const canCreateSharedLinks = useHasAccess({
permissionType: PermissionTypes.SHARED_LINKS,
@@ -206,14 +228,21 @@ function ConvoOptions({
}
archiveConvoMutation.mutate(
- { conversationId: convoId, isArchived: true },
+ { conversationId: convoId, isArchived: !isArchived },
{
onSuccess: () => {
- setAnnouncement(localize('com_ui_convo_archived'));
- setTimeout(() => {
- setAnnouncement('');
- }, 10000);
- if (currentConvoId === convoId || currentConvoId === 'new') {
+ /* The request outlives the row: by the time it resolves the user may have opened
+ another chat, so the open conversation is identified at commit time rather than
+ from the one this callback closed over. */
+ setConversation((prev) =>
+ prev?.conversationId === convoId ? { ...prev, isArchived: !isArchived } : prev,
+ );
+ announcePolite({
+ message: localize(isArchived ? 'com_ui_convo_unarchived' : 'com_ui_convo_archived'),
+ isStatus: true,
+ });
+ const openConvoId = openConvoIdRef.current;
+ if (!isArchived && (openConvoId === convoId || openConvoId === 'new')) {
newConversation();
navigate('/c/new', { replace: true });
}
@@ -222,7 +251,7 @@ function ConvoOptions({
},
onError: () => {
showToast({
- message: localize('com_ui_archive_error'),
+ message: localize(isArchived ? 'com_ui_unarchive_error' : 'com_ui_archive_error'),
severity: NotificationSeverity.ERROR,
showIcon: true,
});
@@ -232,12 +261,14 @@ function ConvoOptions({
},
[
conversationId,
- currentConvoId,
+ isArchived,
+ setConversation,
archiveConvoMutation,
navigate,
newConversation,
retainView,
setIsPopoverActive,
+ announcePolite,
showToast,
localize,
],
@@ -330,14 +361,10 @@ function ConvoOptions({
),
},
{
- label: localize('com_ui_archive'),
+ label: localize(isArchived ? 'com_ui_unarchive' : 'com_ui_archive'),
onClick: handleArchiveClick,
hideOnClick: false,
- icon: isArchiveLoading ? (
- <Spinner className="size-4" />
- ) : (
- <Archive className="icon-sm mr-2 text-text-primary" aria-hidden="true" />
- ),
+ icon: renderArchiveIcon(isArchiveLoading, isArchived, 'icon-sm mr-2 text-text-primary'),
},
{
label: localize('com_ui_delete'),
@@ -360,6 +387,7 @@ function ConvoOptions({
renameHandler,
deleteHandler,
isArchiveLoading,
+ isArchived,
isDuplicateLoading,
handlePinClick,
handleArchiveClick,
@@ -387,16 +415,12 @@ function ConvoOptions({
return (
<div className="flex items-center gap-0.5">
<button
- aria-label={localize('com_ui_archive')}
+ aria-label={localize(isArchived ? 'com_ui_unarchive' : 'com_ui_archive')}
className={cn(buttonClassName, 'hover:bg-surface-hover')}
onClick={handleArchiveClick}
disabled={isArchiveLoading}
>
- {isArchiveLoading ? (
- <Spinner className="size-4" />
- ) : (
- <Archive className="icon-md text-text-secondary" aria-hidden={true} />
- )}
+ {renderArchiveIcon(isArchiveLoading, isArchived, 'icon-md text-text-secondary')}
</button>
<button
aria-label={localize('com_ui_delete')}
@@ -416,9 +440,6 @@ function ConvoOptions({
return (
<>
- <span className="sr-only" aria-live="polite" aria-atomic="true">
- {announcement}
- </span>
<DropdownPopup
/**
* Must portal: the row sits inside the nav's `overflow-hidden` and a
@@ -502,6 +523,7 @@ export default memo(ConvoOptions, (prevProps, nextProps) => {
prevProps.title === nextProps.title &&
prevProps.chatProjectId === nextProps.chatProjectId &&
prevProps.isPinned === nextProps.isPinned &&
+ prevProps.isArchived === nextProps.isArchived &&
prevProps.isPopoverActive === nextProps.isPopoverActive &&
prevProps.isActiveConvo === nextProps.isActiveConvo &&
prevProps.isShiftHeld === nextProps.isShiftHeld
diff --git a/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx b/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx
new file mode 100644
index 0000000000..177f00e686
--- /dev/null
+++ b/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx
@@ -0,0 +1,214 @@
+import React from 'react';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import '@testing-library/jest-dom';
+import ConvoOptions from '../ConvoOptions';
+
+const mockArchiveMutate = jest.fn();
+const mockNavigate = jest.fn();
+const mockNewConversation = jest.fn();
+const mockRetainView = jest.fn();
+const mockSetIsPopoverActive = jest.fn();
+const mockAnnouncePolite = jest.fn();
+const mockSetConversation = jest.fn();
+
+jest.mock('@ariakit/react', () => ({
+ MenuButton: jest
+ .requireActual('react')
+ .forwardRef(
+ (
+ { children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>,
+ ref: React.ForwardedRef<HTMLButtonElement>,
+ ) => (
+ <button ref={ref} {...props}>
+ {children}
+ </button>
+ ),
+ ),
+}));
+jest.mock('~/utils', () => ({
+ cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
+}));
+jest.mock('librechat-data-provider', () => ({
+ QueryKeys: { messages: 'messages' },
+ PermissionTypes: { SHARED_LINKS: 'shared_links' },
+ Permissions: { CREATE: 'create' },
+}));
+jest.mock('@librechat/client', () => ({
+ DropdownPopup: ({
+ trigger,
+ items,
+ }: {
+ trigger: React.ReactNode;
+ items: Array<{ label: string; onClick: () => void }>;
+ }) => (
+ <>
+ {trigger}
+ {items
+ .filter((item) => item.label === 'com_ui_archive' || item.label === 'com_ui_unarchive')
+ .map((item) => (
+ <button key={item.label} type="button" onClick={item.onClick}>
+ {item.label}
+ </button>
+ ))}
+ </>
+ ),
+ Spinner: () => <span role="status" />,
+ buttonVariants: () => '',
+ useToastContext: () => ({ showToast: jest.fn() }),
+ useMediaQuery: () => false,
+}));
+
+jest.mock('~/data-provider', () => ({
+ useDuplicateConversationMutation: () => ({ mutate: jest.fn(), isLoading: false }),
+ useAssignConversationToProjectMutation: () => ({ mutate: jest.fn(), isLoading: false }),
+ useDeleteConversationMutation: () => ({ mutate: jest.fn(), isLoading: false }),
+ useGetStartupConfig: () => ({ data: { sharedLinksEnabled: false } }),
+ useArchiveConvoMutation: () => ({ mutate: mockArchiveMutate, isLoading: false }),
+ usePinConversationMutation: () => ({ mutate: jest.fn(), isLoading: false }),
+}));
+
+jest.mock('~/hooks', () => ({
+ useHasAccess: () => true,
+ useLocalize: () => (key: string) => key,
+ useNavigateToConvo: () => ({ navigateToConvo: jest.fn() }),
+ useNewConvo: () => ({ newConversation: mockNewConversation }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useChatContext: () => ({
+ index: 0,
+ conversation: { conversationId: 'conversation-1', isArchived: true },
+ setConversation: mockSetConversation,
+ }),
+ useLiveAnnouncer: () => ({ announcePolite: mockAnnouncePolite }),
+}));
+
+let mockOpenRouteConvoId: string | undefined = 'conversation-1';
+
+jest.mock('react-router-dom', () => {
+ const actual = jest.requireActual('react-router-dom');
+ return {
+ ...actual,
+ useNavigate: () => mockNavigate,
+ useParams: () => ({ conversationId: mockOpenRouteConvoId }),
+ };
+});
+
+jest.mock('../ProjectButton', () => () => null);
+jest.mock('../DeleteButton', () => () => null);
+jest.mock('../ShareButton', () => () => null);
+
+const renderOptions = (isArchived: boolean, isActiveConvo = false) => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const tree = (active: boolean) => (
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={['/c/conversation-1']}>
+ <Routes>
+ <Route
+ path="/c/:conversationId"
+ element={
+ <ConvoOptions
+ conversationId="conversation-1"
+ title="A conversation"
+ isArchived={isArchived}
+ retainView={mockRetainView}
+ renameHandler={jest.fn()}
+ isPopoverActive={false}
+ setIsPopoverActive={mockSetIsPopoverActive}
+ isActiveConvo={active}
+ />
+ }
+ />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+
+ const { rerender } = render(tree(isActiveConvo));
+ /** Opening another chat moves the route and drops this row's active state. */
+ return { openAnotherChat: () => rerender(tree(false)) };
+};
+
+describe('ConvoOptions archive action', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ mockArchiveMutate.mockReset();
+ mockNavigate.mockReset();
+ mockNewConversation.mockReset();
+ mockRetainView.mockReset();
+ mockSetIsPopoverActive.mockReset();
+ mockAnnouncePolite.mockReset();
+ mockSetConversation.mockReset();
+ mockOpenRouteConvoId = 'conversation-1';
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ /** The row's own state decides the direction: an unarchived pin stays listed beside the
+ * archive, and the previous page's rows outlive a status switch, so a list-level flag
+ * would offer to restore a conversation that was never archived. */
+ it('restores the open archived conversation state without navigating away from it', () => {
+ renderOptions(true);
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_unarchive' }));
+
+ expect(mockArchiveMutate).toHaveBeenCalledWith(
+ { conversationId: 'conversation-1', isArchived: false },
+ expect.objectContaining({ onSuccess: expect.any(Function), onError: expect.any(Function) }),
+ );
+ const [, callbacks] = mockArchiveMutate.mock.calls[0];
+ act(() => callbacks.onSuccess());
+ expect(mockNavigate).not.toHaveBeenCalled();
+ expect(mockNewConversation).not.toHaveBeenCalled();
+ /* The restored row leaves the archived list, unmounting this menu, so the message has
+ to reach the app-level live region rather than one inside the row. */
+ expect(mockAnnouncePolite).toHaveBeenCalledWith({
+ message: 'com_ui_convo_unarchived',
+ isStatus: true,
+ });
+ const [updater] = mockSetConversation.mock.calls[0];
+ expect(updater({ conversationId: 'conversation-1', isArchived: true })).toEqual({
+ conversationId: 'conversation-1',
+ isArchived: false,
+ });
+ /* The request outlives the row: if another chat is open by the time it resolves, the
+ restore must not replace it with the one the callback was created for. */
+ const otherOpen = { conversationId: 'conversation-2', isArchived: false };
+ expect(updater(otherOpen)).toBe(otherOpen);
+ });
+
+ it('archives an unarchived conversation and leaves the one it just hid', () => {
+ renderOptions(false);
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_archive' }));
+
+ expect(mockArchiveMutate).toHaveBeenCalledWith(
+ { conversationId: 'conversation-1', isArchived: true },
+ expect.objectContaining({ onSuccess: expect.any(Function), onError: expect.any(Function) }),
+ );
+ const [, callbacks] = mockArchiveMutate.mock.calls[0];
+ act(() => callbacks.onSuccess());
+ expect(mockNewConversation).toHaveBeenCalledTimes(1);
+ expect(mockNavigate).toHaveBeenCalledWith('/c/new', { replace: true });
+ });
+
+ /** Archiving the open chat opens a new one in its place, but the request outlives the
+ * click: if the user has opened another chat by then, that is the one on screen and it
+ * must be left alone. */
+ it('leaves a newer selection alone when the archive resolves', () => {
+ const { openAnotherChat } = renderOptions(false, true);
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_archive' }));
+ mockOpenRouteConvoId = 'conversation-2';
+ act(() => openAnotherChat());
+
+ const [, callbacks] = mockArchiveMutate.mock.calls[0];
+ act(() => callbacks.onSuccess());
+ expect(mockNewConversation).not.toHaveBeenCalled();
+ expect(mockNavigate).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/Conversations/__tests__/Conversations.test.tsx b/client/src/components/Conversations/__tests__/Conversations.test.tsx
index f60ec5548b..7768882dce 100644
--- a/client/src/components/Conversations/__tests__/Conversations.test.tsx
+++ b/client/src/components/Conversations/__tests__/Conversations.test.tsx
@@ -1,5 +1,5 @@
import React, { createRef } from 'react';
-import { render } from '@testing-library/react';
+import { fireEvent, render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { RecoilRoot } from 'recoil';
import { DndProvider } from 'react-dnd';
@@ -79,7 +79,7 @@ jest.mock('~/data-provider', () => ({
}));
jest.mock('~/utils', () => ({
- groupConversationsByDate: () => [],
+ groupConversations: () => [],
cn: (...args: unknown[]) => args.filter(Boolean).join(' '),
}));
@@ -150,11 +150,17 @@ describe('Conversations: all-pin pages still paginate', () => {
loadMoreConversations,
isChatsExpanded = true,
isLoading = false,
+ isError = false,
+ onRetry,
+ hasNextPage = false,
}: {
conversations: TConversation[];
loadMoreConversations: () => void;
isChatsExpanded?: boolean;
isLoading?: boolean;
+ isError?: boolean;
+ onRetry?: () => void;
+ hasNextPage?: boolean;
}) =>
render(
<QueryClientProvider client={queryClient}>
@@ -168,13 +174,30 @@ describe('Conversations: all-pin pages still paginate', () => {
loadMoreConversations={loadMoreConversations}
isLoading={isLoading}
isSearchLoading={false}
+ isError={isError}
+ onRetry={onRetry}
isChatsExpanded={isChatsExpanded}
setIsChatsExpanded={jest.fn()}
+ hasNextPage={hasNextPage}
/>
</RecoilRoot>
</DndProvider>
</QueryClientProvider>,
);
+ it('renders a retryable load error instead of the empty state', () => {
+ const onRetry = jest.fn();
+ renderList({
+ conversations: [],
+ loadMoreConversations: jest.fn(),
+ isError: true,
+ onRetry,
+ });
+
+ expect(screen.getByTestId('convo-list-error')).toHaveTextContent('com_ui_chats_load_error');
+ expect(screen.queryByTestId('convo-list-empty')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ });
it('requests another page when grouping leaves the chats list empty', () => {
const loadMoreConversations = jest.fn();
@@ -182,6 +205,16 @@ describe('Conversations: all-pin pages still paginate', () => {
expect(loadMoreConversations).toHaveBeenCalled();
});
+ it('does not show no chats when a drained unfiltered page contains only pinned rows', () => {
+ renderList({
+ conversations: [pinnedConvo],
+ loadMoreConversations: jest.fn(),
+ hasNextPage: false,
+ });
+
+ expect(screen.queryByText('com_ui_no_chats')).not.toBeInTheDocument();
+ });
+
it('does not request another page while chats are collapsed', () => {
const loadMoreConversations = jest.fn();
renderList({
diff --git a/client/src/components/Conversations/__tests__/DateLabel.test.tsx b/client/src/components/Conversations/__tests__/DateLabel.test.tsx
index ccd9bc4126..fc5fdb80a5 100644
--- a/client/src/components/Conversations/__tests__/DateLabel.test.tsx
+++ b/client/src/components/Conversations/__tests__/DateLabel.test.tsx
@@ -7,6 +7,7 @@ jest.mock('~/hooks', () => ({
useLocalize: () => (key: string, params?: Record<string, string>) => {
const translations: Record<string, string> = {
com_a11y_chats_date_section: `Chats from ${params?.date ?? ''}`,
+ com_a11y_chats_alpha_section: `Chats with titles starting with ${params?.letter ?? ''}`,
com_ui_date_today: 'Today',
com_ui_date_yesterday: 'Yesterday',
com_ui_date_previous_7_days: 'Previous 7 days',
@@ -21,6 +22,16 @@ describe('DateLabel', () => {
expect(screen.getByRole('heading', { level: 2, name: 'Chats from Today' })).toBeInTheDocument();
});
+ it('uses the alphabetical accessible name for title groups', () => {
+ render(<DateLabel groupName="A" isAlphabetical />);
+ expect(
+ screen.getByRole('heading', {
+ level: 2,
+ name: 'Chats with titles starting with A',
+ }),
+ ).toBeInTheDocument();
+ });
+
it('renders visible text as the localized group name', () => {
render(<DateLabel groupName="com_ui_date_today" />);
expect(screen.getByText('Today')).toBeInTheDocument();
diff --git a/client/src/components/Conversations/chatFilters.spec.ts b/client/src/components/Conversations/chatFilters.spec.ts
new file mode 100644
index 0000000000..c6ed088a19
--- /dev/null
+++ b/client/src/components/Conversations/chatFilters.spec.ts
@@ -0,0 +1,22 @@
+import { createStore } from 'jotai';
+import {
+ DEFAULT_CHAT_SORT,
+ chatFilterStatusAtom,
+ chatSortAtom,
+ setChatFilterStatusAtom,
+} from './chatFilters';
+
+describe('chat filter status changes', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ it('normalizes a malformed persisted sort before switching status', () => {
+ localStorage.setItem('chatListSort', 'null');
+ const store = createStore();
+
+ expect(() => store.set(setChatFilterStatusAtom, 'archived')).not.toThrow();
+ expect(store.get(chatFilterStatusAtom)).toBe('archived');
+ expect(store.get(chatSortAtom)).toEqual(DEFAULT_CHAT_SORT);
+ });
+});
diff --git a/client/src/components/Conversations/chatFilters.ts b/client/src/components/Conversations/chatFilters.ts
new file mode 100644
index 0000000000..2afe31095e
--- /dev/null
+++ b/client/src/components/Conversations/chatFilters.ts
@@ -0,0 +1,113 @@
+import { atom } from 'jotai';
+import type { ConversationListParams } from 'librechat-data-provider';
+import { createStorageAtom } from '~/store/jotai-utils';
+
+/** Which slice of the user's chats the sidebar list is showing. */
+export type ChatFilterStatus = 'active' | 'archived';
+
+export type ChatSortField = NonNullable<ConversationListParams['sortBy']>;
+export type ChatSortDirection = NonNullable<ConversationListParams['sortDirection']>;
+
+export type ChatSort = {
+ field: ChatSortField;
+ direction: ChatSortDirection;
+};
+
+export const DEFAULT_CHAT_SORT: ChatSort = { field: 'updatedAt', direction: 'desc' };
+
+/** Sort fields the list offers, per view. `archivedAt` only means something once the
+ * archive is what is on screen, and the server rejects any field outside this set. */
+export const ACTIVE_SORT_FIELDS: readonly ChatSortField[] = ['updatedAt', 'createdAt', 'title'];
+export const ARCHIVED_SORT_FIELDS: readonly ChatSortField[] = [
+ 'archivedAt',
+ 'updatedAt',
+ 'createdAt',
+ 'title',
+];
+
+export const sortFieldsFor = (status: ChatFilterStatus): readonly ChatSortField[] =>
+ status === 'archived' ? ARCHIVED_SORT_FIELDS : ACTIVE_SORT_FIELDS;
+
+/** `title` orders strings; every other field orders instants. The direction control
+ * and the list's own grouping both read this. */
+export const isAlphabeticalSort = (field: ChatSortField): boolean => field === 'title';
+
+/**
+ * A persisted sort survives a rename of these fields, a downgrade, and hand-editing,
+ * and an unknown field reaches Mongo as a rejected sort — a failed list, not a
+ * fallback. Anything unrecognized, or valid only for the view that is not on screen,
+ * reads as the default instead.
+ */
+const sanitizeSort = (value: unknown, status: ChatFilterStatus): ChatSort => {
+ if (value == null || typeof value !== 'object') {
+ return DEFAULT_CHAT_SORT;
+ }
+ const { field, direction } = value as Partial<ChatSort>;
+ if (field == null || !sortFieldsFor(status).includes(field)) {
+ return DEFAULT_CHAT_SORT;
+ }
+ return { field, direction: direction === 'asc' ? 'asc' : 'desc' };
+};
+
+/** Which chats are listed. Deliberately not persisted: a filter that hides chats
+ * should not greet the user on the next visit. */
+export const chatFilterStatusAtom = atom<ChatFilterStatus>('active');
+
+/** Bookmark (tag) filter, OR-matched by the server. Session-scoped, like the status. */
+export const chatFilterTagsAtom = atom<string[]>([]);
+
+/** Ordering is a preference rather than a filter, so it is the one part that is kept. */
+const storedChatSortAtom = createStorageAtom<ChatSort>('chatListSort', DEFAULT_CHAT_SORT);
+
+export const chatSortAtom = atom(
+ (get) => sanitizeSort(get(storedChatSortAtom), get(chatFilterStatusAtom)),
+ (get, set, next: ChatSort) => {
+ set(storedChatSortAtom, sanitizeSort(next, get(chatFilterStatusAtom)));
+ },
+);
+
+/** Read by conversation rows to offer restoring instead of archiving. */
+export const isArchivedChatViewAtom = atom((get) => get(chatFilterStatusAtom) === 'archived');
+
+/** Drives the trigger's badge: how many choices differ from the default list. */
+export const chatFilterCountAtom = atom((get) => {
+ const sort = get(chatSortAtom);
+ let count = get(chatFilterTagsAtom).length;
+ if (get(chatFilterStatusAtom) !== 'active') {
+ count += 1;
+ }
+ if (sort.field !== DEFAULT_CHAT_SORT.field || sort.direction !== DEFAULT_CHAT_SORT.direction) {
+ count += 1;
+ }
+ return count;
+});
+
+export const resetChatFiltersAtom = atom(null, (_get, set) => {
+ set(chatFilterStatusAtom, 'active');
+ set(chatFilterTagsAtom, []);
+ set(storedChatSortAtom, DEFAULT_CHAT_SORT);
+});
+
+/**
+ * Switching views re-scopes the sort: `archivedAt` cannot order the active list, and
+ * leaving it set would send the server a field it refuses.
+ */
+export const setChatFilterStatusAtom = atom(null, (get, set, status: ChatFilterStatus) => {
+ set(chatFilterStatusAtom, status);
+ const sort = sanitizeSort(get(storedChatSortAtom), status);
+ set(storedChatSortAtom, sort);
+});
+
+/** Reset account-scoped filters without discarding the per-device sort preference. */
+export const resetChatFilterSessionAtom = atom(null, (_get, set) => {
+ set(chatFilterStatusAtom, 'active');
+ set(chatFilterTagsAtom, []);
+});
+
+export const toggleChatFilterTagAtom = atom(null, (get, set, tag: string) => {
+ const tags = get(chatFilterTagsAtom);
+ set(
+ chatFilterTagsAtom,
+ tags.includes(tag) ? tags.filter((current) => current !== tag) : [...tags, tag],
+ );
+});
diff --git a/client/src/components/Conversations/utils.ts b/client/src/components/Conversations/utils.ts
index 281acc11bd..f66141aa6d 100644
--- a/client/src/components/Conversations/utils.ts
+++ b/client/src/components/Conversations/utils.ts
@@ -35,6 +35,7 @@ export function areConversationListItemFieldsEqual(
prevConversation.title === nextConversation.title &&
prevConversation.chatProjectId === nextConversation.chatProjectId &&
prevConversation.pinned === nextConversation.pinned &&
+ prevConversation.isArchived === nextConversation.isArchived &&
prevConversation.isShared === nextConversation.isShared &&
prevConversation.createdAt === nextConversation.createdAt &&
prevConversation.updatedAt === nextConversation.updatedAt
diff --git a/client/src/components/Nav/Bookmarks/BookmarkNav.tsx b/client/src/components/Nav/Bookmarks/BookmarkNav.tsx
deleted file mode 100644
index cb9ec00b8c..0000000000
--- a/client/src/components/Nav/Bookmarks/BookmarkNav.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import { useState, useId, useMemo, useCallback, memo } from 'react';
-import * as Ariakit from '@ariakit/react';
-import { CrossCircledIcon } from '@radix-ui/react-icons';
-import { BookmarkFilledIcon, BookmarkIcon } from '@radix-ui/react-icons';
-import { DropdownPopup, TooltipAnchor, buttonVariants } from '@librechat/client';
-import type { FC } from 'react';
-import type * as t from '~/common';
-import { useGetConversationTags } from '~/data-provider';
-import { useLocalize } from '~/hooks';
-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, matchSearchBar }: BookmarkNavProps) => {
- const localize = useLocalize();
- const menuId = useId();
- const [isMenuOpen, setIsMenuOpen] = useState(false);
- const { data } = useGetConversationTags();
-
- const label = useMemo(
- () => (tags.length > 0 ? tags.join(', ') : localize('com_ui_bookmarks')),
- [tags, localize],
- );
-
- const buttonAriaLabel = useMemo(() => {
- if (tags.length === 0) {
- return localize('com_ui_bookmarks');
- }
- return localize('com_ui_bookmarks_count_selected', { count: tags.length });
- }, [tags.length, localize]);
-
- const bookmarks = useMemo(() => data?.filter((tag) => tag.count > 0) ?? [], [data]);
-
- const handleTagClick = useCallback(
- (tag: string) => {
- if (tags.includes(tag)) {
- setTags(tags.filter((t) => t !== tag));
- } else {
- setTags([...tags, tag]);
- }
- },
- [tags, setTags],
- );
-
- const handleClear = useCallback(() => {
- setTags([]);
- }, [setTags]);
-
- const dropdownItems: t.MenuItemProps[] = useMemo(() => {
- const items: t.MenuItemProps[] = [
- {
- id: 'clear-all',
- label: localize('com_ui_clear_all'),
- icon: <CrossCircledIcon className="size-4" />,
- hideOnClick: false,
- onClick: handleClear,
- },
- ];
-
- if (bookmarks.length === 0) {
- items.push({
- id: 'no-bookmarks',
- label: localize('com_ui_no_bookmarks'),
- icon: '🤔',
- disabled: true,
- });
- } else {
- for (const bookmark of bookmarks) {
- const isSelected = tags.includes(bookmark.tag);
- items.push({
- id: bookmark.tag,
- label: bookmark.tag,
- hideOnClick: false,
- icon: isSelected ? (
- <BookmarkFilledIcon className="size-4" />
- ) : (
- <BookmarkIcon className="size-4" />
- ),
- onClick: () => handleTagClick(bookmark.tag),
- ariaChecked: isSelected,
- });
- }
- }
-
- return items;
- }, [bookmarks, tags, localize, handleTagClick, handleClear]);
-
- return (
- <DropdownPopup
- portal={true}
- menuId={menuId}
- focusLoop={true}
- isOpen={isMenuOpen}
- unmountOnHide={true}
- setIsOpen={setIsMenuOpen}
- keyPrefix="bookmark-nav-"
- className="z-[125]"
- trigger={
- <TooltipAnchor
- description={label}
- render={
- <Ariakit.MenuButton
- 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. */
- className={cn(
- 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"
- >
- {tags.length > 0 ? (
- <BookmarkFilledIcon aria-hidden="true" className="size-4" />
- ) : (
- <BookmarkIcon aria-hidden="true" className="size-4" />
- )}
- </Ariakit.MenuButton>
- }
- />
- }
- items={dropdownItems}
- />
- );
-};
-
-export default memo(BookmarkNav);
diff --git a/client/src/components/Projects/ProjectChatList.tsx b/client/src/components/Projects/ProjectChatList.tsx
index 0b850fda91..8c24d33100 100644
--- a/client/src/components/Projects/ProjectChatList.tsx
+++ b/client/src/components/Projects/ProjectChatList.tsx
@@ -18,8 +18,8 @@ import ConversationEndpointIcon from '~/components/Conversations/ConversationEnd
import { areConversationListItemFieldsEqual } from '~/components/Conversations/utils';
import { useLocalize, useNavigateToConvo, useClockFormat } from '~/hooks';
import { DateLabel } from '~/components/Conversations/Conversations';
-import { cn, groupConversationsByDate } from '~/utils';
import ProjectChatOptions from './ProjectChatOptions';
+import { cn, groupConversations } from '~/utils';
import { useActiveJobs } from '~/data-provider';
type ChatSortField = 'updatedAt' | 'createdAt';
@@ -159,7 +159,7 @@ const ProjectChatList = ({
}
const items: FlattenedItem[] = [];
- groupConversationsByDate(conversations, sortBy).forEach(([groupName, convos]) => {
+ groupConversations(conversations, { field: sortBy }).forEach(([groupName, convos]) => {
items.push({ type: 'date', groupName });
convos.forEach((convo) => items.push({ type: 'convo', convo }));
});
diff --git a/client/src/components/SidePanel/Schedules/useRunSync.ts b/client/src/components/SidePanel/Schedules/useRunSync.ts
index eb7636be56..2a33af6d22 100644
--- a/client/src/components/SidePanel/Schedules/useRunSync.ts
+++ b/client/src/components/SidePanel/Schedules/useRunSync.ts
@@ -1,8 +1,8 @@
import { useRef, useEffect } from 'react';
-import { QueryKeys } from 'librechat-data-provider';
import { useQueryClient } from '@tanstack/react-query';
import type { TSchedule } from 'librechat-data-provider';
import { trackScheduledRun, releaseScheduledRun } from '~/data-provider/Schedules/admission';
+import { invalidateConversationLists } from '~/utils';
type Occurrences = Pick<TSchedule, 'inFlight' | 'lastRun'>;
@@ -95,7 +95,7 @@ export default function useRunSync(schedules?: TSchedule[], observedAt?: number)
: [...previous].some(([id, state]) => current.get(id) !== state) ||
[...current].some(([id, state]) => !previous.has(id) && state !== IDLE_STATE);
if (moved) {
- queryClient.invalidateQueries([QueryKeys.allConversations]);
+ invalidateConversationLists(queryClient);
}
}, [schedules, observedAt, queryClient]);
}
diff --git a/client/src/components/UnifiedSidebar/ConversationsSection.tsx b/client/src/components/UnifiedSidebar/ConversationsSection.tsx
index 7b5f132421..937f96f50e 100644
--- a/client/src/components/UnifiedSidebar/ConversationsSection.tsx
+++ b/client/src/components/UnifiedSidebar/ConversationsSection.tsx
@@ -1,23 +1,23 @@
-import { useCallback, useEffect, useState, useMemo, memo, lazy, Suspense, useRef } from 'react';
+import { useCallback, useEffect, useState, useMemo, memo, useRef } from 'react';
+import { useAtomValue } from 'jotai';
import { useRecoilValue } from 'recoil';
import { useMediaQuery } from '@librechat/client';
-import { PermissionTypes, Permissions } from 'librechat-data-provider';
import type { InfiniteQueryObserverResult } from '@tanstack/react-query';
import type { ConversationListResponse } from 'librechat-data-provider';
import type { List } from 'react-virtualized';
+import {
+ chatFilterTagsAtom,
+ chatSortAtom,
+ isArchivedChatViewAtom,
+} from '~/components/Conversations/chatFilters';
import {
useConversationsInfiniteQuery,
usePinnedConversationsQuery,
useTitleGeneration,
} from '~/data-provider';
-import {
- useLocalize,
- useHasAccess,
- useAuthContext,
- useLocalStorage,
- useNavScrolling,
-} from '~/hooks';
+import { useLocalize, useAuthContext, useLocalStorage, useNavScrolling } from '~/hooks';
import ProjectsSection from '~/components/Conversations/ProjectsSection';
+import ChatFilterMenu from '~/components/Conversations/ChatFilterMenu';
import PinnedSection from '~/components/Conversations/PinnedSection';
import useSidebarToggle from '~/hooks/Nav/useSidebarToggle';
import { Conversations } from '~/components/Conversations';
@@ -25,7 +25,7 @@ import { collectPinnedConversations } from '~/utils';
import SearchBar from '~/components/Nav/SearchBar';
import store from '~/store';
-const BookmarkNav = lazy(() => import('~/components/Nav/Bookmarks/BookmarkNav'));
+const chatsHeaderTrailing = <ChatFilterMenu />;
const ConversationsSection = memo(() => {
const localize = useLocalize();
@@ -35,26 +35,37 @@ const ConversationsSection = memo(() => {
useTitleGeneration(isAuthenticated);
const [isChatsExpanded, setIsChatsExpanded] = useLocalStorage('chatsExpanded', true);
- const [tags, setTags] = useState<string[]>([]);
- const hasAccessToBookmarks = useHasAccess({
- permissionType: PermissionTypes.BOOKMARKS,
- permission: Permissions.USE,
- });
+ const tags = useAtomValue(chatFilterTagsAtom);
+ const sort = useAtomValue(chatSortAtom);
+ const isArchivedView = useAtomValue(isArchivedChatViewAtom);
const search = useRecoilValue(store.search);
- const { data, fetchNextPage, isFetchingNextPage, isLoading, isFetching, isPreviousData } =
- useConversationsInfiniteQuery(
- {
- tags: tags.length === 0 ? undefined : tags,
- search: search.debouncedQuery || undefined,
- },
- {
- enabled: isAuthenticated,
- staleTime: 30000,
- cacheTime: 300000,
- },
- );
+ const {
+ data,
+ fetchNextPage,
+ isFetchingNextPage,
+ isLoading,
+ isFetching,
+ isPreviousData,
+ isError,
+ refetch,
+ } = useConversationsInfiniteQuery(
+ {
+ /** Omitted rather than `false`: the parameter's absence is what the server reads
+ * as "not archived", and a stray `isArchived=false` would key a third cache. */
+ isArchived: isArchivedView ? true : undefined,
+ sortBy: sort.field,
+ sortDirection: sort.direction,
+ tags: tags.length === 0 ? undefined : tags,
+ search: search.debouncedQuery || undefined,
+ },
+ {
+ enabled: isAuthenticated,
+ staleTime: 30000,
+ cacheTime: 300000,
+ },
+ );
const computedHasNextPage = useMemo(() => {
if (data?.pages && data.pages.length > 0) {
@@ -82,24 +93,23 @@ 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. */
+ * The Chats filters are deliberately not passed: they narrow that list alone. */
const {
data: pinnedData,
isSuccess: isPinnedFetched,
isFetching: isPinnedFetching,
dataUpdatedAt: pinnedUpdatedAt,
- } = usePinnedConversationsQuery(
- { tags: tags.length === 0 ? undefined : tags },
- { enabled: isAuthenticated },
- );
+ } = usePinnedConversationsQuery({ enabled: isAuthenticated });
const isPinnedComplete = isPinnedFetched && !isPinnedFetching;
- /* `groupConversationsByDate` strips pins from the chats groups. A failed
+ /* `groupConversations` strips pins from the chats groups. A failed
refetch keeps the previous dedicated result, so merge in pins from the
- live chats cache rather than hiding a newly pinned row. */
+ live chats cache rather than hiding a newly pinned row — but only while that
+ cache holds the same unarchived chats this section shows. */
const pinnedConversations = useMemo(
- () => collectPinnedConversations(pinnedData?.conversations, conversations),
- [pinnedData?.conversations, conversations],
+ () =>
+ collectPinnedConversations(pinnedData?.conversations, isArchivedView ? [] : conversations),
+ [pinnedData?.conversations, conversations, isArchivedView],
);
/**
@@ -128,6 +138,10 @@ const ConversationsSection = memo(() => {
fetchNextPage();
}, [isFetchingNextPage, computedHasNextPage, fetchNextPage]);
+ const retryConversations = useCallback(() => {
+ void refetch();
+ }, [refetch]);
+
const [isSearchLoading, setIsSearchLoading] = useState(
!!search.query && (search.isTyping || isLoading || isFetching),
);
@@ -148,17 +162,12 @@ const ConversationsSection = memo(() => {
role="region"
aria-label={localize('com_ui_chat_history')}
>
- {/* On mobile the search field lives in the drawer's bottom bar, within thumb reach,
- which would leave the bookmark filter alone on a row of its own — so it moves
- beside the Chats heading, where the Projects heading already keeps its actions. */}
- {!isSmallScreen && (
- <div className="flex items-center gap-0.5 px-3">
- {hasAccessToBookmarks && (
- <Suspense fallback={null}>
- <BookmarkNav tags={tags} setTags={setTags} matchSearchBar />
- </Suspense>
- )}
- {search.enabled && <SearchBar isSmallScreen={isSmallScreen} />}
+ {/* The search field owns this row alone; filtering and ordering moved beside the
+ Chats heading, where the list they act on is labelled. On mobile the field
+ itself lives in the drawer's bottom bar, within thumb reach. */}
+ {!isSmallScreen && search.enabled && (
+ <div className="flex items-center px-3">
+ <SearchBar isSmallScreen={isSmallScreen} />
</div>
)}
{!search.query && <ProjectsSection toggleNav={toggleNav} isAuthenticated={isAuthenticated} />}
@@ -168,8 +177,9 @@ const ConversationsSection = memo(() => {
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}
+ page still publishes partial data and stops fetching. The Chats filters
+ never reach this query, so nothing else can truncate it. */
+ membershipComplete={isPinnedComplete}
/* When that drain last ran, which decides whether it is current
enough to prune the stored order against. */
membershipUpdatedAt={pinnedUpdatedAt}
@@ -186,13 +196,10 @@ const ConversationsSection = memo(() => {
isSearchLoading={isSearchLoading || isPreviousData}
isChatsExpanded={isChatsExpanded}
setIsChatsExpanded={setIsChatsExpanded}
- chatsHeaderTrailing={
- isSmallScreen && hasAccessToBookmarks ? (
- <Suspense fallback={null}>
- <BookmarkNav tags={tags} setTags={setTags} />
- </Suspense>
- ) : undefined
- }
+ hasNextPage={computedHasNextPage}
+ isError={isError}
+ onRetry={retryConversations}
+ chatsHeaderTrailing={chatsHeaderTrailing}
/>
</div>
</div>
diff --git a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx
index 71fa22177b..67f1d483b6 100644
--- a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx
+++ b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx
@@ -1,8 +1,8 @@
import React from 'react';
import { DndProvider } from 'react-dnd';
import { BrowserRouter } from 'react-router-dom';
+import { render, act } from '@testing-library/react';
import { HTML5Backend } from 'react-dnd-html5-backend';
-import { render, act, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { atom, RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';
import type { SetterOrUpdater } from 'recoil';
@@ -16,8 +16,6 @@ import type { SetterOrUpdater } from 'recoil';
*/
const streamTickAtom = atom<number>({ key: 'conversations-section-stream-tick', default: 0 });
-/** Generous because it covers a first-require module transform, not a race. */
-const LAZY_CHUNK_TIMEOUT = 15_000;
const TEST_TIMEOUT = 30_000;
const mockUseFavorites = jest.fn(() => ({
@@ -26,6 +24,9 @@ const mockUseFavorites = jest.fn(() => ({
isLoading: false,
}));
const mockUseGetConversationTags = jest.fn(() => ({ data: [] as unknown[] }));
+const mockConversationsRender = jest.fn();
+const mockSetChatsExpanded = jest.fn();
+const mockMoveToTop = jest.fn();
const mockUseTitleGeneration = jest.fn(() => {
useRecoilValue(streamTickAtom);
});
@@ -37,9 +38,11 @@ const mockUseTitleGeneration = jest.fn(() => {
const mockConversationsResult = {
data: { pages: [{ conversations: [] as unknown[], nextCursor: null }] },
fetchNextPage: jest.fn(),
+ refetch: jest.fn(),
isFetchingNextPage: false,
isLoading: false,
isFetching: false,
+ isError: false,
};
/** Same identity rule as above: a fresh `pinnedData.conversations` array would
@@ -65,8 +68,8 @@ jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
useHasAccess: () => true,
useAuthContext: () => ({ isAuthenticated: true }),
- useLocalStorage: () => [true, jest.fn()],
- useNavScrolling: () => ({ moveToTop: jest.fn() }),
+ useLocalStorage: () => [true, mockSetChatsExpanded],
+ useNavScrolling: () => ({ moveToTop: mockMoveToTop }),
useFavorites: () => mockUseFavorites(),
useShowMarketplace: () => false,
useNewConvo: () => ({ newConversation: jest.fn() }),
@@ -94,10 +97,14 @@ jest.mock('~/hooks/Input/useSelectMention', () => ({
default: () => ({ onSelectEndpoint: jest.fn(), onSelectSpec: jest.fn() }),
}));
-jest.mock('~/components/Conversations', () => ({
- __esModule: true,
- Conversations: () => <div data-testid="conversations-stub" />,
-}));
+jest.mock('~/components/Conversations', () => {
+ const { memo } = jest.requireActual('react');
+ const ConversationsStub = memo(function ConversationsStub() {
+ mockConversationsRender();
+ return <div data-testid="conversations-stub" />;
+ });
+ return { __esModule: true, Conversations: ConversationsStub };
+});
jest.mock('~/components/Conversations/ProjectsSection', () => ({
__esModule: true,
@@ -139,14 +146,11 @@ function TickController() {
const createQueryClient = () => new QueryClient({ defaultOptions: { queries: { retry: false } } });
const renderCount = () =>
- mockUseFavorites.mock.calls.length +
- mockUseGetConversationTags.mock.calls.length +
- mockUseTitleGeneration.mock.calls.length;
+ mockUseFavorites.mock.calls.length + mockUseTitleGeneration.mock.calls.length;
/**
- * Yield a full event-loop turn inside act. The lazy BookmarkNav's Suspense commit
- * lands during waitFor's polling, outside act, so its follow-up work sits in the real
- * scheduler as a macrotask that a microtask-only `await act(async () => {})` misses.
+ * Yield a full event-loop turn inside act, so follow-up work that lands in the real
+ * scheduler as a macrotask is flushed before render counts are compared.
*/
const flushEventLoopTurn = () =>
act(async () => {
@@ -195,6 +199,7 @@ describe('ConversationsSection section order', () => {
describe('ConversationsSection streaming re-renders', () => {
beforeEach(() => {
+ mockConversationsRender.mockClear();
mockUseFavorites.mockImplementation(() => ({
favorites: [],
reorderFavorites: jest.fn(),
@@ -207,29 +212,15 @@ describe('ConversationsSection streaming re-renders', () => {
});
it(
- 'does not re-render FavoritesList or BookmarkNav when the section re-renders mid-stream',
+ 'does not re-render memoized children when the section re-renders mid-stream',
async () => {
renderSection();
-
- // BookmarkNav is lazy-loaded; wait until it has actually rendered (its own
- // data hook firing is the deterministic signal that the chunk resolved).
- // Resolving that import means transforming BookmarkNav's whole module graph
- // on first require, which outruns the default one-second budget whenever the
- // transform cache is cold or the machine is busy.
- await waitFor(() => expect(mockUseGetConversationTags).toHaveBeenCalled(), {
- timeout: LAZY_CHUNK_TIMEOUT,
- });
-
- // waitFor resolves once the hook first fires, but on loaded Windows shards the
- // Suspense resolution can leave a trailing pass pending in the real scheduler,
- // which the first stream tick's act would flush into the children's counts.
await settleRenders();
expect(mockUseFavorites.mock.calls.length).toBeGreaterThan(0);
- expect(mockUseGetConversationTags.mock.calls.length).toBeGreaterThan(0);
const favBaseline = mockUseFavorites.mock.calls.length;
- const tagBaseline = mockUseGetConversationTags.mock.calls.length;
+ const conversationsBaseline = mockConversationsRender.mock.calls.length;
const titleBaseline = mockUseTitleGeneration.mock.calls.length;
// Simulate a stream: repeatedly re-render ConversationsSection.
@@ -244,7 +235,7 @@ describe('ConversationsSection streaming re-renders', () => {
// The memoized children, fed referentially stable props, did not re-render.
expect(mockUseFavorites.mock.calls.length).toBe(favBaseline);
- expect(mockUseGetConversationTags.mock.calls.length).toBe(tagBaseline);
+ expect(mockConversationsRender.mock.calls.length).toBe(conversationsBaseline);
},
TEST_TIMEOUT,
);
diff --git a/client/src/data-provider/Projects/__tests__/assignSerialization.spec.tsx b/client/src/data-provider/Projects/__tests__/assignSerialization.spec.tsx
index 6b1cde1683..f61c7e684f 100644
--- a/client/src/data-provider/Projects/__tests__/assignSerialization.spec.tsx
+++ b/client/src/data-provider/Projects/__tests__/assignSerialization.spec.tsx
@@ -96,6 +96,22 @@ describe('useAssignConversationToProjectMutation', () => {
expect(assignConversationToProject.mock.calls[0][0]).toMatchObject({ projectId: 'project-b' });
expect(assignConversationToProject.mock.calls[1][0]).toMatchObject({ projectId: 'project-a' });
});
+ it('invalidates archived conversation list variants after assignment', async () => {
+ const archivedKey = [QueryKeys.archivedConversations, { isArchived: true }];
+ assignConversationToProject.mockResolvedValue(response('c-archived', 'project-b'));
+
+ const { result } = renderHook(() => useAssignConversationToProjectMutation(), { wrapper });
+ activeQueryClient.setQueryData(archivedKey, {
+ pages: [{ conversations: [{ conversationId: 'c-archived', isArchived: true }] }],
+ pageParams: [undefined],
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ conversationId: 'c-archived', projectId: 'project-b' });
+ });
+
+ expect(activeQueryClient.getQueryState(archivedKey)?.isInvalidated).toBe(true);
+ });
it('leaves different conversations independent', async () => {
const held = deferred<never>();
diff --git a/client/src/data-provider/Projects/mutations.ts b/client/src/data-provider/Projects/mutations.ts
index 64f78a5d5c..af28992b45 100644
--- a/client/src/data-provider/Projects/mutations.ts
+++ b/client/src/data-provider/Projects/mutations.ts
@@ -11,8 +11,8 @@ import type {
TAssignConversationToProjectResponse,
} from 'librechat-data-provider';
import type { UseMutationResult } from '@tanstack/react-query';
+import { enqueue, invalidateConversationLists } from '~/utils';
import { getSessionPrincipal } from '~/utils/session';
-import { enqueue } from '~/utils';
import store from '~/store';
export const useCreateProjectMutation = (): UseMutationResult<
@@ -75,7 +75,8 @@ export const useDeleteProjectMutation = (): UseMutationResult<
// refetches (→ not-found) rather than rendering stale cache within `cacheTime`.
queryClient.removeQueries([QueryKeys.project, projectId], { type: 'inactive' });
queryClient.invalidateQueries([QueryKeys.projects]);
- queryClient.invalidateQueries([QueryKeys.allConversations]);
+ /** Archived rows carry the same project field and menu state. */
+ invalidateConversationLists(queryClient);
/** Deleting a project unsets chatProjectId on its chats, pinned ones included. */
queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
},
@@ -206,7 +207,8 @@ export const useAssignConversationToProjectMutation = (): UseMutationResult<
}
});
queryClient.invalidateQueries([QueryKeys.projects]);
- queryClient.invalidateQueries([QueryKeys.allConversations]);
+ /** Archived rows carry the same project field and menu state. */
+ invalidateConversationLists(queryClient);
/** The pinned row carries `chatProjectId` for its options menu. */
queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
queryClient.invalidateQueries([QueryKeys.projectConversations]);
diff --git a/client/src/data-provider/__tests__/archiveAllMutation.test.tsx b/client/src/data-provider/__tests__/archiveAllMutation.test.tsx
index bb70f17174..95c781a26b 100644
--- a/client/src/data-provider/__tests__/archiveAllMutation.test.tsx
+++ b/client/src/data-provider/__tests__/archiveAllMutation.test.tsx
@@ -28,7 +28,9 @@ describe('archive-all mutation cache refresh', () => {
mockArchiveAllConversations.mockReset();
});
- it('refetches archived queries and removes inactive detail caches', async () => {
+ /** Nothing cached survives archiving everything, but an unmounted variant is dropped
+ * rather than refetched: it reconciles from scratch when something mounts it. */
+ it('drops inactive list variants and detail caches', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
@@ -36,13 +38,11 @@ describe('archive-all mutation cache refresh', () => {
},
});
const archivedQuery = jest.fn().mockResolvedValue({ pages: [], pageParams: [] });
+ const archivedKey = [QueryKeys.archivedConversations, { isArchived: true }];
const projectKey = [QueryKeys.project, 'project-1'];
const conversationKey = [QueryKeys.conversation, 'conversation-1'];
- await queryClient.fetchQuery(
- [QueryKeys.archivedConversations, { isArchived: true }],
- archivedQuery,
- );
+ await queryClient.fetchQuery(archivedKey, archivedQuery);
queryClient.setQueryData(projectKey, { _id: 'project-1', conversationCount: 1 });
queryClient.setQueryData(conversationKey, {
conversationId: 'conversation-1',
@@ -59,8 +59,9 @@ describe('archive-all mutation cache refresh', () => {
});
await waitFor(() => {
- expect(archivedQuery).toHaveBeenCalledTimes(2);
+ expect(queryClient.getQueryData(archivedKey)).toBeUndefined();
});
+ expect(archivedQuery).toHaveBeenCalledTimes(1);
expect(queryClient.getQueryData(projectKey)).toBeUndefined();
expect(queryClient.getQueryData(conversationKey)).toBeUndefined();
@@ -179,13 +180,11 @@ describe('archive-all mutation cache refresh', () => {
},
});
const archivedQuery = jest.fn().mockResolvedValue({ pages: [], pageParams: [] });
+ const archivedKey = [QueryKeys.archivedConversations, { isArchived: true }];
const projectKey = [QueryKeys.project, 'project-1'];
const conversationKey = [QueryKeys.conversation, 'conversation-1'];
- await queryClient.fetchQuery(
- [QueryKeys.archivedConversations, { isArchived: true }],
- archivedQuery,
- );
+ await queryClient.fetchQuery(archivedKey, archivedQuery);
queryClient.setQueryData(projectKey, { _id: 'project-1', conversationCount: 1 });
queryClient.setQueryData(conversationKey, {
conversationId: 'conversation-1',
@@ -202,7 +201,7 @@ describe('archive-all mutation cache refresh', () => {
});
await waitFor(() => {
- expect(archivedQuery).toHaveBeenCalledTimes(2);
+ expect(queryClient.getQueryData(archivedKey)).toBeUndefined();
});
expect(queryClient.getQueryData(projectKey)).toBeUndefined();
expect(queryClient.getQueryData(conversationKey)).toBeUndefined();
diff --git a/client/src/data-provider/__tests__/archivedConversationMutations.test.tsx b/client/src/data-provider/__tests__/archivedConversationMutations.test.tsx
new file mode 100644
index 0000000000..a5350774df
--- /dev/null
+++ b/client/src/data-provider/__tests__/archivedConversationMutations.test.tsx
@@ -0,0 +1,233 @@
+import React from 'react';
+import { dataService, QueryKeys } from 'librechat-data-provider';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { useInfiniteQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { ConversationListResponse, TConversation } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import {
+ useArchiveConvoMutation,
+ usePinConversationMutation,
+ useUpdateConversationMutation,
+} from '../mutations';
+import useUpdateTagsInConvo from '~/hooks/Conversations/useUpdateTagsInConvo';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: {
+ ...actual.dataService,
+ updateConversation: jest.fn(),
+ pinConversation: jest.fn(),
+ archiveConversation: jest.fn(),
+ listConversations: jest.fn(),
+ },
+ };
+});
+
+const updateConversation = dataService.updateConversation as jest.MockedFunction<
+ typeof dataService.updateConversation
+>;
+const pinConversation = dataService.pinConversation as jest.MockedFunction<
+ typeof dataService.pinConversation
+>;
+const archiveConversation = dataService.archiveConversation as jest.MockedFunction<
+ typeof dataService.archiveConversation
+>;
+
+const archivedKey = [QueryKeys.archivedConversations, { isArchived: true }];
+
+const createQueryClient = () =>
+ new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+
+const createWrapper = (queryClient: QueryClient) =>
+ function Wrapper({ children }: { children: ReactNode }) {
+ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
+ };
+
+const archivedConversation = {
+ conversationId: 'archived-1',
+ title: 'Old title',
+ isArchived: true,
+ pinned: false,
+} as TConversation;
+
+const listResponse = (conversations: TConversation[], nextCursor: string | null = null) => ({
+ conversations,
+ nextCursor,
+});
+
+describe('archived conversation mutation cache reconciliation', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('invalidates archived variants after a rename changes title ordering', async () => {
+ const queryClient = createQueryClient();
+ queryClient.setQueryData(archivedKey, {
+ pages: [listResponse([archivedConversation])],
+ pageParams: [undefined],
+ });
+ updateConversation.mockResolvedValue({
+ ...archivedConversation,
+ title: 'New title',
+ updatedAt: '2026-09-12T00:00:00.000Z',
+ });
+
+ const { result } = renderHook(() => useUpdateConversationMutation('archived-1'), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ conversationId: 'archived-1', title: 'New title' });
+ });
+
+ expect(queryClient.getQueryState(archivedKey)?.isInvalidated).toBe(true);
+ });
+
+ it('invalidates archived variants when pin state changes', async () => {
+ const queryClient = createQueryClient();
+ queryClient.setQueryData(archivedKey, {
+ pages: [listResponse([archivedConversation])],
+ pageParams: [undefined],
+ });
+ pinConversation.mockResolvedValue({ ...archivedConversation, pinned: true });
+
+ const { result } = renderHook(() => usePinConversationMutation(), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ conversationId: 'archived-1', pinned: true });
+ });
+
+ expect(queryClient.getQueryState(archivedKey)?.isInvalidated).toBe(true);
+ });
+
+ it('updates and invalidates archived variants when a tag removal changes membership', () => {
+ const queryClient = createQueryClient();
+ queryClient.setQueryData([QueryKeys.conversation, archivedConversation.conversationId], {
+ ...archivedConversation,
+ tags: ['bookmark'],
+ });
+ queryClient.setQueryData(archivedKey, {
+ pages: [listResponse([{ ...archivedConversation, tags: ['bookmark'] } as TConversation])],
+ pageParams: [undefined],
+ });
+
+ const { result } = renderHook(() => useUpdateTagsInConvo(), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ act(() => {
+ result.current.updateTagsInConversation('archived-1', []);
+ });
+
+ const cached = queryClient.getQueryData<{
+ pages: Array<{ conversations: TConversation[] }>;
+ }>(archivedKey);
+ expect(cached?.pages[0].conversations[0].tags).toEqual([]);
+ expect(queryClient.getQueryState(archivedKey)?.isInvalidated).toBe(true);
+ });
+
+ it('marks inactive archived variants stale without refetching them', async () => {
+ const queryClient = createQueryClient();
+ const firstPage = listResponse(
+ [
+ { ...archivedConversation, conversationId: 'archived-first', title: 'A' },
+ ] as TConversation[],
+ 'cursor-2',
+ );
+ const oldSecondPage = listResponse([
+ { ...archivedConversation, conversationId: 'archived-second', title: 'B' },
+ ] as TConversation[]);
+ const archivedQuery = jest.fn(({ pageParam }: { pageParam?: string }) =>
+ Promise.resolve(pageParam === 'cursor-2' ? oldSecondPage : firstPage),
+ );
+
+ await queryClient.fetchInfiniteQuery(archivedKey, archivedQuery, {
+ getNextPageParam: (page: ConversationListResponse) => page.nextCursor,
+ });
+ queryClient.setQueryData(archivedKey, {
+ pages: [firstPage, oldSecondPage],
+ pageParams: [undefined, 'cursor-2'],
+ });
+ archiveConversation.mockResolvedValue({ ...archivedConversation, isArchived: true });
+
+ const { result } = renderHook(() => useArchiveConvoMutation(), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ await act(async () => {
+ await result.current.mutateAsync({ conversationId: 'archived-1', isArchived: true });
+ });
+
+ expect(archivedQuery).toHaveBeenCalledTimes(1);
+ expect(queryClient.getQueryState(archivedKey)?.isInvalidated).toBe(true);
+ });
+
+ it('refetches every loaded active page when restoring a row onto a later page', async () => {
+ const queryClient = createQueryClient();
+ const activeKey = [
+ QueryKeys.allConversations,
+ {
+ isArchived: false,
+ sortBy: 'title',
+ sortDirection: 'asc',
+ tags: [],
+ search: undefined,
+ projectId: undefined,
+ },
+ ];
+ const firstPage = listResponse(
+ [{ ...archivedConversation, conversationId: 'active-first', title: 'A' }] as TConversation[],
+ 'cursor-2',
+ );
+ const staleSecondPage = listResponse([
+ { ...archivedConversation, conversationId: 'active-second', title: 'B' },
+ ] as TConversation[]);
+ const restored = { ...archivedConversation, isArchived: false };
+ const restoredSecondPage = listResponse([restored], null);
+ const activeQuery = jest.fn(({ pageParam }: { pageParam?: string }) =>
+ Promise.resolve(pageParam === 'cursor-2' ? restoredSecondPage : firstPage),
+ );
+
+ const { result: activeResult } = renderHook(
+ () =>
+ useInfiniteQuery<ConversationListResponse>({
+ queryKey: activeKey,
+ queryFn: ({ pageParam }) => activeQuery({ pageParam: pageParam as string | undefined }),
+ getNextPageParam: (page) => page.nextCursor,
+ }),
+ { wrapper: createWrapper(queryClient) },
+ );
+ await waitFor(() => expect(activeResult.current.isSuccess).toBe(true));
+ queryClient.setQueryData(activeKey, {
+ pages: [firstPage, staleSecondPage],
+ pageParams: [undefined, 'cursor-2'],
+ });
+ archiveConversation.mockResolvedValue(restored);
+
+ const { result } = renderHook(() => useArchiveConvoMutation(), {
+ wrapper: createWrapper(queryClient),
+ });
+ await act(async () => {
+ await result.current.mutateAsync({
+ conversationId: restored.conversationId!,
+ isArchived: false,
+ });
+ });
+
+ await waitFor(() => {
+ const cached = queryClient.getQueryData<{
+ pages: Array<{ conversations: TConversation[] }>;
+ }>(activeKey);
+ expect(cached?.pages[1].conversations).toEqual([restored]);
+ });
+ });
+});
diff --git a/client/src/data-provider/__tests__/pinnedConversations.test.tsx b/client/src/data-provider/__tests__/pinnedConversations.test.tsx
index 6805d4488d..4e9292f7fd 100644
--- a/client/src/data-provider/__tests__/pinnedConversations.test.tsx
+++ b/client/src/data-provider/__tests__/pinnedConversations.test.tsx
@@ -1,4 +1,5 @@
import { createElement } from 'react';
+import { getDefaultStore } from 'jotai';
import { dataService, QueryKeys } from 'librechat-data-provider';
import { act, renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@@ -21,7 +22,12 @@ import {
useDeleteConversationTagMutation,
usePinConversationMutation,
} from '../mutations';
-import { pinnedConversationsPageSize, usePinnedConversationsQuery } from '../queries';
+import {
+ pinnedConversationsPageSize,
+ useConversationsInfiniteQuery,
+ usePinnedConversationsQuery,
+} from '../queries';
+import { chatFilterTagsAtom } from '~/components/Conversations/chatFilters';
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
@@ -76,13 +82,11 @@ const createWrapper = (queryClient: QueryClient) =>
};
const readPinnedCache = (queryClient: QueryClient) =>
- queryClient.getQueryData<ConversationListResponse>([
- QueryKeys.pinnedConversations,
- { tags: undefined },
- ]);
+ queryClient.getQueryData<ConversationListResponse>([QueryKeys.pinnedConversations]);
beforeEach(() => {
jest.clearAllMocks();
+ getDefaultStore().set(chatFilterTagsAtom, []);
});
describe('usePinnedConversationsQuery', () => {
@@ -98,7 +102,6 @@ describe('usePinnedConversationsQuery', () => {
expect(listConversations).toHaveBeenCalledTimes(1);
expect(listConversations).toHaveBeenCalledWith({
pinned: true,
- tags: undefined,
limit: pinnedConversationsPageSize,
cursor: undefined,
});
@@ -109,7 +112,7 @@ describe('usePinnedConversationsQuery', () => {
listConversations.mockResolvedValue(listResponse([]));
const queryClient = createQueryClient();
- const { result } = renderHook(() => usePinnedConversationsQuery({}, { enabled: false }), {
+ const { result } = renderHook(() => usePinnedConversationsQuery({ enabled: false }), {
wrapper: createWrapper(queryClient),
});
@@ -146,7 +149,7 @@ describe('usePinnedConversationsQuery', () => {
await waitFor(() => expect(result.current.query.data?.conversations).toEqual([pinnedConvo]));
});
- /** `groupConversationsByDate` keeps pins out of the chats groups, so a pin this query
+ /** `groupConversations` keeps pins out of the chats groups, so a pin this query
* drops is invisible everywhere, not merely further down a list. */
it('drains the cursor instead of truncating at one page', async () => {
const second = { ...pinnedConvo, conversationId: 'convo-pinned-2' } as TConversation;
@@ -198,31 +201,65 @@ describe('usePinnedConversationsQuery', () => {
expect(readPinnedCache(queryClient)).toBeUndefined();
});
- /** The chats list beside it is filtered by the selected bookmarks; the pinned section
- * showed every pin regardless until the tags were threaded through. */
- it('applies the active bookmark filter and keys the cache by it', async () => {
+ /** The Chats list's bookmark, status and sort choices narrow that list alone: a
+ * curated shortcut row that emptied itself under a filter would stop being one. */
+ it('ignores the chats list filters and keys one cache for every view', async () => {
listConversations.mockResolvedValue(listResponse([pinnedConvo]));
const queryClient = createQueryClient();
- const { result } = renderHook(() => usePinnedConversationsQuery({ tags: ['work'] }), {
+ const { result } = renderHook(() => usePinnedConversationsQuery(), {
wrapper: createWrapper(queryClient),
});
await waitFor(() => expect(result.current.isSuccess).toBe(true));
- expect(listConversations).toHaveBeenCalledWith(expect.objectContaining({ tags: ['work'] }));
- expect(
- queryClient.getQueryData([QueryKeys.pinnedConversations, { tags: ['work'] }]),
- ).toBeDefined();
+ expect(listConversations).toHaveBeenCalledWith(
+ expect.not.objectContaining({ tags: expect.anything() }),
+ );
+ expect(listConversations).toHaveBeenCalledWith(
+ expect.not.objectContaining({ isArchived: expect.anything() }),
+ );
+ expect(queryClient.getQueryData([QueryKeys.pinnedConversations])).toBeDefined();
+ });
+});
+
+describe('useConversationsInfiniteQuery', () => {
+ /** A row's own `isArchived` decides what its menu offers. A backend that predates that
+ * field in the list projection would otherwise have archived rows offering Archive. */
+ it('fills a missing archive state from what the variant asked for', async () => {
+ listConversations.mockResolvedValue(
+ listResponse([{ conversationId: 'convo-1', title: 'Archived roadmap' } as TConversation]),
+ );
+ const queryClient = createQueryClient();
+
+ const { result } = renderHook(() => useConversationsInfiniteQuery({ isArchived: true }), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.pages[0].conversations[0].isArchived).toBe(true);
+ });
+
+ it('leaves an explicit archive state alone', async () => {
+ listConversations.mockResolvedValue(
+ listResponse([
+ { conversationId: 'convo-1', title: 'Unarchived pin', isArchived: false } as TConversation,
+ ]),
+ );
+ const queryClient = createQueryClient();
+
+ const { result } = renderHook(() => useConversationsInfiniteQuery({ isArchived: true }), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.pages[0].conversations[0].isArchived).toBe(false);
});
});
describe('pinned list cache synchronization', () => {
it('drops a chat from the pinned cache as soon as it is unpinned', () => {
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
updateConvoInAllQueries(queryClient, pinnedConvo.conversationId as string, (convo) => ({
...convo,
@@ -234,10 +271,7 @@ describe('pinned list cache synchronization', () => {
it('keeps a renamed pin in the section with its new title', () => {
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
updateConvoInAllQueries(queryClient, pinnedConvo.conversationId as string, (convo) => ({
...convo,
@@ -251,10 +285,7 @@ describe('pinned list cache synchronization', () => {
it('removes a deleted or archived pin from the section', () => {
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
removeConvoFromAllQueries(queryClient, pinnedConvo.conversationId as string);
@@ -266,10 +297,7 @@ describe('pinned list cache synchronization', () => {
it('moves a pin to the top when the caller asks for it', () => {
const other = { ...pinnedConvo, conversationId: 'convo-other' } as TConversation;
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([other, pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([other, pinnedConvo]));
updateConvoInAllQueries(
queryClient,
@@ -295,7 +323,7 @@ describe('pinned list cache synchronization', () => {
} as TConversation;
const queryClient = createQueryClient();
queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
+ [QueryKeys.pinnedConversations],
listResponse([other, { ...pinnedConvo, updatedAt: stale } as TConversation]),
);
@@ -321,10 +349,7 @@ describe('pinned list cache synchronization', () => {
* a message then dropped the chat out of Pinned and back into the date groups. */
it('keeps a pin in the section when a new turn writes back stale chat state', () => {
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
const staleChatState = { ...pinnedConvo, title: 'Replied', pinned: false } as TConversation;
updateConvoInAllQueries(
@@ -369,10 +394,7 @@ describe('pinned list cache synchronization', () => {
it('keeps list flags when an older pin upserts into the chats cache', () => {
const queryClient = createQueryClient();
const cachedPin = { ...pinnedConvo, isShared: true } as TConversation;
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([cachedPin]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([cachedPin]));
queryClient.setQueryData([QueryKeys.allConversations, { tags: undefined }], {
pages: [
{
@@ -428,10 +450,7 @@ describe('pinned list cache synchronization', () => {
it('leaves the pinned cache untouched for an unrelated conversation', () => {
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
updateConvoInAllQueries(queryClient, 'some-other-convo', (convo) => ({
...convo,
@@ -445,10 +464,7 @@ describe('pinned list cache synchronization', () => {
* update, so the independently cached pin has to follow that path too. */
it('updates an existing pin when the conversation is upserted', () => {
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
upsertConvoInAllQueries(queryClient, {
...pinnedConvo,
@@ -463,10 +479,7 @@ describe('pinned list cache synchronization', () => {
it('moves an upserted pin to the top of the pinned cache', () => {
const other = { ...pinnedConvo, conversationId: 'convo-other' } as TConversation;
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([other, pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([other, pinnedConvo]));
upsertConvoInAllQueries(queryClient, {
...pinnedConvo,
@@ -481,10 +494,7 @@ describe('pinned list cache synchronization', () => {
it('does not insert a conversation that is not already in the pinned cache', () => {
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
upsertConvoInAllQueries(queryClient, {
conversationId: 'convo-new',
@@ -498,10 +508,7 @@ describe('pinned list cache synchronization', () => {
it('keeps the cached pinned flag when the upsert payload omits it', () => {
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
upsertConvoInAllQueries(queryClient, {
conversationId: pinnedConvo.conversationId,
@@ -527,7 +534,7 @@ describe('delete mutation project lookup', () => {
const queryClient = createQueryClient();
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries');
queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
+ [QueryKeys.pinnedConversations],
listResponse([{ ...pinnedConvo, chatProjectId: projectId }]),
);
@@ -555,8 +562,10 @@ const tagResponse: TConversationTag = {
};
describe('bookmark mutations invalidate the pinned cache', () => {
- it('invalidates pins when a bookmark is renamed', async () => {
+ it('invalidates pins and carries a selected bookmark filter across a rename', async () => {
updateConversationTag.mockResolvedValue(tagResponse);
+ const jotaiStore = getDefaultStore();
+ jotaiStore.set(chatFilterTagsAtom, ['work', 'other']);
const queryClient = createQueryClient();
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries');
@@ -571,10 +580,13 @@ describe('bookmark mutations invalidate the pinned cache', () => {
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(invalidateSpy).toHaveBeenCalledWith([QueryKeys.pinnedConversations]);
+ expect(jotaiStore.get(chatFilterTagsAtom)).toEqual(['office', 'other']);
});
- it('invalidates pins when a bookmark is deleted', async () => {
+ it('invalidates pins and removes a selected bookmark filter on delete', async () => {
deleteConversationTag.mockResolvedValue({ ...tagResponse, tag: 'work' });
+ const jotaiStore = getDefaultStore();
+ jotaiStore.set(chatFilterTagsAtom, ['work', 'other']);
const queryClient = createQueryClient();
const invalidateSpy = jest.spyOn(queryClient, 'invalidateQueries');
@@ -588,6 +600,7 @@ describe('bookmark mutations invalidate the pinned cache', () => {
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(invalidateSpy).toHaveBeenCalledWith([QueryKeys.pinnedConversations]);
+ expect(jotaiStore.get(chatFilterTagsAtom)).toEqual(['other']);
});
});
@@ -596,10 +609,7 @@ describe('unpinning a pin that is not on a loaded chats page', () => {
const unpinned = { ...pinnedConvo, pinned: false } as TConversation;
pinConversation.mockResolvedValue(unpinned);
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
queryClient.setQueryData([QueryKeys.allConversations], {
pages: [
{
@@ -645,7 +655,7 @@ describe('unpinning a pin that is not on a loaded chats page', () => {
pinConversation.mockResolvedValue(unpinned);
const queryClient = createQueryClient();
queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
+ [QueryKeys.pinnedConversations],
listResponse([{ ...pinnedConvo, isShared: true } as TConversation]),
);
queryClient.setQueryData([QueryKeys.allConversations], {
@@ -678,10 +688,7 @@ describe('unpinning a pin that is not on a loaded chats page', () => {
const unpinned = { ...pinnedConvo, pinned: false } as TConversation;
pinConversation.mockResolvedValue(unpinned);
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
queryClient.setQueryData([QueryKeys.allConversations], {
pages: [
{
@@ -722,10 +729,7 @@ describe('unpinning a pin that is not on a loaded chats page', () => {
const unpinned = { ...pinnedConvo, pinned: false, tags: [] } as TConversation;
pinConversation.mockResolvedValue(unpinned);
const queryClient = createQueryClient();
- queryClient.setQueryData(
- [QueryKeys.pinnedConversations, { tags: undefined }],
- listResponse([pinnedConvo]),
- );
+ queryClient.setQueryData([QueryKeys.pinnedConversations], listResponse([pinnedConvo]));
queryClient.setQueryData([QueryKeys.allConversations, { tags: ['work'] }], {
pages: [
{
diff --git a/client/src/data-provider/mutations.ts b/client/src/data-provider/mutations.ts
index 60d54ba4c8..7be5f45b7f 100644
--- a/client/src/data-provider/mutations.ts
+++ b/client/src/data-provider/mutations.ts
@@ -1,3 +1,4 @@
+import { useSetAtom } from 'jotai';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { dataService, MutationKeys, QueryKeys, defaultOrderQuery } from 'librechat-data-provider';
import {
@@ -19,6 +20,7 @@ import {
clearDeletedConversationMessagesCache,
} from '~/utils';
import useUpdateTagsInConvo from '~/hooks/Conversations/useUpdateTagsInConvo';
+import { chatFilterTagsAtom } from '~/components/Conversations/chatFilters';
import { updateConversationTag } from '~/utils/conversationTags';
import { useConversationTagsQuery } from './queries';
@@ -47,6 +49,10 @@ export const useUpdateConversationMutation = (
: updatedConvo;
queryClient.setQueryData<t.TConversation>([QueryKeys.conversation, targetId], applyRename);
updateConvoInAllQueries(queryClient, targetId, applyRename);
+ /* A title-keyset cursor encodes the old ordering; patching loaded rows
+ * cannot repair boundaries that have not been fetched yet. */
+ queryClient.invalidateQueries({ queryKey: [QueryKeys.allConversations] });
+ queryClient.invalidateQueries({ queryKey: [QueryKeys.archivedConversations] });
queryClient.invalidateQueries([QueryKeys.projectConversations]);
},
},
@@ -100,29 +106,19 @@ export const useArchiveConvoMutation = (
removeConvoFromAllQueries(queryClient, vars.conversationId);
- const archivedQueries = queryClient
- .getQueryCache()
- .findAll([QueryKeys.archivedConversations], { exact: false });
-
- for (const query of archivedQueries) {
- queryClient.setQueryData<InfiniteData<ConversationListResponse>>(
- query.queryKey,
- (oldData) => {
- if (!oldData) {
- return oldData;
- }
- if (isArchived) {
- return {
- ...oldData,
- pages: [
- {
- ...oldData.pages[0],
- conversations: [_data, ...oldData.pages[0].conversations],
- },
- ...oldData.pages.slice(1),
- ],
- };
- } else {
+ /* Restoring removes the row from every cached archived variant immediately.
+ * Archiving itself is reconciled by the all-pages invalidation in onSettled;
+ * the mutation cannot know which sort/filter cursor owns the new row. */
+ if (!isArchived) {
+ for (const query of queryClient
+ .getQueryCache()
+ .findAll([QueryKeys.archivedConversations], { exact: false })) {
+ queryClient.setQueryData<InfiniteData<ConversationListResponse>>(
+ query.queryKey,
+ (oldData) => {
+ if (!oldData) {
+ return oldData;
+ }
return {
...oldData,
pages: oldData.pages.map((page) => ({
@@ -132,9 +128,9 @@ export const useArchiveConvoMutation = (
),
})),
};
- }
- },
- );
+ },
+ );
+ }
}
queryClient.setQueryData(
@@ -154,11 +150,16 @@ export const useArchiveConvoMutation = (
onSettled: () => {
queryClient.invalidateQueries({
queryKey: convoQueryKey,
- refetchPage: (_, index) => index === 0,
+ refetchPage: () => true,
+ refetchType: 'active',
});
+ /* Archived ordering and membership depend on the selected sort/filter, which
+ * this mutation does not receive. Refetch every loaded page in mounted variants;
+ * inactive variants are marked stale and refresh when mounted. */
queryClient.invalidateQueries({
queryKey: archivedConvoQueryKey,
- refetchPage: (_, index) => index === 0,
+ refetchPage: () => true,
+ refetchType: 'active',
});
/** Archiving drops the chat from the pinned cache, so restoring one that is
* still pinned has to refetch or the section would stay missing it. */
@@ -178,11 +179,17 @@ export const useArchiveAllConversationsMutation = (
const { onSuccess, onError, ..._options } = options || {};
const reconcileCaches = () => {
- queryClient.invalidateQueries([QueryKeys.allConversations]);
- queryClient.invalidateQueries({
- queryKey: [QueryKeys.archivedConversations],
- refetchType: 'all',
- });
+ /* Archiving everything leaves no cached list trustworthy, but only the mounted ones are
+ worth the round trips: the rest are dropped, so a remembered sort or bookmark variant
+ cannot render chats that are all archived now and refetches from scratch when mounted. */
+ for (const listKey of [QueryKeys.allConversations, QueryKeys.archivedConversations]) {
+ queryClient.invalidateQueries({
+ queryKey: [listKey],
+ refetchPage: () => true,
+ refetchType: 'active',
+ });
+ queryClient.removeQueries({ queryKey: [listKey], type: 'inactive' });
+ }
/** The pinned section fetches on its own key with a five-minute stale time, so an
* archived pin would keep rendering in the sidebar without this. */
queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
@@ -230,6 +237,9 @@ export const usePinConversationMutation = (
? { ...data, isShared: cachedPin.isShared }
: data;
updateConvoInAllQueries(queryClient, vars.conversationId, () => next);
+ /* Pinned state is list-relevant in both active and archived views. The
+ * archived variants carry filter/sort parameters, so invalidate by prefix. */
+ queryClient.invalidateQueries({ queryKey: [QueryKeys.archivedConversations] });
/** An older pin may exist only in the dedicated pinned cache. Unpinning
* it has to put the returned row onto the chats list; later pages
* cannot recover a conversation whose updatedAt just jumped ahead of
@@ -292,6 +302,7 @@ const syncSharedLinkQueries = (
);
setConversationSharedFlag(queryClient, data.conversationId, true);
+ queryClient.invalidateQueries({ queryKey: [QueryKeys.archivedConversations] });
queryClient.invalidateQueries({ queryKey: [QueryKeys.sharedLinks], exact: false });
};
@@ -455,11 +466,10 @@ export const useDeleteSharedLinkMutation = (
queryKey: [QueryKeys.sharedLinks],
exact: false,
});
- /* A conversation can hold several links (one per target message), so clearing the
- badge optimistically is only a guess. Let the server, which derives `isShared`
- from the links that are actually left, settle it. Every cached page refetches:
- the affected conversation is as likely to sit on page three as on page one. */
+ /* Shared state is derived on every list response; an archived row needs the
+ * same refresh as the active and pinned sections. */
queryClient.invalidateQueries({ queryKey: [QueryKeys.allConversations] });
+ queryClient.invalidateQueries({ queryKey: [QueryKeys.archivedConversations] });
/** The pinned section renders the same badge from its own cache. */
queryClient.invalidateQueries({ queryKey: [QueryKeys.pinnedConversations] });
},
@@ -489,6 +499,7 @@ export const useConversationTagMutation = ({
}): UseMutationResult<t.TConversationTagResponse, unknown, t.TConversationTagRequest, unknown> => {
const queryClient = useQueryClient();
const { onSuccess, ..._options } = options || {};
+ const setChatFilterTags = useSetAtom(chatFilterTagsAtom);
const onMutationSuccess: typeof onSuccess = (_data, vars) => {
queryClient.setQueryData<t.TConversationTag[]>([QueryKeys.conversationTags], (queryData) => {
if (!queryData) {
@@ -530,6 +541,11 @@ export const useConversationTagMutation = ({
logger.log('tag_mutation', `Updating tag from ${context}`, queryData, _data);
return updateConversationTag(queryData, vars, _data, tag);
});
+ if (tag != null && _data.tag) {
+ setChatFilterTags((selectedTags) =>
+ selectedTags.map((selectedTag) => (selectedTag === tag ? _data.tag : selectedTag)),
+ );
+ }
if (vars.addToConversation === true && vars.conversationId != null && _data.tag) {
const currentConvo = queryClient.getQueryData<t.TConversation>([
QueryKeys.conversation,
@@ -574,60 +590,51 @@ export const useConversationTagMutation = ({
export const useDeleteTagInConversations = () => {
const queryClient = useQueryClient();
const deleteTagInAllConversation = (deletedTag: string) => {
- const data = queryClient.getQueryData<InfiniteData<ConversationListResponse>>([
- QueryKeys.allConversations,
- ]);
+ const conversationIdsWithTag = new Set<string>();
+
+ for (const listKey of [QueryKeys.allConversations, QueryKeys.archivedConversations]) {
+ const queries = queryClient.getQueryCache().findAll([listKey], { exact: false });
+ for (const query of queries) {
+ queryClient.setQueryData<InfiniteData<ConversationListResponse>>(query.queryKey, (data) => {
+ if (!data) {
+ return data;
+ }
- // If there is no conversations cache yet, nothing to update
- if (!data || !Array.isArray(data.pages) || data.pages.length === 0) {
- return;
+ return {
+ ...data,
+ pages: data.pages.map((page) => ({
+ ...page,
+ conversations: page.conversations.map((conversation) => {
+ const conversationTags = (conversation as t.TConversation).tags;
+ if (
+ conversation.conversationId &&
+ Array.isArray(conversationTags) &&
+ conversationTags.includes(deletedTag)
+ ) {
+ conversationIdsWithTag.add(conversation.conversationId);
+ return {
+ ...conversation,
+ tags: conversationTags.filter((tag) => tag !== deletedTag),
+ };
+ }
+ return conversation;
+ }),
+ })),
+ };
+ });
+ }
+ queryClient.invalidateQueries({ queryKey: [listKey] });
}
- const conversationIdsWithTag: string[] = [];
-
- // Create an updated copy of the infinite query data without mutating the cache directly
- const updatedData: InfiniteData<ConversationListResponse> = {
- pageParams: Array.isArray(data.pageParams) ? [...data.pageParams] : [],
- pages: data.pages.map((page) => ({
- ...page,
- conversations: page.conversations.map((conversation) => {
- if (
- conversation.conversationId &&
- 'tags' in conversation &&
- Array.isArray((conversation as unknown as { tags?: string[] }).tags) &&
- (conversation as unknown as { tags: string[] }).tags.includes(deletedTag)
- ) {
- conversationIdsWithTag.push(conversation.conversationId);
- return {
- ...conversation,
- tags: (conversation as unknown as { tags: string[] }).tags.filter(
- (tag: string) => tag !== deletedTag,
- ),
- } as t.TConversation;
- }
- return conversation as t.TConversation;
- }),
- })),
- };
-
- queryClient.setQueryData<InfiniteData<ConversationListResponse>>(
- [QueryKeys.allConversations],
- updatedData,
- );
-
- // Remove the deleted tag from the cache of each individual conversation
- for (let i = 0; i < conversationIdsWithTag.length; i++) {
- const conversationId = conversationIdsWithTag[i];
+ for (const conversationId of conversationIdsWithTag) {
const conversationData = queryClient.getQueryData<t.TConversation>([
QueryKeys.conversation,
conversationId,
]);
- if (conversationData && Array.isArray((conversationData as { tags?: string[] }).tags)) {
+ if (conversationData?.tags) {
queryClient.setQueryData<t.TConversation>([QueryKeys.conversation, conversationId], {
...conversationData,
- tags: (conversationData as { tags: string[] }).tags.filter(
- (tag: string) => tag !== deletedTag,
- ),
+ tags: conversationData.tags.filter((tag) => tag !== deletedTag),
});
}
}
@@ -642,6 +649,7 @@ export const useDeleteConversationTagMutation = (
const deleteTagInAllConversations = useDeleteTagInConversations();
const { onSuccess, ..._options } = options || {};
+ const setChatFilterTags = useSetAtom(chatFilterTagsAtom);
return useMutation((tag: string) => dataService.deleteConversationTag(tag), {
onSuccess: (_data, tagToDelete, context) => {
@@ -653,6 +661,9 @@ export const useDeleteConversationTagMutation = (
});
deleteTagInAllConversations(tagToDelete);
+ setChatFilterTags((selectedTags) =>
+ selectedTags.filter((selectedTag) => selectedTag !== tagToDelete),
+ );
/** Deleting a selected bookmark empties that tag-keyed pinned set. */
queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
onSuccess?.(_data, tagToDelete, context);
@@ -692,7 +703,12 @@ export const useDeleteConversationMutation = (
: undefined;
let deletedProjectId = deletedConversation?.chatProjectId;
if (!deletedProjectId && vars.conversationId) {
- const cacheKeys = [QueryKeys.allConversations, QueryKeys.projectConversations];
+ /* An archived row can be the only cached copy carrying `chatProjectId`. */
+ const cacheKeys = [
+ QueryKeys.allConversations,
+ QueryKeys.archivedConversations,
+ QueryKeys.projectConversations,
+ ];
for (const cacheKey of cacheKeys) {
const queries = queryClient.getQueryCache().findAll([cacheKey], { exact: false });
for (const query of queries) {
@@ -769,13 +785,17 @@ export const useDeleteConversationMutation = (
exact: true,
});
+ /* The row is gone from both lists, and cancelled races mean neither cache can be
+ trusted to have settled. */
queryClient.invalidateQueries({
queryKey: [QueryKeys.allConversations],
- refetchPage: (_, index) => index === 0,
+ refetchPage: () => true,
+ refetchType: 'active',
});
queryClient.invalidateQueries({
queryKey: [QueryKeys.archivedConversations],
- refetchPage: (_, index) => index === 0,
+ refetchPage: () => true,
+ refetchType: 'active',
});
/** Cancelling races is best effort, so reconcile the pinned list afterwards too. */
queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
@@ -812,9 +832,17 @@ export const useDuplicateConversationMutation = (
[QueryKeys.messages, duplicatedConversation.conversationId],
data.messages,
);
+ /* The copy inherits the source's archive state, so a duplicate made from an archived
+ row belongs to the archived list, not the active one. */
queryClient.invalidateQueries({
queryKey: [QueryKeys.allConversations],
- refetchPage: (_, index) => index === 0,
+ refetchPage: () => true,
+ refetchType: 'active',
+ });
+ queryClient.invalidateQueries({
+ queryKey: [QueryKeys.archivedConversations],
+ refetchPage: () => true,
+ refetchType: 'active',
});
/** A duplicated, forked or imported chat can arrive already pinned. */
queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
@@ -862,9 +890,16 @@ export const useForkConvoMutation = (
queryClient.setQueryData([QueryKeys.conversation, forkedConversationId], forkedConversation);
addConvoToAllQueries(queryClient, forkedConversation);
queryClient.setQueryData([QueryKeys.messages, forkedConversationId], data.messages);
+ /* A fork inherits the source's archive state, so it can belong to either list. */
queryClient.invalidateQueries({
queryKey: [QueryKeys.allConversations],
- refetchPage: (_, index) => index === 0,
+ refetchPage: () => true,
+ refetchType: 'active',
+ });
+ queryClient.invalidateQueries({
+ queryKey: [QueryKeys.archivedConversations],
+ refetchPage: () => true,
+ refetchType: 'active',
});
/** A duplicated, forked or imported chat can arrive already pinned. */
queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
@@ -919,9 +954,16 @@ export const useForkSharedConvoMutation = (
);
addConvoToAllQueries(queryClient, forkedConversation);
queryClient.setQueryData([QueryKeys.messages, forkedConversationId], data.messages);
+ /* A fork inherits the source's archive state, so it can belong to either list. */
queryClient.invalidateQueries({
queryKey: [QueryKeys.allConversations],
- refetchPage: (_, index) => index === 0,
+ refetchPage: () => true,
+ refetchType: 'active',
+ });
+ queryClient.invalidateQueries({
+ queryKey: [QueryKeys.archivedConversations],
+ refetchPage: () => true,
+ refetchType: 'active',
});
onSuccess?.(data, vars, context);
@@ -942,6 +984,8 @@ export const useUploadConversationsMutation = (
onSuccess: (data, variables, context) => {
/* TODO: optimize to return imported conversations and add manually */
queryClient.invalidateQueries([QueryKeys.allConversations]);
+ /** An import can carry already-archived chats. */
+ queryClient.invalidateQueries([QueryKeys.archivedConversations]);
/** An imported chat can carry `pinned: true`. */
queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
if (onSuccess) {
diff --git a/client/src/data-provider/queries.ts b/client/src/data-provider/queries.ts
index b343421357..2a27d50f8a 100644
--- a/client/src/data-provider/queries.ts
+++ b/client/src/data-provider/queries.ts
@@ -93,8 +93,8 @@ export const useConversationsInfiniteQuery = (
isArchived ? QueryKeys.archivedConversations : QueryKeys.allConversations,
{ isArchived, sortBy, sortDirection, tags, search, projectId },
],
- queryFn: ({ pageParam }) =>
- dataService.listConversations({
+ queryFn: async ({ pageParam }) => {
+ const page = await dataService.listConversations({
isArchived,
sortBy,
sortDirection,
@@ -102,7 +102,19 @@ export const useConversationsInfiniteQuery = (
search,
projectId,
cursor: pageParam?.toString(),
- }),
+ });
+ /* A row's own `isArchived` decides what its menu offers, so a backend that predates
+ that field in the list projection would make archived rows offer Archive and submit
+ a no-op. What the variant asked for is the answer for any row that omits it. */
+ return {
+ ...page,
+ conversations: page.conversations.map((conversation) =>
+ conversation.isArchived == null
+ ? { ...conversation, isArchived: isArchived === true }
+ : conversation,
+ ),
+ };
+ },
getNextPageParam: (lastPage) => lastPage?.nextCursor ?? undefined,
keepPreviousData: true,
staleTime: 5 * 60 * 1000, // 5 minutes
@@ -115,19 +127,21 @@ export const useConversationsInfiniteQuery = (
* Pinned chats are a hand-curated set, so the sidebar fetches the whole thing rather
* than paginating it: a pin older than the first page of the Chats list would
* otherwise stay hidden until that list scrolled far enough to reach it, and
- * `groupConversationsByDate` keeps pins out of the Chats groups entirely, so any pin
+ * `groupConversations` keeps pins out of the Chats groups entirely, so any pin
* this query does not return is invisible in the sidebar. The page size is therefore a
* request size, not a cap; the query drains the cursor.
+ *
+ * It takes no filters on purpose: the Chats list's status, bookmark and sort choices
+ * narrow that list alone, and a curated shortcut row that emptied itself whenever a
+ * filter was on would be the opposite of a shortcut.
*/
export const pinnedConversationsPageSize = 100;
export const usePinnedConversationsQuery = (
- params: Pick<ConversationListParams, 'tags'> = {},
config?: UseQueryOptions<ConversationListResponse>,
): QueryObserverResult<ConversationListResponse> => {
- const { tags } = params;
const queryClient = useQueryClient();
- const queryKey = [QueryKeys.pinnedConversations, { tags }];
+ const queryKey = [QueryKeys.pinnedConversations];
return useQuery<ConversationListResponse>(
queryKey,
@@ -140,7 +154,6 @@ export const usePinnedConversationsQuery = (
try {
page = await dataService.listConversations({
pinned: true,
- tags,
limit: pinnedConversationsPageSize,
cursor,
});
diff --git a/client/src/hooks/AuthContext.tsx b/client/src/hooks/AuthContext.tsx
index 44fa110df4..c21eadcd22 100644
--- a/client/src/hooks/AuthContext.tsx
+++ b/client/src/hooks/AuthContext.tsx
@@ -8,6 +8,7 @@ import {
createContext,
} from 'react';
import { debounce } from 'lodash';
+import { getDefaultStore } from 'jotai';
import { useNavigate } from 'react-router-dom';
import { useRecoilState, useSetRecoilState } from 'recoil';
import {
@@ -34,6 +35,7 @@ import {
useLogoutUserMutation,
useRefreshTokenMutation,
} from '~/data-provider';
+import { resetChatFilterSessionAtom } from '~/components/Conversations/chatFilters';
import { TAuthConfig, TUserContext, TAuthContext, TResError } from '~/common';
import useTimeout from './useTimeout';
import store from '~/store';
@@ -51,6 +53,7 @@ if (import.meta.hot) {
* that reliably sees the transition. Both are cleared together so neither can be added to an exit
* path the other was wired into. */
const endSessionClientState = (): void => {
+ getDefaultStore().set(resetChatFilterSessionAtom);
clearRetainedFileDeletions();
clearComposerDraftStorage();
};
diff --git a/client/src/hooks/Conversations/useUpdateTagsInConvo.ts b/client/src/hooks/Conversations/useUpdateTagsInConvo.ts
index 4e545c86fe..5d07ae16de 100644
--- a/client/src/hooks/Conversations/useUpdateTagsInConvo.ts
+++ b/client/src/hooks/Conversations/useUpdateTagsInConvo.ts
@@ -1,5 +1,5 @@
-import { useQueryClient } from '@tanstack/react-query';
import { QueryKeys } from 'librechat-data-provider';
+import { useQueryClient } from '@tanstack/react-query';
import type { ConversationListResponse } from 'librechat-data-provider';
import type { InfiniteData } from '@tanstack/react-query';
import type t from 'librechat-data-provider';
@@ -23,77 +23,90 @@ const useUpdateTagsInConvo = () => {
tags,
} as t.TConversation;
queryClient.setQueryData([QueryKeys.conversation, conversationId], updatedConvo);
- queryClient.setQueryData<InfiniteData<ConversationListResponse>>(
- [QueryKeys.allConversations],
- (convoData) => {
- if (!convoData) {
- return convoData;
- }
- return {
- ...convoData,
- pages: convoData.pages.map((page) => ({
- ...page,
- conversations: page.conversations.map((conversation) =>
- conversation.conversationId === (currentConvo.conversationId ?? '')
- ? { ...conversation, tags: updatedConvo.tags }
- : conversation,
- ),
- })),
- };
- },
- );
+
+ for (const listKey of [QueryKeys.allConversations, QueryKeys.archivedConversations]) {
+ const queries = queryClient.getQueryCache().findAll([listKey], { exact: false });
+ for (const query of queries) {
+ queryClient.setQueryData<InfiniteData<ConversationListResponse>>(
+ query.queryKey,
+ (convoData) => {
+ if (!convoData) {
+ return convoData;
+ }
+ return {
+ ...convoData,
+ pages: convoData.pages.map((page) => ({
+ ...page,
+ conversations: page.conversations.map((conversation) =>
+ conversation.conversationId === conversationId
+ ? { ...conversation, tags: updatedConvo.tags }
+ : conversation,
+ ),
+ })),
+ };
+ },
+ );
+ }
+ /* A tag filter can change membership, so a patched row is not enough to make
+ * every parameterized list variant correct. */
+ queryClient.invalidateQueries({ queryKey: [listKey] });
+ }
};
// update the tag to newTag in all conversations when a tag is updated to a newTag
// The difference with updateTagsInConversation is that it adds or removes tags for a specific conversation,
// whereas this function is for changing the title of a specific tag.
const replaceTagsInAllConversations = (tag: string, newTag: string) => {
- const data = queryClient.getQueryData<InfiniteData<ConversationListResponse>>([
- QueryKeys.allConversations,
- ]);
+ const conversationIdsWithTag = new Set<string>();
- if (data) {
- const newData = JSON.parse(JSON.stringify(data)) as InfiniteData<ConversationListResponse>;
- for (let pageIndex = 0; pageIndex < newData.pages.length; pageIndex++) {
- const page = newData.pages[pageIndex];
- page.conversations = page.conversations.map((conversation) => {
- if (
- conversation.conversationId &&
- 'tags' in conversation &&
- Array.isArray((conversation as { tags?: string[] }).tags) &&
- (conversation as { tags?: string[] }).tags?.includes(tag)
- ) {
- (conversation as { tags: string[] }).tags = (
- conversation as { tags: string[] }
- ).tags.map((t: string) => (t === tag ? newTag : t));
+ for (const listKey of [QueryKeys.allConversations, QueryKeys.archivedConversations]) {
+ const queries = queryClient.getQueryCache().findAll([listKey], { exact: false });
+ for (const query of queries) {
+ queryClient.setQueryData<InfiniteData<ConversationListResponse>>(query.queryKey, (data) => {
+ if (!data) {
+ return data;
}
- return conversation;
+
+ return {
+ ...data,
+ pages: data.pages.map((page) => ({
+ ...page,
+ conversations: page.conversations.map((conversation) => {
+ const conversationTags = (conversation as t.TConversation).tags;
+ if (
+ conversation.conversationId &&
+ Array.isArray(conversationTags) &&
+ conversationTags.includes(tag)
+ ) {
+ conversationIdsWithTag.add(conversation.conversationId);
+ return {
+ ...conversation,
+ tags: conversationTags.map((conversationTag) =>
+ conversationTag === tag ? newTag : conversationTag,
+ ),
+ };
+ }
+ return conversation;
+ }),
+ })),
+ };
});
}
- queryClient.setQueryData<InfiniteData<ConversationListResponse>>(
- [QueryKeys.allConversations],
- newData,
- );
+ queryClient.invalidateQueries({ queryKey: [listKey] });
}
- const conversationIdsWithTag = [] as string[];
-
- // update the tag to newTag from the cache of each conversation
- for (let i = 0; i < conversationIdsWithTag.length; i++) {
- const conversationId = conversationIdsWithTag[i];
+ for (const conversationId of conversationIdsWithTag) {
const conversation = queryClient.getQueryData<t.TConversation>([
QueryKeys.conversation,
conversationId,
]);
- if (conversation && conversation.tags) {
- const updatedConvo = {
+ if (conversation?.tags) {
+ queryClient.setQueryData<t.TConversation>([QueryKeys.conversation, conversationId], {
...conversation,
- tags: conversation.tags.map((t) => (t === tag ? newTag : t)),
- } as t.TConversation;
- queryClient.setQueryData<t.TConversation>(
- [QueryKeys.conversation, conversationId],
- updatedConvo,
- );
+ tags: conversation.tags.map((conversationTag) =>
+ conversationTag === tag ? newTag : conversationTag,
+ ),
+ });
}
}
};
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 8a9696b439..737a065457 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -61,6 +61,7 @@ import {
mergeRestagedQuotes,
removeConvoFromAllQueries,
upsertConvoInAllQueries,
+ invalidateConversationLists,
countTaggedApprovalParts,
countTrailingOutputChars,
markStreamStartFailedMetadata,
@@ -2809,7 +2810,7 @@ export default function useResumableSSE(
if (!isCurrentSubscription()) {
return;
}
- await queryClient.invalidateQueries({ queryKey: [QueryKeys.allConversations] });
+ await invalidateConversationLists(queryClient);
if (!isCurrentSubscription()) {
return;
}
@@ -3208,7 +3209,7 @@ export default function useResumableSSE(
// persisted (the original completed and was cleaned up) or may never have
// existed (the winner died before persisting). Don't guess: reconcile against
// the server so a real conversation stays and a phantom is dropped.
- queryClient.invalidateQueries({ queryKey: [QueryKeys.allConversations] });
+ invalidateConversationLists(queryClient);
queryClient.invalidateQueries({ queryKey: [QueryKeys.pinnedConversations] });
} else {
// Fresh optimistic stream that never started: prune immediately.
@@ -4203,7 +4204,7 @@ export default function useResumableSSE(
if (!isCurrentEffect()) {
return;
}
- await queryClient.invalidateQueries({ queryKey: [QueryKeys.allConversations] });
+ await invalidateConversationLists(queryClient);
if (!isCurrentEffect()) {
return;
}
@@ -4273,7 +4274,7 @@ export default function useResumableSSE(
if (!isCurrentEffect()) {
return;
}
- await queryClient.invalidateQueries({ queryKey: [QueryKeys.allConversations] });
+ await invalidateConversationLists(queryClient);
if (!isCurrentEffect()) {
return;
}
@@ -4419,7 +4420,7 @@ export default function useResumableSSE(
if (!isCurrentEffect()) {
return;
}
- await queryClient.invalidateQueries({ queryKey: [QueryKeys.allConversations] });
+ await invalidateConversationLists(queryClient);
if (!isCurrentEffect()) {
return;
}
diff --git a/client/src/hooks/__tests__/AuthContext.spec.tsx b/client/src/hooks/__tests__/AuthContext.spec.tsx
index 7a5c65d158..28ee520c27 100644
--- a/client/src/hooks/__tests__/AuthContext.spec.tsx
+++ b/client/src/hooks/__tests__/AuthContext.spec.tsx
@@ -3,10 +3,17 @@
*/
import React from 'react';
import { RecoilRoot } from 'recoil';
+import { getDefaultStore } from 'jotai';
import { MemoryRouter } from 'react-router-dom';
import { render, act } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TAuthConfig } from '~/common';
+import {
+ chatFilterStatusAtom,
+ chatFilterTagsAtom,
+ chatSortAtom,
+ resetChatFilterSessionAtom,
+} from '~/components/Conversations/chatFilters';
import { AuthContextProvider, useAuthContext } from '../AuthContext';
import { SESSION_KEY } from '~/utils';
@@ -248,6 +255,23 @@ describe('AuthContextProvider — logout onSuccess/onError handling', () => {
expect(replaceSpy).toHaveBeenCalledWith('https://idp.example.com/logout?id_token_hint=abc');
expect(mockSetTokenHeader).toHaveBeenCalledWith(undefined);
});
+ it('resets account-scoped chat filters at the logout session boundary', () => {
+ const jotaiStore = getDefaultStore();
+ jotaiStore.set(chatFilterStatusAtom, 'archived');
+ jotaiStore.set(chatFilterTagsAtom, ['legacy-bookmark']);
+ jotaiStore.set(chatSortAtom, { field: 'title', direction: 'asc' });
+
+ renderProvider();
+
+ act(() => {
+ mockCapturedLogoutOptions.onSuccess({ message: 'Logout successful' });
+ });
+
+ expect(jotaiStore.get(chatFilterStatusAtom)).toBe('active');
+ expect(jotaiStore.get(chatFilterTagsAtom)).toEqual([]);
+ expect(jotaiStore.get(chatSortAtom)).toEqual({ field: 'title', direction: 'asc' });
+ jotaiStore.set(resetChatFilterSessionAtom);
+ });
it('does not call window.location.replace when redirect is absent', async () => {
const replaceSpy = jest.spyOn(window.location, 'replace').mockImplementation(() => {});
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index fdd8d513b1..b80732b296 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -44,6 +44,7 @@
"chat_direction_right_to_left": "Right to Left",
"com_a11y_ai_composing": "The AI is still composing.",
"com_a11y_chats_date_section": "Chats from {{date}}",
+ "com_a11y_chats_alpha_section": "Chats with titles starting with {{letter}}",
"com_a11y_end": "The AI has finished their reply.",
"com_a11y_selected": "selected",
"com_a11y_start": "The AI has started their reply.",
@@ -811,6 +812,7 @@
"com_ui_accept": "I accept",
"com_ui_action_button": "Action Button",
"com_ui_active": "Active",
+ "com_ui_active_chats": "Active chats",
"com_ui_add": "Add",
"com_ui_add_description": "Add a description",
"com_ui_add_first_bookmark": "Click on a chat to add one",
@@ -1069,11 +1071,13 @@
"com_ui_change_version": "Change Version",
"com_ui_chat": "Chat",
"com_ui_chat_history": "Chat History",
+ "com_ui_chats_load_error": "Couldn't load your chats",
"com_ui_chats": "Chats",
"com_ui_check_internet": "Check your internet connection",
"com_ui_clear": "Clear",
"com_ui_clear_all": "Clear all",
"com_ui_clear_browser_cache": "Clear your browser cache",
+ "com_ui_clear_filters": "Clear filters",
"com_ui_clear_presets": "Clear Presets",
"com_ui_clear_search": "Clear search",
"com_ui_click_to_close": "Click to close",
@@ -1161,6 +1165,7 @@
"com_ui_convo_archived": "Conversation archived",
"com_ui_convo_delete_error": "Failed to delete conversation",
"com_ui_convo_delete_success": "Conversation successfully deleted",
+ "com_ui_convo_unarchived": "Conversation unarchived",
"com_ui_copied": "Copied",
"com_ui_copied_to_clipboard": "Copied to clipboard",
"com_ui_copy": "Copy",
@@ -1385,11 +1390,13 @@
"com_ui_file_token_limit_desc": "Set maximum token limit for file processing to control costs and resource usage",
"com_ui_files": "Files",
"com_ui_files_count_size": "{{0}} Files ({{1}}KB)",
+ "com_ui_filter_and_sort_chats": "Filter and sort chats",
"com_ui_filter_by": "Filter by {{title}}",
"com_ui_filter_mcp_servers": "Filter MCP servers by name",
"com_ui_filter_prompts": "Filter Prompts",
"com_ui_filter_prompts_name": "Filter prompts by name",
"com_ui_filter_skills_name": "Filter skills by name",
+ "com_ui_filters_active": "Filters active: {{count}}",
"com_ui_final_touch": "Final touch",
"com_ui_finance": "Finance",
"com_ui_fork": "Fork",
@@ -1719,6 +1726,7 @@
"com_ui_next_result": "Next result",
"com_ui_next_sibling": "Next sibling message",
"com_ui_no": "No",
+ "com_ui_no_archived_chats": "No archived chats",
"com_ui_no_auth": "None (Auto-detect)",
"com_ui_no_bookmarks": "it seems like you have no bookmarks yet. Click on a chat and add a new one",
"com_ui_no_bookmarks_match": "No bookmarks match your search",
@@ -1726,6 +1734,8 @@
"com_ui_no_categories": "No categories available",
"com_ui_no_category": "No category",
"com_ui_no_changes": "No changes were made",
+ "com_ui_no_chats": "No chats yet",
+ "com_ui_no_chats_match_filters": "No chats match your filters",
"com_ui_no_data": "Nothing here yet",
"com_ui_no_individual_resource_access": "No individual users or groups have access",
"com_ui_no_labels": "No Labels",
@@ -2269,10 +2279,16 @@
"com_ui_skills_remove": "Remove {{name}}",
"com_ui_skip": "Skip",
"com_ui_something_else": "Something else...",
+ "com_ui_sort_a_z": "A to Z",
"com_ui_sort_chats_by": "Sort chats by",
"com_ui_sort_created": "Created",
+ "com_ui_sort_newest": "Newest first",
+ "com_ui_sort_oldest": "Oldest first",
+ "com_ui_sort_order": "Order",
"com_ui_sort_projects_by": "Sort projects by",
+ "com_ui_sort_title": "Title",
"com_ui_sort_updated": "Updated",
+ "com_ui_sort_z_a": "Z to A",
"com_ui_special": "special",
"com_ui_special_var_current_date": "Current Date",
"com_ui_special_var_current_datetime": "Current Date & Time",
diff --git a/client/src/utils/convos.spec.ts b/client/src/utils/convos.spec.ts
index 7236e4cbbc..544ffcd4e3 100644
--- a/client/src/utils/convos.spec.ts
+++ b/client/src/utils/convos.spec.ts
@@ -1,5 +1,6 @@
import { QueryClient, InfiniteData } from '@tanstack/react-query';
import type { TConversation } from 'librechat-data-provider';
+import type { ConversationCursorData } from './convos';
import {
dateKeys,
storeEndpointSettings,
@@ -7,7 +8,7 @@ import {
updateInfiniteConvoPage,
findConversationInInfinite,
removeConvoFromInfinitePages,
- groupConversationsByDate,
+ groupConversations,
updateConvoFieldsInfinite,
addConvoToAllQueries,
collectPinnedConversations,
@@ -15,6 +16,7 @@ import {
updateConvoInAllQueries,
removeConvoFromAllQueries,
addConversationToAllConversationsQueries,
+ invalidateConversationLists,
} from './convos';
import { normalizeData } from './collection';
@@ -27,7 +29,7 @@ jest.mock('date-fns', () => {
});
describe('Conversation Utilities', () => {
- describe('groupConversationsByDate', () => {
+ describe('groupConversations', () => {
it('groups conversations by date correctly', () => {
const conversations = [
{ conversationId: '1', updatedAt: '2023-04-01T12:00:00Z' },
@@ -36,7 +38,7 @@ describe('Conversation Utilities', () => {
{ conversationId: '4', updatedAt: new Date(Date.now() - 86400000 * 2).toISOString() },
{ conversationId: '5', updatedAt: new Date(Date.now() - 86400000 * 8).toISOString() },
];
- const grouped = groupConversationsByDate(conversations as TConversation[]);
+ const grouped = groupConversations(conversations as TConversation[]);
expect(grouped[0][0]).toBe(dateKeys.today);
expect(grouped[0][1]).toHaveLength(1);
expect(grouped[1][0]).toBe(dateKeys.yesterday);
@@ -57,7 +59,7 @@ describe('Conversation Utilities', () => {
{ conversationId: '3', updatedAt: '2022-12-01T12:00:00Z' },
];
- const grouped = groupConversationsByDate(conversations as TConversation[]);
+ const grouped = groupConversations(conversations as TConversation[]);
expect(grouped).toEqual(
expect.arrayContaining([
@@ -81,7 +83,7 @@ describe('Conversation Utilities', () => {
{ conversationId: '5', updatedAt: '2022-12-01T12:00:00Z' },
];
- const grouped = groupConversationsByDate(conversations as TConversation[]);
+ const grouped = groupConversations(conversations as TConversation[]);
// Now expect grouping by year for 2023 and 2022
const expectedGroups = [' 2023', ' 2022'];
@@ -108,7 +110,7 @@ describe('Conversation Utilities', () => {
{ conversationId: '5', updatedAt: '2021-12-01T12:00:00Z' },
];
- const grouped = groupConversationsByDate(conversations as TConversation[]);
+ const grouped = groupConversations(conversations as TConversation[]);
expect(grouped.map(([key]) => key)).toEqual([' 2023', ' 2022', ' 2021']);
expect(grouped[0][1].map((c) => new Date(c.updatedAt).getFullYear())).toEqual([2023, 2023]);
@@ -123,7 +125,7 @@ describe('Conversation Utilities', () => {
{ conversationId: '3', updatedAt: '2023-06-30T12:00:00Z' },
];
- const grouped = groupConversationsByDate(conversations as TConversation[]);
+ const grouped = groupConversations(conversations as TConversation[]);
expect(grouped.length).toBe(1);
expect(grouped[0][0]).toBe(' 2023');
@@ -137,7 +139,7 @@ describe('Conversation Utilities', () => {
{ conversationId: '3', updatedAt: undefined },
];
- const grouped = groupConversationsByDate(conversations as TConversation[]);
+ const grouped = groupConversations(conversations as TConversation[]);
expect(grouped.length).toBe(2);
expect(grouped[0][0]).toBe(dateKeys.today);
@@ -154,7 +156,7 @@ describe('Conversation Utilities', () => {
{ conversationId: '4', updatedAt: '2023-06-01T12:00:00Z' },
];
- const grouped = groupConversationsByDate(conversations as TConversation[]);
+ const grouped = groupConversations(conversations as TConversation[]);
const allGroupedIds = grouped.flatMap(([, convs]) => convs.map((c) => c.conversationId));
expect(allGroupedIds).not.toContain('1');
@@ -162,6 +164,145 @@ describe('Conversation Utilities', () => {
expect(allGroupedIds).toContain('2');
expect(allGroupedIds).toContain('4');
});
+ it('keeps pinned conversations when requested', () => {
+ const timestamp = '2023-06-01T12:00:00Z';
+ const conversations = [
+ { conversationId: 'pinned', updatedAt: timestamp, pinned: true },
+ { conversationId: 'regular', updatedAt: timestamp },
+ ];
+
+ const defaultIds = groupConversations(conversations as TConversation[])
+ .flatMap(([, convos]) => convos)
+ .map((conversation) => conversation.conversationId);
+ const includedIds = groupConversations(conversations as TConversation[], {
+ includePinned: true,
+ })
+ .flatMap(([, convos]) => convos)
+ .map((conversation) => conversation.conversationId);
+
+ expect(defaultIds).toEqual(['regular']);
+ expect(includedIds).toEqual(['pinned', 'regular']);
+ });
+
+ it('inverts date group and conversation order when ascending', () => {
+ const conversations = [
+ { conversationId: 'today', title: 'Today', updatedAt: new Date().toISOString() },
+ {
+ conversationId: 'month-new',
+ title: 'Month new',
+ updatedAt: '2023-06-30T12:00:00Z',
+ },
+ {
+ conversationId: 'month-old',
+ title: 'Month old',
+ updatedAt: '2023-06-01T12:00:00Z',
+ },
+ {
+ conversationId: 'year',
+ title: 'Year',
+ updatedAt: '2022-06-01T12:00:00Z',
+ },
+ ];
+
+ const grouped = groupConversations(conversations as TConversation[], { direction: 'asc' });
+
+ expect(grouped.map(([key]) => key)).toEqual([' 2022', ' 2023', dateKeys.today]);
+ expect(grouped[1][1].map((conversation) => conversation.conversationId)).toEqual([
+ 'month-old',
+ 'month-new',
+ ]);
+ });
+
+ /** The server pages titles by its own string order, so the grouping must not reorder
+ * what arrived: a re-sort would show an alphabet the cursor cannot keep filling. */
+ it('keeps the fetched order for title groups and shares one non-letter bucket', () => {
+ const conversations = [
+ { conversationId: 'avocado', title: 'Avocado' },
+ { conversationId: 'zoo', title: 'Zoo' },
+ { conversationId: 'apple', title: 'apple' },
+ { conversationId: 'number', title: '42 things' },
+ { conversationId: 'empty', title: '' },
+ ];
+
+ const grouped = groupConversations(conversations as TConversation[], {
+ field: 'title',
+ direction: 'asc',
+ });
+
+ expect(grouped.map(([key]) => key)).toEqual(['A', 'Z', 'a', '#']);
+ expect(
+ grouped.map(([, group]) => group.map((conversation) => conversation.conversationId)),
+ ).toEqual([['avocado'], ['zoo'], ['apple'], ['number', 'empty']]);
+ });
+
+ it('keeps a leading-space title in the server order and labels it as non-letter', () => {
+ const conversations = [
+ { conversationId: 'zebra', title: ' Zebra' },
+ { conversationId: 'apple', title: 'Apple' },
+ ];
+
+ const grouped = groupConversations(conversations as TConversation[], {
+ field: 'title',
+ direction: 'asc',
+ });
+
+ expect(grouped.map(([key]) => key)).toEqual(['#', 'A']);
+ expect(
+ grouped.flatMap(([, group]) => group.map((conversation) => conversation.conversationId)),
+ ).toEqual(['zebra', 'apple']);
+ });
+
+ /** A non-letter heading can appear on either side of a letter in the server's order
+ * (`!draft`, `Apple`, `_scratch`), and merging those two `#` rows into one group would
+ * move a row across the cursor boundary the next page continues from. */
+ it('emits repeated title headings as separate runs', () => {
+ const conversations = [
+ { conversationId: 'draft', title: '!draft' },
+ { conversationId: 'apple', title: 'Apple' },
+ { conversationId: 'scratch', title: '_scratch' },
+ ];
+
+ const grouped = groupConversations(conversations as TConversation[], {
+ field: 'title',
+ direction: 'asc',
+ });
+
+ expect(grouped.map(([key]) => key)).toEqual(['#', 'A', '#']);
+ expect(
+ grouped.map(([, group]) => group.map((conversation) => conversation.conversationId)),
+ ).toEqual([['draft'], ['apple'], ['scratch']]);
+ });
+
+ /** `charAt(0)` would return a lone surrogate here, which renders as a replacement
+ * character and merges every supplementary-plane initial into one heading. */
+ it('heads a title group with its first code point', () => {
+ const grouped = groupConversations(
+ [{ conversationId: 'deseret', title: '𐐖ohn' }] as TConversation[],
+ { field: 'title' },
+ );
+
+ expect(grouped.map(([key]) => key)).toEqual(['𐐖']);
+ });
+
+ /** The cursor orders the archive's legacy group — archived before `archivedAt` was
+ * recorded — by `createdAt`, so reading `updatedAt` first would misplace those rows. */
+ it('dates a legacy archived chat by createdAt rather than last activity', () => {
+ const conversations = [
+ {
+ conversationId: 'legacy',
+ archivedAt: null,
+ createdAt: '2022-06-01T12:00:00Z',
+ updatedAt: '2023-06-01T12:00:00Z',
+ },
+ ];
+
+ const grouped = groupConversations(conversations as unknown as TConversation[], {
+ field: 'archivedAt',
+ });
+
+ expect(grouped).toHaveLength(1);
+ expect(grouped[0][0]).toBe(' 2022');
+ });
it('correctly groups and sorts conversations for every month of the year', () => {
const months = [
@@ -191,7 +332,7 @@ describe('Conversation Utilities', () => {
},
]);
- const grouped = groupConversationsByDate(conversations as TConversation[]);
+ const grouped = groupConversations(conversations as TConversation[]);
// All 2023 conversations should be in a single group
const group2023 = grouped.find(([key]) => key === ' 2023');
@@ -692,6 +833,113 @@ describe('Conversation Utilities', () => {
).toEqual(['a']);
});
+ /** Only newest-first can be reproduced client-side: seeding a row at the front of a
+ * title- or created-at-ordered page invents a position the next page contradicts. */
+ it('leaves a non-default sort variant to the server instead of seeding a row into it', () => {
+ const sortedKey = ['allConversations', { sortBy: 'title', sortDirection: 'asc' }];
+ queryClient.setQueryData(sortedKey, {
+ pages: [{ conversations: [convoA], nextCursor: null }],
+ pageParams: [],
+ });
+
+ upsertConvoInAllQueries(queryClient, convoB);
+
+ const sorted = queryClient.getQueryData<InfiniteData<any>>(sortedKey);
+ expect(sorted!.pages[0].conversations.map((c: TConversation) => c.conversationId)).toEqual([
+ 'a',
+ ]);
+ expect(queryClient.getQueryState(sortedKey)?.isInvalidated).toBe(true);
+ });
+
+ /** The sidebar lists the archive from the same components, so both prefixes are live
+ * caches: an SSE update to an archived chat must reach the list showing it. */
+ it('updates an archived row in the archived cache', () => {
+ const archivedKey = ['archivedConversations', { isArchived: true }];
+ const archived = { ...convoA, isArchived: true } as TConversation;
+ queryClient.setQueryData(archivedKey, {
+ pages: [{ conversations: [archived], nextCursor: null }],
+ pageParams: [],
+ });
+
+ updateConvoInAllQueries(queryClient, 'a', (c) => ({ ...c, title: 'Renamed archived' }));
+
+ const data = queryClient.getQueryData<InfiniteData<ConversationCursorData>>(archivedKey);
+ expect(data!.pages[0].conversations[0].title).toBe('Renamed archived');
+ });
+
+ /** A copy of an archived chat inherits its archive state, so it belongs to the archived
+ * list; seeding it into the active one would show a row the server would not return. */
+ it('keeps an archived conversation out of the active list caches', () => {
+ addConvoToAllQueries(queryClient, { ...convoB, isArchived: true } as TConversation);
+
+ const active = queryClient.getQueryData<InfiniteData<ConversationCursorData>>([
+ 'allConversations',
+ ]);
+ expect(active!.pages[0].conversations.map((c) => c.conversationId)).toEqual(['a']);
+ });
+
+ it('drops a row from the active cache once it is archived', () => {
+ updateConvoInAllQueries(queryClient, 'a', (c) => ({ ...c, isArchived: true }));
+
+ const active = queryClient.getQueryData<InfiniteData<ConversationCursorData>>([
+ 'allConversations',
+ ]);
+ expect(
+ active!.pages.flatMap((page) => page.conversations.map((c) => c.conversationId)),
+ ).not.toContain('a');
+ });
+
+ /** A search is evaluated by the server, so a new row may or may not belong in a cached
+ * result: skipping it silently would leave a mounted search list missing it. */
+ it('refetches a cached search variant instead of deciding its membership', () => {
+ const searchKey = ['allConversations', { search: 'draft' }];
+ queryClient.setQueryData(searchKey, {
+ pages: [{ conversations: [convoA], nextCursor: null }],
+ pageParams: [],
+ });
+
+ addConvoToAllQueries(queryClient, convoB);
+
+ const searched = queryClient.getQueryData<InfiniteData<ConversationCursorData>>(searchKey);
+ expect(searched!.pages[0].conversations.map((c) => c.conversationId)).toEqual(['a']);
+ expect(queryClient.getQueryState(searchKey)?.isInvalidated).toBe(true);
+ });
+
+ /** A title edit or a new message can make a row start or stop matching a search, and
+ * only the server can say which: the mounted result has to be refetched either way. */
+ it('refetches a cached search variant after a field update', () => {
+ const searchKey = ['allConversations', { search: 'draft' }];
+ queryClient.setQueryData(searchKey, {
+ pages: [{ conversations: [convoA], nextCursor: null }],
+ pageParams: [],
+ });
+
+ updateConvoInAllQueries(queryClient, 'a', (c) => ({ ...c, title: 'No longer a draft' }));
+
+ const searched = queryClient.getQueryData<InfiniteData<ConversationCursorData>>(searchKey);
+ expect(searched!.pages[0].conversations[0].title).toBe('No longer a draft');
+ expect(queryClient.getQueryState(searchKey)?.isInvalidated).toBe(true);
+ });
+
+ it('updates a row in place under a non-default sort rather than moving it to the top', () => {
+ const sortedKey = ['allConversations', { sortBy: 'createdAt' }];
+ const convoC = { conversationId: 'c', updatedAt: '2024-01-03T12:00:00Z' } as TConversation;
+ queryClient.setQueryData(sortedKey, {
+ pages: [{ conversations: [convoC, convoA], nextCursor: null }],
+ pageParams: [],
+ });
+
+ updateConvoInAllQueries(queryClient, 'a', (c) => ({ ...c, title: 'Renamed' }), true);
+
+ const sorted = queryClient.getQueryData<InfiniteData<any>>(sortedKey);
+ expect(sorted!.pages[0].conversations.map((c: TConversation) => c.conversationId)).toEqual([
+ 'c',
+ 'a',
+ ]);
+ expect(sorted!.pages[0].conversations[1].title).toBe('Renamed');
+ expect(queryClient.getQueryState(sortedKey)?.isInvalidated).toBe(true);
+ });
+
it('upsertConvoInAllQueries adds missing conversations to the top', () => {
upsertConvoInAllQueries(queryClient, convoB);
const data = queryClient.getQueryData<InfiniteData<{ conversations: TConversation[] }>>([
@@ -891,6 +1139,22 @@ describe('Conversation Utilities', () => {
expect(mainData!.pages[0].conversations[0].conversationId).toBe('b');
expect(otherData!.pages[0].conversations[0].conversationId).toBe('b');
});
+
+ /** Callers that cannot say what changed — a recovered stream, a schedule that moved,
+ * a deleted project — reach both prefixes through this, or the archive keeps a row
+ * the server has already changed. */
+ it('invalidateConversationLists reaches the archived prefix too', async () => {
+ const archivedKey = ['archivedConversations', { isArchived: true }];
+ queryClient.setQueryData(archivedKey, {
+ pages: [{ conversations: [convoA], nextCursor: null }],
+ pageParams: [],
+ });
+
+ await invalidateConversationLists(queryClient);
+
+ expect(queryClient.getQueryState(['allConversations'])?.isInvalidated).toBe(true);
+ expect(queryClient.getQueryState(archivedKey)?.isInvalidated).toBe(true);
+ });
});
});
});
diff --git a/client/src/utils/convos.ts b/client/src/utils/convos.ts
index 7256c50c4e..19ef1399c6 100644
--- a/client/src/utils/convos.ts
+++ b/client/src/utils/convos.ts
@@ -11,6 +11,7 @@ import {
isWithinInterval,
} from 'date-fns';
import type { TConversation, GroupedConversations } from 'librechat-data-provider';
+import type { InvalidateQueryFilters } from '@tanstack/react-query';
import type { InfiniteData } from '@tanstack/react-query';
import { isTemporaryConversation } from './conversation';
@@ -77,72 +78,120 @@ const dateGroupsSet = new Set([
dateKeys.previous30Days,
]);
-export const groupConversationsByDate = (
+type ConversationDateField = 'updatedAt' | 'createdAt' | 'archivedAt';
+
+export type ConversationGroupOptions = {
+ field?: ConversationDateField | 'title';
+ direction?: 'asc' | 'desc';
+ includePinned?: boolean;
+};
+
+const getConversationDate = (
+ conversation: TConversation,
+ field: ConversationDateField,
+ fallbackDate: Date,
+) => {
+ /* The archive's legacy group — archived before `archivedAt` was recorded — is ordered
+ and dated by `createdAt` on the server, so reading `updatedAt` first here would put
+ those rows in a bucket the cursor never sorted them into. */
+ const fallbackField = field === 'archivedAt' ? conversation.createdAt : conversation.updatedAt;
+ const dateValue = conversation[field] ?? fallbackField ?? conversation.createdAt;
+ return dateValue ? parseISO(dateValue) : fallbackDate;
+};
+
+/** A title's own initial, as a code point: `charAt(0)` on a supplementary-plane letter
+ * returns half a surrogate pair, which renders as a replacement character and collapses
+ * unrelated initials into one heading. Non-letters share a single `#` group. The case is
+ * left as written so each heading matches the order the server paged the titles in. */
+const getTitleInitial = (title: string): string => {
+ const initial = [...title][0];
+ if (initial == null || !/\p{L}/u.test(initial)) {
+ return '#';
+ }
+ return initial;
+};
+
+export const groupConversations = (
conversations: Array<TConversation | null>,
- dateField: 'updatedAt' | 'createdAt' = 'updatedAt',
+ { field = 'updatedAt', direction = 'desc', includePinned = false }: ConversationGroupOptions = {},
): GroupedConversations => {
if (!Array.isArray(conversations)) {
return [];
}
- const seenConversationIds = new Set();
- const groups = new Map();
+
+ const seenConversationIds = new Set<string | null>();
+ const groups = new Map<string, TConversation[]>();
+ /* Title paging is a keyset over the server's own string order, so re-sorting what arrived
+ can only disagree with it: a title that belongs before this page sits behind its cursor
+ and arrives later. These groups therefore keep the fetched order, which means a heading
+ can repeat — `!draft`, `Apple`, `_scratch` puts two non-letter rows either side of `A` —
+ and merging those two into one `#` group would move a row across the cursor boundary. */
+ const runs: GroupedConversations = [];
const now = new Date(Date.now());
conversations.forEach((conversation) => {
- if (
- !conversation ||
- seenConversationIds.has(conversation.conversationId) ||
- conversation.pinned
- ) {
+ if (!conversation || (!includePinned && conversation.pinned)) {
+ return;
+ }
+ if (seenConversationIds.has(conversation.conversationId)) {
return;
}
seenConversationIds.add(conversation.conversationId);
- let date: Date;
- const dateValue = conversation[dateField] ?? conversation.updatedAt ?? conversation.createdAt;
- if (dateValue) {
- date = parseISO(dateValue);
- } else {
- date = now;
- }
- const groupName = getGroupName(date);
- if (!groups.has(groupName)) {
- groups.set(groupName, []);
+ if (field === 'title') {
+ const title = typeof conversation.title === 'string' ? conversation.title : '';
+ const groupName = getTitleInitial(title);
+ const currentRun = runs[runs.length - 1];
+ if (currentRun && currentRun[0] === groupName) {
+ currentRun[1].push(conversation);
+ } else {
+ runs.push([groupName, [conversation]]);
+ }
+ return;
}
- groups.get(groupName).push(conversation);
- });
- const sortedGroups = new Map();
- dateGroupsSet.forEach((group) => {
- if (groups.has(group)) {
- sortedGroups.set(group, groups.get(group));
+ const groupName = getGroupName(getConversationDate(conversation, field, now));
+ const group = groups.get(groupName);
+ if (group) {
+ group.push(conversation);
+ } else {
+ groups.set(groupName, [conversation]);
}
});
+ if (field === 'title') {
+ return runs;
+ }
+
const yearMonthGroups = Array.from(groups.keys())
.filter((group) => !dateGroupsSet.has(group))
.sort((a, b) => {
- const [yearA, yearB] = [parseInt(a.trim()), parseInt(b.trim())];
- if (yearA !== yearB) {
- return yearB - yearA;
- }
- const [monthA, monthB] = [dateKeysReverse[a], dateKeysReverse[b]];
- const bOrder = monthOrderMap.get(monthB) ?? -1,
- aOrder = monthOrderMap.get(monthA) ?? -1;
- return bOrder - aOrder;
+ const getOrder = (group: string) => {
+ const month = dateKeysReverse[group];
+ if (month) {
+ return now.getFullYear() * 12 + (monthOrderMap.get(month) ?? 0);
+ }
+ return parseInt(group.trim(), 10) * 12;
+ };
+ const orderA = getOrder(a);
+ const orderB = getOrder(b);
+ return direction === 'asc' ? orderA - orderB : orderB - orderA;
+ });
+ const recentGroups = Array.from(dateGroupsSet).filter((group) => groups.has(group));
+ const orderedGroupNames =
+ direction === 'asc'
+ ? [...yearMonthGroups, ...recentGroups.reverse()]
+ : [...recentGroups, ...yearMonthGroups];
+
+ orderedGroupNames.forEach((groupName) => {
+ groups.get(groupName)!.sort((a, b) => {
+ const comparison =
+ getConversationDate(b, field, now).getTime() - getConversationDate(a, field, now).getTime();
+ return direction === 'asc' ? -comparison : comparison;
});
- yearMonthGroups.forEach((group) => {
- sortedGroups.set(group, groups.get(group));
});
- sortedGroups.forEach((conversations) => {
- conversations.sort(
- (a: TConversation, b: TConversation) =>
- new Date(b[dateField] ?? b.updatedAt ?? 0).getTime() -
- new Date(a[dateField] ?? a.updatedAt ?? 0).getTime(),
- );
- });
- return Array.from(sortedGroups, ([key, value]) => [key, value]);
+ return orderedGroupNames.map((groupName) => [groupName, groups.get(groupName)!]);
};
export type ConversationCursorData = {
@@ -175,36 +224,132 @@ function conversationMatchesProjectQuery(
function getConversationListQueryParams(queryKey: readonly unknown[]): {
tags?: string[];
search?: string;
+ sortBy?: string;
+ sortDirection?: string;
+ isArchived?: boolean;
} {
const params = queryKey[1];
if (!params || typeof params !== 'object') {
return {};
}
- return params as { tags?: string[]; search?: string };
+ return params as {
+ tags?: string[];
+ search?: string;
+ sortBy?: string;
+ sortDirection?: string;
+ isArchived?: boolean;
+ };
+}
+
+/**
+ * Newest-first is the only order these writers can reproduce. A title or created-at
+ * variant, or an ascending one, orders rows by a key the client cannot place a row
+ * against without the server's cursor, so moving a row to the front of those pages —
+ * or seeding one there — would invent an order the next page contradicts. Those
+ * variants take the field update in place and are refetched instead.
+ */
+function queryListsNewestFirst(queryKey: readonly unknown[]): boolean {
+ const { sortBy, sortDirection } = getConversationListQueryParams(queryKey);
+ return (
+ (sortBy == null || sortBy === 'updatedAt') &&
+ (sortDirection == null || sortDirection === 'desc')
+ );
+}
+
+/**
+ * Every cached conversation list, active and archived alike. A write that visits only
+ * one prefix leaves the other rendering the row it just changed: the sidebar lists the
+ * archive from the same components, so both are live caches now.
+ */
+export const CONVERSATION_LIST_KEYS = [
+ QueryKeys.allConversations,
+ QueryKeys.archivedConversations,
+] as const;
+
+function findConversationListQueries(queryClient: QueryClient) {
+ return CONVERSATION_LIST_KEYS.flatMap((listKey) =>
+ queryClient.getQueryCache().findAll([listKey], { exact: false }),
+ );
}
-/** Inserts must not land in a bookmark or search cache the row would not
- * appear in on the server. Search is not matchable client-side, so those
- * variants are skipped. */
-function conversationMatchesListQuery(
+/**
+ * Reconciles both list prefixes against the server. For callers that cannot say what
+ * changed — a recovered stream, a schedule that moved, a project that took its chats'
+ * fields with it — and so cannot write the row themselves.
+ */
+export function invalidateConversationLists(
+ queryClient: QueryClient,
+ filters?: Omit<InvalidateQueryFilters, 'queryKey'>,
+): Promise<void> {
+ return Promise.all(
+ CONVERSATION_LIST_KEYS.map((listKey) =>
+ queryClient.invalidateQueries({ queryKey: [listKey], ...filters }),
+ ),
+ ).then(() => undefined);
+}
+
+/** Whether a list variant shows archived chats, which its key states and its root implies. */
+function queryListsArchived(queryKey: readonly unknown[]): boolean {
+ if (queryKey[0] === QueryKeys.archivedConversations) {
+ return true;
+ }
+ return getConversationListQueryParams(queryKey).isArchived === true;
+}
+
+/**
+ * Whether a row still belongs in a variant at all, by the facets the client can decide:
+ * its project and whether it is archived. Bookmark and search membership are deliberately
+ * excluded — a search cache matches nothing client-side, so judging a row that is already
+ * in one by that rule would evict every row it holds.
+ */
+function conversationBelongsToListQuery(
queryKey: readonly unknown[],
- conversation: Pick<TConversation, 'chatProjectId' | 'tags'>,
+ conversation: Pick<TConversation, 'chatProjectId' | 'isArchived'>,
): boolean {
- if (!conversationMatchesProjectQuery(queryKey, conversation)) {
- return false;
+ return (
+ conversationMatchesProjectQuery(queryKey, conversation) &&
+ queryListsArchived(queryKey) === (conversation.isArchived === true)
+ );
+}
+
+/**
+ * Whether only the server can say what a variant holds after a write. Two things put it
+ * out of the client's reach: an order keyed on something other than last activity, which
+ * these writers cannot place a row against, and a search, which the server evaluates —
+ * a title edit or a new message can make a row start or stop matching one.
+ */
+function queryNeedsServerReconciliation(queryKey: readonly unknown[]): boolean {
+ if (!queryListsNewestFirst(queryKey)) {
+ return true;
}
- const { tags, search } = getConversationListQueryParams(queryKey);
- if (typeof search === 'string' && search.trim() !== '') {
- return false;
+ const { search } = getConversationListQueryParams(queryKey);
+ return typeof search === 'string' && search.trim() !== '';
+}
+
+/**
+ * What a writer may do with a row it wants to add to a variant.
+ *
+ * `skip` is only for a variant the row provably does not belong to, by the facets the
+ * client decides: project, archive state, bookmarks. Anything left to the server is
+ * refetched instead — skipping it silently would leave a mounted list missing a row.
+ */
+type ListInsertVerdict = 'insert' | 'skip' | 'refetch';
+
+function conversationInsertVerdict(
+ queryKey: readonly unknown[],
+ conversation: Pick<TConversation, 'chatProjectId' | 'tags' | 'isArchived'>,
+): ListInsertVerdict {
+ if (!conversationBelongsToListQuery(queryKey, conversation)) {
+ return 'skip';
}
+ const { tags } = getConversationListQueryParams(queryKey);
if (Array.isArray(tags) && tags.length > 0) {
const conversationTags = conversation.tags;
- if (!Array.isArray(conversationTags) || conversationTags.length === 0) {
- return false;
+ if (!Array.isArray(conversationTags) || !tags.some((tag) => conversationTags.includes(tag))) {
+ return 'skip';
}
- return tags.some((tag) => conversationTags.includes(tag));
}
- return true;
+ return queryNeedsServerReconciliation(queryKey) ? 'refetch' : 'insert';
}
/** Dedicated pinned data wins for ids it already has. Pins that only live on
@@ -312,13 +457,13 @@ export function addConversationToAllConversationsQueries(
queryClient: QueryClient,
newConversation: TConversation,
) {
- // Find all keys that start with QueryKeys.allConversations
- const queries = queryClient
- .getQueryCache()
- .findAll([QueryKeys.allConversations], { exact: false });
-
- for (const query of queries) {
- if (!conversationMatchesProjectQuery(query.queryKey, newConversation)) {
+ for (const query of findConversationListQueries(queryClient)) {
+ const verdict = conversationInsertVerdict(query.queryKey, newConversation);
+ if (verdict === 'skip') {
+ continue;
+ }
+ if (verdict === 'refetch') {
+ queryClient.invalidateQueries({ queryKey: query.queryKey, refetchType: 'active' });
continue;
}
queryClient.setQueryData<InfiniteData<ConversationCursorData>>(query.queryKey, (old) => {
@@ -430,12 +575,15 @@ export function storeEndpointSettings(conversation: TConversation | null) {
// Add
export function addConvoToAllQueries(queryClient: QueryClient, newConvo: TConversation) {
- const queries = queryClient
- .getQueryCache()
- .findAll([QueryKeys.allConversations], { exact: false });
-
- for (const query of queries) {
- if (!conversationMatchesListQuery(query.queryKey, newConvo)) {
+ for (const query of findConversationListQueries(queryClient)) {
+ /* The unpin path reinserts a row that the update helper may have just marked stale;
+ seeding it at page one would clear that invalidation and fabricate a position. */
+ const verdict = conversationInsertVerdict(query.queryKey, newConvo);
+ if (verdict === 'skip') {
+ continue;
+ }
+ if (verdict === 'refetch') {
+ queryClient.invalidateQueries({ queryKey: query.queryKey, refetchType: 'active' });
continue;
}
queryClient.setQueryData<InfiniteData<ConversationCursorData>>(query.queryKey, (oldData) => {
@@ -504,11 +652,13 @@ export function upsertConvoInAllQueries(
moveToTop,
);
- const queries = queryClient
- .getQueryCache()
- .findAll([QueryKeys.allConversations], { exact: false });
+ const queries = findConversationListQueries(queryClient);
for (const query of queries) {
+ /* A variant the writers cannot order takes the merge in place and is refetched, so the
+ row's new text shows at once while the server decides where it belongs. */
+ const newestFirst = queryListsNewestFirst(query.queryKey);
+ const verdict = conversationInsertVerdict(query.queryKey, listConvo);
queryClient.setQueryData<InfiniteData<ConversationCursorData>>(query.queryKey, (oldData) => {
if (!oldData) {
return oldData;
@@ -529,7 +679,7 @@ export function upsertConvoInAllQueries(
const now = new Date().toISOString();
if (pageIdx === -1) {
- if (!conversationMatchesListQuery(query.queryKey, listConvo)) {
+ if (verdict !== 'insert') {
return oldData;
}
const firstPage = oldData.pages[0] ?? { conversations: [], nextCursor: null };
@@ -555,11 +705,11 @@ export function upsertConvoInAllQueries(
updatedAt: listConvo.updatedAt ?? (moveToTop ? now : found.updatedAt),
};
- if (!conversationMatchesProjectQuery(query.queryKey, updated)) {
+ if (!conversationBelongsToListQuery(query.queryKey, updated)) {
return removeConvoFromInfinitePages(oldData, updated.conversationId ?? '');
}
- if (!moveToTop || (pageIdx === 0 && convoIdx === 0)) {
+ if (!moveToTop || !newestFirst || (pageIdx === 0 && convoIdx === 0)) {
return {
...oldData,
pages: oldData.pages.map((page, pi) =>
@@ -592,6 +742,10 @@ export function upsertConvoInAllQueries(
return { ...oldData, pages };
});
+ if (queryNeedsServerReconciliation(query.queryKey)) {
+ /* Inactive variants are only marked stale: they refresh when something mounts them. */
+ queryClient.invalidateQueries({ queryKey: query.queryKey, refetchType: 'active' });
+ }
}
}
@@ -724,11 +878,12 @@ export function updateConvoInAllQueries(
) {
updatePinnedConvosQuery(queryClient, conversationId, updater, moveToTop);
- const queries = queryClient
- .getQueryCache()
- .findAll([QueryKeys.allConversations], { exact: false });
+ const queries = findConversationListQueries(queryClient);
for (const query of queries) {
+ /* A variant ordered by a key the client cannot place a row against keeps its positions
+ and is refetched instead: a rename also moves a row under a title sort. */
+ const newestFirst = queryListsNewestFirst(query.queryKey);
queryClient.setQueryData<InfiniteData<ConversationCursorData>>(query.queryKey, (oldData) => {
if (!oldData) {
return oldData;
@@ -759,12 +914,12 @@ export function updateConvoInAllQueries(
const merged = preserveListFlags(updater(found), found);
const updated = moveToTop ? { ...merged, updatedAt: new Date().toISOString() } : merged;
- if (!conversationMatchesProjectQuery(query.queryKey, updated)) {
+ if (!conversationBelongsToListQuery(query.queryKey, updated)) {
return removeConvoFromInfinitePages(oldData, conversationId);
}
// If not moving to top, or already at top of page 0, update in place
- if (!moveToTop || (pageIdx === 0 && convoIdx === 0)) {
+ if (!moveToTop || !newestFirst || (pageIdx === 0 && convoIdx === 0)) {
return {
...oldData,
pages: oldData.pages.map((page, pi) =>
@@ -801,6 +956,10 @@ export function updateConvoInAllQueries(
return { ...oldData, pages: newPages };
});
+ if (queryNeedsServerReconciliation(query.queryKey)) {
+ /* Inactive variants are only marked stale: they refresh when something mounts them. */
+ queryClient.invalidateQueries({ queryKey: query.queryKey, refetchType: 'active' });
+ }
}
}
@@ -808,9 +967,7 @@ export function updateConvoInAllQueries(
export function removeConvoFromAllQueries(queryClient: QueryClient, conversationId: string) {
updatePinnedConvosQuery(queryClient, conversationId, () => null);
- const queries = queryClient
- .getQueryCache()
- .findAll([QueryKeys.allConversations], { exact: false });
+ const queries = findConversationListQueries(queryClient);
for (const query of queries) {
queryClient.setQueryData<InfiniteData<ConversationCursorData>>(query.queryKey, (oldData) => {
diff --git a/packages/api/src/utils/query.spec.ts b/packages/api/src/utils/query.spec.ts
index 405eb284c4..09844d7389 100644
--- a/packages/api/src/utils/query.spec.ts
+++ b/packages/api/src/utils/query.spec.ts
@@ -1,4 +1,12 @@
-import { DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT, normalizeLimit, queryString } from './query';
+import {
+ CONVERSATION_SORT_FIELDS,
+ DEFAULT_PAGE_LIMIT,
+ MAX_PAGE_LIMIT,
+ normalizeLimit,
+ normalizeSortDirection,
+ normalizeSortField,
+ queryString,
+} from './query';
describe('queryString', () => {
it('returns a string value unchanged', () => {
@@ -54,3 +62,40 @@ describe('normalizeLimit', () => {
expect(normalizeLimit('7.9')).toBe(7);
});
});
+
+describe('conversation sort normalizers', () => {
+ it('falls back for an unknown sort field', () => {
+ expect(
+ normalizeSortField('not-a-sort', {
+ fields: CONVERSATION_SORT_FIELDS,
+ fallback: 'updatedAt',
+ }),
+ ).toBe('updatedAt');
+ });
+
+ it('uses the first value for a repeated sort field parameter', () => {
+ expect(
+ normalizeSortField(['createdAt', 'title'], {
+ fields: CONVERSATION_SORT_FIELDS,
+ fallback: 'updatedAt',
+ }),
+ ).toBe('createdAt');
+ });
+
+ it.each(Object.keys(CONVERSATION_SORT_FIELDS))('accepts the %s sort field', (field) => {
+ expect(
+ normalizeSortField(field, {
+ fields: CONVERSATION_SORT_FIELDS,
+ fallback: 'updatedAt',
+ }),
+ ).toBe(field);
+ });
+
+ it('passes through ascending sort direction', () => {
+ expect(normalizeSortDirection('asc')).toBe('asc');
+ });
+
+ it('falls back for an invalid sort direction', () => {
+ expect(normalizeSortDirection('sideways')).toBe('desc');
+ });
+});
diff --git a/packages/api/src/utils/query.ts b/packages/api/src/utils/query.ts
index 4ca5a4e9bd..e263fbbbdc 100644
--- a/packages/api/src/utils/query.ts
+++ b/packages/api/src/utils/query.ts
@@ -5,6 +5,19 @@ type QueryValue = Request['query'][string];
export const DEFAULT_PAGE_LIMIT = 25;
export const MAX_PAGE_LIMIT = 100;
+export type SortDirection = 'asc' | 'desc';
+
+/** The sort fields `getConvosByCursor` accepts; anything else makes it throw. Keep this
+ * in sync with the whitelist in `packages/data-schemas/src/methods/conversation.ts`. */
+export type ConversationSortField = 'title' | 'createdAt' | 'updatedAt' | 'archivedAt';
+
+export const CONVERSATION_SORT_FIELDS: Readonly<Record<ConversationSortField, true>> = {
+ title: true,
+ createdAt: true,
+ updatedAt: true,
+ archivedAt: true,
+};
+
/** Express parses a repeated `?limit=a&limit=b` into an array, which `parseInt` reads as its first element's digits. */
export const queryString = (value: QueryValue): string | undefined => {
if (typeof value === 'string') {
@@ -16,6 +29,22 @@ export const queryString = (value: QueryValue): string | undefined => {
return undefined;
};
+export const normalizeSortField = <T extends string>(
+ value: QueryValue,
+ { fields, fallback }: { fields: Readonly<Record<T, true>>; fallback: T },
+): T => {
+ const sortField = queryString(value);
+ return sortField != null && fields[sortField as T] === true ? (sortField as T) : fallback;
+};
+
+export const normalizeSortDirection = (
+ value: QueryValue,
+ { fallback = 'desc' }: { fallback?: SortDirection } = {},
+): SortDirection => {
+ const sortDirection = queryString(value);
+ return sortDirection === 'asc' || sortDirection === 'desc' ? sortDirection : fallback;
+};
+
/**
* Clamps a page size from user input. An unclamped limit reaches Mongo's `.limit()`,
* where a negative value means "one batch" and `0` means "no limit at all".
diff --git a/packages/data-provider/src/types/queries.ts b/packages/data-provider/src/types/queries.ts
index 565c9e1b0b..73bbf447d6 100644
--- a/packages/data-provider/src/types/queries.ts
+++ b/packages/data-provider/src/types/queries.ts
@@ -33,6 +33,7 @@ export type MinimalConversation = Pick<
| 'createdAt'
| 'updatedAt'
| 'archivedAt'
+ | 'isArchived'
| 'user'
| 'chatProjectId'
| 'pinned'
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index e449535240..50acbccead 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -2896,8 +2896,11 @@ export function createConversationMethods(
sortObj._id = sortOrder;
const convos = await Conversation.find(query)
+ /* `isArchived` rides along so a row can offer archive or restore from its own state:
+ the sidebar lists archived and unarchived chats in the same session, and the
+ active list also carries the unarchived pins beside them. */
.select(
- 'conversationId endpoint title createdAt updatedAt archivedAt user model agent_id assistant_id spec iconURL chatProjectId pinned',
+ 'conversationId endpoint title createdAt updatedAt archivedAt isArchived user model agent_id assistant_id spec iconURL chatProjectId pinned',
)
.sort(sortObj)
.limit(pageSize + 1)
diff --git a/packages/data-schemas/src/schema/convo.ts b/packages/data-schemas/src/schema/convo.ts
index 78ff9e6cea..e8692fe9c2 100644
--- a/packages/data-schemas/src/schema/convo.ts
+++ b/packages/data-schemas/src/schema/convo.ts
@@ -403,6 +403,12 @@ convoSchema.index({ user: 1, chatProjectId: 1, createdAt: -1, _id: -1 });
* carries the legacy group, whose rows all share a missing `archivedAt`. */
convoSchema.index({ user: 1, isArchived: 1, archivedAt: -1, createdAt: -1, _id: -1 });
+/** Sidebar list indexes for the active/archive filters: each sort carries its secondary
+ * key and `_id` tie-breaker so MongoDB can serve the cursor order without an in-memory sort. */
+convoSchema.index({ user: 1, isArchived: 1, updatedAt: -1, _id: -1 });
+convoSchema.index({ user: 1, isArchived: 1, createdAt: -1, updatedAt: -1, _id: -1 });
+convoSchema.index({ user: 1, isArchived: 1, title: 1, updatedAt: 1, _id: 1 });
+
/** The sidebar's pinned section filters on user + pinned and pages by `updatedAt`. */
convoSchema.index({ user: 1, pinned: 1, updatedAt: -1, _id: -1 });