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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🗂️ feat: Chat List Properties Menu and Project-Scoped Chats (#16246)
Marco Beretta8ffdee3b4b6c
diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.jsindex df9d4eda5b..2b8e6c02e6 100644--- a/api/server/routes/__tests__/config.spec.js+++ b/api/server/routes/__tests__/config.spec.js@@ -1101,3 +1101,52 @@ describe('passkey enrollment cap', () => {expect(anonymous.body).not.toHaveProperty('maxPasskeysPerUser');});});++describe('chat list endpoint filter limit', () => {+ it('publishes the base config limits only after authentication', async () => {+ const { AppService } = require('@librechat/data-schemas');+ const baseConfig = await AppService({+ config: { conversationList: { maxEndpointFilters: 3, maxEndpointNameLength: 40 } },+ });+ mockGetAppConfig.mockResolvedValue(baseConfig);++ const authenticated = await request(createApp(mockUser)).get('/api/config');+ expect(authenticated.status).toBe(200);+ expect(authenticated.body.conversationListLimits).toEqual({+ maxEndpointFilters: 3,+ maxEndpointNameLength: 40,+ });+ expect(mockGetAppConfig).toHaveBeenCalledWith({ baseOnly: true });++ const anonymous = await request(createApp()).get('/api/config');+ expect(anonymous.status).toBe(200);+ expect(anonymous.body).not.toHaveProperty('conversationListLimits');+ });++ it('publishes the limits the list route enforces, not a principal override', async () => {+ const { AppService } = require('@librechat/data-schemas');+ const baseConfig = await AppService({+ config: { conversationList: { maxEndpointFilters: 2 } },+ });+ const mergedConfig = await AppService({+ config: { conversationList: { maxEndpointFilters: 9 } },+ });+ mockGetAppConfig.mockImplementation(async (options) =>+ options?.baseOnly === true ? baseConfig : mergedConfig,+ );++ const response = await request(createApp(mockUser)).get('/api/config');+ expect(response.body.conversationListLimits.maxEndpointFilters).toBe(2);+ });++ it('publishes the schema defaults for a deployment that sets none', async () => {+ const { AppService } = require('@librechat/data-schemas');+ mockGetAppConfig.mockResolvedValue(await AppService({ config: {} }));++ const response = await request(createApp(mockUser)).get('/api/config');+ expect(response.body.conversationListLimits).toEqual({+ maxEndpointFilters: 50,+ maxEndpointNameLength: 128,+ });+ });+});diff --git a/api/server/routes/config.js b/api/server/routes/config.jsindex 1648edd6cf..977781c861 100644--- a/api/server/routes/config.js+++ b/api/server/routes/config.js@@ -19,6 +19,7 @@ const {isPasskeyEnabled,buildPreLoginInterface,resolveMaxPasskeysPerUser,+ loadConversationListLimits,} = require('@librechat/api');const {DEFAULT_MCP_APP_CSP_LIMITS,@@ -250,10 +251,13 @@ router.get('/', async function (req, res) {return res.status(200).send(payload);}- const appConfig = await getAppConfig({- ...getAppConfigOptionsFromUser(req.user),- failClosed: true,- });+ const [appConfig, conversationListLimits] = await Promise.all([+ getAppConfig({+ ...getAppConfigOptionsFromUser(req.user),+ failClosed: true,+ }),+ loadConversationListLimits(getAppConfig),+ ]);const codeEnvironmentDecisionVersion = resolveCodeEnvironmentDecisionVersion(process.env.CODE_ENVIRONMENT_DECISION_VERSION,);@@ -296,6 +300,7 @@ router.get('/', async function (req, res) {...preLoginPayload,...publicSharePayload,...buildPostLoginPayload(appConfig),+ conversationListLimits,sharedLinksSnapshotFilesEnabled: sharedLinksEnabled && isFileSnapshotEnabled(appConfig),socialLogins: appConfig?.registration?.socialLogins ?? defaultSocialLogins,interface: appConfig?.interfaceConfig,diff --git a/client/src/components/Conversations/ChatFilterMenu.tsx b/client/src/components/Conversations/ChatFilterMenu.tsxindex 7dd0b50bb2..91262abe89 100644--- a/client/src/components/Conversations/ChatFilterMenu.tsx+++ b/client/src/components/Conversations/ChatFilterMenu.tsx@@ -1,22 +1,31 @@-import { memo, useCallback, useId, useMemo, useState } from 'react';+import { memo, useCallback, useId, useMemo, useRef, 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 { alternateName, PermissionTypes, Permissions } from 'librechat-data-provider';import {Archive,ArrowDownAZ,+ ArrowUpDown,CalendarPlus,+ CalendarRange,Check,+ ChevronRight,Clock,ListFilter,MessagesSquare,+ Paperclip,+ Search,+ Share2,+ Plug,RotateCcw,+ SlidersHorizontal,} from 'lucide-react';-import type { ReactNode } from 'react';+import type { ReactNode, RefObject } from 'react';import type { ChatFilterStatus, ChatSortDirection, ChatSortField } from './chatFilters';import type { TranslationKeys } from '~/hooks';+import type { DateRange } from './facets';import {chatFilterCountAtom,chatFilterStatusAtom,@@ -24,17 +33,34 @@ import {chatSortAtom,isAlphabeticalSort,resetChatFiltersAtom,+ selectableBookmarks,setChatFilterStatusAtom,sortFieldsFor,toggleChatFilterTagAtom,} from './chatFilters';-import { useGetConversationTags } from '~/data-provider';+import {+ createdRangeAtom,+ DATE_RANGE_OPTIONS,+ endpointFilterAtom,+ facetFilterCountAtom,+ hasAttachmentsAtom,+ resetFacetsAtom,+ selectableEndpoints,+ sharedOnlyAtom,+ toggleEndpointFilterAtom,+ updatedRangeAtom,+} from './facets';+import { useGetConversationTags, useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';+import MinimalIcon from '~/components/Endpoints/MinimalIcon';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-hidden data-[active-item]:bg-surface-hover md:py-1.5';+/** A property row: name on the left, its current value on the right, submenu behind it. */+const rowClassName = cn(itemClassName, 'aria-expanded:bg-surface-hover');+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. */@@ -70,6 +96,93 @@ const Choice = ({ label, icon, checked, onSelect }: ChoiceProps) => (</Ariakit.MenuItem>);+type ToggleProps = {+ label: string;+ icon: ReactNode;+ checked: boolean;+ onSelect: () => void;+ /** Still announced, so a screen reader hears the option and why it cannot be taken. */+ disabled?: boolean;+};++/** A facet that is simply on or off, so it needs no submenu of its own. */+const Toggle = ({ label, icon, checked, onSelect, disabled = false }: ToggleProps) => (+ <Ariakit.MenuItem+ role="menuitemcheckbox"+ aria-checked={checked}+ hideOnClick={false}+ onClick={onSelect}+ disabled={disabled}+ accessibleWhenDisabled={true}+ className={cn(itemClassName, 'aria-disabled:cursor-not-allowed aria-disabled:opacity-50')}+ >+ <span className="text-text-secondary shrink-0" aria-hidden="true">+ {icon}+ </span>+ <span className="truncate">{label}</span>+ <CheckSlot checked={checked} />+ </Ariakit.MenuItem>+);++type PropertyRowProps = {+ icon: ReactNode;+ label: string;+ value: string;+ valueIcon?: ReactNode;+ testId?: string;+ initialFocus?: RefObject<HTMLElement | null>;+ children: ReactNode;+};++/**+ * One facet of the list, collapsed to a single row that reads as a sentence:+ * "Sort: Updated". The choices live in the submenu, so the menu opens showing+ * what the list is doing rather than every option it could take.+ */+const PropertyRow = ({+ icon,+ label,+ value,+ valueIcon,+ testId,+ initialFocus,+ children,+}: PropertyRowProps) => {+ const zIndex = usePopoverZIndex();++ return (+ <Ariakit.MenuProvider placement="right-start" focusLoop={true}>+ <Ariakit.MenuButton+ render={<Ariakit.MenuItem />}+ data-testid={testId}+ className={rowClassName}+ >+ <span className="text-text-secondary shrink-0" aria-hidden="true">+ {icon}+ </span>+ <span className="shrink-0">{label}</span>+ <span className="text-text-secondary ml-auto flex min-w-0 items-center gap-1.5 pl-4">+ {valueIcon}+ <span className="truncate">{value}</span>+ <ChevronRight className="text-text-tertiary size-4 shrink-0" aria-hidden="true" />+ </span>+ </Ariakit.MenuButton>+ <Ariakit.Menu+ portal={true}+ gutter={4}+ shift={-8}+ unmountOnHide={true}+ initialFocus={initialFocus}+ /** Portaled beside modal dialog layers, which disable pointer events on body. */+ className="popover-ui pointer-events-auto max-w-72 min-w-48"+ style={{ zIndex }}+ >+ {children}+ </Ariakit.Menu>+ </Ariakit.MenuProvider>+ );+};+const STATUS_OPTIONS: Array<{ value: ChatFilterStatus; label: TranslationKeys; icon: ReactNode }> =[{@@ -87,6 +200,12 @@ const SORT_OPTIONS: Record<ChatSortField, { label: TranslationKeys; icon: ReactNarchivedAt: { label: 'com_nav_archive_created_at', icon: <Archive className="size-4" /> },};+const DirectionGlyph = ({ direction }: { direction: ChatSortDirection }) => (+ <span className="flex size-4 shrink-0 items-center justify-center text-xs" aria-hidden="true">+ {direction === 'asc' ? '↑' : '↓'}+ </span>+);+/** Bookmarks are their own query and their own permission, so they mount with the* open menu rather than with the sidebar. */const BookmarkChoices = memo(() => {@@ -95,8 +214,7 @@ const BookmarkChoices = memo(() => {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]);+ const bookmarks = useMemo(() => selectableBookmarks(data, tags), [data, tags]);if (bookmarks.length === 0) {return (@@ -142,24 +260,533 @@ const BookmarkChoices = memo(() => {BookmarkChoices.displayName = 'BookmarkChoices';+/** One selectable value inside a facet, as the cross-category search sees it. */+type FilterOption = {+ id: string;+ label: string;+ checked: boolean;+ /** Multi-select facets render as checkboxes; a date window is one of a set. */+ multiple: boolean;+ icon: ReactNode;+ onSelect: () => void;+ disabled?: boolean;+};++type DateFacetProps = {+ label: string;+ icon: ReactNode;+ value: DateRange;+ onSelect: (value: DateRange) => void;+};++/** Updated and Created take the same windows, so they are one component twice. */+const DateFacet = ({ label, icon, value, onSelect }: DateFacetProps) => {+ const localize = useLocalize();+ const selected = DATE_RANGE_OPTIONS.find((option) => option.value === value);++ return (+ <PropertyRow icon={icon} label={label} value={localize(selected?.label ?? 'com_ui_any_time')}>+ <Ariakit.MenuGroup>+ <Ariakit.MenuGroupLabel className={groupLabelClassName}>{label}</Ariakit.MenuGroupLabel>+ {DATE_RANGE_OPTIONS.map((option) => (+ <Choice+ key={option.value}+ label={localize(option.label)}+ icon={<CalendarRange className="size-4" />}+ checked={value === option.value}+ onSelect={() => onSelect(option.value)}+ />+ ))}+ </Ariakit.MenuGroup>+ </PropertyRow>+ );+};++/**+ * What the list route accepts in one request (`conversationList`). Past `maxEndpointFilters`+ * the request would be refused and the Chats section would show its error, so further+ * endpoints are offered disabled, as they are while the post-login config that carries the+ * limits is loading. A config that failed leaves the server's own validation as the only check.+ */+const useEndpointFilterLimit = (selectedCount: number) => {+ const { data: startupConfig, isLoading } = useGetStartupConfig();+ const limits = startupConfig?.conversationListLimits;+ const limit = limits?.maxEndpointFilters;+ return {+ limit,+ maxNameLength: limits?.maxEndpointNameLength,+ atLimit: isLoading || (limit != null && selectedCount >= limit),+ };+};++const EndpointLimitNote = ({ limit }: { limit: number }) => {+ const localize = useLocalize();+ return (+ <Ariakit.MenuItem+ disabled={true}+ accessibleWhenDisabled={true}+ className={cn(itemClassName, 'text-text-secondary cursor-default')}+ >+ <span className="text-xs">{localize('com_ui_endpoint_filter_limit', { count: limit })}</span>+ </Ariakit.MenuItem>+ );+};++/** The endpoints this deployment actually serves, named the way the rest of the app+ * names them. A chat matches if it used any of the chosen ones. */+const EndpointFacet = memo(() => {+ const localize = useLocalize();+ const selected = useAtomValue(endpointFilterAtom);+ const toggleEndpoint = useSetAtom(toggleEndpointFilterAtom);+ const { data: endpointsConfig } = useGetEndpointsQuery();+ const { limit, maxNameLength, atLimit } = useEndpointFilterLimit(selected.length);++ const endpoints = useMemo(+ () =>+ selectableEndpoints(endpointsConfig, selected, maxNameLength).map((endpoint) => ({+ value: endpoint,+ label: (alternateName[endpoint] as string | undefined) ?? endpoint,+ })),+ [endpointsConfig, selected, maxNameLength],+ );++ const value = useMemo(() => {+ if (selected.length === 0) {+ return localize('com_ui_any');+ }+ if (selected.length === 1) {+ return (alternateName[selected[0]] as string | undefined) ?? selected[0];+ }+ return localize('com_ui_selected_count', { count: selected.length });+ }, [localize, selected]);++ return (+ <PropertyRow+ icon={<Plug className="size-4" />}+ label={localize('com_ui_endpoint')}+ value={value}+ >+ <Ariakit.MenuGroup>+ <Ariakit.MenuGroupLabel className={groupLabelClassName}>+ {localize('com_ui_endpoint')}+ </Ariakit.MenuGroupLabel>+ {endpoints.map((endpoint) => (+ <Toggle+ key={endpoint.value}+ label={endpoint.label}+ icon={+ <MinimalIcon+ size={16}+ model={null}+ isCreatedByUser={false}+ endpoint={endpoint.value}+ endpointsConfig={endpointsConfig}+ className="size-4"+ />+ }+ checked={selected.includes(endpoint.value)}+ onSelect={() => toggleEndpoint(endpoint.value)}+ disabled={atLimit && !selected.includes(endpoint.value)}+ />+ ))}+ {atLimit && limit != null && <EndpointLimitNote limit={limit} />}+ </Ariakit.MenuGroup>+ </PropertyRow>+ );+});++EndpointFacet.displayName = 'EndpointFacet';++/**+ * A facet list long enough to scan is long enough to search. The field owns focus+ * when the submenu opens, so typing narrows immediately, and ArrowDown hands the+ * keyboard back to the rows rather than stranding it in the input.+ */+const FacetSearch = ({+ value,+ onChange,+ inputRef,+}: {+ value: string;+ onChange: (next: string) => void;+ inputRef?: RefObject<HTMLInputElement>;+}) => {+ const localize = useLocalize();+ const menu = Ariakit.useMenuContext();+ const inputId = useId();++ return (+ <div className="px-1 pt-0.5 pb-1.5">+ <label className="sr-only" htmlFor={inputId}>+ {localize('com_ui_search_filters')}+ </label>+ <div className="text-text-secondary focus-within:text-text-primary flex items-center gap-2 rounded-lg px-1">+ <Search className="size-4 shrink-0" aria-hidden="true" />+ <input+ id={inputId}+ ref={inputRef}+ type="text"+ value={value}+ autoComplete="off"+ placeholder={localize('com_ui_search_filters')}+ onChange={(event) => onChange(event.target.value)}+ onKeyDown={(event) => {+ if (event.key !== 'ArrowDown') {+ return;+ }+ event.preventDefault();+ menu?.move(menu.first());+ }}+ className="text-text-primary placeholder:text-text-tertiary w-full bg-transparent py-1 text-sm outline-hidden"+ />+ </div>+ </div>+ );+};++/**+ * Everything that narrows the list, one level in: bookmarks, the two date windows,+ * the endpoint a chat ran on, and the two flags. Keeping them here rather than at the+ * root is what lets the menu grow a facet without growing a screenful.+ */+const FilterFacets = ({+ showBookmarks,+ searchRef,+}: {+ showBookmarks: boolean;+ searchRef?: RefObject<HTMLInputElement>;+}) => {+ const localize = useLocalize();+ const [search, setSearch] = useState('');+ const updatedRange = useAtomValue(updatedRangeAtom);+ const createdRange = useAtomValue(createdRangeAtom);+ const hasAttachments = useAtomValue(hasAttachmentsAtom);+ const sharedOnly = useAtomValue(sharedOnlyAtom);+ const tags = useAtomValue(chatFilterTagsAtom);+ const facetCount = useAtomValue(facetFilterCountAtom);+ const selectedEndpoints = useAtomValue(endpointFilterAtom);+ const setUpdatedRange = useSetAtom(updatedRangeAtom);+ const setCreatedRange = useSetAtom(createdRangeAtom);+ const setHasAttachments = useSetAtom(hasAttachmentsAtom);+ const setSharedOnly = useSetAtom(sharedOnlyAtom);+ const setTags = useSetAtom(chatFilterTagsAtom);+ const toggleTag = useSetAtom(toggleChatFilterTagAtom);+ const toggleEndpoint = useSetAtom(toggleEndpointFilterAtom);+ const resetFacets = useSetAtom(resetFacetsAtom);++ /** Searching reaches into the categories, so both lists have to be here rather than+ * inside the submenu that normally owns them. Both are cached queries. The bookmark+ * one stays off without `BOOKMARKS:USE`, whose route would only answer 403. */+ const { data: bookmarkData } = useGetConversationTags({ enabled: showBookmarks });+ const { data: endpointsConfig } = useGetEndpointsQuery();+ const { atLimit: endpointsAtLimit, maxNameLength: endpointNameLimit } = useEndpointFilterLimit(+ selectedEndpoints.length,+ );+ /** A deployment with sharing switched off has no shared chats to filter to. */+ const { data: startupConfig } = useGetStartupConfig();+ const showShared = startupConfig?.sharedLinksEnabled === true;++ const query = search.trim().toLowerCase();++ /**+ * Every value a person can filter by, flattened. A query matches an option by its own+ * name or by the name of the category it belongs to, so "endpoint" offers every+ * endpoint and "anthropic" offers the one.+ */+ const results = useMemo(() => {+ if (query === '') {+ return [];+ }++ const groups: Array<{ category: string; options: FilterOption[] }> = [];+ const collect = (category: string, options: FilterOption[]) => {+ const categoryMatches = category.toLowerCase().includes(query);+ const matched = categoryMatches+ ? options+ : options.filter((option) => option.label.toLowerCase().includes(query));+ if (matched.length > 0) {+ groups.push({ category, options: matched });+ }+ };++ if (showBookmarks) {+ collect(+ localize('com_ui_bookmarks'),+ selectableBookmarks(bookmarkData, tags).map((bookmark) => ({+ id: `bookmark:${bookmark.tag}`,+ label: bookmark.tag,+ checked: tags.includes(bookmark.tag),+ multiple: true,+ icon: tags.includes(bookmark.tag) ? <BookmarkFilledIcon /> : <BookmarkIcon />,+ onSelect: () => toggleTag(bookmark.tag),+ })),+ );+ }++ const dateOptions = (value: DateRange, onSelect: (next: DateRange) => void) =>+ DATE_RANGE_OPTIONS.map((option) => ({+ id: `${option.value}`,+ label: localize(option.label),+ checked: value === option.value,+ multiple: false,+ icon: <CalendarRange />,+ onSelect: () => onSelect(option.value),+ }));++ collect(+ localize('com_ui_sort_updated'),+ dateOptions(updatedRange, setUpdatedRange).map((option) => ({+ ...option,+ id: `updated:${option.id}`,+ })),+ );+ collect(+ localize('com_ui_sort_created'),+ dateOptions(createdRange, setCreatedRange).map((option) => ({+ ...option,+ id: `created:${option.id}`,+ })),+ );++ collect(+ localize('com_ui_endpoint'),+ selectableEndpoints(endpointsConfig, selectedEndpoints, endpointNameLimit).map(+ (endpoint) => ({+ id: `endpoint:${endpoint}`,+ label: (alternateName[endpoint] as string | undefined) ?? endpoint,+ checked: selectedEndpoints.includes(endpoint),+ disabled: endpointsAtLimit && !selectedEndpoints.includes(endpoint),+ multiple: true,+ icon: (+ <MinimalIcon+ size={16}+ model={null}+ isCreatedByUser={false}+ endpoint={endpoint}+ endpointsConfig={endpointsConfig}+ className="size-4"+ />+ ),+ onSelect: () => toggleEndpoint(endpoint),+ }),+ ),+ );++ /** A flag is its own category and its own single option. */+ collect(localize('com_ui_attachments'), [+ {+ id: 'has-attachments',+ label: localize('com_ui_has_attachments'),+ checked: hasAttachments,+ multiple: true,+ icon: <Paperclip />,+ onSelect: () => setHasAttachments(!hasAttachments),+ },+ ]);++ if (showShared) {+ collect(localize('com_ui_sharing'), [+ {+ id: 'shared-only',+ label: localize('com_ui_shared_only'),+ checked: sharedOnly,+ multiple: true,+ icon: <Share2 />,+ onSelect: () => setSharedOnly(!sharedOnly),+ },+ ]);+ }++ return groups;+ }, [+ query,+ showBookmarks,+ localize,+ bookmarkData,+ tags,+ toggleTag,+ updatedRange,+ setUpdatedRange,+ createdRange,+ setCreatedRange,+ endpointsConfig,+ selectedEndpoints,+ endpointsAtLimit,+ endpointNameLimit,+ toggleEndpoint,+ hasAttachments,+ setHasAttachments,+ showShared,+ sharedOnly,+ setSharedOnly,+ ]);++ const facets = [+ showBookmarks ? <BookmarkFacet key="bookmarks" /> : null,+ <DateFacet+ key="updated"+ label={localize('com_ui_sort_updated')}+ icon={<Clock className="size-4" />}+ value={updatedRange}+ onSelect={setUpdatedRange}+ />,+ <DateFacet+ key="created"+ label={localize('com_ui_sort_created')}+ icon={<CalendarPlus className="size-4" />}+ value={createdRange}+ onSelect={setCreatedRange}+ />,+ <EndpointFacet key="endpoint" />,+ ].filter(Boolean);++ const flags = [+ <Toggle+ key="attachments"+ label={localize('com_ui_has_attachments')}+ icon={<Paperclip className="size-4" />}+ checked={hasAttachments}+ onSelect={() => setHasAttachments(!hasAttachments)}+ />,+ showShared ? (+ <Toggle+ key="shared"+ label={localize('com_ui_shared_only')}+ icon={<Share2 className="size-4" />}+ checked={sharedOnly}+ onSelect={() => setSharedOnly(!sharedOnly)}+ />+ ) : null,+ ].filter(Boolean);++ /** The reset belongs to what this submenu owns: the facets and the bookmarks,+ * not the sort and the view sitting a level up. */+ const narrowingCount = facetCount + (tags.length > 0 ? 1 : 0);+ const clearFilters = () => {+ resetFacets();+ setTags([]);+ };++ return (+ <>+ <FacetSearch value={search} onChange={setSearch} inputRef={searchRef} />++ {query === '' ? (+ <>+ {facets}+ <Ariakit.MenuSeparator className="border-border-medium my-1 h-px" />+ {flags}+ </>+ ) : (+ <>+ {results.map((group) => (+ <Ariakit.MenuGroup key={group.category}>+ <Ariakit.MenuGroupLabel className={groupLabelClassName}>+ {group.category}+ </Ariakit.MenuGroupLabel>+ {group.options.map((option) =>+ option.multiple ? (+ <Toggle+ key={option.id}+ label={option.label}+ icon={option.icon}+ checked={option.checked}+ onSelect={option.onSelect}+ disabled={option.disabled}+ />+ ) : (+ <Choice+ key={option.id}+ label={option.label}+ icon={option.icon}+ checked={option.checked}+ onSelect={option.onSelect}+ />+ ),+ )}+ </Ariakit.MenuGroup>+ ))}+ {results.length === 0 && (+ <Ariakit.MenuItem+ disabled={true}+ className={cn(itemClassName, 'text-text-secondary cursor-default')}+ >+ <span className="truncate text-xs">{localize('com_ui_no_results_found')}</span>+ </Ariakit.MenuItem>+ )}+ </>+ )}++ <Ariakit.MenuSeparator className="border-border-medium my-1 h-px" />+ <Ariakit.MenuItem+ hideOnClick={false}+ disabled={narrowingCount === 0}+ onClick={clearFilters}+ 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>+ </>+ );+};++/** Bookmarks keep their own row so the count of chosen tags stays visible one level up. */+const BookmarkFacet = () => {+ const localize = useLocalize();+ const tags = useAtomValue(chatFilterTagsAtom);++ /** One bookmark names itself; several are worth a count, none reads as "None". */+ const value = useMemo(() => {+ if (tags.length === 0) {+ return localize('com_ui_none');+ }+ if (tags.length === 1) {+ return tags[0];+ }+ return localize('com_ui_selected_count', { count: tags.length });+ }, [localize, tags]);++ return (+ <PropertyRow+ icon={<BookmarkIcon className="size-4" />}+ label={localize('com_ui_bookmarks')}+ value={value}+ testId="chat-filter-bookmarks"+ >+ <Ariakit.MenuGroup>+ <Ariakit.MenuGroupLabel className={groupLabelClassName}>+ {localize('com_ui_bookmarks')}+ </Ariakit.MenuGroupLabel>+ <BookmarkChoices />+ </Ariakit.MenuGroup>+ </PropertyRow>+ );+};+/*** 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.+ * Chats heading: which chats (active or archived), what orders them, and what they+ * must match. Each facet is a row carrying its current value, so the menu is read at+ * a glance and only the facet being changed expands.*/const ChatFilterMenu = () => {const localize = useLocalize();const menuId = useId();const zIndex = usePopoverZIndex();+ const facetSearchRef = useRef<HTMLInputElement>(null);const [isOpen, setIsOpen] = useState(false);const status = useAtomValue(chatFilterStatusAtom);const sort = useAtomValue(chatSortAtom);+ const tags = useAtomValue(chatFilterTagsAtom);const activeCount = useAtomValue(chatFilterCountAtom);+ const facetCount = useAtomValue(facetFilterCountAtom);const setStatus = useSetAtom(setChatFilterStatusAtom);const setSort = useSetAtom(chatSortAtom);const resetFilters = useSetAtom(resetChatFiltersAtom);+ const resetAllFacets = useSetAtom(resetFacetsAtom);const hasAccessToBookmarks = useHasAccess({permissionType: PermissionTypes.BOOKMARKS,@@ -196,9 +823,27 @@ const ChatFilterMenu = () => {[setSort, sort.direction, sort.field],);+ const statusOption = STATUS_OPTIONS.find((option) => option.value === status);++ /** Bookmarks sit inside Filter now, so the row counts them alongside the rest. */+ const narrowingCount = facetCount + (tags.length > 0 ? 1 : 0);+ const filterValue =+ narrowingCount === 0+ ? localize('com_ui_none')+ : localize('com_ui_active_count', { count: narrowingCount });++ const totalCount = activeCount + facetCount;++ /** The header's Reset undoes the whole menu, sort and view included; the one inside+ * Filter clears only what that submenu owns. */+ const resetAll = useCallback(() => {+ resetFilters();+ resetAllFacets();+ }, [resetAllFacets, resetFilters]);+const triggerLabel =- activeCount > 0- ? localize('com_ui_filters_active', { count: activeCount })+ totalCount > 0+ ? localize('com_ui_filters_active', { count: totalCount }): localize('com_ui_filter_and_sort_chats');return (@@ -209,17 +854,17 @@ const ChatFilterMenu = () => {<Ariakit.MenuButtonid="chat-filter-menu-button"aria-label={triggerLabel}- aria-pressed={activeCount > 0}+ aria-pressed={totalCount > 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',+ (isOpen || totalCount > 0) && 'bg-surface-active-alt text-text-primary',)}><ListFilter aria-hidden="true" className="size-4" />- {activeCount > 0 && (+ {totalCount > 0 && (<spanclassName="bg-text-primary absolute top-0.5 right-0.5 size-1.5 rounded-full"aria-hidden="true"@@ -233,86 +878,105 @@ const ChatFilterMenu = () => {portal={true}gutter={8}unmountOnHide={true}- className="popover-ui max-w-72 min-w-56"+ aria-label={localize('com_ui_filter_and_sort_chats')}+ className="popover-ui pointer-events-auto max-w-80 min-w-60"/** Portaled beside modal dialog layers, which disable pointer events on body. */- style={{ zIndex, pointerEvents: 'auto' }}+ style={{ zIndex }}>- <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="border-border-medium my-1 h-px" />-- <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="border-border-medium my-1 h-px" />-- <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>+ <div className="flex items-center justify-between gap-2 px-2 pt-0.5 pb-1.5">+ <span className="text-text-secondary text-xs font-medium">+ {localize('com_ui_chat_list')}+ </span>+ <Ariakit.MenuItem+ hideOnClick={false}+ disabled={totalCount === 0}+ onClick={resetAll}+ data-testid="chat-filter-reset-all"+ className={cn(+ /** The size and radius of the chip the empty state offers, so the two+ * ways out of a filter are the same control in two places. It stays a+ * MenuItem: a button here would leave the menu's arrow keys behind. */+ buttonVariants({ variant: 'ghost', size: 'xs' }),+ 'text-text-secondary cursor-pointer font-medium outline-hidden',+ 'aria-disabled:hover:text-text-secondary aria-disabled:opacity-50',+ 'data-[active-item]:bg-surface-hover data-[active-item]:text-text-primary',+ )}+ >+ {localize('com_ui_reset')}+ </Ariakit.MenuItem>+ </div>- {hasAccessToBookmarks && (- <>- <Ariakit.MenuSeparator className="border-border-medium my-1 h-px" />- <Ariakit.MenuGroup>- <Ariakit.MenuGroupLabel className={groupLabelClassName}>- {localize('com_ui_bookmarks')}- </Ariakit.MenuGroupLabel>- <BookmarkChoices />- </Ariakit.MenuGroup>- </>- )}-- <Ariakit.MenuSeparator className="border-border-medium my-1 h-px" />- <Ariakit.MenuItem- hideOnClick={false}- disabled={activeCount === 0}- onClick={() => resetFilters()}- className={cn(itemClassName, 'text-text-secondary aria-disabled:opacity-50')}- data-testid="chat-filter-reset"+ <PropertyRow+ icon={<MessagesSquare className="size-4" />}+ label={localize('com_ui_show')}+ value={statusOption ? localize(statusOption.label) : ''}+ testId="chat-filter-show"+ >+ <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>+ </PropertyRow>++ <PropertyRow+ icon={<ArrowUpDown className="size-4" />}+ label={localize('com_ui_sort')}+ value={localize(SORT_OPTIONS[sort.field].label)}+ valueIcon={<DirectionGlyph direction={sort.direction} />}+ testId="chat-filter-sort"+ >+ <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="border-border-medium my-1 h-px" />++ <Ariakit.MenuGroup>+ <Ariakit.MenuGroupLabel className={groupLabelClassName}>+ {localize('com_ui_sort_order')}+ </Ariakit.MenuGroupLabel>+ {directionOptions.map((option) => (+ <Choice+ key={option.value}+ label={option.label}+ icon={<DirectionGlyph direction={option.value} />}+ checked={sort.direction === option.value}+ onSelect={() => setSort({ field: sort.field, direction: option.value })}+ />+ ))}+ </Ariakit.MenuGroup>+ </PropertyRow>++ <PropertyRow+ icon={<SlidersHorizontal className="size-4" />}+ label={localize('com_ui_filter')}+ value={filterValue}+ testId="chat-filter-facets"+ initialFocus={facetSearchRef}>- <RotateCcw className="size-4 shrink-0" aria-hidden="true" />- <span className="truncate">{localize('com_ui_clear_filters')}</span>- </Ariakit.MenuItem>+ <FilterFacets showBookmarks={hasAccessToBookmarks} searchRef={facetSearchRef} />+ </PropertyRow></Ariakit.Menu></Ariakit.MenuProvider>);diff --git a/client/src/components/Conversations/Conversations.tsx b/client/src/components/Conversations/Conversations.tsxindex 33b2fea2d0..be4dce2c64 100644--- a/client/src/components/Conversations/Conversations.tsx+++ b/client/src/components/Conversations/Conversations.tsx@@ -2,11 +2,19 @@ import { useMemo, memo, type FC, useCallback, useEffect, useRef } from 'react';import { useDrop } from 'react-dnd';import throttle from 'lodash/throttle';import { useRecoilValue } from 'recoil';-import { ChevronDown } from 'lucide-react';import { useAtomValue, useSetAtom } from 'jotai';import { List, CellMeasurer, CellMeasurerCache } from 'react-virtualized';-import { Spinner, useMediaQuery, buttonVariants } from '@librechat/client';+import { Button, EmptyState, Spinner, useMediaQuery, buttonVariants } from '@librechat/client';+import {+ Archive,+ ChevronDown,+ MessageSquareDashed,+ MessageSquareOff,+ SearchX,+ TriangleAlert,+} from 'lucide-react';import type { TConversation } from 'librechat-data-provider';+import type { LucideIcon } from 'lucide-react';import type { ReactNode } from 'react';import type { ConversationDragItem } from './dnd';import {@@ -25,7 +33,7 @@ import {useUnpinDroppedConversation,} from './dnd';import { useLocalize, TranslationKeys, useElementSize, useOuterScrollWindow } from '~/hooks';-import { groupConversationsWithRunning, RUNNING_CHATS_GROUP } from './running';+import { facetFilterCountAtom, resetFacetsAtom } from './facets';import { groupConversations, cn } from '~/utils';import { useActiveJobs } from '~/data-provider';import Convo from './Convo';@@ -65,6 +73,10 @@ interface ConversationsProps {/** Wrapper around everything inside that viewport, whose height changes when a* section above the list expands or collapses. */scrollContent: HTMLElement | null;+ /** The account holds projects, rendered above this list. The Chats section asks for+ * chats that belong to no project, so its emptiness then means "everything is filed"+ * rather than "the account has nothing". */+ accountHasProjects?: boolean;}interface MeasuredRowProps {@@ -103,9 +115,9 @@ const LoadingSpinner = memo(() => {const localize = useLocalize();return (- <div className="mx-auto mt-2 flex items-center justify-center gap-2">- <Spinner className="text-text-primary" />- <span className="text-text-primary animate-pulse">{localize('com_ui_loading')}</span>+ <div className="text-text-primary mx-auto mt-2 flex items-center justify-center gap-2">+ <Spinner className="m-0" />+ <span className="shimmer">{localize('com_ui_loading')}</span></div>);});@@ -164,8 +176,10 @@ const DateLabel: FC<{ groupName: string; isFirst?: boolean; isAlphabetical?: booisAlphabetical ? 'com_a11y_chats_alpha_section' : 'com_a11y_chats_date_section',isAlphabetical ? { letter: displayName } : { date: displayName },)}- className={cn('text-text-secondary pt-0.5 pl-1', isFirst === true ? 'mt-0' : 'mt-1.5')}- style={{ fontSize: '0.7rem' }}+ className={cn(+ 'text-text-secondary pt-0.5 pl-1 text-xs',+ isFirst === true ? 'mt-0' : 'mt-1.5',+ )}>{displayName}</h2>@@ -196,6 +210,7 @@ const Conversations: FC<ConversationsProps> = ({onRetry,scrollViewport,scrollContent,+ accountHasProjects = false,}) => {const localize = useLocalize();const search = useRecoilValue(store.search);@@ -203,7 +218,19 @@ const Conversations: FC<ConversationsProps> = ({const isArchivedView = useAtomValue(isArchivedChatViewAtom);const activeFilterCount = useAtomValue(chatFilterCountAtom);const filterTags = useAtomValue(chatFilterTagsAtom);+ /** Date, endpoint and attachment facets narrow the same list as the bookmark tags,+ * so an empty result under either has to read as "nothing matched", not as an+ * account with no chats in it. */+ const facetFilterCount = useAtomValue(facetFilterCountAtom);const resetFilters = useSetAtom(resetChatFiltersAtom);+ const resetFacets = useSetAtom(resetFacetsAtom);+ /** What the menu's Reset clears, counted the same way: the empty state offers the+ * way out of every narrowing, not only of the ones the tag filters know about. */+ const narrowedCount = activeFilterCount + facetFilterCount;+ const clearNarrowing = useCallback(() => {+ resetFilters();+ resetFacets();+ }, [resetFilters, resetFacets]);const isSmallScreen = useMediaQuery('(max-width: 768px)');/* Dropping a chat on the Chats section makes it an ordinary chat: out of its* project, and unpinned. A root-list chat that is not pinned already is one,@@ -512,7 +539,11 @@ const Conversations: FC<ConversationsProps> = ({* 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;+ !search.query &&+ filterTags.length === 0 &&+ facetFilterCount === 0 &&+ !isArchivedView &&+ filteredConversations.length > 0;const isEmpty =isChatsExpanded &&!isLoading &&@@ -522,14 +553,28 @@ const Conversations: FC<ConversationsProps> = ({groupedConversations.length === 0 &&!hasUnfilteredRows;+ /** Which dead end this is decides both the line and the glyph above it: a search+ * that found nothing, a filter that matched nothing, an empty archive, an account+ * whose chats all live under projects, and an account with no chats yet are five+ * different situations wearing one sentence. */let emptyLabel: TranslationKeys = 'com_ui_no_chats';+ let emptyIcon: LucideIcon = MessageSquareDashed;if (search.query) {emptyLabel = 'com_ui_no_search_results';- } else if (filterTags.length > 0) {+ emptyIcon = SearchX;+ } else if (filterTags.length > 0 || facetFilterCount > 0) {emptyLabel = 'com_ui_no_chats_match_filters';+ emptyIcon = MessageSquareOff;} else if (isArchivedView) {emptyLabel = 'com_ui_no_archived_chats';+ emptyIcon = Archive;+ } else if (accountHasProjects) {+ emptyLabel = 'com_ui_no_unassigned_chats';+ emptyIcon = MessageSquareDashed;}+ /** Nothing has been narrowed: the list is empty because the account is. That reads+ * as a heading, where the narrowed states are a single line under the glyph. */+ const isUntouched = emptyLabel === 'com_ui_no_chats';let body: ReactNode = (<div ref={setListNode} className="flex-1">@@ -549,53 +594,52 @@ const Conversations: FC<ConversationsProps> = ({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="text-text-primary ml-2">{localize('com_ui_loading')}</span>+ <div className="text-text-primary flex flex-1 items-center justify-center">+ <Spinner className="m-0" />+ <span className="shimmer ml-2">{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"+ className="flex flex-1 items-center justify-center"data-testid="convo-list-error"role="alert">- <span className="text-text-secondary text-sm">{localize('com_ui_chats_load_error')}</span>- {onRetry && (- <button- type="button"- onClick={onRetry}- className="text-text-primary focus-visible:ring-text-primary rounded-lg px-2 py-1 text-sm underline-offset-2 hover:underline focus-visible:ring-2 focus-visible:outline-hidden"- >- {localize('com_ui_retry')}- </button>- )}+ <EmptyState+ icon={TriangleAlert}+ title={localize('com_ui_chats_load_error')}+ action={+ onRetry && (+ <Button type="button" variant="outline" size="sm" onClick={onRetry}>+ {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-text-secondary text-sm">{localize(emptyLabel)}</span>- {activeFilterCount > 0 && (- <button- type="button"- onClick={() => resetFilters()}- className="text-text-primary focus-visible:ring-text-primary rounded-lg px-2 py-1 text-sm underline-offset-2 hover:underline focus-visible:ring-2 focus-visible:outline-hidden"- >- {localize('com_ui_clear_filters')}- </button>- )}+ <div className="flex flex-1 items-center justify-center" data-testid="convo-list-empty">+ <EmptyState+ icon={emptyIcon}+ title={isUntouched ? localize(emptyLabel) : undefined}+ description={isUntouched ? undefined : localize(emptyLabel)}+ action={+ narrowedCount > 0 && (+ <Button type="button" variant="secondary" size="xs" onClick={clearNarrowing}>+ {localize('com_ui_clear_filters')}+ </Button>+ )+ }+ /></div>);}diff --git a/client/src/components/Conversations/ProjectsSection.tsx b/client/src/components/Conversations/ProjectsSection.tsxindex 554f949245..108bde61fd 100644--- a/client/src/components/Conversations/ProjectsSection.tsx+++ b/client/src/components/Conversations/ProjectsSection.tsx@@ -89,7 +89,7 @@ const ProjectChatsInline = memo(function ProjectChatsInline({);/** Collapse keeps its children mounted, so without this every project row in* the sidebar would fetch its chats on load whether or not it is open. */- const { data, isLoading } = useConversationsInfiniteQuery(+ const { data, isLoading, isError, refetch } = useConversationsInfiniteQuery({ projectId, sortBy: 'updatedAt', sortDirection: 'desc' },{ staleTime: 30000, cacheTime: 300000, enabled: expanded },);@@ -115,6 +115,23 @@ const ProjectChatsInline = memo(function ProjectChatsInline({);}+ /** Chats scopes itself to chats outside any project, so a project whose own list failed+ * says so and offers a retry rather than reading as empty. */+ if (isError && conversations.length === 0) {+ return (+ <div+ className="text-text-secondary flex items-center gap-1 py-1.5 pl-2 text-xs"+ data-testid={`project-chats-error-${projectId}`}+ role="alert"+ >+ <span>{localize('com_ui_chats_load_error')}</span>+ <Button type="button" variant="ghost" size="sm" onClick={() => refetch()}>+ {localize('com_ui_retry')}+ </Button>+ </div>+ );+ }+if (conversations.length === 0) {return (<div className="text-text-secondary py-1.5 pl-2 text-xs">diff --git a/client/src/components/Conversations/__tests__/Conversations.test.tsx b/client/src/components/Conversations/__tests__/Conversations.test.tsxindex 53bdb3a412..a297b3332c 100644--- a/client/src/components/Conversations/__tests__/Conversations.test.tsx+++ b/client/src/components/Conversations/__tests__/Conversations.test.tsx@@ -1,4 +1,5 @@import React, { createRef } from 'react';+import { getDefaultStore } from 'jotai';import { fireEvent, render, screen } from '@testing-library/react';import '@testing-library/jest-dom';import { RecoilRoot } from 'recoil';@@ -7,6 +8,7 @@ import { HTML5Backend } from 'react-dnd-html5-backend';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import type { CellMeasurerCache, List } from 'react-virtualized';import type { TConversation } from 'librechat-data-provider';+import { hasAttachmentsAtom, resetFacetsAtom } from '../facets';import Conversations from '../Conversations';import store from '~/store';@@ -75,6 +77,26 @@ jest.mock('~/hooks', () => ({jest.mock('@librechat/client', () => ({/* The section headers compose through the shared variant recipe. */buttonVariants: () => '',+ Button: ({ children, ...props }: React.ComponentProps<'button'>) => (+ <button {...props}>{children}</button>+ ),+ /* The empty and error states are the shared panel state, rendered here with the+ glyph dropped: what these tests read is the line and its action. */+ EmptyState: ({+ title,+ description,+ action,+ }: {+ title?: string;+ description?: string;+ action?: React.ReactNode;+ }) => (+ <div>+ {title != null && <p>{title}</p>}+ {description != null && <p>{description}</p>}+ {action}+ </div>+ ),Spinner: () => <div data-testid="spinner" />,useMediaQuery: () => false,useToastContext: () => ({ showToast: jest.fn() }),@@ -406,3 +428,55 @@ describe('Conversations: all-pin pages still paginate', () => {expect(loadMoreConversations).toHaveBeenCalledTimes(1);});});++describe('Conversations: the empty state offers the way back', () => {+ const containerRef = createRef<List>();+ const jotaiStore = getDefaultStore();++ afterEach(() => {+ jotaiStore.set(resetFacetsAtom);+ });++ const renderEmpty = () =>+ render(+ <QueryClientProvider client={queryClient}>+ <DndProvider backend={HTML5Backend}>+ <RecoilRoot>+ <Conversations+ conversations={[]}+ moveToTop={jest.fn()}+ toggleNav={jest.fn()}+ containerRef={containerRef}+ loadMoreConversations={jest.fn()}+ isLoading={false}+ isSearchLoading={false}+ isChatsExpanded={true}+ setIsChatsExpanded={jest.fn()}+ scrollViewport={null}+ scrollContent={null}+ />+ </RecoilRoot>+ </DndProvider>+ </QueryClientProvider>,+ );++ it('says the account is empty, with nothing to clear', () => {+ const { getByTestId, queryByRole } = renderEmpty();++ expect(getByTestId('convo-list-empty')).toHaveTextContent('com_ui_no_chats');+ expect(queryByRole('button', { name: 'com_ui_clear_filters' })).not.toBeInTheDocument();+ });++ /** A facet narrows the same list the bookmark tags do, so an empty result under one+ * has to read as "nothing matched" and carry the same way out. */+ it('offers to clear a facet that matched nothing', () => {+ jotaiStore.set(hasAttachmentsAtom, true);+ const { getByTestId, getByRole } = renderEmpty();++ expect(getByTestId('convo-list-empty')).toHaveTextContent('com_ui_no_chats_match_filters');++ fireEvent.click(getByRole('button', { name: 'com_ui_clear_filters' }));++ expect(jotaiStore.get(hasAttachmentsAtom)).toBe(false);+ });+});diff --git a/client/src/components/Conversations/__tests__/chatFilters.spec.ts b/client/src/components/Conversations/__tests__/chatFilters.spec.tsnew file mode 100644index 0000000000..a61ea659c3--- /dev/null+++ b/client/src/components/Conversations/__tests__/chatFilters.spec.ts@@ -0,0 +1,56 @@+import { createStore } from 'jotai';+import type { TConversationTag } from 'librechat-data-provider';+import {+ chatFilterCountAtom,+ chatFilterStatusAtom,+ chatFilterTagsAtom,+ selectableBookmarks,+} from '../chatFilters';++describe('chatFilterCountAtom', () => {+ it('counts nothing while every property is at its default', () => {+ expect(createStore().get(chatFilterCountAtom)).toBe(0);+ });++ it('counts bookmarks once, however many are selected', () => {+ const store = createStore();+ store.set(chatFilterTagsAtom, ['work', 'travel', 'ideas']);+ expect(store.get(chatFilterCountAtom)).toBe(1);+ });++ it('adds the archived view to the bookmark group', () => {+ const store = createStore();+ store.set(chatFilterTagsAtom, ['work', 'travel']);+ store.set(chatFilterStatusAtom, 'archived');+ expect(store.get(chatFilterCountAtom)).toBe(2);+ });+});++describe('selectableBookmarks', () => {+ const tag = (name: string, count: number): TConversationTag => ({+ _id: name,+ user: 'user',+ tag: name,+ count,+ position: 0,+ createdAt: '',+ updatedAt: '',+ });++ it('offers the bookmarks some chat carries', () => {+ const choices = selectableBookmarks([tag('work', 2), tag('unused', 0)], []);+ expect(choices.map((choice) => choice.tag)).toEqual(['work']);+ });++ it('keeps a selected bookmark no chat carries any more', () => {+ const choices = selectableBookmarks([tag('work', 2), tag('unused', 0)], ['unused']);+ expect(choices.map((choice) => choice.tag)).toEqual(['work', 'unused']);+ });++ it('keeps a selected bookmark that was deleted', () => {+ expect(selectableBookmarks([tag('work', 2)], ['gone'])).toEqual([+ tag('work', 2),+ { tag: 'gone', count: 0 },+ ]);+ });+});diff --git a/client/src/components/Conversations/__tests__/facets.spec.ts b/client/src/components/Conversations/__tests__/facets.spec.tsnew file mode 100644index 0000000000..db2154fd38--- /dev/null+++ b/client/src/components/Conversations/__tests__/facets.spec.ts@@ -0,0 +1,173 @@+import { createStore } from 'jotai';+import type { TEndpointsConfig } from 'librechat-data-provider';+import {+ chatFacetParamsAtom,+ createdRangeAtom,+ endpointFilterAtom,+ facetFilterCountAtom,+ hasAttachmentsAtom,+ localDayStartAtom,+ rangeCutoff,+ sharedOnlyAtom,+ resetFacetsAtom,+ selectableEndpoints,+ toggleEndpointFilterAtom,+ updatedRangeAtom,+} from '../facets';++describe('rangeCutoff', () => {+ const now = new Date(2026, 8, 20, 15, 42, 7, 123);++ it('has no cutoff for "any time"', () => {+ expect(rangeCutoff('any', now)).toBeUndefined();+ });++ it('snaps to local midnight so the cutoff is stable within a day', () => {+ const morning = rangeCutoff('today', new Date(2026, 8, 20, 0, 0, 1));+ const evening = rangeCutoff('today', new Date(2026, 8, 20, 23, 59, 59));++ expect(morning?.getTime()).toBe(evening?.getTime());+ expect(morning?.getHours()).toBe(0);+ expect(morning?.getMinutes()).toBe(0);+ });++ it('counts today as the first of the previous-N-days windows', () => {+ /** "Previous 7 days" is today plus the six before it, not 7 x 24 hours. */+ expect(rangeCutoff('week', now)).toEqual(new Date(2026, 8, 14));+ expect(rangeCutoff('month', now)).toEqual(new Date(2026, 7, 22));+ });++ it('crosses a month boundary correctly', () => {+ expect(rangeCutoff('week', new Date(2026, 8, 3, 9, 0))).toEqual(new Date(2026, 7, 28));+ });+});++describe('chatFacetParamsAtom', () => {+ it('sends nothing while every facet is at its default', () => {+ const store = createStore();++ expect(store.get(chatFacetParamsAtom)).toEqual({+ updatedAfter: undefined,+ createdAfter: undefined,+ endpoints: undefined,+ hasFiles: undefined,+ sharedOnly: undefined,+ });+ expect(store.get(facetFilterCountAtom)).toBe(0);+ });++ it('sends the shared flag only when it is on', () => {+ const store = createStore();+ expect(store.get(chatFacetParamsAtom).sharedOnly).toBeUndefined();++ store.set(sharedOnlyAtom, true);+ expect(store.get(chatFacetParamsAtom).sharedOnly).toBe(true);+ expect(store.get(facetFilterCountAtom)).toBe(1);+ });++ it('shapes each facet as the list parameter the server takes', () => {+ const store = createStore();+ store.set(updatedRangeAtom, 'week');+ store.set(createdRangeAtom, 'today');+ store.set(toggleEndpointFilterAtom, 'openAI');+ store.set(hasAttachmentsAtom, true);+ store.set(sharedOnlyAtom, true);++ const params = store.get(chatFacetParamsAtom);++ expect(typeof params.updatedAfter).toBe('string');+ expect(new Date(params.updatedAfter as string).getTime()).not.toBeNaN();+ expect(typeof params.createdAfter).toBe('string');+ expect(params.endpoints).toEqual(['openAI']);+ expect(params.hasFiles).toBe(true);+ expect(params.sharedOnly).toBe(true);+ expect(store.get(facetFilterCountAtom)).toBe(5);+ });++ it('keeps the params identical across reads so the query key does not churn', () => {+ const store = createStore();+ store.set(updatedRangeAtom, 'week');++ expect(store.get(chatFacetParamsAtom).updatedAfter).toBe(+ store.get(chatFacetParamsAtom).updatedAfter,+ );+ });++ it('advances the cutoff when the local day anchor moves past midnight', () => {+ /** A derived atom caches until a source changes, so the cutoff follows the day+ * anchor rather than the clock: a tab open across midnight must not keep serving+ * yesterday's "today". */+ const store = createStore();+ store.set(localDayStartAtom, new Date(2026, 8, 20).getTime());+ store.set(updatedRangeAtom, 'today');+ expect(store.get(chatFacetParamsAtom).updatedAfter).toBe(new Date(2026, 8, 20).toISOString());++ store.set(localDayStartAtom, new Date(2026, 8, 21).getTime());+ expect(store.get(chatFacetParamsAtom).updatedAfter).toBe(new Date(2026, 8, 21).toISOString());+ });++ it('toggles an endpoint off again rather than repeating it', () => {+ const store = createStore();+ store.set(toggleEndpointFilterAtom, 'openAI');+ store.set(toggleEndpointFilterAtom, 'agents');+ expect(store.get(endpointFilterAtom)).toEqual(['openAI', 'agents']);++ store.set(toggleEndpointFilterAtom, 'openAI');+ expect(store.get(endpointFilterAtom)).toEqual(['agents']);+ });++ it('counts a multi-value facet once', () => {+ const store = createStore();+ store.set(toggleEndpointFilterAtom, 'openAI');+ store.set(toggleEndpointFilterAtom, 'agents');++ expect(store.get(facetFilterCountAtom)).toBe(1);+ });++ it('returns every facet to its default on reset', () => {+ const store = createStore();+ store.set(updatedRangeAtom, 'month');+ store.set(createdRangeAtom, 'year');+ store.set(toggleEndpointFilterAtom, 'openAI');+ store.set(hasAttachmentsAtom, true);+ store.set(sharedOnlyAtom, true);++ store.set(resetFacetsAtom);++ expect(store.get(facetFilterCountAtom)).toBe(0);+ expect(store.get(chatFacetParamsAtom)).toEqual({+ updatedAfter: undefined,+ createdAfter: undefined,+ endpoints: undefined,+ hasFiles: undefined,+ sharedOnly: undefined,+ });+ });+});++describe('selectableEndpoints', () => {+ const served: TEndpointsConfig = { openAI: { order: 0 }, anthropic: { order: 1 }, google: null };++ it('lists the endpoints the deployment serves', () => {+ expect(selectableEndpoints(served, [])).toEqual(['openAI', 'anthropic']);+ });++ it('keeps a selected endpoint the deployment no longer serves, so it can be turned off', () => {+ expect(selectableEndpoints(served, ['anthropic', 'bedrock'])).toEqual([+ 'openAI',+ 'anthropic',+ 'bedrock',+ ]);+ });++ it('leaves out a served name longer than the list route accepts, unless it is selected', () => {+ const long = 'x'.repeat(12);+ const withLong: TEndpointsConfig = { openAI: { order: 0 }, [long]: { order: 1 } };+ expect(selectableEndpoints(withLong, [], 10)).toEqual(['openAI']);+ expect(selectableEndpoints(withLong, [long], 10)).toEqual(['openAI', long]);+ });++ it('still lists the selection when the endpoints are unavailable', () => {+ expect(selectableEndpoints(undefined, ['openAI'])).toEqual(['openAI']);+ });+});diff --git a/client/src/components/Conversations/chatFilters.ts b/client/src/components/Conversations/chatFilters.tsindex 2afe31095e..b4770235e0 100644--- a/client/src/components/Conversations/chatFilters.ts+++ b/client/src/components/Conversations/chatFilters.ts@@ -1,5 +1,5 @@import { atom } from 'jotai';-import type { ConversationListParams } from 'librechat-data-provider';+import type { ConversationListParams, TConversationTag } from 'librechat-data-provider';import { createStorageAtom } from '~/store/jotai-utils';/** Which slice of the user's chats the sidebar list is showing. */@@ -70,9 +70,11 @@ export const chatSortAtom = atom(export const isArchivedChatViewAtom = atom((get) => get(chatFilterStatusAtom) === 'archived');/** Drives the trigger's badge: how many choices differ from the default list. */+/** Each property that departs from the default counts once, however many values it+ * carries: bookmarks count as one, the way the Filter row and the endpoint facet count. */export const chatFilterCountAtom = atom((get) => {const sort = get(chatSortAtom);- let count = get(chatFilterTagsAtom).length;+ let count = get(chatFilterTagsAtom).length > 0 ? 1 : 0;if (get(chatFilterStatusAtom) !== 'active') {count += 1;}@@ -111,3 +113,26 @@ export const toggleChatFilterTagAtom = atom(null, (get, set, tag: string) => {tags.includes(tag) ? tags.filter((current) => current !== tag) : [...tags, tag],);});++export type BookmarkChoice = Pick<TConversationTag, 'tag' | 'count'>;++/**+ * The bookmarks worth offering as filters: those some chat carries, since one no chat+ * carries filters the list down to nothing, plus every selected one, including a bookmark+ * no chat carries any more or one that was deleted, so a chosen bookmark can always be+ * turned off.+ */+export const selectableBookmarks = (+ bookmarks: TConversationTag[] | undefined,+ selected: string[],+): BookmarkChoice[] => {+ const known = new Set<string>();+ const listed: BookmarkChoice[] = [];+ for (const bookmark of bookmarks ?? []) {+ known.add(bookmark.tag);+ if (bookmark.count > 0 || selected.includes(bookmark.tag)) {+ listed.push(bookmark);+ }+ }+ return listed.concat(selected.filter((tag) => !known.has(tag)).map((tag) => ({ tag, count: 0 })));+};diff --git a/client/src/components/Conversations/facets.ts b/client/src/components/Conversations/facets.tsnew file mode 100644index 0000000000..a9797eb8d8--- /dev/null+++ b/client/src/components/Conversations/facets.ts@@ -0,0 +1,173 @@+import { useEffect } from 'react';+import { atom, useSetAtom } from 'jotai';+import type { ConversationListParams, TEndpointsConfig } from 'librechat-data-provider';+import type { TranslationKeys } from '~/hooks';++/** Coarse windows, matching the headings the list already groups chats under. */+export type DateRange = 'any' | 'today' | 'week' | 'month' | 'year';++export const DATE_RANGE_OPTIONS: Array<{ value: DateRange; label: TranslationKeys }> = [+ { value: 'any', label: 'com_ui_any_time' },+ { value: 'today', label: 'com_ui_date_today' },+ { value: 'week', label: 'com_ui_date_previous_7_days' },+ { value: 'month', label: 'com_ui_date_previous_30_days' },+ { value: 'year', label: 'com_ui_date_previous_year' },+];++/** How many whole days back each window starts, counting today as the first. */+const RANGE_DAYS: Record<Exclude<DateRange, 'any'>, number> = {+ today: 1,+ week: 7,+ month: 30,+ year: 365,+};++/**+ * The instant a window starts, snapped to local midnight.+ *+ * Snapping is not cosmetic. The cutoff travels in the query key, so a cutoff derived+ * from the current instant would differ on every render and refetch the list each+ * time. Anchored to midnight it is stable for the whole day, which is also what+ * "previous 7 days" means to the person reading it.+ */+export function rangeCutoff(range: DateRange, now: Date = new Date()): Date | undefined {+ if (range === 'any') {+ return undefined;+ }+ const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());+ startOfToday.setDate(startOfToday.getDate() - (RANGE_DAYS[range] - 1));+ return startOfToday;+}++const startOfLocalDay = (now: Date = new Date()): number =>+ new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();++/**+ * The local midnight the cutoffs are anchored to, as a timestamp. A derived atom would+ * otherwise cache a cutoff computed yesterday and keep serving it until a facet changes,+ * so the anchor is its own atom that a mounted consumer advances at midnight.+ */+export const localDayStartAtom = atom(startOfLocalDay());++/**+ * Advances the day anchor when the local day changes, then sleeps until the next+ * midnight. One mounted consumer is enough for every reader of the cutoffs; a day with+ * no date facet selected costs a single timer that fires once.+ */+export function useFreshLocalDay(): void {+ const setDay = useSetAtom(localDayStartAtom);+ useEffect(() => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const check = () => {+ const now = new Date();+ const todayStart = startOfLocalDay(now);+ setDay((previous) => (previous === todayStart ? previous : todayStart));+ const nextMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);+ timer = setTimeout(check, Math.max(0, nextMidnight.getTime() - Date.now()) + 500);+ };+ check();+ return () => {+ if (timer != null) {+ clearTimeout(timer);+ }+ };+ }, [setDay]);+}++export const updatedRangeAtom = atom<DateRange>('any');+export const createdRangeAtom = atom<DateRange>('any');++/** OR-matched: a chat qualifies if it ran on any of the chosen endpoints. */+export const endpointFilterAtom = atom<string[]>([]);++export const hasAttachmentsAtom = atom(false);++/** Chats the user is actively sharing through a link. */+export const sharedOnlyAtom = atom(false);++export const toggleEndpointFilterAtom = atom(null, (get, set, endpoint: string) => {+ const endpoints = get(endpointFilterAtom);+ set(+ endpointFilterAtom,+ endpoints.includes(endpoint)+ ? endpoints.filter((current) => current !== endpoint)+ : [...endpoints, endpoint],+ );+});++/** One facet narrowing the list counts once, however many values it carries. */+export const facetFilterCountAtom = atom((get) => {+ let count = 0;+ if (get(updatedRangeAtom) !== 'any') {+ count += 1;+ }+ if (get(createdRangeAtom) !== 'any') {+ count += 1;+ }+ if (get(endpointFilterAtom).length > 0) {+ count += 1;+ }+ if (get(hasAttachmentsAtom)) {+ count += 1;+ }+ if (get(sharedOnlyAtom)) {+ count += 1;+ }+ return count;+});++/**+ * The facets as the list query takes them. Derived rather than assembled at the call+ * site so the query key and the request are built from one description of the filter,+ * and an unset facet is absent rather than sent as an empty value.+ */+export const chatFacetParamsAtom = atom<+ Pick<+ ConversationListParams,+ 'updatedAfter' | 'createdAfter' | 'endpoints' | 'hasFiles' | 'sharedOnly'+ >+>((get) => {+ /** Anchored to the advancing day rather than `new Date()`: the cutoff must be stable+ * within a day (it is the query key) yet must not outlive the day it names. */+ const day = new Date(get(localDayStartAtom));+ const updatedAfter = rangeCutoff(get(updatedRangeAtom), day);+ const createdAfter = rangeCutoff(get(createdRangeAtom), day);+ const endpoints = get(endpointFilterAtom);+ const hasFiles = get(hasAttachmentsAtom);+ const sharedOnly = get(sharedOnlyAtom);++ return {+ updatedAfter: updatedAfter?.toISOString(),+ createdAfter: createdAfter?.toISOString(),+ endpoints: endpoints.length > 0 ? endpoints : undefined,+ hasFiles: hasFiles ? true : undefined,+ sharedOnly: sharedOnly ? true : undefined,+ };+});++export const resetFacetsAtom = atom(null, (_get, set) => {+ set(updatedRangeAtom, 'any');+ set(createdRangeAtom, 'any');+ set(endpointFilterAtom, []);+ set(hasAttachmentsAtom, false);+ set(sharedOnlyAtom, false);+});++/**+ * The endpoints this deployment serves whose names the list route accepts+ * (`conversationList.maxEndpointNameLength`), plus any still selected that are not among+ * them, so a chosen endpoint can always be turned off.+ */+export const selectableEndpoints = (+ endpointsConfig: TEndpointsConfig | undefined,+ selected: string[],+ maxNameLength?: number,+): string[] => {+ const served = Object.keys(endpointsConfig ?? {}).filter(+ (endpoint) =>+ endpointsConfig?.[endpoint] != null &&+ (maxNameLength == null || endpoint.length <= maxNameLength),+ );+ const known = new Set(served);+ return served.concat(selected.filter((endpoint) => !known.has(endpoint)));+};diff --git a/client/src/components/UnifiedSidebar/ConversationsSection.tsx b/client/src/components/UnifiedSidebar/ConversationsSection.tsxindex 5ac828a8aa..65664eae21 100644--- a/client/src/components/UnifiedSidebar/ConversationsSection.tsx+++ b/client/src/components/UnifiedSidebar/ConversationsSection.tsx@@ -5,23 +5,31 @@ import { useMediaQuery } from '@librechat/client';import type { InfiniteQueryObserverResult } from '@tanstack/react-query';import type { ConversationListResponse } from 'librechat-data-provider';import type { List } from 'react-virtualized';+import {+ useProjectsInfiniteQuery,+ useConversationsInfiniteQuery,+ usePinnedConversationsQuery,+ useTitleGeneration,+} from '~/data-provider';import {chatFilterTagsAtom,chatSortAtom,isArchivedChatViewAtom,} from '~/components/Conversations/chatFilters';import {- useConversationsInfiniteQuery,- usePinnedConversationsQuery,- useTitleGeneration,-} from '~/data-provider';-import { useLocalize, useAuthContext, useLocalStorage, useNavScrolling } from '~/hooks';+ useLocalize,+ useAuthContext,+ useLocalStorage,+ useNavScrolling,+ useScrollFade,+} from '~/hooks';+import { chatFacetParamsAtom, useFreshLocalDay } from '~/components/Conversations/facets';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';-import { collectPinnedConversations } from '~/utils';+import { cn, collectPinnedConversations } from '~/utils';import SearchBar from '~/components/Nav/SearchBar';import store from '~/store';@@ -39,7 +47,33 @@ const ConversationsSection = memo(() => {const tags = useAtomValue(chatFilterTagsAtom);const sort = useAtomValue(chatSortAtom);const isArchivedView = useAtomValue(isArchivedChatViewAtom);+ /** Date, endpoint and attachment facets, already shaped as list parameters. */+ const facetParams = useAtomValue(chatFacetParamsAtom);+ /** Keeps the date facets' midnight anchor advancing while the list is mounted. */+ useFreshLocalDay();const search = useRecoilValue(store.search);+ /** The same projects ProjectsSection reads, so an empty Chats list can tell "every+ * chat lives under a project" from "this account has nothing yet". Shared key, so+ * this costs no second request. */+ const {+ data: projectsData,+ isSuccess: projectsLoaded,+ isError: projectsFailed,+ } = useProjectsInfiniteQuery(+ { sortBy: 'lastConversationAt', sortDirection: 'desc', limit: 25 },+ { enabled: isAuthenticated, staleTime: 30000, cacheTime: 300000 },+ );+ /** Only a loaded, empty project list proves the account has nothing yet. While the+ * projects are loading or failed to load, an empty Chats list claims no more than+ * that nothing sits outside a project. */+ const hasProjects = !projectsLoaded || (projectsData?.pages[0]?.projects?.length ?? 0) > 0;+ /** A chat that belongs to a project is shown under that project, not twice. Search and+ * the archived view stay whole: both are places the user goes to find something, and a+ * project chat that appears in neither list nor result would have no way back. So does+ * a list whose projects failed to load, which would otherwise hide every project chat+ * behind a section that cannot show them. */+ const scopeToUnassigned =+ !isArchivedView && !search.debouncedQuery && !(projectsFailed && projectsData == null);const {data,@@ -59,6 +93,8 @@ const ConversationsSection = memo(() => {sortDirection: sort.direction,tags: tags.length === 0 ? undefined : tags,search: search.debouncedQuery || undefined,+ projectId: scopeToUnassigned ? 'unassigned' : undefined,+ ...facetParams,},{enabled: isAuthenticated,@@ -150,6 +186,16 @@ const ConversationsSection = memo(() => {* as a single surface: the chats list is virtualized against this viewport* rather than scrolling inside a pane of its own. */const [scrollViewport, setScrollViewport] = useState<HTMLDivElement | null>(null);+ const { attach: attachScrollFade, hasMore: hasMoreBelow } = useScrollFade<HTMLDivElement>();+ /** The viewport is both the element sections measure against and the one that+ * scrolls, so the fade and the state setter share one callback ref. */+ const setScrollViewportNode = useCallback(+ (node: HTMLDivElement | null) => {+ setScrollViewport(node);+ attachScrollFade(node);+ },+ [attachScrollFade],+ );const [scrollContent, setScrollContent] = useState<HTMLDivElement | null>(null);/** Searching replaces what the surface holds: Projects and Pinned leave and@@ -166,7 +212,7 @@ const ConversationsSection = memo(() => {return (<div- className="flex h-full min-h-0 flex-col overflow-hidden pb-3 pt-2"+ className="flex h-full min-h-0 flex-col overflow-hidden pt-2 pb-3"role="region"aria-label={localize('com_ui_chat_history')}>@@ -178,48 +224,60 @@ const ConversationsSection = memo(() => {<SearchBar isSmallScreen={isSmallScreen} /></div>)}- <div- ref={setScrollViewport}- className="scrollbar-gutter-stable min-h-0 flex-1 overflow-y-auto overflow-x-hidden"- >- {/* `min-h-full` keeps the sections filling a tall sidebar, so the chats+ <div className="relative flex min-h-0 flex-1 flex-col">+ <div+ ref={setScrollViewportNode}+ className="min-h-0 flex-1 scrollbar-gutter-stable overflow-x-hidden overflow-y-auto"+ >+ {/* `min-h-full` keeps the sections filling a tall sidebar, so the chatslist still claims the space below them when there is little to show. */}- <div ref={setScrollContent} className="flex min-h-full flex-col">- {!search.query && (- <ProjectsSection toggleNav={toggleNav} isAuthenticated={isAuthenticated} />- )}- {!search.query && (- <PinnedSection- conversations={pinnedConversations}- toggleNav={toggleNav}- isSmallScreen={isSmallScreen}- /* Only a successful drain proves the list is whole: a failed later+ <div ref={setScrollContent} className="flex min-h-full flex-col">+ {!search.query && (+ <ProjectsSection toggleNav={toggleNav} isAuthenticated={isAuthenticated} />+ )}+ {!search.query && (+ <PinnedSection+ conversations={pinnedConversations}+ toggleNav={toggleNav}+ isSmallScreen={isSmallScreen}+ /* Only a successful drain proves the list is whole: a failed laterpage still publishes partial data and stops fetching. The Chats filtersnever reach this query, so nothing else can truncate it. */- membershipComplete={isPinnedComplete}- /* When that drain last ran, which decides whether it is current+ membershipComplete={isPinnedComplete}+ /* When that drain last ran, which decides whether it is currentenough to prune the stored order against. */- membershipUpdatedAt={pinnedUpdatedAt}+ membershipUpdatedAt={pinnedUpdatedAt}+ />+ )}+ <Conversations+ conversations={conversations}+ moveToTop={moveToTop}+ toggleNav={toggleNav}+ containerRef={conversationsRef}+ loadMoreConversations={loadMoreConversations}+ isLoading={isFetchingNextPage || isLoading}+ isSearchLoading={isSearchLoading || isPreviousData}+ isChatsExpanded={isChatsExpanded}+ setIsChatsExpanded={setIsChatsExpanded}+ hasNextPage={computedHasNextPage}+ isError={isError}+ onRetry={retryConversations}+ chatsHeaderTrailing={chatsHeaderTrailing}+ accountHasProjects={scopeToUnassigned && hasProjects}+ scrollViewport={scrollViewport}+ scrollContent={scrollContent}/>- )}- <Conversations- conversations={conversations}- moveToTop={moveToTop}- toggleNav={toggleNav}- containerRef={conversationsRef}- loadMoreConversations={loadMoreConversations}- isLoading={isFetchingNextPage || isLoading}- isSearchLoading={isSearchLoading || isPreviousData}- isChatsExpanded={isChatsExpanded}- setIsChatsExpanded={setIsChatsExpanded}- hasNextPage={computedHasNextPage}- isError={isError}- onRetry={retryConversations}- chatsHeaderTrailing={chatsHeaderTrailing}- scrollViewport={scrollViewport}- scrollContent={scrollContent}- />+ </div></div>+ {/* The last row fades rather than being cut off, so a list that continues+ below the fold says so without a scrollbar having to appear. */}+ <div+ aria-hidden="true"+ className={cn(+ 'from-surface-primary-alt pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t to-transparent transition-opacity duration-200 motion-reduce:transition-none',+ hasMoreBelow ? 'opacity-100' : 'opacity-0',+ )}+ /></div></div>);diff --git a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsxindex 0a298fbd80..4fc5b35d20 100644--- a/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx+++ b/client/src/components/UnifiedSidebar/__tests__/ConversationsSection.spec.tsx@@ -26,6 +26,20 @@ const mockUseFavorites = jest.fn(() => ({}));const mockUseGetConversationTags = jest.fn(() => ({ data: [] as unknown[] }));const mockConversationsRender = jest.fn();+/** The projects the section reads to word an empty Chats list; none, loaded, by default. */+type ProjectsResult = {+ data?: { pages: { projects: unknown[]; nextCursor: null }[]; pageParams: undefined[] };+ isSuccess: boolean;+ isError?: boolean;+};+const mockUseProjectsInfiniteQuery = jest.fn(+ (): ProjectsResult => ({+ data: { pages: [{ projects: [], nextCursor: null }], pageParams: [undefined] },+ isSuccess: true,+ }),+);+/** What the chats list asks the server for, captured per render. */+const mockListParams = jest.fn();const mockSetChatsExpanded = jest.fn();const mockMoveToTop = jest.fn();const mockUseTitleGeneration = jest.fn(() => {@@ -74,6 +88,7 @@ jest.mock('~/hooks', () => ({useAuthContext: () => ({ isAuthenticated: true }),useLocalStorage: () => [true, mockSetChatsExpanded],useNavScrolling: () => ({ moveToTop: mockMoveToTop }),+ useScrollFade: () => ({ attach: jest.fn(), hasMore: false }),useFavorites: () => mockUseFavorites(),useShowMarketplace: () => false,useNewConvo: () => ({ newConversation: jest.fn() }),@@ -82,8 +97,14 @@ jest.mock('~/hooks', () => ({jest.mock('~/data-provider', () => ({__esModule: true,- useConversationsInfiniteQuery: () => mockConversationsResult,+ useConversationsInfiniteQuery: (params: Record<string, unknown>) => {+ mockListParams(params);+ return mockConversationsResult;+ },usePinnedConversationsQuery: () => mockPinnedResult,+ /** The section reads the same projects ProjectsSection does, to tell an empty+ * unassigned list from an empty account; these specs carry no projects. */+ useProjectsInfiniteQuery: () => mockUseProjectsInfiniteQuery(),useTitleGeneration: () => mockUseTitleGeneration(),useGetEndpointsQuery: () => ({ data: {}, isLoading: false }),useGetStartupConfig: () => ({ data: { modelSpecs: { list: [] } } }),@@ -103,33 +124,11 @@ jest.mock('~/hooks/Input/useSelectMention', () => ({jest.mock('~/components/Conversations', () => {const { memo } = jest.requireActual('react');- const ConversationsStub = memo(function ConversationsStub({- conversations,- isSearchLoading,- isError,- onRetry,- }: {- conversations: Array<{ conversationId: string; title: string }>;- isSearchLoading: boolean;- isError: boolean;- onRetry: () => void;+ const ConversationsStub = memo(function ConversationsStub(props: {+ accountHasProjects?: boolean;}) {- mockConversationsRender();- const localize: (key: string) => string = jest.requireMock('~/hooks').useLocalize();- let body: React.ReactNode = conversations.map((convo) => (- <span key={convo.conversationId}>{convo.title}</span>- ));- if (isError && conversations.length === 0) {- body = (- <button type="button" onClick={onRetry}>- {localize('com_ui_retry')}- </button>- );- }- if (isSearchLoading) {- body = <div data-testid="search-spinner" />;- }- return <div data-testid="conversations-stub">{body}</div>;+ mockConversationsRender(props);+ return <div data-testid="conversations-stub" />;});return { __esModule: true, Conversations: ConversationsStub };});@@ -284,150 +283,102 @@ describe('ConversationsSection streaming re-renders', () => {);});-describe('ConversationsSection search refetch', () => {- it('does not display old matches as unfiltered chats while clearing the search', async () => {- const previousData = mockConversationsResult.data;- mockConversationsResult.data = {- pages: [- {- conversations: [{ conversationId: 'chat-1', title: 'Old search match' }],- nextCursor: null,- },- ],- };-- try {- renderSection('draft');- await settleRenders();- expect(screen.getByText('Old search match')).toBeInTheDocument();-- act(() => {- setSearchState({- query: '',- debouncedQuery: 'draft',- enabled: true,- isTyping: true,- isSearching: false,- });- });-- expect(screen.getByTestId('projects-stub')).toBeInTheDocument();- expect(screen.queryByText('Old search match')).not.toBeInTheDocument();- expect(screen.getByTestId('search-spinner')).toBeInTheDocument();- } finally {- mockConversationsResult.data = previousData;- }+describe('ConversationsSection project chats', () => {+ beforeEach(() => {+ mockListParams.mockClear();});- it('shows progress while retrying a failed cached search with no results', async () => {- const previousData = mockConversationsResult.data;- mockConversationsResult.isError = true;+ /** A chat that belongs to a project is shown under that project. Listing it in+ * Chats as well puts the same conversation in two places in one sidebar. */+ it('asks only for chats that belong to no project', async () => {+ renderSection();+ await settleRenders();- try {- renderSection('draft');- await settleRenders();- expect(screen.getByRole('button', { name: 'com_ui_retry' })).toBeInTheDocument();+ expect(mockListParams).toHaveBeenCalled();+ expect(mockListParams.mock.calls.at(-1)?.[0]).toMatchObject({ projectId: 'unassigned' });+ });- fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));- expect(mockConversationsResult.refetch).toHaveBeenCalledTimes(1);+ /** Searching is how a chat is found, and Projects is not rendered while a search+ * is on: excluding project chats there would make them unreachable. */+ it('searches across every chat, project or not', async () => {+ let setSearch: SetterOrUpdater<SearchState>;- act(() => {- mockConversationsResult.isFetching = true;- setStreamTick((prev) => prev + 1);- });+ function SearchController() {+ setSearch = useSetRecoilState(store.search);+ return null;+ }- expect(screen.getByTestId('search-spinner')).toBeInTheDocument();- expect(screen.queryByRole('button', { name: 'com_ui_retry' })).not.toBeInTheDocument();-- act(() => {- mockConversationsResult.isFetching = false;- mockConversationsResult.isError = false;- mockConversationsResult.data = {- pages: [- {- conversations: [{ conversationId: 'chat-1', title: 'Found match' }],- nextCursor: null,- },- ],- };- setStreamTick((prev) => prev + 1);+ render(+ <QueryClientProvider client={createQueryClient()}>+ <RecoilRoot>+ <BrowserRouter>+ <DndProvider backend={HTML5Backend}>+ <SearchController />+ <ConversationsSection />+ </DndProvider>+ </BrowserRouter>+ </RecoilRoot>+ </QueryClientProvider>,+ );+ await settleRenders();++ act(() => {+ setSearch({+ query: 'draft',+ debouncedQuery: 'draft',+ enabled: true,+ isTyping: false,+ isSearching: true,});+ });- expect(screen.getByText('Found match')).toBeInTheDocument();- expect(screen.queryByTestId('search-spinner')).not.toBeInTheDocument();- } finally {- mockConversationsResult.data = previousData;- mockConversationsResult.isError = false;- mockConversationsResult.isFetching = false;- mockConversationsResult.refetch.mockClear();- }+ expect(mockListParams.mock.calls.at(-1)?.[0]).toMatchObject({+ search: 'draft',+ projectId: undefined,+ });});+});- it('shows loading for an uncached search', async () => {- const previousData = mockConversationsResult.data;- mockConversationsResult.data = undefined;- mockConversationsResult.isLoading = true;+describe('ConversationsSection empty Chats wording', () => {+ const lastAccountHasProjects = () =>+ (mockConversationsRender.mock.calls.at(-1)?.[0] as { accountHasProjects?: boolean })+ .accountHasProjects;- try {- renderSection('draft');- await settleRenders();- expect(screen.getByTestId('search-spinner')).toBeInTheDocument();- } finally {- mockConversationsResult.data = previousData;- mockConversationsResult.isLoading = false;- }+ beforeEach(() => {+ mockConversationsRender.mockClear();+ mockUseProjectsInfiniteQuery.mockReset();});- it('does not show results from the previous search while the next one loads', async () => {- const previousData = mockConversationsResult.data;- mockConversationsResult.data = {- pages: [- {- conversations: [{ conversationId: 'chat-1', title: 'Previous match' }],- nextCursor: null,- },- ],- };- mockConversationsResult.isPreviousData = true;-- try {- renderSection('new term');- await settleRenders();- expect(screen.getByTestId('search-spinner')).toBeInTheDocument();- expect(screen.queryByText('Previous match')).not.toBeInTheDocument();- } finally {- mockConversationsResult.data = previousData;- mockConversationsResult.isPreviousData = false;- }+ it('calls the account empty only once its projects have loaded and there are none', async () => {+ mockUseProjectsInfiniteQuery.mockReturnValue({+ data: { pages: [{ projects: [], nextCursor: null }], pageParams: [undefined] },+ isSuccess: true,+ });+ renderSection();+ await settleRenders();+ expect(lastAccountHasProjects()).toBe(false);});- it('keeps cached results visible when a message triggers a background list refetch', async () => {- const previousData = mockConversationsResult.data;- mockConversationsResult.data = {- pages: [- {- conversations: [{ conversationId: 'chat-1', title: 'Matching chat' }],- nextCursor: null,- },- ],- };-- try {- renderSection('draft');- await settleRenders();- expect(screen.getByText('Matching chat')).toBeInTheDocument();-- act(() => {- mockConversationsResult.isFetching = true;- setStreamTick((prev) => prev + 1);- });+ it('does not call the account empty while its projects are still loading', async () => {+ mockUseProjectsInfiniteQuery.mockReturnValue({ data: undefined, isSuccess: false });+ renderSection();+ await settleRenders();+ expect(lastAccountHasProjects()).toBe(true);+ });- expect(screen.getByText('Matching chat')).toBeInTheDocument();- expect(screen.queryByTestId('search-spinner')).not.toBeInTheDocument();- } finally {- mockConversationsResult.isFetching = false;- mockConversationsResult.data = previousData;- }+ it('lists every chat when the projects failed to load, so project chats keep a way back', async () => {+ mockUseProjectsInfiniteQuery.mockReturnValue({+ data: undefined,+ isSuccess: false,+ isError: true,+ });+ mockListParams.mockClear();+ renderSection();+ await settleRenders();+ expect(mockListParams.mock.calls.at(-1)?.[0]).toEqual(+ expect.objectContaining({ projectId: undefined }),+ );+ expect(lastAccountHasProjects()).toBe(false);});});diff --git a/client/src/data-provider/queries.ts b/client/src/data-provider/queries.tsindex 2a27d50f8a..2a3fd1c9c2 100644--- a/client/src/data-provider/queries.ts+++ b/client/src/data-provider/queries.ts@@ -86,12 +86,39 @@ export const useConversationsInfiniteQuery = (params: ConversationListParams,config?: UseInfiniteQueryOptions<ConversationListResponse, unknown>,) => {- const { isArchived, sortBy, sortDirection, tags, search, projectId } = params;+ const {+ isArchived,+ sortBy,+ sortDirection,+ tags,+ search,+ projectId,+ updatedAfter,+ createdAfter,+ endpoints,+ hasFiles,+ sharedOnly,+ } = params;return useInfiniteQuery<ConversationListResponse>({+ /* Every filter belongs in the key: a facet left out would serve one filter's pages+ to another and, because the cursor is part of that cache entry, keep paging the+ wrong list. */queryKey: [isArchived ? QueryKeys.archivedConversations : QueryKeys.allConversations,- { isArchived, sortBy, sortDirection, tags, search, projectId },+ {+ isArchived,+ sortBy,+ sortDirection,+ tags,+ search,+ projectId,+ updatedAfter,+ createdAfter,+ endpoints,+ hasFiles,+ sharedOnly,+ },],queryFn: async ({ pageParam }) => {const page = await dataService.listConversations({@@ -101,6 +128,11 @@ export const useConversationsInfiniteQuery = (tags,search,projectId,+ updatedAfter,+ createdAfter,+ endpoints,+ hasFiles,+ sharedOnly,cursor: pageParam?.toString(),});/* A row's own `isArchived` decides what its menu offers, so a backend that predatesdiff --git a/client/src/hooks/AuthContext.tsx b/client/src/hooks/AuthContext.tsxindex 9995d46d1d..2e343dc14f 100644--- a/client/src/hooks/AuthContext.tsx+++ b/client/src/hooks/AuthContext.tsx@@ -39,6 +39,7 @@ import {} from '~/data-provider';import { resetChatFilterSessionAtom } from '~/components/Conversations/chatFilters';import { TAuthConfig, TUserContext, TAuthContext, TResError } from '~/common';+import { resetFacetsAtom } from '~/components/Conversations/facets';import useTimeout from './useTimeout';import store from '~/store';@@ -56,6 +57,7 @@ if (import.meta.hot) {* path the other was wired into. */const endSessionClientState = (): void => {getDefaultStore().set(resetChatFilterSessionAtom);+ getDefaultStore().set(resetFacetsAtom);clearRetainedFileDeletions();clearComposerDraftStorage();};diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 522eb9e22d..05e6215641 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1,4 +1,5 @@{+ "com_ui_attachments": "Attachments","com_ui_no_schedules_match": "No schedules match your search","com_ui_repository_instructions": "Repository instructions","com_ui_repository_instructions_prefer": "Prefer repository conventions",@@ -940,6 +941,7 @@"com_ui_accept": "I accept","com_ui_active": "Active","com_ui_active_chats": "Active chats",+ "com_ui_active_count": "{{count}} active","com_ui_add": "Add","com_ui_add_description": "Add a description","com_ui_add_first_bookmark": "Click on a chat to add one",@@ -1050,6 +1052,8 @@"com_ui_always_interrupt": "Steer sooner by default","com_ui_analyzing": "Analyzing","com_ui_analyzing_finished": "Finished analyzing",+ "com_ui_any": "Any",+ "com_ui_any_time": "Any time","com_ui_api_key": "API Key","com_ui_api_key_create_error": "Failed to create API key","com_ui_api_key_created": "API key created successfully",@@ -1213,6 +1217,7 @@"com_ui_change_version": "Change Version","com_ui_chat": "Chat","com_ui_chat_history": "Chat History",+ "com_ui_chat_list": "Chat list","com_ui_chats_load_error": "Couldn't load your chats","com_ui_chats": "Chats","com_ui_check_internet": "Check your internet connection",@@ -1368,6 +1373,7 @@"com_ui_date_october": "October","com_ui_date_previous_30_days": "Previous 30 days","com_ui_date_previous_7_days": "Previous 7 days",+ "com_ui_date_previous_year": "Previous year","com_ui_date_september": "September","com_ui_date_sort": "Sort by Date","com_ui_date_today": "Today",@@ -1474,6 +1480,7 @@"com_ui_empty_category": "-","com_ui_enabled": "Enabled","com_ui_endpoint": "Endpoint",+ "com_ui_endpoint_filter_limit": "Endpoint limit reached ({{count}})","com_ui_endpoint_menu": "LLM Endpoint Menu","com_ui_enter": "Enter","com_ui_enter_api_key": "Enter API Key",@@ -1545,6 +1552,7 @@"com_ui_file_size": "File Size","com_ui_file_token_limit": "File Token Limit","com_ui_file_token_limit_desc": "Set maximum token limit for file processing to control costs and resource usage",+ "com_ui_filter": "Filter","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",@@ -1640,6 +1648,7 @@"com_ui_handoff_field_instructions": "Instructions","com_ui_handoff_instructions": "Handoff instructions","com_ui_happy_birthday": "It's my 1st birthday!",+ "com_ui_has_attachments": "Has attachments","com_ui_header_format": "Header Format","com_ui_hide": "Hide","com_ui_hide_code": "Hide Code",@@ -1911,6 +1920,7 @@"com_ui_no_category": "No category","com_ui_no_changes": "No changes were made","com_ui_no_chats": "No chats yet",+ "com_ui_no_unassigned_chats": "No chats outside your projects 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",@@ -2013,6 +2023,7 @@"com_ui_permissions_failed_update": "Failed to update permissions. Please try again.","com_ui_permissions_updated_success": "Permissions updated successfully","com_ui_schedules_filter": "Filter schedules...",+ "com_ui_sharing": "Sharing","com_ui_skills_toggle_files": "Toggle files for {{0}}","com_ui_view_agent_insights": "View insights","com_ui_view_agent_insights_description": "Allows this principal to view usage and conversation content for this agent.",@@ -2282,6 +2293,7 @@"com_ui_search_above_to_add_people": "Search above to add people","com_ui_search_agent_category": "Search categories...","com_ui_search_default_placeholder": "Search by name or email (min 2 chars)",+ "com_ui_search_filters": "Search filters","com_ui_search_language": "Search languages...","com_ui_search_people_placeholder": "Search for people or groups by name or email","com_ui_search_projects": "Search projects",@@ -2401,6 +2413,7 @@"com_ui_shared_link": "shared link","com_ui_shared_link_bulk_delete_success": "Successfully deleted shared links","com_ui_shared_link_delete_success": "Successfully deleted shared link",+ "com_ui_shared_only": "Shared only","com_ui_shared_link_manage_access": "Manage Access","com_ui_shared_link_not_found": "Shared link not found","com_ui_shared_link_updated": "This shared link was updated. Reloading the latest version, then try again",@@ -2528,6 +2541,7 @@"com_ui_skills_remove": "Remove {{name}}","com_ui_skip": "Skip","com_ui_something_else": "Something else...",+ "com_ui_sort": "Sort","com_ui_sort_a_z": "A to Z","com_ui_sort_chats_by": "Sort chats by","com_ui_sort_created": "Created",diff --git a/client/src/utils/convos.spec.ts b/client/src/utils/convos.spec.tsindex 0e0dd5bfa2..539632dad0 100644--- a/client/src/utils/convos.spec.ts+++ b/client/src/utils/convos.spec.ts@@ -1,3 +1,4 @@+import { EModelEndpoint } from 'librechat-data-provider';import { QueryClient, InfiniteData } from '@tanstack/react-query';import type { TConversation } from 'librechat-data-provider';import type { ConversationCursorData } from './convos';@@ -1560,5 +1561,127 @@ describe('Conversation Utilities', () => {expect(queryClient.getQueryState(archivedKey)?.isInvalidated).toBe(true);});});++ describe('addConversationToAllConversationsQueries with list facets', () => {+ const emptyPages = { pages: [{ conversations: [], nextCursor: null }], pageParams: [] };+ /** A row the endpoint and date facets can judge from its own fields. */+ const facetConvo = {+ conversationId: 'facet',+ endpoint: 'openAI',+ createdAt: '2026-09-20T10:00:00.000Z',+ updatedAt: '2026-09-24T10:00:00.000Z',+ isArchived: false,+ } as TConversation;++ it('skips a variant whose endpoint facet excludes the row', () => {+ const queryClient = new QueryClient();+ const key = ['allConversations', { endpoints: ['google'] }];+ queryClient.setQueryData(key, emptyPages);++ addConversationToAllConversationsQueries(queryClient, facetConvo);++ expect(+ queryClient.getQueryData<InfiniteData<any>>(key)!.pages[0].conversations,+ ).toHaveLength(0);+ });++ it('skips a row older than the variant date cutoff', () => {+ const queryClient = new QueryClient();+ const key = ['allConversations', { updatedAfter: '2026-09-25T00:00:00.000Z' }];+ queryClient.setQueryData(key, emptyPages);++ addConversationToAllConversationsQueries(queryClient, facetConvo);++ expect(+ queryClient.getQueryData<InfiniteData<any>>(key)!.pages[0].conversations,+ ).toHaveLength(0);+ });++ it('keeps inserting into a date facet the row satisfies', () => {+ const queryClient = new QueryClient();+ const key = ['allConversations', { updatedAfter: '2026-09-24T00:00:00.000Z' }];+ queryClient.setQueryData(key, emptyPages);++ addConversationToAllConversationsQueries(queryClient, facetConvo);++ expect(+ queryClient.getQueryData<InfiniteData<any>>(key)!.pages[0].conversations[0]+ .conversationId,+ ).toBe('facet');+ });++ it('drops a cached row from an endpoint facet once the chat moves to another provider', () => {+ const queryClient = new QueryClient();+ const key = ['allConversations', { endpoints: ['openAI'] }];+ queryClient.setQueryData(key, {+ pages: [{ conversations: [facetConvo], nextCursor: null }],+ pageParams: [],+ });++ upsertConvoInAllQueries(queryClient, { ...facetConvo, endpoint: EModelEndpoint.google });++ expect(+ queryClient+ .getQueryData<InfiniteData<any>>(key)!+ .pages.flatMap((page) => page.conversations),+ ).toHaveLength(0);+ });++ it('drops a row from an endpoint facet when an in-place update changes its provider', () => {+ const queryClient = new QueryClient();+ const key = ['allConversations', { endpoints: ['openAI'] }];+ queryClient.setQueryData(key, {+ pages: [{ conversations: [facetConvo], nextCursor: null }],+ pageParams: [],+ });++ updateConvoInAllQueries(queryClient, 'facet', (convo) => ({+ ...convo,+ endpoint: EModelEndpoint.google,+ }));++ expect(+ queryClient+ .getQueryData<InfiniteData<any>>(key)!+ .pages.flatMap((page) => page.conversations),+ ).toHaveLength(0);+ });++ it('keeps a cached row whose update carries no endpoint to judge', () => {+ const queryClient = new QueryClient();+ const key = ['allConversations', { endpoints: ['openAI'] }];+ queryClient.setQueryData(key, {+ pages: [{ conversations: [{ ...facetConvo, endpoint: null }], nextCursor: null }],+ pageParams: [],+ });++ upsertConvoInAllQueries(queryClient, { ...facetConvo, endpoint: null, title: 'Renamed' });++ expect(+ queryClient.getQueryData<InfiniteData<any>>(key)!.pages[0].conversations[0].title,+ ).toBe('Renamed');+ });++ /** Attachments and sharing live in collections the list row does not carry, so+ * only the server can place a row in those variants. */+ it.each([+ ['attachments', { hasFiles: true }],+ ['sharing', { sharedOnly: true }],+ ])('refetches a variant filtered on %s instead of inserting', (_name, facet) => {+ const queryClient = new QueryClient();+ const key = ['allConversations', facet];+ queryClient.setQueryData(key, emptyPages);+ const invalidate = jest.spyOn(queryClient, 'invalidateQueries');++ addConversationToAllConversationsQueries(queryClient, facetConvo);++ expect(invalidate).toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: key, refetchType: 'active' }),+ );+ expect(+ queryClient.getQueryData<InfiniteData<any>>(key)!.pages[0].conversations,+ ).toHaveLength(0);+ });+ });});});diff --git a/client/src/utils/convos.ts b/client/src/utils/convos.tsindex 66cb9e137d..dfa67474cb 100644--- a/client/src/utils/convos.ts+++ b/client/src/utils/convos.ts@@ -248,6 +248,11 @@ function getConversationListQueryParams(queryKey: readonly unknown[]): {sortBy?: string;sortDirection?: string;isArchived?: boolean;+ updatedAfter?: string;+ createdAfter?: string;+ endpoints?: string[];+ hasFiles?: boolean;+ sharedOnly?: boolean;} {const params = queryKey[1];if (!params || typeof params !== 'object') {@@ -259,6 +264,11 @@ function getConversationListQueryParams(queryKey: readonly unknown[]): {sortBy?: string;sortDirection?: string;isArchived?: boolean;+ updatedAfter?: string;+ createdAfter?: string;+ endpoints?: string[];+ hasFiles?: boolean;+ sharedOnly?: boolean;};}@@ -319,57 +329,109 @@ function queryListsArchived(queryKey: readonly unknown[]): boolean {/*** 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.+ * its project, whether it is archived, and the endpoint it ran on. 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. The+ * date cutoffs are left out too: `updatedAt` only moves forward and `createdAt` never+ * moves, so a row that matched them keeps matching.*/function conversationBelongsToListQuery(queryKey: readonly unknown[],- conversation: Pick<TConversation, 'chatProjectId' | 'isArchived'>,+ conversation: Pick<TConversation, 'chatProjectId' | 'isArchived' | 'endpoint'>,): boolean {+ if (!conversationMatchesProjectQuery(queryKey, conversation)) {+ return false;+ }+ if (queryListsArchived(queryKey) !== (conversation.isArchived === true)) {+ return false;+ }+ /* A chat switched to another provider leaves an endpoint-filtered list; an endpoint-less+ * row cannot be proven either way and stays until the server says otherwise. */+ const { endpoints } = getConversationListQueryParams(queryKey);return (- conversationMatchesProjectQuery(queryKey, conversation) &&- queryListsArchived(queryKey) === (conversation.isArchived === true)+ !Array.isArray(endpoints) ||+ endpoints.length === 0 ||+ typeof conversation.endpoint !== 'string' ||+ endpoints.includes(conversation.endpoint));}/**- * Whether only the server can say what a variant holds after a write. Two things put it+ * Whether only the server can say what a variant holds after a write. Three 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.+ * these writers cannot place a row against; a search, which the server evaluates,+ * since a title edit or a new message can make a row start or stop matching one; and the+ * attachment and sharing facets, whose truth lives in collections the list row does+ * not carry.*/function queryNeedsServerReconciliation(queryKey: readonly unknown[]): boolean {if (!queryListsNewestFirst(queryKey)) {return true;}- const { search } = getConversationListQueryParams(queryKey);- return typeof search === 'string' && search.trim() !== '';+ const { search, hasFiles, sharedOnly } = getConversationListQueryParams(queryKey);+ if (typeof search === 'string' && search.trim() !== '') {+ return true;+ }+ return hasFiles === true || sharedOnly === true;}/*** 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.+ * client decides: project, archive state, bookmarks, the endpoint it ran on, and the+ * date cutoffs it carries. Anything left to the server (attachments, sharing) 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'>,+ conversation: Pick<+ TConversation,+ 'chatProjectId' | 'tags' | 'isArchived' | 'endpoint' | 'createdAt' | 'updatedAt'+ >,): ListInsertVerdict {if (!conversationBelongsToListQuery(queryKey, conversation)) {return 'skip';}- const { tags } = getConversationListQueryParams(queryKey);+ const { tags, endpoints, updatedAfter, createdAfter } = getConversationListQueryParams(queryKey);if (Array.isArray(tags) && tags.length > 0) {const conversationTags = conversation.tags;if (!Array.isArray(conversationTags) || !tags.some((tag) => conversationTags.includes(tag))) {return 'skip';}}+ if (Array.isArray(endpoints) && endpoints.length > 0) {+ if (typeof conversation.endpoint === 'string') {+ if (!endpoints.includes(conversation.endpoint)) {+ return 'skip';+ }+ } else {+ /* An endpoint-less row cannot be proven either way, and inserting it on a guess+ * would put a chat the server excluded into the filtered list. */+ return 'refetch';+ }+ }+ const dateFacets: Array<[cutoff: string | undefined, at: string | null | undefined]> = [+ [updatedAfter, conversation.updatedAt ?? null],+ [createdAfter, conversation.createdAt ?? null],+ ];+ for (const [cutoff, at] of dateFacets) {+ if (typeof cutoff !== 'string') {+ continue;+ }+ const cutoffMs = Date.parse(cutoff);+ if (Number.isNaN(cutoffMs)) {+ continue;+ }+ if (at == null) {+ return 'refetch';+ }+ if (Date.parse(at) < cutoffMs) {+ return 'skip';+ }+ }return queryNeedsServerReconciliation(queryKey) ? 'refetch' : 'insert';}diff --git a/e2e/specs/mock/scenarios/chat-filter-menu.spec.ts b/e2e/specs/mock/scenarios/chat-filter-menu.spec.tsnew file mode 100644index 0000000000..2ce99aabaf--- /dev/null+++ b/e2e/specs/mock/scenarios/chat-filter-menu.spec.ts@@ -0,0 +1,686 @@+import { randomUUID } from 'node:crypto';+import { expect, test } from '@playwright/test';+import type { APIRequestContext, Locator, Page, Route } from '@playwright/test';+import type { User } from '../../../types';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ mockReply,+ selectMockEndpoint,+ sendMessage,+} from '../helpers';+import { deleteConversations, withMongo } from '../db';+import { getE2EUser } from '../../../setup/user';+import cleanupUser from '../../../setup/cleanupUser';++test.describe.configure({ timeout: 120_000 });++type SeedRow = {+ title: string;+ files?: string[];+ updatedAt?: Date;+ chatProjectId?: string;+ isArchived?: boolean;+};++const DAY = 24 * 60 * 60 * 1000;+const userEmail = getE2EUser().email;+const createdConversationIds: string[] = [];+const createdProjectIds: string[] = [];++/* Every spec in the run shares this user, so each title carries its own id: a row is+ * then identified by its title alone, whatever else the list holds. */+const uniqueTitle = (label: string) => `Menu ${label} ${randomUUID().slice(0, 8)}`;++async function seedRows(rows: SeedRow[]): Promise<void> {+ await withMongo(async (db) => {+ const user = await db.collection('users').findOne({ email: userEmail });+ if (!user) throw new Error(`E2E seed: user "${userEmail}" not found`);+ const docs = rows.map((row) => {+ const conversationId = randomUUID();+ createdConversationIds.push(conversationId);+ const at = row.updatedAt ?? new Date();+ return {+ conversationId,+ title: row.title,+ user: user._id.toString(),+ endpoint: 'openAI',+ isArchived: row.isArchived ?? false,+ ...(row.isArchived ? { archivedAt: at } : {}),+ ...(row.files ? { files: row.files } : {}),+ ...(row.chatProjectId ? { chatProjectId: row.chatProjectId } : {}),+ createdAt: at,+ updatedAt: at,+ __v: 0,+ };+ });+ await db.collection('conversations').insertMany(docs);+ });+}++async function createProject(page: Page, name: string): Promise<string> {+ await page.goto('/projects', { timeout: 10000 });+ await page.getByRole('button', { name: 'New project' }).first().click();+ const dialog = page.getByRole('dialog');+ await dialog.getByRole('textbox', { name: 'Project name' }).fill(name);+ await dialog.getByRole('button', { name: 'Create project' }).click();+ await expect(page.getByRole('heading', { name })).toBeVisible();+ const projectId = new URL(page.url()).pathname.split('/projects/')[1];+ expect(projectId).toBeTruthy();+ createdProjectIds.push(projectId);+ return projectId;+}++/** A row of the Chats section, as opposed to one filed under a project or pinned. */+const chatsRow = (page: Page, title: string): Locator =>+ page.getByTestId('convo-list-row').filter({ hasText: title });++const trigger = (page: Page) => page.getByTestId('chat-filter-menu');+const menu = (page: Page) => page.getByRole('menu', { name: 'Filter and sort chats' });++const isPhone = (page: Page) => (page.viewportSize()?.width ?? 1280) < 768;++/** Below `md` the sidebar is a drawer that starts closed; open it before reading the+ * list. A no-op on desktop, where the list is already on screen. */+async function showSidebar(page: Page): Promise<void> {+ if (isPhone(page) && !(await trigger(page).isVisible())) {+ await page.getByTestId('header-open-sidebar-button').click();+ }+ await expect(trigger(page)).toBeVisible();+}++/** The drawer covers the composer on a phone, so it closes before a message is sent. */+async function hideSidebar(page: Page): Promise<void> {+ if (isPhone(page) && (await trigger(page).isVisible())) {+ await page.getByTestId('close-sidebar-button').click();+ await expect(trigger(page)).toBeHidden();+ }+}++async function openFilterSubmenu(page: Page): Promise<void> {+ if (!(await menu(page).isVisible())) {+ await trigger(page).click();+ }+ await expect(menu(page)).toBeVisible();+ await page.getByTestId('chat-filter-facets').click();+ await expect(page.getByRole('menuitemcheckbox', { name: 'Has attachments' })).toBeVisible();+}++async function closeMenus(page: Page): Promise<void> {+ for (let i = 0; i < 3 && (await menu(page).isVisible()); i++) {+ await page.keyboard.press('Escape');+ }+ await expect(menu(page)).toBeHidden();+}++async function toggleHasAttachments(page: Page): Promise<void> {+ await openFilterSubmenu(page);+ await page.getByRole('menuitemcheckbox', { name: 'Has attachments' }).click();+ await closeMenus(page);+}++test.afterEach(async () => {+ const conversationIds = createdConversationIds.splice(0, createdConversationIds.length);+ if (conversationIds.length > 0) {+ await deleteConversations(conversationIds);+ }+ const projectIds = createdProjectIds.splice(0, createdProjectIds.length);+ if (projectIds.length > 0) {+ await withMongo(async (db) => {+ const projects = await db+ .collection('chatprojects')+ .find({})+ .project({ _id: 1, projectId: 1 })+ .toArray();+ const ids = projects+ .filter((doc) => projectIds.includes(String(doc.projectId ?? doc._id)))+ .map((doc) => doc._id);+ await db.collection('chatprojects').deleteMany({ _id: { $in: ids } });+ await db.collection('conversations').deleteMany({ chatProjectId: { $in: projectIds } });+ });+ }+});++test.describe('chat list properties menu', () => {+ test('a facet chosen from the keyboard narrows the Chats list @scenario:chat-menu-facet-narrows-list', async ({+ page,+ }) => {+ const withFile = uniqueTitle('file');+ const withoutFile = uniqueTitle('plain');+ await seedRows([{ title: withFile, files: [randomUUID()] }, { title: withoutFile }]);+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await showSidebar(page);+ await expect(chatsRow(page, withFile)).toBeVisible();+ await expect(chatsRow(page, withoutFile)).toBeVisible();++ await trigger(page).focus();+ await page.keyboard.press('Enter');+ await expect(menu(page)).toBeVisible();+ await expect(page.getByTestId('chat-filter-show')).toBeVisible();+ await expect(page.getByTestId('chat-filter-sort')).toBeVisible();++ const filterRow = page.getByTestId('chat-filter-facets');+ for (let i = 0; i < 6; i++) {+ if (await filterRow.evaluate((node) => node === document.activeElement)) {+ break;+ }+ await page.keyboard.press('ArrowDown');+ }+ await expect(filterRow).toBeFocused();+ await page.keyboard.press('ArrowRight');+ await expect(+ page+ .getByRole('combobox', { name: 'Search filters' })+ .or(page.getByRole('textbox', { name: 'Search filters' })),+ ).toBeFocused();++ await page.getByRole('menuitemcheckbox', { name: 'Has attachments' }).click();+ await expect(page.getByRole('menuitemcheckbox', { name: 'Has attachments' })).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ await closeMenus(page);++ await expect(chatsRow(page, withFile)).toBeVisible();+ await expect(chatsRow(page, withoutFile)).toHaveCount(0);+ await expect(trigger(page)).toHaveAttribute('aria-label', 'Filters active: 1');+ await expect(trigger(page)).toHaveAttribute('aria-pressed', 'true');+ });++ test('Reset in the menu restores the unfiltered list @scenario:chat-menu-reset-restores-list', async ({+ page,+ }) => {+ const withFile = uniqueTitle('file');+ const withoutFile = uniqueTitle('plain');+ await seedRows([{ title: withFile, files: [randomUUID()] }, { title: withoutFile }]);+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await showSidebar(page);++ await toggleHasAttachments(page);+ await expect(chatsRow(page, withoutFile)).toHaveCount(0);++ await trigger(page).click();+ const reset = page.getByTestId('chat-filter-reset-all');+ await expect(reset).not.toHaveAttribute('aria-disabled', 'true');+ await reset.click();+ await expect(reset).toHaveAttribute('aria-disabled', 'true');+ await closeMenus(page);++ await expect(chatsRow(page, withoutFile)).toBeVisible();+ await expect(chatsRow(page, withFile)).toBeVisible();+ await expect(trigger(page)).toHaveAttribute('aria-label', 'Filter and sort chats');+ });++ test('an Updated window of Today hides a chat last touched ten days ago @scenario:chat-date-window-hides-older', async ({+ page,+ }) => {+ const recent = uniqueTitle('recent');+ const older = uniqueTitle('older');+ /* Both carry a file, so the attachment facet reduces the list to rows this+ * test and its siblings seeded: the ten-day-old row is then on screen before+ * the date window, however many chats the shared user has. */+ await seedRows([+ { title: recent, files: [randomUUID()] },+ { title: older, files: [randomUUID()], updatedAt: new Date(Date.now() - 10 * DAY) },+ ]);+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await showSidebar(page);+ await toggleHasAttachments(page);+ await expect(chatsRow(page, older)).toBeVisible();++ await openFilterSubmenu(page);+ await page.getByRole('menuitem', { name: /^Updated\b/ }).click();+ await page.getByRole('menuitemradio', { name: 'Today' }).click();+ await closeMenus(page);++ await expect(chatsRow(page, recent)).toBeVisible();+ await expect(chatsRow(page, older)).toHaveCount(0);+ await expect(trigger(page)).toHaveAttribute('aria-label', 'Filters active: 2');+ });++ test('a project chat is listed under its project, not in Chats, and stays reachable from the archive @scenario:project-chat-listed-under-project-only', async ({+ page,+ }) => {+ const projectName = `Menu project ${randomUUID().slice(0, 8)}`;+ const projectId = await createProject(page, projectName);+ const inProject = uniqueTitle('project');+ const archivedInProject = uniqueTitle('archived');+ const unassigned = uniqueTitle('unassigned');+ await seedRows([+ { title: inProject, chatProjectId: projectId },+ { title: archivedInProject, chatProjectId: projectId, isArchived: true },+ { title: unassigned },+ ]);+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await showSidebar(page);++ await expect(chatsRow(page, unassigned)).toBeVisible();+ await expect(chatsRow(page, inProject)).toHaveCount(0);++ const projectRow = page.getByRole('button', { name: projectName }).first();+ if ((await projectRow.getAttribute('aria-expanded')) !== 'true') {+ await projectRow.click();+ }+ await expect(+ page.getByTestId(`project-chats-${projectId}`).getByTestId('convo-item').filter({+ hasText: inProject,+ }),+ ).toBeVisible();++ await trigger(page).click();+ await page.getByTestId('chat-filter-show').click();+ await page.getByRole('menuitemradio', { name: 'Archived chats' }).click();+ await closeMenus(page);+ await expect(chatsRow(page, archivedInProject)).toBeVisible();+ });++ test('a project chat stays in Chats when the projects fail to load @scenario:project-chats-reachable-when-projects-fail', async ({+ page,+ }) => {+ const inProject = uniqueTitle('orphaned');+ const unassigned = uniqueTitle('unassigned');+ /* No project document is needed: the list request is what hides a project chat, and+ * the project list it depends on is made to fail below. */+ await seedRows([+ { title: inProject, chatProjectId: randomUUID().replace(/-/g, '').slice(0, 24) },+ { title: unassigned },+ ]);+ await page.route(+ (url) => url.pathname === '/api/projects',+ (route) =>+ route.request().method() === 'GET'+ ? route.fulfill({ status: 500, body: '{}' })+ : route.continue(),+ );+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await showSidebar(page);++ await expect(chatsRow(page, unassigned)).toBeVisible();+ await expect(chatsRow(page, inProject)).toBeVisible({ timeout: 30000 });+ });++ test('a project whose chats fail to load says so and recovers on retry @scenario:project-chats-failure-offers-retry', async ({+ page,+ }) => {+ const projectName = `Menu project ${randomUUID().slice(0, 8)}`;+ const projectId = await createProject(page, projectName);+ const inProject = uniqueTitle('project');+ await seedRows([{ title: inProject, chatProjectId: projectId }]);++ let failProjectChats = true;+ await page.route(+ (url) => url.pathname === '/api/convos' && url.searchParams.get('projectId') === projectId,+ (route) => (failProjectChats ? route.fulfill({ status: 500, body: '{}' }) : route.continue()),+ );+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await showSidebar(page);++ const projectRow = page.getByRole('button', { name: projectName }).first();+ if ((await projectRow.getAttribute('aria-expanded')) !== 'true') {+ await projectRow.click();+ }+ const failure = page.getByTestId(`project-chats-error-${projectId}`);+ await expect(failure).toBeVisible({ timeout: 30000 });+ await expect(failure).toHaveAttribute('role', 'alert');++ failProjectChats = false;+ await failure.getByRole('button', { name: 'Retry' }).click();+ await expect(+ page.getByTestId(`project-chats-${projectId}`).getByTestId('convo-item').filter({+ hasText: inProject,+ }),+ ).toBeVisible();+ });++ test('the Endpoint facet stops at the limit the deployment publishes @scenario:endpoint-filter-stops-at-limit', async ({+ page,+ }) => {+ /* The harness serves one librechat.yaml to every spec, so the published limit is set+ * on the startup config this page reads; the route spec covers the server side. The+ * response is held so the facet is seen before the limit is known. */+ let releaseConfig = () => {};+ const configHeld = new Promise<void>((resolve) => {+ releaseConfig = resolve;+ });+ await page.route(+ (url) => url.pathname === '/api/config',+ async (route) => {+ const response = await route.fetch();+ const body = await response.json();+ await configHeld;+ await route.fulfill({+ response,+ json: {+ ...body,+ conversationListLimits: { ...body.conversationListLimits, maxEndpointFilters: 1 },+ },+ });+ },+ );+ /* A phone's header waits for the config before it offers the sidebar, so the+ * unknown-limit window is only reachable on a desktop layout. */+ const sidebarWaitsForConfig = test.info().project.name === 'mobile';+ if (sidebarWaitsForConfig) {+ releaseConfig();+ }+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await showSidebar(page);++ const endpoints = page.getByRole('menu').last().getByRole('menuitemcheckbox');+ const openEndpointFacet = async () => {+ await openFilterSubmenu(page);+ await page.getByRole('menuitem', { name: /^Endpoint\b/ }).click();+ await expect(endpoints.nth(1)).toBeVisible();+ };++ if (!sidebarWaitsForConfig) {+ await openEndpointFacet();+ await expect(endpoints.first()).toHaveAttribute('aria-disabled', 'true');+ await endpoints.first().click({ force: true });+ await expect(endpoints.first()).toHaveAttribute('aria-checked', 'false');++ /* The arriving config rebuilds the shell, so the menu is opened afresh once it lands. */+ await closeMenus(page);+ const configLoaded = page.waitForResponse((response) =>+ response.url().endsWith('/api/config'),+ );+ releaseConfig();+ await configLoaded;+ }++ await openEndpointFacet();+ await expect(endpoints.first()).not.toHaveAttribute('aria-disabled', 'true');+ await endpoints.first().click();+ await expect(endpoints.first()).toHaveAttribute('aria-checked', 'true');++ await expect(endpoints.nth(1)).toHaveAttribute('aria-disabled', 'true');+ await expect(page.getByText('Endpoint limit reached (1)')).toBeVisible();+ await endpoints.nth(1).click({ force: true });+ await expect(endpoints.nth(1)).toHaveAttribute('aria-checked', 'false');++ await closeMenus(page);+ await expect(trigger(page)).toHaveAttribute('aria-label', 'Filters active: 1');+ await expect(page.getByTestId('convo-list-error')).toHaveCount(0);+ });++ test('a chat sent while a server-only facet is active is not added to the filtered list @scenario:live-chat-respects-active-facet', async ({+ page,+ }) => {+ const withFile = uniqueTitle('file');+ await seedRows([{ title: withFile, files: [randomUUID()] }]);+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await showSidebar(page);+ await toggleHasAttachments(page);+ await expect(chatsRow(page, withFile)).toBeVisible();+ const rowsBefore = await page.getByTestId('convo-list-row').count();++ /* The facet's own refetch is held until the list has been read: whatever the+ * cache writers put in the list while the reply streamed is then still on+ * screen, instead of being papered over by the server's answer. */+ const held: Route[] = [];+ let holding = true;+ await page.route(+ (url) => url.pathname === '/api/convos' && url.searchParams.get('hasFiles') === 'true',+ async (route) => {+ if (holding) {+ held.push(route);+ return;+ }+ await route.continue();+ },+ );++ await hideSidebar(page);+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ const response = await sendMessage(page, `no attachment ${randomUUID().slice(0, 8)}`);+ expect(response.ok()).toBeTruthy();+ await expect(mockReply(page)).toBeVisible({ timeout: 20000 });+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });+ const conversationId = new URL(page.url()).pathname.split('/c/')[1];+ createdConversationIds.push(conversationId);+ await showSidebar(page);++ await expect(page.getByTestId('convo-list-row')).toHaveCount(rowsBefore);++ holding = false;+ await Promise.all(held.splice(0, held.length).map((route) => route.continue()));+ await expect(chatsRow(page, withFile)).toBeVisible();+ });++ test('filters chosen by one account are gone after signing out and back in @scenario:facets-cleared-after-sign-out', async ({+ browser,+ baseURL,+ }) => {+ if (typeof baseURL !== 'string') {+ throw new Error('baseURL must be configured for mock scenarios');+ }+ const user: User = {+ name: 'Facet Reset',+ email: `facet-reset-${randomUUID().slice(0, 8)}@example.com`,+ password: `Pw-${randomUUID()}`,+ };+ await cleanupUser(user);+ const context = await browser.newContext({ storageState: undefined, baseURL });+ await context.addInitScript(() => {+ localStorage.setItem('navVisible', 'true');+ });+ const page = await context.newPage();++ const register = async (request: APIRequestContext) => {+ const registered = await request.post('/api/auth/register', {+ data: {+ email: user.email,+ name: user.name,+ password: user.password,+ confirm_password: user.password,+ },+ });+ expect(registered.ok()).toBeTruthy();+ };+ const logIn = async () => {+ await page.getByLabel('Email').fill(user.email);+ await page.getByLabel('Password').fill(user.password);+ await page.getByTestId('login-button').click();+ await page.waitForURL(/\/c\/new/, { timeout: 10000 });+ await showSidebar(page);+ };++ try {+ await register(context.request);+ await page.goto('/login', { timeout: 10000 });+ await logIn();++ await toggleHasAttachments(page);+ await expect(trigger(page)).toHaveAttribute('aria-label', 'Filters active: 1');++ await showSidebar(page);+ await page.getByTestId('nav-user').click();+ await page.getByRole('menuitem', { name: 'Log out' }).click();+ await page.waitForURL(/\/login/, { timeout: 10000 });+ await logIn();++ await expect(trigger(page)).toHaveAttribute('aria-label', 'Filter and sort chats');+ await expect(trigger(page)).toHaveAttribute('aria-pressed', 'false');+ } finally {+ await context.close().catch(() => undefined);+ await cleanupUser(user);+ }+ });++ test('a chosen bookmark stays in the Filter submenu after its last chat drops it @scenario:selected-bookmark-stays-removable', async ({+ page,+ }) => {+ const tag = `Menu tag ${randomUUID().slice(0, 8)}`;+ const title = uniqueTitle('bookmarked');+ const conversationId = randomUUID();+ createdConversationIds.push(conversationId);+ await withMongo(async (db) => {+ const user = await db.collection('users').findOne({ email: userEmail });+ if (!user) throw new Error(`E2E seed: user "${userEmail}" not found`);+ const now = new Date();+ await db.collection('conversations').insertOne({+ conversationId,+ title,+ user: user._id.toString(),+ endpoint: 'openAI',+ isArchived: false,+ tags: [tag],+ createdAt: now,+ updatedAt: now,+ __v: 0,+ });+ await db.collection('conversationtags').insertOne({+ tag,+ user: user._id.toString(),+ count: 1,+ position: 0,+ createdAt: now,+ updatedAt: now,+ __v: 0,+ });+ });++ /* Only the header's bookmark menu, shown from `md` up, can drop a bookmark while this+ * list is open, so a phone cannot reach this state and the phone project runs wide. */+ const viewport = page.viewportSize();+ if (isPhone(page) && viewport) {+ await page.setViewportSize({ width: 1280, height: viewport.height });+ }++ try {+ await page.goto(`/c/${conversationId}`, { timeout: 10000 });+ await showSidebar(page);+ await openFilterSubmenu(page);+ await page.getByRole('menuitem', { name: /^Bookmarks\b/ }).click();+ /* A choice is named by its tag and then its count. */+ const choice = page+ .getByRole('menu')+ .last()+ .getByRole('menuitemcheckbox', {+ name: new RegExp(`^${tag} \\d+$`),+ });+ await choice.click();+ await expect(choice).toHaveAttribute('aria-checked', 'true');+ await closeMenus(page);+ await expect(trigger(page)).toHaveAttribute('aria-label', 'Filters active: 1');++ /* Removing the bookmark from its only chat takes its count to zero. */+ await hideSidebar(page);+ const bookmarkButton = page.locator('#bookmark-menu-button');+ await bookmarkButton.click();+ const [untagged] = await Promise.all([+ page.waitForResponse(+ (r) =>+ r.request().method() === 'PUT' &&+ new URL(r.url()).pathname.startsWith('/api/tags/convo/'),+ ),+ page.getByRole('menuitemcheckbox', { name: tag, exact: true }).click(),+ ]);+ expect(untagged.ok()).toBeTruthy();+ await page.keyboard.press('Escape');++ await showSidebar(page);+ await openFilterSubmenu(page);+ await page.getByRole('menuitem', { name: /^Bookmarks\b/ }).click();+ await expect(choice).toHaveAttribute('aria-checked', 'true');+ /* Once turned off it is an unused bookmark again, which the list leaves out. */+ await choice.click();+ await expect(choice).toHaveCount(0);+ await closeMenus(page);+ await expect(trigger(page)).toHaveAttribute('aria-label', 'Filter and sort chats');+ } finally {+ await withMongo((db) => db.collection('conversationtags').deleteMany({ tag }));+ }+ });++ test('a role without bookmark access opens the Filter submenu without asking for bookmarks @scenario:bookmark-filter-quiet-without-access', async ({+ browser,+ baseURL,+ }) => {+ if (typeof baseURL !== 'string') {+ throw new Error('baseURL must be configured for mock scenarios');+ }+ const suffix = randomUUID().slice(0, 8);+ const roleName = `E2E_NO_BOOKMARKS_${suffix}`;+ const user: User = {+ name: 'No Bookmarks',+ email: `no-bookmarks-${suffix}@example.com`,+ password: `Pw-${randomUUID()}`,+ };+ await cleanupUser(user);+ /* A copy of the default role with only bookmarks switched off, held by this test's+ * own account: the role every other spec signs in with stays untouched. */+ await withMongo(async (db) => {+ const fields = await db+ .collection('roles')+ .findOne({ name: 'USER' }, { projection: { _id: 0 } });+ if (!fields) throw new Error('E2E seed: USER role not found');+ await db.collection('roles').insertOne({+ ...fields,+ name: roleName,+ permissions: {+ ...(fields.permissions ?? {}),+ BOOKMARKS: { ...(fields.permissions?.BOOKMARKS ?? {}), USE: false },+ },+ });+ });++ const context = await browser.newContext({ storageState: undefined, baseURL });+ await context.addInitScript(() => {+ localStorage.setItem('navVisible', 'true');+ });+ const page = await context.newPage();+ try {+ const registered = await context.request.post('/api/auth/register', {+ data: {+ email: user.email,+ name: user.name,+ password: user.password,+ confirm_password: user.password,+ },+ });+ expect(registered.ok()).toBeTruthy();+ await withMongo((db) =>+ db.collection('users').updateOne({ email: user.email }, { $set: { role: roleName } }),+ );++ /* The page header asks for bookmarks on its own, gated or not, and retries the+ * refusal; that request predates this menu. Its cycle is let to settle first, so+ * what is counted afterwards is only what the Filter submenu asks for. */+ let tagRequests = 0;+ let lastTagRequestAt = Date.now();+ page.on('request', (request) => {+ if (new URL(request.url()).pathname.startsWith('/api/tags')) {+ tagRequests += 1;+ lastTagRequestAt = Date.now();+ }+ });++ await page.goto('/login', { timeout: 10000 });+ await page.getByLabel('Email').fill(user.email);+ await page.getByLabel('Password').fill(user.password);+ await page.getByTestId('login-button').click();+ await page.waitForURL(/\/c\/new/, { timeout: 10000 });+ await showSidebar(page);+ await expect+ .poll(() => Date.now() - lastTagRequestAt, { timeout: 30000, intervals: [500] })+ .toBeGreaterThan(8000);+ const settledRequests = tagRequests;++ await openFilterSubmenu(page);+ await expect(page.getByRole('menuitem', { name: /^Updated\b/ })).toBeVisible();+ await expect(page.getByRole('menuitem', { name: /^Bookmarks\b/ })).toHaveCount(0);+ await page.getByRole('menuitemcheckbox', { name: 'Has attachments' }).click();+ await closeMenus(page);+ await expect(trigger(page)).toHaveAttribute('aria-label', 'Filters active: 1');+ await openFilterSubmenu(page);+ await closeMenus(page);++ expect(tagRequests).toBe(settledRequests);+ } finally {+ await context.close().catch(() => undefined);+ await cleanupUser(user);+ await withMongo((db) => db.collection('roles').deleteOne({ name: roleName }));+ }+ });+});diff --git a/eslint-suppressions.json b/eslint-suppressions.jsonindex d1154c8a55..748b965d7b 100644--- a/eslint-suppressions.json+++ b/eslint-suppressions.json@@ -1050,19 +1050,6 @@"count": 8}},- "client/src/components/Conversations/ChatFilterMenu.tsx": {- "shadcn/no-inline-styles": {- "count": 1- }- },- "client/src/components/Conversations/Conversations.tsx": {- "shadcn/no-inline-styles": {- "count": 2- },- "shadcn/no-restyle": {- "count": 2- }- },"client/src/components/Conversations/Convo.tsx": {"shadcn/no-inline-styles": {"count": 1diff --git a/packages/api/src/conversations/filters.ts b/packages/api/src/conversations/filters.tsindex 8cb50d585b..3757355b9c 100644--- a/packages/api/src/conversations/filters.ts+++ b/packages/api/src/conversations/filters.ts@@ -21,10 +21,11 @@ export interface ConversationListFilterResult {error?: string;}-/** Reads the deployment config; injected so this module does not reach for the app's. */+/** Reads the deployment config; injected so this module does not reach for the app's. A+ * config not yet loaded reads as none, so the schema defaults apply. */export type ConversationListConfigReader = (options: {baseOnly: true;-}) => Promise<{ conversationList?: TConversationListConfig }>;+}) => Promise<{ conversationList?: TConversationListConfig } | undefined>;const firstValue = (value: unknown): unknown => (Array.isArray(value) ? value[0] : value);@@ -193,19 +194,30 @@ export function parseConversationListFilters(}/**- * The list route's entry point. The limits are deployment-level, so they come from the- * base config rather than the caller's merged config, and only a request naming endpoints- * reads it at all: the limits bound nothing else, and an unfiltered sidebar request should- * not wait on, or fail with, a config cache it does not use.+ * The list route's entry point. Only a request naming endpoints reads the limits at all:+ * they bound nothing else, and an unfiltered sidebar request should not wait on, or fail+ * with, a config cache it does not use.*/export async function resolveConversationListFilters(query: Request['query'],getAppConfig: ConversationListConfigReader,): Promise<ConversationListFilterResult> {- const { conversationList } =- query.endpoints == null ? {} : await getAppConfig({ baseOnly: true });- return parseConversationListFilters(- query,- conversationList ?? conversationListConfigSchema.parse({}),- );+ const limits =+ query.endpoints == null+ ? conversationListConfigSchema.parse({})+ : await loadConversationListLimits(getAppConfig);+ return parseConversationListFilters(query, limits);+}++/**+ * The limits a deployment enforces on list filters. They are deployment-level, so they come+ * from the base config rather than a caller's merged one, with the schema defaults standing+ * in for an unconfigured deployment. The startup config publishes what this returns, so the+ * sidebar stops a selection exactly where the list route would refuse it.+ */+export async function loadConversationListLimits(+ getAppConfig: ConversationListConfigReader,+): Promise<TConversationListConfig> {+ const config = await getAppConfig({ baseOnly: true });+ return config?.conversationList ?? conversationListConfigSchema.parse({});}diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 7c60e5da03..a1ba5fc018 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -2750,6 +2750,9 @@ export type TStartupConfig = {passkeyLoginEnabled: boolean;/** Per-account passkey enrollment cap, from `passkeys.perUserMax`; post-login only. */maxPasskeysPerUser?: number;+ /** What one chat list filter request may name (`conversationList`), resolved from the+ * deployment's base config as the list route resolves it; post-login only. */+ conversationListLimits?: TConversationListConfig;openidLabel: string;openidImageUrl: string;openidAutoRedirect: boolean;