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
♾️ style: Infinite Scroll Nav and Sort Convos by Date/Usage (#1708)
Danny Avila74459d6261cc
diff --git a/api/cache/getLogStores.js b/api/cache/getLogStores.jsindex 03aaf84703..7f759e5f33 100644--- a/api/cache/getLogStores.js+++ b/api/cache/getLogStores.js@@ -27,6 +27,10 @@ const tokenConfig = isEnabled(USE_REDIS) // ttl: 30 minutes? new Keyv({ store: keyvRedis, ttl: 1800000 }): new Keyv({ namespace: CacheKeys.TOKEN_CONFIG, ttl: 1800000 });+const genTitle = isEnabled(USE_REDIS) // ttl: 2 minutes+ ? new Keyv({ store: keyvRedis, ttl: 120000 })+ : new Keyv({ namespace: CacheKeys.GEN_TITLE, ttl: 120000 });+const namespaces = {[CacheKeys.CONFIG_STORE]: config,pending_req,@@ -39,6 +43,7 @@ const namespaces = {registrations: createViolationInstance('registrations'),logins: createViolationInstance('logins'),[CacheKeys.TOKEN_CONFIG]: tokenConfig,+ [CacheKeys.GEN_TITLE]: genTitle,};/**diff --git a/api/models/Conversation.js b/api/models/Conversation.jsindex f1aa7bfe71..1ef47241ca 100644--- a/api/models/Conversation.js+++ b/api/models/Conversation.js@@ -30,12 +30,12 @@ module.exports = {return { message: 'Error saving conversation' };}},- getConvosByPage: async (user, pageNumber = 1, pageSize = 14) => {+ getConvosByPage: async (user, pageNumber = 1, pageSize = 25) => {try {const totalConvos = (await Conversation.countDocuments({ user })) || 1;const totalPages = Math.ceil(totalConvos / pageSize);const convos = await Conversation.find({ user })- .sort({ createdAt: -1 })+ .sort({ updatedAt: -1 }).skip((pageNumber - 1) * pageSize).limit(pageSize).lean();@@ -45,7 +45,7 @@ module.exports = {return { message: 'Error getting conversations' };}},- getConvosQueried: async (user, convoIds, pageNumber = 1, pageSize = 14) => {+ getConvosQueried: async (user, convoIds, pageNumber = 1, pageSize = 25) => {try {if (!convoIds || convoIds.length === 0) {return { conversations: [], pages: 1, pageNumber, pageSize };diff --git a/api/server/routes/convos.js b/api/server/routes/convos.jsindex a410b6fd58..6213cfd2c7 100644--- a/api/server/routes/convos.js+++ b/api/server/routes/convos.js@@ -1,6 +1,9 @@const express = require('express');+const { CacheKeys } = require('librechat-data-provider');const { getConvosByPage, deleteConvos } = require('~/models/Conversation');const requireJwtAuth = require('~/server/middleware/requireJwtAuth');+const { sleep } = require('~/server/services/AssistantService');+const getLogStores = require('~/cache/getLogStores');const { getConvo, saveConvo } = require('~/models');const { logger } = require('~/config');@@ -29,6 +32,29 @@ router.get('/:conversationId', async (req, res) => {}});+router.post('/gen_title', async (req, res) => {+ const { conversationId } = req.body;+ const titleCache = getLogStores(CacheKeys.GEN_TITLE);+ const key = `${req.user.id}-${conversationId}`;+ let title = await titleCache.get(key);++ if (!title) {+ await sleep(2500);+ title = await titleCache.get(key);+ }++ if (title) {+ await titleCache.delete(key);+ res.status(200).json({ title });+ } else {+ res+ .status(404)+ .json({+ message: 'Title not found or method not implemented for the conversation\'s endpoint',+ });+ }+});+router.post('/clear', async (req, res) => {let filter = {};const { conversationId, source } = req.body.arg;diff --git a/api/server/services/AssistantService.js b/api/server/services/AssistantService.jsindex 4b92919348..b6eabb7539 100644--- a/api/server/services/AssistantService.js+++ b/api/server/services/AssistantService.js@@ -357,5 +357,6 @@ module.exports = {waitForRun,getResponse,handleRun,+ sleep,mapMessagesToSteps,};diff --git a/api/server/services/Endpoints/openAI/addTitle.js b/api/server/services/Endpoints/openAI/addTitle.jsindex ab15443f94..9bb0ec3487 100644--- a/api/server/services/Endpoints/openAI/addTitle.js+++ b/api/server/services/Endpoints/openAI/addTitle.js@@ -1,5 +1,7 @@-const { saveConvo } = require('~/models');+const { CacheKeys } = require('librechat-data-provider');+const getLogStores = require('~/cache/getLogStores');const { isEnabled } = require('~/server/utils');+const { saveConvo } = require('~/models');const addTitle = async (req, { text, response, client }) => {const { TITLE_CONVO = 'true' } = process.env ?? {};@@ -16,7 +18,11 @@ const addTitle = async (req, { text, response, client }) => {return;}+ const titleCache = getLogStores(CacheKeys.GEN_TITLE);+ const key = `${req.user.id}-${response.conversationId}`;+const title = await client.titleConvo({ text, responseText: response?.text });+ await titleCache.set(key, title);await saveConvo(req.user.id, {conversationId: response.conversationId,title,diff --git a/client/src/components/Chat/Header.tsx b/client/src/components/Chat/Header.tsxindex 0f19db956d..a6e790558b 100644--- a/client/src/components/Chat/Header.tsx+++ b/client/src/components/Chat/Header.tsx@@ -1,6 +1,6 @@import { useOutletContext } from 'react-router-dom';import type { ContextType } from '~/common';-import { EndpointsMenu, PresetsMenu, NewChat } from './Menus';+import { EndpointsMenu, PresetsMenu, HeaderNewChat } from './Menus';import HeaderOptions from './Input/HeaderOptions';export default function Header() {@@ -8,7 +8,7 @@ export default function Header() {return (<div className="sticky top-0 z-10 flex h-14 w-full items-center justify-between bg-white/95 p-2 font-semibold dark:bg-gray-800/90 dark:text-white "><div className="hide-scrollbar flex items-center gap-2 overflow-x-auto">- {!navVisible && <NewChat />}+ {!navVisible && <HeaderNewChat />}<EndpointsMenu /><HeaderOptions /><PresetsMenu />diff --git a/client/src/components/Chat/Landing.tsx b/client/src/components/Chat/Landing.tsxindex 1cc5df08e2..d495ce3058 100644--- a/client/src/components/Chat/Landing.tsx+++ b/client/src/components/Chat/Landing.tsx@@ -7,8 +7,9 @@ import { getEndpointField } from '~/utils';import { useLocalize } from '~/hooks';export default function Landing({ Header }: { Header?: ReactNode }) {- const { data: endpointsConfig } = useGetEndpointsQuery();const { conversation } = useChatContext();+ const { data: endpointsConfig } = useGetEndpointsQuery();+const localize = useLocalize();let { endpoint } = conversation ?? {};if (diff --git a/client/src/components/Chat/Menus/HeaderNewChat.tsx b/client/src/components/Chat/Menus/HeaderNewChat.tsxnew file mode 100644index 0000000000..5ccf4f35bc--- /dev/null+++ b/client/src/components/Chat/Menus/HeaderNewChat.tsx@@ -0,0 +1,23 @@+import { NewChatIcon } from '~/components/svg';+import { useChatContext } from '~/Providers';+import { useMediaQuery } from '~/hooks';++export default function HeaderNewChat() {+ const { newConversation } = useChatContext();+ const isSmallScreen = useMediaQuery('(max-width: 768px)');+ if (isSmallScreen) {+ return null;+ }+ return (+ <button+ data-testid="wide-header-new-chat-button"+ type="button"+ className="btn btn-neutral btn-small border-token-border-medium relative ml-2 flex hidden h-9 w-9 items-center justify-center whitespace-nowrap rounded-lg rounded-lg border focus:ring-0 focus:ring-offset-0 md:flex"+ onClick={() => newConversation()}+ >+ <div className="flex w-full items-center justify-center gap-2">+ <NewChatIcon />+ </div>+ </button>+ );+}diff --git a/client/src/components/Chat/Menus/NewChat.tsx b/client/src/components/Chat/Menus/NewChat.tsxdeleted file mode 100644index 4035714f9c..0000000000--- a/client/src/components/Chat/Menus/NewChat.tsx+++ /dev/null@@ -1,36 +0,0 @@-import { useChatContext } from '~/Providers';-import { useMediaQuery } from '~/hooks';--export default function NewChat() {- const { newConversation } = useChatContext();- const isSmallScreen = useMediaQuery('(max-width: 768px)');- if (isSmallScreen) {- return null;- }- return (- <button- data-testid="wide-header-new-chat-button"- type="button"- className="btn btn-neutral btn-small border-token-border-medium relative ml-2 flex hidden h-9 w-9 items-center justify-center whitespace-nowrap rounded-lg rounded-lg border focus:ring-0 focus:ring-offset-0 md:flex"- onClick={() => newConversation()}- >- <div className="flex w-full items-center justify-center gap-2">- <svg- width="24"- height="24"- viewBox="0 0 24 24"- fill="none"- xmlns="http://www.w3.org/2000/svg"- className="text-black dark:text-white"- >- <path- fillRule="evenodd"- clipRule="evenodd"- d="M16.7929 2.79289C18.0118 1.57394 19.9882 1.57394 21.2071 2.79289C22.4261 4.01184 22.4261 5.98815 21.2071 7.20711L12.7071 15.7071C12.5196 15.8946 12.2652 16 12 16H9C8.44772 16 8 15.5523 8 15V12C8 11.7348 8.10536 11.4804 8.29289 11.2929L16.7929 2.79289ZM19.7929 4.20711C19.355 3.7692 18.645 3.7692 18.2071 4.2071L10 12.4142V14H11.5858L19.7929 5.79289C20.2308 5.35499 20.2308 4.64501 19.7929 4.20711ZM6 5C5.44772 5 5 5.44771 5 6V18C5 18.5523 5.44772 19 6 19H18C18.5523 19 19 18.5523 19 18V14C19 13.4477 19.4477 13 20 13C20.5523 13 21 13.4477 21 14V18C21 19.6569 19.6569 21 18 21H6C4.34315 21 3 19.6569 3 18V6C3 4.34314 4.34315 3 6 3H10C10.5523 3 11 3.44771 11 4C11 4.55228 10.5523 5 10 5H6Z"- fill="currentColor"- />- </svg>- </div>- </button>- );-}diff --git a/client/src/components/Chat/Menus/index.ts b/client/src/components/Chat/Menus/index.tsindex 26913eb964..d505f76510 100644--- a/client/src/components/Chat/Menus/index.ts+++ b/client/src/components/Chat/Menus/index.ts@@ -1,3 +1,3 @@export { default as EndpointsMenu } from './EndpointsMenu';export { default as PresetsMenu } from './PresetsMenu';-export { default as NewChat } from './NewChat';+export { default as HeaderNewChat } from './HeaderNewChat';diff --git a/client/src/components/Chat/SearchView.tsx b/client/src/components/Chat/SearchView.tsxnew file mode 100644index 0000000000..5feed132cc--- /dev/null+++ b/client/src/components/Chat/SearchView.tsx@@ -0,0 +1,22 @@+import { memo } from 'react';+import { useRecoilValue } from 'recoil';+import MessagesView from './Messages/MessagesView';+import store from '~/store';++import Header from './Header';++function SearchView() {+ const searchResultMessagesTree = useRecoilValue(store.searchResultMessagesTree);++ return (+ <div className="relative flex w-full grow overflow-hidden bg-white dark:bg-gray-800">+ <div className="transition-width relative flex h-full w-full flex-1 flex-col items-stretch overflow-hidden bg-white pt-0 dark:bg-gray-800">+ <div className="flex h-full flex-col" role="presentation" tabIndex={0}>+ <MessagesView messagesTree={searchResultMessagesTree} Header={<Header />} />+ </div>+ </div>+ </div>+ );+}++export default memo(SearchView);diff --git a/client/src/components/Conversations/Conversation.jsx b/client/src/components/Conversations/Conversation.jsxindex 375edddd32..1dc9bf4e1a 100644--- a/client/src/components/Conversations/Conversation.jsx+++ b/client/src/components/Conversations/Conversation.jsx@@ -1,6 +1,6 @@import { useState, useRef } from 'react';import { useRecoilState, useSetRecoilState } from 'recoil';-import { useUpdateConversationMutation } from 'librechat-data-provider/react-query';+import { useUpdateConversationMutation } from '~/data-provider';import { useConversations, useConversation } from '~/hooks';import { MinimalIcon } from '~/components/Endpoints';import { NotificationSeverity } from '~/common';diff --git a/client/src/components/Conversations/Conversations.tsx b/client/src/components/Conversations/Conversations.tsxindex 5ce4f1f8b9..4c46a64687 100644--- a/client/src/components/Conversations/Conversations.tsx+++ b/client/src/components/Conversations/Conversations.tsx@@ -1,7 +1,10 @@-import Convo from './Convo';-import Conversation from './Conversation';+import { useMemo } from 'react';+import { parseISO, isToday } from 'date-fns';import { useLocation } from 'react-router-dom';import { TConversation } from 'librechat-data-provider';+import { groupConversationsByDate } from '~/utils';+import Conversation from './Conversation';+import Convo from './Convo';export default function Conversations({conversations,@@ -15,22 +18,50 @@ export default function Conversations({const location = useLocation();const { pathname } = location;const ConvoItem = pathname.includes('chat') ? Conversation : Convo;+ const groupedConversations = useMemo(+ () => groupConversationsByDate(conversations),+ [conversations],+ );+ const firstTodayConvoId = conversations.find((convo) =>+ isToday(parseISO(convo.updatedAt)),+ )?.conversationId;return (- <>- {conversations &&- conversations.length > 0 &&- conversations.map((convo: TConversation, i) => {- return (- <ConvoItem- key={convo.conversationId}- conversation={convo}- retainView={moveToTop}- toggleNav={toggleNav}- i={i}- />- );- })}- </>+ <div className="text-token-text-primary flex flex-col gap-2 pb-2 text-sm">+ <div>+ <span>+ {groupedConversations.map(([groupName, convos]) => (+ <div key={groupName}>+ <div+ style={{+ color: '#aaa',+ fontSize: '0.7rem',+ marginTop: '20px',+ marginBottom: '5px',+ paddingLeft: '10px',+ }}+ >+ {groupName}+ </div>+ {convos.map((convo, i) => (+ <ConvoItem+ key={`${groupName}-${convo.conversationId}-${i}`}+ isLatestConvo={convo.conversationId === firstTodayConvoId}+ conversation={convo}+ retainView={moveToTop}+ toggleNav={toggleNav}+ />+ ))}+ <div+ style={{+ marginTop: '5px',+ marginBottom: '5px',+ }}+ />+ </div>+ ))}+ </span>+ </div>+ </div>);}diff --git a/client/src/components/Conversations/Convo.tsx b/client/src/components/Conversations/Convo.tsxindex adf30e2851..4bf23fa901 100644--- a/client/src/components/Conversations/Convo.tsx+++ b/client/src/components/Conversations/Convo.tsx@@ -1,13 +1,11 @@import { useRecoilValue } from 'recoil';import { useState, useRef } from 'react';import { useParams } from 'react-router-dom';-import {- useGetEndpointsQuery,- useUpdateConversationMutation,-} from 'librechat-data-provider/react-query';import { EModelEndpoint } from 'librechat-data-provider';+import { useGetEndpointsQuery } from 'librechat-data-provider/react-query';import type { MouseEvent, FocusEvent, KeyboardEvent } from 'react';import { useConversations, useNavigateToConvo } from '~/hooks';+import { useUpdateConversationMutation } from '~/data-provider';import { MinimalIcon } from '~/components/Endpoints';import { NotificationSeverity } from '~/common';import { useToastContext } from '~/Providers';@@ -18,7 +16,7 @@ import store from '~/store';type KeyEvent = KeyboardEvent<HTMLInputElement>;-export default function Conversation({ conversation, retainView, toggleNav, i }) {+export default function Conversation({ conversation, retainView, toggleNav, isLatestConvo }) {const { conversationId: currentConvoId } = useParams();const updateConvoMutation = useUpdateConversationMutation(currentConvoId ?? '');const activeConvos = useRecoilValue(store.allConversationsSelector);@@ -32,7 +30,13 @@ export default function Conversation({ conversation, retainView, toggleNav, i })const [titleInput, setTitleInput] = useState(title);const [renaming, setRenaming] = useState(false);- const clickHandler = async () => {+ const clickHandler = async (event: React.MouseEvent<HTMLAnchorElement>) => {+ if (event.button === 0 && event.ctrlKey) {+ toggleNav();+ return;+ }++ event.preventDefault();if (currentConvoId === conversationId) {return;}@@ -109,22 +113,28 @@ export default function Conversation({ conversation, retainView, toggleNav, i })const aProps = {className:- 'animate-flash group relative flex cursor-pointer items-center gap-3 break-all rounded-md bg-gray-900 py-3 px-3 pr-14 hover:bg-gray-900',+ 'group relative rounded-lg active:opacity-50 flex cursor-pointer items-center mt-2 gap-3 break-all rounded-lg bg-gray-800 py-2 px-2',};const activeConvo =currentConvoId === conversationId ||- (i === 0 && currentConvoId === 'new' && activeConvos[0] && activeConvos[0] !== 'new');+ (isLatestConvo && currentConvoId === 'new' && activeConvos[0] && activeConvos[0] !== 'new');if (!activeConvo) {aProps.className =- 'group relative flex cursor-pointer items-center gap-3 break-all rounded-md py-3 px-3 hover:bg-gray-900 hover:pr-4';+ 'group relative rounded-lg active:opacity-50 flex cursor-pointer items-center mt-2 gap-3 break-all rounded-lg py-2 px-2 hover:bg-gray-900';}return (- <a data-testid="convo-item" onClick={() => clickHandler()} {...aProps} title={title}>+ <a+ href={`/c/${conversationId}`}+ data-testid="convo-item"+ onClick={clickHandler}+ {...aProps}+ title={title}+ >{icon}- <div className="relative line-clamp-1 max-h-5 flex-1 text-ellipsis break-all">+ <div className="relative line-clamp-1 max-h-5 flex-1 grow overflow-hidden">{renaming === true ? (<inputref={inputRef}@@ -139,6 +149,11 @@ export default function Conversation({ conversation, retainView, toggleNav, i })title)}</div>+ {activeConvo ? (+ <div className="absolute bottom-0 right-1 top-0 w-20 bg-gradient-to-l from-gray-800 from-60% to-transparent"></div>+ ) : (+ <div className="from--gray-900 absolute bottom-0 right-0 top-0 w-2 bg-gradient-to-l from-0% to-transparent group-hover:w-1 group-hover:from-60%"></div>+ )}{activeConvo ? (<div className="visible absolute right-1 z-10 flex text-gray-400"><RenameButton renaming={renaming} onRename={onRename} renameHandler={renameHandler} />@@ -150,7 +165,7 @@ export default function Conversation({ conversation, retainView, toggleNav, i })/></div>) : (- <div className="absolute inset-y-0 right-0 z-10 w-8 rounded-r-md bg-gradient-to-l from-black group-hover:from-gray-900" />+ <div className="absolute bottom-0 right-0 top-0 w-20 rounded-lg bg-gradient-to-l from-black from-0% to-transparent group-hover:from-gray-900" />)}</a>);diff --git a/client/src/components/Conversations/DeleteButton.tsx b/client/src/components/Conversations/DeleteButton.tsxindex 75e2bfc5bd..7b54e587bc 100644--- a/client/src/components/Conversations/DeleteButton.tsx+++ b/client/src/components/Conversations/DeleteButton.tsx@@ -1,6 +1,6 @@import { useParams } from 'react-router-dom';-import { useDeleteConversationMutation } from 'librechat-data-provider/react-query';import { useLocalize, useConversations, useConversation } from '~/hooks';+import { useDeleteConversationMutation } from '~/data-provider';import { Dialog, DialogTrigger, Label } from '~/components/ui';import DialogTemplate from '~/components/ui/DialogTemplate';import { TrashIcon, CrossIcon } from '~/components/svg';diff --git a/client/src/components/Conversations/NewDeleteButton.tsx b/client/src/components/Conversations/NewDeleteButton.tsxindex 337bc8fb61..7710a77b93 100644--- a/client/src/components/Conversations/NewDeleteButton.tsx+++ b/client/src/components/Conversations/NewDeleteButton.tsx@@ -1,6 +1,6 @@import { useParams } from 'react-router-dom';-import { useDeleteConversationMutation } from 'librechat-data-provider/react-query';import { useLocalize, useConversations, useNewConvo } from '~/hooks';+import { useDeleteConversationMutation } from '~/data-provider';import { Dialog, DialogTrigger, Label } from '~/components/ui';import DialogTemplate from '~/components/ui/DialogTemplate';import { TrashIcon, CrossIcon } from '~/components/svg';diff --git a/client/src/components/Nav/Nav.tsx b/client/src/components/Nav/Nav.tsxindex 86a3e33597..dae0f54667 100644--- a/client/src/components/Nav/Nav.tsx+++ b/client/src/components/Nav/Nav.tsx@@ -1,16 +1,18 @@-import { useSearchQuery, useGetConversationsQuery } from 'librechat-data-provider/react-query';+import { useParams } from 'react-router-dom';import { useRecoilValue, useSetRecoilState } from 'recoil';-import { useCallback, useEffect, useRef, useState } from 'react';-import type { TConversation, TSearchResults } from 'librechat-data-provider';+import { useCallback, useEffect, useState, useMemo } from 'react';+import type { ConversationListResponse } from 'librechat-data-provider';import {- useAuthContext,useMediaQuery,+ useAuthContext,useConversation,- useConversations,useLocalStorage,+ useNavScrolling,+ useConversations,} from '~/hooks';+import { useSearchInfiniteQuery, useConversationsInfiniteQuery } from '~/data-provider';import { TooltipProvider, Tooltip } from '~/components/ui';-import { Conversations, Pages } from '../Conversations';+import { Conversations } from '~/components/Conversations';import { Spinner } from '~/components/svg';import SearchBar from './SearchBar';import NavToggle from './NavToggle';@@ -20,14 +22,14 @@ import { cn } from '~/utils';import store from '~/store';export default function Nav({ navVisible, setNavVisible }) {- const [isToggleHovering, setIsToggleHovering] = useState(false);- const [isHovering, setIsHovering] = useState(false);- const [navWidth, setNavWidth] = useState('260px');+ const { conversationId } = useParams();const { isAuthenticated } = useAuthContext();- const containerRef = useRef<HTMLDivElement | null>(null);- const scrollPositionRef = useRef<number | null>(null);++ const [navWidth, setNavWidth] = useState('260px');+ const [isHovering, setIsHovering] = useState(false);const isSmallScreen = useMediaQuery('(max-width: 768px)');const [newUser, setNewUser] = useLocalStorage('newUser', true);+ const [isToggleHovering, setIsToggleHovering] = useState(false);useEffect(() => {if (isSmallScreen) {@@ -37,44 +39,42 @@ export default function Nav({ navVisible, setNavVisible }) {}}, [isSmallScreen]);- const [conversations, setConversations] = useState<TConversation[]>([]);- // current pageconst [pageNumber, setPageNumber] = useState(1);- // total pages- const [pages, setPages] = useState(1);-- // data provider- const getConversationsQuery = useGetConversationsQuery(pageNumber + '', {- enabled: isAuthenticated,- });+ const [showLoading, setShowLoading] = useState(false);- // searchconst searchQuery = useRecoilValue(store.searchQuery);const isSearchEnabled = useRecoilValue(store.isSearchEnabled);- const isSearching = useRecoilValue(store.isSearching);const { newConversation, searchPlaceholderConversation } = useConversation();- // current conversation- const conversation = useRecoilValue(store.conversation);- const { conversationId } = conversation || {};- const setSearchResultMessages = useSetRecoilState(store.searchResultMessages);- const refreshConversationsHint = useRecoilValue(store.refreshConversationsHint);const { refreshConversations } = useConversations();+ const setSearchResultMessages = useSetRecoilState(store.searchResultMessages);- const [isFetching, setIsFetching] = useState(false);+ const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useConversationsInfiniteQuery(+ { pageNumber: pageNumber.toString() },+ { enabled: isAuthenticated },+ );++ const searchQueryRes = useSearchInfiniteQuery(+ { pageNumber: pageNumber.toString(), searchQuery: searchQuery },+ { enabled: isAuthenticated && !!searchQuery.length },+ );- const searchQueryFn = useSearchQuery(searchQuery, pageNumber + '', {- enabled: !!(!!searchQuery && searchQuery.length > 0 && isSearchEnabled && isSearching),+ const { containerRef, moveToTop } = useNavScrolling({+ setShowLoading,+ hasNextPage: searchQuery ? searchQueryRes.hasNextPage : hasNextPage,+ fetchNextPage: searchQuery ? searchQueryRes.fetchNextPage : fetchNextPage,+ isFetchingNextPage: searchQuery ? searchQueryRes.isFetchingNextPage : isFetchingNextPage,});- const onSearchSuccess = useCallback((data: TSearchResults, expectedPage?: number) => {+ const conversations = useMemo(+ () =>+ (searchQuery ? searchQueryRes?.data : data)?.pages.flatMap((page) => page.conversations) ||+ [],+ [data, searchQuery, searchQueryRes?.data],+ );++ const onSearchSuccess = useCallback(({ data }: { data: ConversationListResponse }) => {const res = data;- setConversations(res.conversations);- if (expectedPage) {- setPageNumber(expectedPage);- }- setPages(Number(res.pages));- setIsFetching(false);searchPlaceholderConversation();setSearchResultMessages(res.messages);/* disabled due recoil methods not recognized as state setters */@@ -83,12 +83,10 @@ export default function Nav({ navVisible, setNavVisible }) {useEffect(() => {//we use isInitialLoading here instead of isLoading because query is disabled by default- if (searchQueryFn.isInitialLoading) {- setIsFetching(true);- } else if (searchQueryFn.data) {- onSearchSuccess(searchQueryFn.data);+ if (searchQueryRes.data) {+ onSearchSuccess({ data: searchQueryRes.data.pages[0] });}- }, [searchQueryFn.data, searchQueryFn.isInitialLoading, onSearchSuccess]);+ }, [searchQueryRes.data, searchQueryRes.isInitialLoading, onSearchSuccess]);const clearSearch = () => {setPageNumber(1);@@ -98,51 +96,6 @@ export default function Nav({ navVisible, setNavVisible }) {}};- const moveToTop = useCallback(() => {- const container = containerRef.current;- if (container) {- scrollPositionRef.current = container.scrollTop;- }- }, [containerRef, scrollPositionRef]);-- const nextPage = async () => {- moveToTop();- setPageNumber(pageNumber + 1);- };-- const previousPage = async () => {- moveToTop();- setPageNumber(pageNumber - 1);- };-- useEffect(() => {- if (getConversationsQuery.data) {- if (isSearching) {- return;- }- let { conversations, pages } = getConversationsQuery.data;- pages = Number(pages);- if (pageNumber > pages) {- setPageNumber(pages);- } else {- if (!isSearching) {- conversations = conversations.sort(- (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),- );- }- setConversations(conversations);- setPages(pages);- }- }- }, [getConversationsQuery.isSuccess, getConversationsQuery.data, isSearching, pageNumber]);-- useEffect(() => {- if (!isSearching) {- getConversationsQuery.refetch();- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [pageNumber, conversationId, refreshConversationsHint]);-const toggleNavVisible = () => {setNavVisible((prev: boolean) => !prev);if (newUser) {@@ -156,11 +109,6 @@ export default function Nav({ navVisible, setNavVisible }) {}};- const containerClasses =- getConversationsQuery.isLoading && pageNumber === 1- ? 'flex flex-col gap-2 text-gray-100 text-sm h-full justify-center items-center'- : 'flex flex-col gap-2 text-gray-100 text-sm';-return (<TooltipProvider delayDuration={150}><Tooltip>@@ -178,44 +126,44 @@ export default function Nav({ navVisible, setNavVisible }) {<div className="flex h-full min-h-0 flex-col"><divclassName={cn(- 'scrollbar-trigger relative flex h-full w-full flex-1 items-start border-white/20 transition-opacity',+ 'flex h-full min-h-0 flex-col transition-opacity',isToggleHovering && !isSmallScreen ? 'opacity-50' : 'opacity-100',)}>- <nav className="relative flex h-full flex-1 flex-col space-y-1 p-2">- <div className="mb-1 flex h-11 flex-row">- <NewChat toggleNav={itemToggleNav} />- </div>- {isSearchEnabled && <SearchBar clearSearch={clearSearch} />}- <div- className={`flex-1 flex-col overflow-y-auto ${- isHovering ? '' : 'scrollbar-transparent'- } border-b border-white/20`}- onMouseEnter={() => setIsHovering(true)}- onMouseLeave={() => setIsHovering(false)}- ref={containerRef}- >- <div className={containerClasses}>- {(getConversationsQuery.isLoading && pageNumber === 1) || isFetching ? (- <Spinner />- ) : (- <Conversations- conversations={conversations}- moveToTop={moveToTop}- toggleNav={itemToggleNav}- />+ <div+ className={cn(+ 'scrollbar-trigger relative h-full w-full flex-1 items-start border-white/20',+ )}+ >+ <nav className="flex h-full w-full flex-col px-3 pb-3.5">+ <div+ className={cn(+ '-mr-2 flex-1 flex-col overflow-y-auto pr-2 transition-opacity duration-500',+ isHovering ? '' : 'scrollbar-transparent',)}- <Pages- pageNumber={pageNumber}- pages={pages}- nextPage={nextPage}- previousPage={previousPage}- setPageNumber={setPageNumber}+ onMouseEnter={() => setIsHovering(true)}+ onMouseLeave={() => setIsHovering(false)}+ ref={containerRef}+ >+ <NewChat+ toggleNav={itemToggleNav}+ subHeaders={isSearchEnabled && <SearchBar clearSearch={clearSearch} />}+ />+ <Conversations+ conversations={conversations}+ moveToTop={moveToTop}+ toggleNav={itemToggleNav}+ />+ <Spinner+ className={cn(+ 'm-1 mx-auto mb-4 h-4 w-4',+ isFetchingNextPage || showLoading ? 'opacity-1' : 'opacity-0',+ )}/></div>- </div>- <NavLinks />- </nav>+ <NavLinks />+ </nav>+ </div></div></div></div>diff --git a/client/src/components/Nav/NewChat.tsx b/client/src/components/Nav/NewChat.tsxindex b0ebb195dc..75a5facf08 100644--- a/client/src/components/Nav/NewChat.tsx+++ b/client/src/components/Nav/NewChat.tsx@@ -1,11 +1,36 @@-import { useLocalize, useConversation, useNewConvo, useOriginNavigate } from '~/hooks';+import { EModelEndpoint } from 'librechat-data-provider';+import { useGetEndpointsQuery } from 'librechat-data-provider/react-query';+import {+ useLocalize,+ useConversation,+ useNewConvo,+ useOriginNavigate,+ useLocalStorage,+} from '~/hooks';+import { icons } from '~/components/Chat/Menus/Endpoints/Icons';+import { NewChatIcon } from '~/components/svg';+import { getEndpointField } from '~/utils';-export default function NewChat({ toggleNav }: { toggleNav: () => void }) {- const { newConversation } = useConversation();+export default function NewChat({+ toggleNav,+ subHeaders,+}: {+ toggleNav: () => void;+ subHeaders?: React.ReactNode;+}) {const { newConversation: newConvo } = useNewConvo();+ const { newConversation } = useConversation();const navigate = useOriginNavigate();const localize = useLocalize();+ const { data: endpointsConfig } = useGetEndpointsQuery();+ const [convo] = useLocalStorage('lastConversationSetup', { endpoint: EModelEndpoint.openAI });+ const { endpoint } = convo;+ const endpointType = getEndpointField(endpointsConfig, endpoint, 'type');+ const iconURL = getEndpointField(endpointsConfig, endpoint, 'iconURL');+ const iconKey = endpointType ? 'unknown' : endpoint ?? 'unknown';+ const Icon = icons[iconKey];+const clickHandler = (event: React.MouseEvent<HTMLAnchorElement>) => {if (event.button === 0 && !event.ctrlKey) {event.preventDefault();@@ -17,28 +42,40 @@ export default function NewChat({ toggleNav }: { toggleNav: () => void }) {};return (- <a- href="/"- data-testid="nav-new-chat-button"- onClick={clickHandler}- className="flex h-11 flex-shrink-0 flex-grow cursor-pointer items-center gap-3 rounded-md border border-white/20 px-3 py-3 text-sm text-white transition-colors duration-200 hover:bg-gray-500/10"- >- <svg- stroke="currentColor"- fill="none"- strokeWidth="2"- viewBox="0 0 24 24"- strokeLinecap="round"- strokeLinejoin="round"- className="h-4 w-4"- height="1em"- width="1em"- xmlns="http://www.w3.org/2000/svg"- >- <line x1="12" y1="5" x2="12" y2="19" />- <line x1="5" y1="12" x2="19" y2="12" />- </svg>- {localize('com_ui_new_chat')}- </a>+ <div className="sticky left-0 right-0 top-0 z-20 bg-black pt-3.5">+ <div className="pb-0.5 last:pb-0" tabIndex={0} style={{ transform: 'none' }}>+ <a+ href="/"+ data-testid="nav-new-chat-button"+ onClick={clickHandler}+ className="group flex h-10 items-center gap-2 rounded-lg px-2 font-medium hover:bg-gray-900"+ >+ <div className="h-7 w-7 flex-shrink-0">+ <div className="shadow-stroke relative flex h-full items-center justify-center rounded-full bg-white text-black">+ {endpoint &&+ Icon &&+ Icon({+ size: 41,+ context: 'nav',+ className: 'h-2/3 w-2/3',+ endpoint: endpoint,+ iconURL: iconURL,+ })}+ </div>+ </div>+ <div className="text-token-text-primary grow overflow-hidden text-ellipsis whitespace-nowrap text-sm">+ {localize('com_ui_new_chat')}+ </div>+ <div className="flex gap-3">+ <span className="flex items-center" data-state="closed">+ <button type="button" className="text-token-text-primary">+ <NewChatIcon className="h-[18px] w-[18px]" />+ </button>+ </span>+ </div>+ </a>+ </div>+ {subHeaders ? subHeaders : null}+ </div>);}diff --git a/client/src/components/Nav/SearchBar.tsx b/client/src/components/Nav/SearchBar.tsxindex 6f6fe6c21d..713a41cc84 100644--- a/client/src/components/Nav/SearchBar.tsx+++ b/client/src/components/Nav/SearchBar.tsx@@ -3,6 +3,7 @@ import { Search, X } from 'lucide-react';import { useSetRecoilState } from 'recoil';import debounce from 'lodash/debounce';import { useLocalize } from '~/hooks';+import { cn } from '~/utils';import store from '~/store';type SearchBarProps = {@@ -43,7 +44,7 @@ const SearchBar = forwardRef((props: SearchBarProps, ref: Ref<HTMLDivElement>) =return (<divref={ref}- className="relative flex w-full cursor-pointer items-center gap-3 rounded-md border border-white/20 px-3 py-3 text-sm text-white transition-colors duration-200 hover:bg-gray-500/10"+ className="relative mt-1 flex flex h-10 cursor-pointer items-center gap-3 rounded-lg border-white bg-black px-2 px-3 py-2 text-white transition-colors duration-200 hover:bg-gray-900 focus:bg-gray-900">{<Search className="absolute left-3 h-4 w-4" />}<input@@ -58,9 +59,10 @@ const SearchBar = forwardRef((props: SearchBarProps, ref: Ref<HTMLDivElement>) =onKeyUp={handleKeyUp}/><X- className={`absolute right-3 h-5 w-5 cursor-pointer ${- showClearIcon ? 'opacity-100' : 'opacity-0'- } transition-opacity duration-1000`}+ className={cn(+ 'absolute right-[7px] h-5 w-5 cursor-pointer transition-opacity duration-1000',+ showClearIcon ? 'opacity-100' : 'opacity-0',+ )}onClick={clearText}/></div>diff --git a/client/src/components/svg/GoogleIconChat.tsx b/client/src/components/svg/GoogleIconChat.tsxnew file mode 100644index 0000000000..4c2f4eb8fc--- /dev/null+++ b/client/src/components/svg/GoogleIconChat.tsx@@ -0,0 +1,26 @@+import { cn } from '~/utils/';++export default function Google({+ size = 25,+ className = '',+}: {+ size?: number;+ className?: string;+}) {+ const unit = '41';+ const height = size;+ const width = size;+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ fill="currentColor"+ width="24px"+ height="24px"+ viewBox="0 0 512 512"+ strokeWidth="1.5"+ className={cn(className, '')}+ >+ <path d="M473.16,221.48l-2.26-9.59H262.46v88.22H387c-12.93,61.4-72.93,93.72-121.94,93.72-35.66,0-73.25-15-98.13-39.11a140.08,140.08,0,0,1-41.8-98.88c0-37.16,16.7-74.33,41-98.78s61-38.13,97.49-38.13c41.79,0,71.74,22.19,82.94,32.31l62.69-62.36C390.86,72.72,340.34,32,261.6,32h0c-60.75,0-119,23.27-161.58,65.71C58,139.5,36.25,199.93,36.25,256S56.83,369.48,97.55,411.6C141.06,456.52,202.68,480,266.13,480c57.73,0,112.45-22.62,151.45-63.66,38.34-40.4,58.17-96.3,58.17-154.9C475.75,236.77,473.27,222.12,473.16,221.48Z"></path>+ </svg>+ );+}diff --git a/client/src/components/svg/NewChatIcon.tsx b/client/src/components/svg/NewChatIcon.tsxnew file mode 100644index 0000000000..59bc7ac1ec--- /dev/null+++ b/client/src/components/svg/NewChatIcon.tsx@@ -0,0 +1,20 @@+import { cn } from '~/utils';+export default function NewChatIcon({ className = '' }: { className?: string }) {+ return (+ <svg+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ className={cn('text-black dark:text-white', className)}+ >+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M16.7929 2.79289C18.0118 1.57394 19.9882 1.57394 21.2071 2.79289C22.4261 4.01184 22.4261 5.98815 21.2071 7.20711L12.7071 15.7071C12.5196 15.8946 12.2652 16 12 16H9C8.44772 16 8 15.5523 8 15V12C8 11.7348 8.10536 11.4804 8.29289 11.2929L16.7929 2.79289ZM19.7929 4.20711C19.355 3.7692 18.645 3.7692 18.2071 4.2071L10 12.4142V14H11.5858L19.7929 5.79289C20.2308 5.35499 20.2308 4.64501 19.7929 4.20711ZM6 5C5.44772 5 5 5.44771 5 6V18C5 18.5523 5.44772 19 6 19H18C18.5523 19 19 18.5523 19 18V14C19 13.4477 19.4477 13 20 13C20.5523 13 21 13.4477 21 14V18C21 19.6569 19.6569 21 18 21H6C4.34315 21 3 19.6569 3 18V6C3 4.34314 4.34315 3 6 3H10C10.5523 3 11 3.44771 11 4C11 4.55228 10.5523 5 10 5H6Z"+ fill="currentColor"+ />+ </svg>+ );+}diff --git a/client/src/components/svg/Spinner.tsx b/client/src/components/svg/Spinner.tsxindex 3e60397cd6..eb473fe3e7 100644--- a/client/src/components/svg/Spinner.tsx+++ b/client/src/components/svg/Spinner.tsx@@ -4,7 +4,7 @@ import { cn } from '~/utils/';export default function Spinner({ className = 'm-auto' }) {return (<svg- stroke="currentColor"+ stroke="#ffffff"fill="none"strokeWidth="2"viewBox="0 0 24 24"diff --git a/client/src/components/svg/index.ts b/client/src/components/svg/index.tsindex ac4ad7f0b8..97ea21e611 100644--- a/client/src/components/svg/index.ts+++ b/client/src/components/svg/index.ts@@ -42,4 +42,6 @@ export { default as GoogleMinimalIcon } from './GoogleMinimalIcon';export { default as AnthropicMinimalIcon } from './AnthropicMinimalIcon';export { default as SendMessageIcon } from './SendMessageIcon';export { default as UserIcon } from './UserIcon';+export { default as NewChatIcon } from './NewChatIcon';export { default as ExperimentIcon } from './ExperimentIcon';+export { default as GoogleIconChat } from './GoogleIconChat';diff --git a/client/src/data-provider/mutations.ts b/client/src/data-provider/mutations.tsindex e607818cc7..a4737b6a76 100644--- a/client/src/data-provider/mutations.ts+++ b/client/src/data-provider/mutations.ts@@ -1,5 +1,6 @@import { useMutation, useQueryClient } from '@tanstack/react-query';import type { UseMutationResult } from '@tanstack/react-query';+import type t from 'librechat-data-provider';import type {TFileUpload,UploadMutationOptions,@@ -14,12 +15,99 @@ import type {TPreset,UploadAvatarOptions,AvatarUploadResponse,+ TConversation,} from 'librechat-data-provider';--import { dataService, MutationKeys } from 'librechat-data-provider';+import { dataService, MutationKeys, QueryKeys } from 'librechat-data-provider';+import { updateConversation, deleteConversation, updateConvoFields } from '~/utils';import { useSetRecoilState } from 'recoil';import store from '~/store';+/** Conversations */+export const useGenTitleMutation = (): UseMutationResult<+ t.TGenTitleResponse,+ unknown,+ t.TGenTitleRequest,+ unknown+> => {+ const queryClient = useQueryClient();+ return useMutation((payload: t.TGenTitleRequest) => dataService.genTitle(payload), {+ onSuccess: (response, vars) => {+ queryClient.setQueryData(+ [QueryKeys.conversation, vars.conversationId],+ (convo: TConversation | undefined) => {+ if (!convo) {+ return convo;+ }+ return { ...convo, title: response.title };+ },+ );+ queryClient.setQueryData<t.ConversationData>([QueryKeys.allConversations], (convoData) => {+ if (!convoData) {+ return convoData;+ }+ return updateConvoFields(convoData, {+ conversationId: vars.conversationId,+ title: response.title,+ } as TConversation);+ });+ },+ });+};++export const useUpdateConversationMutation = (+ id: string,+): UseMutationResult<+ t.TUpdateConversationResponse,+ unknown,+ t.TUpdateConversationRequest,+ unknown+> => {+ const queryClient = useQueryClient();+ return useMutation(+ (payload: t.TUpdateConversationRequest) => dataService.updateConversation(payload),+ {+ onSuccess: (updatedConvo) => {+ queryClient.setQueryData([QueryKeys.conversation, id], updatedConvo);+ queryClient.setQueryData<t.ConversationData>([QueryKeys.allConversations], (convoData) => {+ if (!convoData) {+ return convoData;+ }+ return updateConversation(convoData, updatedConvo);+ });+ },+ },+ );+};++export const useDeleteConversationMutation = (+ id?: string,+): UseMutationResult<+ t.TDeleteConversationResponse,+ unknown,+ t.TDeleteConversationRequest,+ unknown+> => {+ const queryClient = useQueryClient();+ return useMutation(+ (payload: t.TDeleteConversationRequest) => dataService.deleteConversation(payload),+ {+ onSuccess: () => {+ if (!id) {+ return;+ }+ queryClient.setQueryData([QueryKeys.conversation, id], null);+ queryClient.setQueryData<t.ConversationData>([QueryKeys.allConversations], (convoData) => {+ if (!convoData) {+ return convoData;+ }+ const update = deleteConversation(convoData, id);+ return update;+ });+ },+ },+ );+};+export const useUploadImageMutation = (options?: UploadMutationOptions,): UseMutationResult<diff --git a/client/src/data-provider/queries.ts b/client/src/data-provider/queries.tsindex 2ae6aaf81b..431b4f813b 100644--- a/client/src/data-provider/queries.ts+++ b/client/src/data-provider/queries.ts@@ -1,6 +1,18 @@import { QueryKeys, dataService } from 'librechat-data-provider';-import { UseQueryOptions, useQuery, QueryObserverResult } from '@tanstack/react-query';-import type { TPreset, TFile } from 'librechat-data-provider';+import { useQuery, useInfiniteQuery, useQueryClient } from '@tanstack/react-query';+import type {+ UseInfiniteQueryOptions,+ QueryObserverResult,+ UseQueryOptions,+} from '@tanstack/react-query';+import type t from 'librechat-data-provider';+import type {+ TPreset,+ TFile,+ ConversationListResponse,+ ConversationListParams,+} from 'librechat-data-provider';+import { findPageForConversation } from '~/utils';export const useGetFiles = <TData = TFile[] | boolean>(config?: UseQueryOptions<TFile[], unknown, TData>,@@ -38,3 +50,82 @@ export const useGetEndpointsConfigOverride = <TData = unknown | boolean>(},);};++export const useGetConvoIdQuery = (+ id: string,+ config?: UseQueryOptions<t.TConversation>,+): QueryObserverResult<t.TConversation> => {+ const queryClient = useQueryClient();+ return useQuery<t.TConversation>(+ [QueryKeys.conversation, id],+ () => {+ const defaultQuery = () => dataService.getConversationById(id);+ const convosQuery = queryClient.getQueryData<t.ConversationData>([+ QueryKeys.allConversations,+ ]);++ if (!convosQuery) {+ return defaultQuery();+ }++ const { pageIndex, convIndex } = findPageForConversation(convosQuery, { conversationId: id });++ if (pageIndex > -1 && convIndex > -1) {+ return convosQuery.pages[pageIndex].conversations[convIndex];+ }++ return defaultQuery();+ },+ {+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ refetchOnMount: false,+ ...config,+ },+ );+};++export const useSearchInfiniteQuery = (+ params?: ConversationListParams & { searchQuery?: string },+ config?: UseInfiniteQueryOptions<ConversationListResponse, unknown>,+) => {+ return useInfiniteQuery<ConversationListResponse, unknown>(+ [QueryKeys.searchConversations, params], // Include the searchQuery in the query key+ ({ pageParam = '1' }) =>+ dataService.listConversationsByQuery({ ...params, pageNumber: pageParam }),+ {+ getNextPageParam: (lastPage) => {+ const currentPageNumber = Number(lastPage.pageNumber);+ const totalPages = Number(lastPage.pages);+ return currentPageNumber < totalPages ? currentPageNumber + 1 : undefined;+ },+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ refetchOnMount: false,+ ...config,+ },+ );+};++export const useConversationsInfiniteQuery = (+ params?: ConversationListParams,+ config?: UseInfiniteQueryOptions<ConversationListResponse, unknown>,+) => {+ return useInfiniteQuery<ConversationListResponse, unknown>(+ [QueryKeys.allConversations],+ ({ pageParam = '' }) =>+ dataService.listConversations({ ...params, pageNumber: pageParam?.toString() }),+ {+ getNextPageParam: (lastPage) => {+ const currentPageNumber = Number(lastPage.pageNumber);+ const totalPages = Number(lastPage.pages); // Convert totalPages to a number+ // If the current page number is less than total pages, return the next page number+ return currentPageNumber < totalPages ? currentPageNumber + 1 : undefined;+ },+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ refetchOnMount: false,+ ...config,+ },+ );+};diff --git a/client/src/hooks/Nav/index.ts b/client/src/hooks/Nav/index.tsnew file mode 100644index 0000000000..ff2140639e--- /dev/null+++ b/client/src/hooks/Nav/index.ts@@ -0,0 +1 @@+export { default as useNavScrolling } from './useNavScrolling';diff --git a/client/src/hooks/Nav/useNavScrolling.ts b/client/src/hooks/Nav/useNavScrolling.tsnew file mode 100644index 0000000000..ba45d3eabf--- /dev/null+++ b/client/src/hooks/Nav/useNavScrolling.ts@@ -0,0 +1,64 @@+import throttle from 'lodash/throttle';+import React, { useCallback, useEffect, useRef } from 'react';+import type { FetchNextPageOptions, InfiniteQueryObserverResult } from '@tanstack/react-query';+import type { ConversationListResponse } from 'librechat-data-provider';++export default function useNavScrolling({+ hasNextPage,+ isFetchingNextPage,+ setShowLoading,+ fetchNextPage,+}: {+ hasNextPage?: boolean;+ isFetchingNextPage: boolean;+ setShowLoading: React.Dispatch<React.SetStateAction<boolean>>;+ fetchNextPage: (+ options?: FetchNextPageOptions | undefined,+ ) => Promise<InfiniteQueryObserverResult<ConversationListResponse, unknown>>;+}) {+ const scrollPositionRef = useRef<number | null>(null);+ const containerRef = useRef<HTMLDivElement | null>(null);++ // eslint-disable-next-line react-hooks/exhaustive-deps+ const fetchNext = useCallback(+ throttle(() => fetchNextPage(), 750, { leading: true }),+ [fetchNextPage],+ );++ const handleScroll = useCallback(() => {+ if (containerRef.current) {+ const { scrollTop, clientHeight, scrollHeight } = containerRef.current;+ const nearBottomOfList = scrollTop + clientHeight >= scrollHeight * 0.97;++ if (nearBottomOfList && hasNextPage && !isFetchingNextPage) {+ setShowLoading(true);+ fetchNext();+ } else {+ setShowLoading(false);+ }+ }+ }, [hasNextPage, isFetchingNextPage, fetchNext, setShowLoading]);++ useEffect(() => {+ const container = containerRef.current;+ if (container) {+ container.addEventListener('scroll', handleScroll);+ }++ return () => {+ container?.removeEventListener('scroll', handleScroll);+ };+ }, [handleScroll, fetchNext]);++ const moveToTop = useCallback(() => {+ const container = containerRef.current;+ if (container) {+ scrollPositionRef.current = container.scrollTop;+ }+ }, [containerRef, scrollPositionRef]);++ return {+ containerRef,+ moveToTop,+ };+}diff --git a/client/src/hooks/index.ts b/client/src/hooks/index.tsindex 649ea9c0bd..e4a60931be 100644--- a/client/src/hooks/index.ts+++ b/client/src/hooks/index.ts@@ -2,6 +2,7 @@ export * from './Messages';export * from './Config';export * from './Input';export * from './Conversations';+export * from './Nav';export * from './AuthContext';export * from './ThemeContext';diff --git a/client/src/hooks/useChatHelpers.ts b/client/src/hooks/useChatHelpers.tsindex 3d19685925..fd48524631 100644--- a/client/src/hooks/useChatHelpers.ts+++ b/client/src/hooks/useChatHelpers.ts@@ -8,9 +8,7 @@ import type {TMessage,TSubmission,TEndpointOption,- TConversation,TEndpointsConfig,- TGetConversationsResponse,} from 'librechat-data-provider';import type { TAskFunction } from '~/common';import useSetFilesToDelete from './useSetFilesToDelete';@@ -60,42 +58,6 @@ export default function useChatHelpers(index = 0, paramId: string | undefined) {[queryParam, queryClient],);- const addConvo = useCallback(- (convo: TConversation) => {- const convoData = queryClient.getQueryData<TGetConversationsResponse>([- QueryKeys.allConversations,- { pageNumber: '1', active: true },- ]) ?? { conversations: [] as TConversation[], pageNumber: '1', pages: 1, pageSize: 14 };-- let { conversations: convos, pageSize = 14 } = convoData;- pageSize = Number(pageSize);- convos = convos.filter((c) => c.conversationId !== convo.conversationId);- convos = convos.length < pageSize ? convos : convos.slice(0, -1);-- const conversations = [- {- ...convo,- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString(),- },- ...convos,- ];-- queryClient.setQueryData<TGetConversationsResponse>(- [QueryKeys.allConversations, { pageNumber: '1', active: true }],- {- ...convoData,- conversations,- },- );- },- [queryClient],- );-- const invalidateConvos = useCallback(() => {- queryClient.invalidateQueries([QueryKeys.allConversations, { active: true }]);- }, [queryClient]);-const getMessages = useCallback(() => {return queryClient.getQueryData<TMessage[]>([QueryKeys.messages, queryParam]);}, [queryParam, queryClient]);@@ -341,7 +303,6 @@ export default function useChatHelpers(index = 0, paramId: string | undefined) {newConversation,conversation,setConversation,- addConvo,// getConvos,// setConvos,isSubmitting,@@ -373,7 +334,6 @@ export default function useChatHelpers(index = 0, paramId: string | undefined) {setShowAgentSettings,files,setFiles,- invalidateConvos,filesLoading,setFilesLoading,showStopButton,diff --git a/client/src/hooks/useSSE.ts b/client/src/hooks/useSSE.tsindex 94629b2d7a..13e04935b1 100644--- a/client/src/hooks/useSSE.ts+++ b/client/src/hooks/useSSE.ts@@ -1,9 +1,11 @@import { v4 } from 'uuid';-import { useEffect, useState } from 'react';import { useParams } from 'react-router-dom';+import { useQueryClient } from '@tanstack/react-query';+import { useEffect, useState } from 'react';import {/* @ts-ignore */SSE,+ QueryKeys,EndpointURLs,createPayload,tPresetSchema,@@ -13,7 +15,15 @@ import {removeNullishValues,} from 'librechat-data-provider';import { useGetUserBalance, useGetStartupConfig } from 'librechat-data-provider/react-query';-import type { TResPlugin, TMessage, TConversation, TSubmission } from 'librechat-data-provider';+import type {+ TResPlugin,+ TMessage,+ TConversation,+ TSubmission,+ ConversationData,+} from 'librechat-data-provider';+import { addConversation, deleteConversation, updateConversation } from '~/utils';+import { useGenTitleMutation } from '~/data-provider';import { useAuthContext } from './AuthContext';import useChatHelpers from './useChatHelpers';import useSetStorage from './useSetStorage';@@ -30,18 +40,14 @@ type TResData = {export default function useSSE(submission: TSubmission | null, index = 0) {const setStorage = useSetStorage();+ const queryClient = useQueryClient();+ const genTitle = useGenTitleMutation();+const { conversationId: paramId } = useParams();const { token, isAuthenticated } = useAuthContext();const [completed, setCompleted] = useState(new Set());- const {- addConvo,- setMessages,- setConversation,- setIsSubmitting,- resetLatestMessage,- invalidateConvos,- newConversation,- } = useChatHelpers(index, paramId);+ const { setMessages, setConversation, setIsSubmitting, newConversation, resetLatestMessage } =+ useChatHelpers(index, paramId);const { data: startupConfig } = useGetStartupConfig();const balanceQuery = useGetUserBalance({@@ -103,16 +109,21 @@ export default function useSSE(submission: TSubmission | null, index = 0) {setMessages(messagesUpdate);}- // refresh title- if (requestMessage?.parentMessageId == '00000000-0000-0000-0000-000000000000') {- setTimeout(() => {- invalidateConvos();- }, 2000);+ const isNewConvo = conversation.conversationId !== submission.conversation.conversationId;+ if (isNewConvo) {+ queryClient.setQueryData<ConversationData>([QueryKeys.allConversations], (convoData) => {+ if (!convoData) {+ return convoData;+ }+ return deleteConversation(convoData, submission.conversation.conversationId as string);+ });+ }- // in case it takes too long.+ // refresh title+ if (isNewConvo && requestMessage?.parentMessageId == '00000000-0000-0000-0000-000000000000') {setTimeout(() => {- invalidateConvos();- }, 5000);+ genTitle.mutate({ conversationId: convoUpdate.conversationId as string });+ }, 2500);}setConversation((prevState) => {@@ -164,9 +175,17 @@ export default function useSSE(submission: TSubmission | null, index = 0) {setStorage(update);return update;});- if (message.parentMessageId == '00000000-0000-0000-0000-000000000000') {- addConvo(update);- }++ queryClient.setQueryData<ConversationData>([QueryKeys.allConversations], (convoData) => {+ if (!convoData) {+ return convoData;+ }+ if (message.parentMessageId == '00000000-0000-0000-0000-000000000000') {+ return addConversation(convoData, update);+ } else {+ return updateConversation(convoData, update);+ }+ });resetLatestMessage();};@@ -183,16 +202,21 @@ export default function useSSE(submission: TSubmission | null, index = 0) {setMessages([...messages, requestMessage, responseMessage]);}- // refresh title- if (requestMessage.parentMessageId == '00000000-0000-0000-0000-000000000000') {- setTimeout(() => {- invalidateConvos();- }, 1500);+ const isNewConvo = conversation.conversationId !== submissionConvo.conversationId;+ if (isNewConvo) {+ queryClient.setQueryData<ConversationData>([QueryKeys.allConversations], (convoData) => {+ if (!convoData) {+ return convoData;+ }+ return deleteConversation(convoData, submissionConvo.conversationId as string);+ });+ }- // in case it takes too long.+ // refresh title+ if (isNewConvo && requestMessage.parentMessageId == '00000000-0000-0000-0000-000000000000') {setTimeout(() => {- invalidateConvos();- }, 5000);+ genTitle.mutate({ conversationId: conversation.conversationId as string });+ }, 2500);}setConversation((prevState) => {diff --git a/client/src/routes/ChatRoute.tsx b/client/src/routes/ChatRoute.tsxindex 36807d560f..39baa8170f 100644--- a/client/src/routes/ChatRoute.tsx+++ b/client/src/routes/ChatRoute.tsx@@ -2,13 +2,13 @@ import { useRecoilValue } from 'recoil';import { useEffect, useRef } from 'react';import { useParams } from 'react-router-dom';import {- useGetConvoIdQuery,useGetModelsQuery,useGetStartupConfig,useGetEndpointsQuery,} from 'librechat-data-provider/react-query';import type { TPreset } from 'librechat-data-provider';import { useNewConvo, useConfigOverride } from '~/hooks';+import { useGetConvoIdQuery } from '~/data-provider';import ChatView from '~/components/Chat/ChatView';import useAuthRedirect from './useAuthRedirect';import { Spinner } from '~/components/svg';diff --git a/client/src/routes/Root.tsx b/client/src/routes/Root.tsxindex 7e4a3750ed..59847b7c77 100644--- a/client/src/routes/Root.tsx+++ b/client/src/routes/Root.tsx@@ -60,8 +60,8 @@ export default function Root() {return (<><div className="flex h-dvh">- <Nav navVisible={navVisible} setNavVisible={setNavVisible} /><div className="relative z-0 flex h-full w-full overflow-hidden">+ <Nav navVisible={navVisible} setNavVisible={setNavVisible} /><div className="relative flex h-full max-w-full flex-1 flex-col overflow-hidden"><MobileNav setNavVisible={setNavVisible} /><Outlet context={{ navVisible, setNavVisible } satisfies ContextType} />diff --git a/client/src/style.css b/client/src/style.cssindex c94212d99a..4a30683c8f 100644--- a/client/src/style.css+++ b/client/src/style.css@@ -1051,27 +1051,42 @@ button {}::-webkit-scrollbar {- height: 0.85em;+ height: 0.1em;width: 0.5rem;}+.scrollbar-trigger:hover ::-webkit-scrollbar-thumb {+ visibility: hide;+}+::-webkit-scrollbar-thumb {- --tw-border-opacity: 1;- /* background-color: rgba(217,217,227,.8); Original */- background-color: rgba(217, 217, 227, 0.26);- border-color: rgba(255, 255, 255, var(--tw-border-opacity));+ background-color: hsla(0,0%,100%,.1);border-radius: 9999px;- border-width: 1px;}.scrollbar-transparent::-webkit-scrollbar-thumb {background-color: rgba(0, 0, 0, 0.1);}+.bg-token-surface-secondary {+ background-color: #f7f7f8;+ background-color: var(--surface-secondary);+}++.from-token-surface-secondary {+ --tw-gradient-from: var(--surface-secondary) var(--tw-gradient-from-position);+ --tw-gradient-to: hsla(0,0%,100%,0) var(--tw-gradient-to-position);+ --tw-gradient-stops: var(--tw-gradient-from),var(--tw-gradient-to);+}+::-webkit-scrollbar-track {background-color: transparent;border-radius: 9999px;}+::-webkit-scrollbar-thumb:hover {+ background-color: hsla(0,0%,100%,.3);++}body,html {diff --git a/client/src/utils/convos.fakeData.ts b/client/src/utils/convos.fakeData.tsnew file mode 100644index 0000000000..0a6367167f--- /dev/null+++ b/client/src/utils/convos.fakeData.ts@@ -0,0 +1,637 @@+import type { ConversationData } from 'librechat-data-provider';++/* @ts-ignore */+export const convoData: ConversationData = {+ pages: [+ {+ conversations: [+ {+ _id: '65bd0a2f7cb605e374e93ed1',+ conversationId: 'bf71b257-3625-440c-b6a6-03f6a3fd6a4d',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-02T15:28:47.123Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65bd0a2f7cb605e374e93ea3',+ '65bd0a2f7cb605e374e94028',+ '65bec4af7cb605e3741e84d1',+ '65bec4af7cb605e3741e86aa',+ ],+ model: 'gpt-3.5-turbo-0125',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'A Long Story',+ top_p: 1,+ updatedAt: '2024-02-03T22:56:46.269Z',+ _meiliIndex: true,+ },+ {+ _id: '65bec2c27cb605e374189730',+ conversationId: '544f1c4f-030f-4ea2-997c-35923f5d8ee2',+ user: 'my-user-id',+ __v: 0,+ _meiliIndex: true,+ chatGptLabel: null,+ createdAt: '2024-02-03T22:48:33.144Z',+ endpoint: 'OpenRouter',+ endpointType: 'custom',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65bec2c27cb605e3741896fd',+ '65bec2c47cb605e374189c16',+ '65bec2d97cb605e37418d7dc',+ '65bec2e67cb605e374190490',+ '65bec2e77cb605e3741907df',+ ],+ model: 'meta-llama/llama-2-13b-chat',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'How Are You Doing?',+ top_p: 1,+ updatedAt: '2024-02-03T22:49:21.140Z',+ },+ {+ _id: '65be8c0d7cb605e3747323ad',+ conversationId: 'e3f19866-190e-43ab-869f-10260f07530f',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T18:55:09.560Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65be8c0d7cb605e37473236c', '65be8c0d7cb605e374732475'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'A Long Story',+ top_p: 1,+ updatedAt: '2024-02-03T18:55:17.586Z',+ _meiliIndex: true,+ },+ {+ _id: '65be6bd17cb605e37412706b',+ conversationId: '4d569723-3aff-4f52-9bbf-e127783a06ac',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T16:37:37.600Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65be6bd17cb605e374127036',+ '65be6bd17cb605e374127156',+ '65be8c007cb605e37472f7a9',+ '65be8c007cb605e37472f8b5',+ '65be8c057cb605e374730c05',+ '65be8c067cb605e374730dae',+ ],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Write Einstein\'s Famous Equation in LaTeX',+ top_p: 1,+ updatedAt: '2024-02-03T18:55:02.407Z',+ _meiliIndex: true,+ },+ {+ _id: '65be6b7b7cb605e374117546',+ conversationId: '640db89d-459f-4411-a0b0-26cb1d53bf1a',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T16:36:11.010Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65be6b7a7cb605e374117519',+ '65be6b7b7cb605e37411766c',+ '65be6e1c7cb605e374195898',+ '65be6e1d7cb605e374195985',+ '65be6e767cb605e3741a5d94',+ '65be6e767cb605e3741a5e8e',+ '65be89ee7cb605e3746ccb52',+ ],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Fibonacci Solver in Python',+ top_p: 1,+ updatedAt: '2024-02-03T18:46:06.636Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde6117cb605e37481d315',+ conversationId: 'a9b39a05-fdc0-47f4-bd3b-b0aca618f656',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:06:55.573Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65bde6117cb605e37481d294',+ '65bde6117cb605e37481d4eb',+ '65be6e7b7cb605e3741a6dd4',+ '65be6e7b7cb605e3741a6ebe',+ '65be6fa97cb605e3741df0ed',+ '65be6fa97cb605e3741df249',+ '65be709a7cb605e37420ca1b',+ '65be709a7cb605e37420cb24',+ '65be71ba7cb605e374244131',+ '65be71bb7cb605e37424423e',+ '65be79017cb605e37439dddd',+ '65be79027cb605e37439df49',+ '65be82e57cb605e37457d6b5',+ '65be84727cb605e3745c76ff',+ ],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'test',+ top_p: 1,+ updatedAt: '2024-02-03T18:22:42.524Z',+ _meiliIndex: true,+ },+ {+ _id: '65bd1b347cb605e3741e29dc',+ conversationId: '3ce779d7-8535-4a43-9b70-e0d3160f299e',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-02T16:41:24.324Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65bd1b347cb605e3741e299d',+ '65bd1b347cb605e3741e2ba6',+ '65be82ed7cb605e37457f381',+ ],+ model: 'gpt-3.5-turbo-0125',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T18:16:13.357Z',+ _meiliIndex: true,+ },+ {+ _id: '65bdd6d77cb605e37454b694',+ conversationId: 'c162f906-06fb-405a-b7e6-773a0fc5f8e9',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T06:01:57.968Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65bdd6d77cb605e37454b66c',+ '65bdd6d87cb605e37454b892',+ '65bddca57cb605e37465ceea',+ '65bddcab7cb605e37465de2b',+ '65bddccb7cb605e374663d37',+ '65bddccc7cb605e374663ea9',+ '65bddce17cb605e374667f08',+ '65bddce27cb605e374668096',+ '65bdeb557cb605e37491787a',+ '65bdeb567cb605e374917aa2',+ '65be82dc7cb605e37457b70e',+ ],+ model: 'gpt-4-0125-preview',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'test',+ top_p: 1,+ updatedAt: '2024-02-03T18:15:57.133Z',+ _meiliIndex: true,+ },+ {+ _id: '65be82c87cb605e374577820',+ conversationId: '48bbc7d5-1815-4024-8ac6-6c9f59242426',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T18:15:36.759Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65be82c87cb605e3745777f6',+ '65be82c97cb605e374577911',+ '65be82d57cb605e37457a2fc',+ ],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T18:15:49.536Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde8567cb605e37488ac01',+ conversationId: '97d6e676-b05b-43f9-8f56-1c07e8a1eb4e',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:16:36.407Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65bde8557cb605e37488abe2',+ '65bde8567cb605e37488ad32',+ '65be6eb97cb605e3741b267b',+ '65be6eba7cb605e3741b2849',+ '65be703c7cb605e3741fb06d',+ '65be703d7cb605e3741fb182',+ '65be710b7cb605e374221776',+ '65be710b7cb605e37422193a',+ '65be72137cb605e37425544c',+ '65be72137cb605e37425556c',+ '65be7e2c7cb605e3744975ee',+ '65be7e6c7cb605e3744a3d29',+ '65be81147cb605e374525ccb',+ '65be826b7cb605e374565dcf',+ '65be827e7cb605e37456986c',+ '65be82967cb605e37456db94',+ '65be82c07cb605e374575ef6',+ ],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'test',+ top_p: 1,+ updatedAt: '2024-02-03T18:15:28.531Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde95c7cb605e3748ba8ae',+ conversationId: '293f230b-ceaa-4802-9611-c4fe7e4b1fd6',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:20:58.933Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65bde95c7cb605e3748ba84d',+ '65bde95c7cb605e3748baa9d',+ '65be6b3a7cb605e37410ab2d',+ '65be6b3a7cb605e37410ac16',+ ],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello, How Can I Help You?',+ top_p: 1,+ updatedAt: '2024-02-03T16:35:07.134Z',+ _meiliIndex: true,+ },+ {+ _id: '65be6a967cb605e3740ebdc4',+ conversationId: '279db3ad-2219-4229-b99a-e19a2b191dd7',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T16:32:22.480Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65be6a967cb605e3740ebd60', '65be6a967cb605e3740ebf38'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello there! How may I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T16:32:25.066Z',+ _meiliIndex: true,+ },+ {+ _id: '65bdea947cb605e3748f42c0',+ conversationId: '3e62a081-055c-4ee5-9e33-7ab8b3d367c9',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:26:10.988Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bdea947cb605e3748f4275', '65bdea947cb605e3748f43af'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How may I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T07:26:13.177Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde8aa7cb605e37489a27b',+ conversationId: 'b97836fc-8566-48e2-a28d-99f99528ca20',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:18:01.245Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bde8aa7cb605e37489a256', '65bde8ab7cb605e37489a3a1'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T07:18:04.006Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde8357cb605e3748850a7',+ conversationId: 'aa52b79d-ebe7-49d1-9fee-5f5b89d56069',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:16:03.728Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bde8357cb605e37488508e', '65bde8357cb605e37488520e'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How may I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T07:16:06.189Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde7887cb605e374864527',+ conversationId: 'fe50b20f-8465-4866-b5ef-9bc519a00eef',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:13:10.682Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bde7887cb605e3748644e0', '65bde7887cb605e37486463b'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T07:13:12.960Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde6f47cb605e37484824b',+ conversationId: '2fbb4a34-4d17-4e05-8c0a-949e78572aa3',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:10:42.904Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bde6f47cb605e374848207', '65bde6f47cb605e3748483b5'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T07:10:45.245Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde6a77cb605e37483941b',+ conversationId: 'c0d587d0-e881-42be-a2cf-5bf01198bdac',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:09:25.506Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bde6a77cb605e3748393d7', '65bde6a77cb605e374839506'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T07:09:27.717Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde65c7cb605e37482b717',+ conversationId: 'acd7fa14-4165-4fa1-b2a6-637041743a78',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:08:10.607Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bde65c7cb605e37482b6f7', '65bde65c7cb605e37482b822'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T07:08:12.971Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde6467cb605e37482700c',+ conversationId: '61ba520e-d53b-4816-b8cc-059d89f15ed4',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T07:07:49.166Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bde6467cb605e374826fee', '65bde6477cb605e374827125'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T07:07:51.592Z',+ _meiliIndex: true,+ },+ {+ _id: '65bde4677cb605e3747cd139',+ conversationId: 'd4f599af-aeae-4a54-b34c-bd85ce8134af',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T06:59:49.834Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bde4677cb605e3747cd0ed', '65bde4677cb605e3747cd26d'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T06:59:52.004Z',+ _meiliIndex: true,+ },+ {+ _id: '65bddfd37cb605e3746f4328',+ conversationId: 'e424c98c-8540-428a-ae43-dc314e15849d',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T06:40:18.167Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bddfd37cb605e3746f42c5', '65bddfd47cb605e3746f4471'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T06:40:20.382Z',+ _meiliIndex: true,+ },+ {+ _id: '65bddeb97cb605e3746bfb8c',+ conversationId: 'edac9c4d-bb66-4550-acaf-98006b83db4d',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T06:35:35.937Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: ['65bddeb97cb605e3746bfb5e', '65bddeb97cb605e3746bfc8a'],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hello! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T06:35:38.519Z',+ _meiliIndex: true,+ },+ {+ _id: '65bdd6817cb605e37453b949',+ conversationId: 'dbeca051-8af8-42cb-a611-70f669c66502',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T06:00:31.691Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65bdd6817cb605e37453b904',+ '65bdd6817cb605e37453ba9b',+ '65bddd7e7cb605e3746858ff',+ '65bddd7f7cb605e374685ac6',+ ],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'test 2',+ top_p: 1,+ updatedAt: '2024-02-03T06:30:21.941Z',+ _meiliIndex: true,+ },+ {+ _id: '65bdd9ac7cb605e3745cf331',+ conversationId: '4a69c491-5cfc-4a62-b7d3-6a54d890dfa8',+ user: 'my-user-id',+ __v: 0,+ chatGptLabel: null,+ createdAt: '2024-02-03T06:14:02.394Z',+ endpoint: 'openAI',+ frequency_penalty: 0,+ imageDetail: 'auto',+ messages: [+ '65bdd9ab7cb605e3745cf30b',+ '65bdd9ac7cb605e3745cf3f6',+ '65bddc417cb605e37464abc7',+ '65bddc427cb605e37464ad09',+ '65bddc4a7cb605e37464c7cc',+ '65bddc767cb605e374654895',+ ],+ model: 'gpt-3.5-turbo-0301',+ presence_penalty: 0,+ promptPrefix: null,+ resendImages: false,+ temperature: 1,+ title: 'Hi there! How can I assist you today?',+ top_p: 1,+ updatedAt: '2024-02-03T06:25:59.827Z',+ _meiliIndex: true,+ },+ ],+ pages: 49,+ pageNumber: 1,+ pageSize: 25,+ },+ ],+ pageParams: [null],+};diff --git a/client/src/utils/convos.spec.ts b/client/src/utils/convos.spec.tsnew file mode 100644index 0000000000..1d21d8654c--- /dev/null+++ b/client/src/utils/convos.spec.ts@@ -0,0 +1,219 @@+import { convoData } from './convos.fakeData';+import {+ groupConversationsByDate,+ addConversation,+ updateConversation,+ updateConvoFields,+ deleteConversation,+ findPageForConversation,+} from './convos';+import type { TConversation, ConversationData } from 'librechat-data-provider';++describe('Conversation Utilities', () => {+ describe('groupConversationsByDate', () => {+ it('groups conversations by date correctly', () => {+ const conversations = [+ { conversationId: '1', updatedAt: '2023-04-01T12:00:00Z' },+ { conversationId: '2', updatedAt: new Date().toISOString() },+ ];+ const grouped = groupConversationsByDate(conversations as TConversation[]);+ expect(grouped[0][0]).toBe('Today');+ expect(grouped[0][1]).toHaveLength(1);+ expect(grouped[1][0]).toBe(' 2023');+ expect(grouped[1][1]).toHaveLength(1);+ });++ it('returns an empty array for no conversations', () => {+ expect(groupConversationsByDate([])).toEqual([]);+ });++ it('skips conversations with duplicate conversationIds', () => {+ const conversations = [+ { conversationId: '1', updatedAt: '2023-12-01T12:00:00Z' }, // " 2023"+ { conversationId: '2', updatedAt: '2023-11-25T12:00:00Z' }, // " 2023"+ { conversationId: '1', updatedAt: '2023-11-20T12:00:00Z' }, // Should be skipped because of duplicate ID+ { conversationId: '3', updatedAt: '2022-12-01T12:00:00Z' }, // " 2022"+ ];++ const grouped = groupConversationsByDate(conversations as TConversation[]);++ expect(grouped).toEqual(+ expect.arrayContaining([+ expect.arrayContaining([' 2023', expect.arrayContaining(conversations.slice(0, 2))]),+ expect.arrayContaining([' 2022', expect.arrayContaining([conversations[3]])]),+ ]),+ );++ // No duplicate IDs are present+ const allGroupedIds = grouped.flatMap(([, convs]) => convs.map((c) => c.conversationId));+ const uniqueIds = [...new Set(allGroupedIds)];+ expect(allGroupedIds.length).toBe(uniqueIds.length);+ });+ });++ describe('addConversation', () => {+ it('adds a new conversation to the top of the list', () => {+ const data = { pages: [{ conversations: [] }] };+ const newConversation = { conversationId: 'new', updatedAt: '2023-04-02T12:00:00Z' };+ const newData = addConversation(+ data as unknown as ConversationData,+ newConversation as TConversation,+ );+ expect(newData.pages[0].conversations).toHaveLength(1);+ expect(newData.pages[0].conversations[0].conversationId).toBe('new');+ });+ });++ describe('updateConversation', () => {+ it('updates an existing conversation and moves it to the top', () => {+ const initialData = {+ pages: [+ {+ conversations: [+ { conversationId: '1', updatedAt: '2023-04-01T12:00:00Z' },+ { conversationId: '2', updatedAt: '2023-04-01T13:00:00Z' },+ ],+ },+ ],+ };+ const updatedConversation = { conversationId: '1', updatedAt: '2023-04-02T12:00:00Z' };+ const newData = updateConversation(+ initialData as unknown as ConversationData,+ updatedConversation as TConversation,+ );+ expect(newData.pages[0].conversations).toHaveLength(2);+ expect(newData.pages[0].conversations[0].conversationId).toBe('1');+ });+ });++ describe('updateConvoFields', () => {+ it('updates specific fields of a conversation', () => {+ const initialData = {+ pages: [+ {+ conversations: [+ { conversationId: '1', title: 'Old Title', updatedAt: '2023-04-01T12:00:00Z' },+ ],+ },+ ],+ };+ const updatedFields = { conversationId: '1', title: 'New Title' };+ const newData = updateConvoFields(+ initialData as ConversationData,+ updatedFields as TConversation,+ );+ expect(newData.pages[0].conversations[0].title).toBe('New Title');+ });+ });++ describe('deleteConversation', () => {+ it('removes a conversation by id', () => {+ const initialData = {+ pages: [+ {+ conversations: [+ { conversationId: '1', updatedAt: '2023-04-01T12:00:00Z' },+ { conversationId: '2', updatedAt: '2023-04-01T13:00:00Z' },+ ],+ },+ ],+ };+ const newData = deleteConversation(initialData as ConversationData, '1');+ expect(newData.pages[0].conversations).toHaveLength(1);+ expect(newData.pages[0].conversations[0].conversationId).not.toBe('1');+ });+ });++ describe('findPageForConversation', () => {+ it('finds the correct page and index for a given conversation', () => {+ const data = {+ pages: [+ {+ conversations: [+ { conversationId: '1', updatedAt: '2023-04-01T12:00:00Z' },+ { conversationId: '2', updatedAt: '2023-04-02T13:00:00Z' },+ ],+ },+ ],+ };+ const { pageIndex, convIndex } = findPageForConversation(data as ConversationData, {+ conversationId: '2',+ });+ expect(pageIndex).toBe(0);+ expect(convIndex).toBe(1);+ });+ });+});++describe('Conversation Utilities with Fake Data', () => {+ describe('groupConversationsByDate', () => {+ it('correctly groups conversations from fake data by date', () => {+ const { pages } = convoData;+ const allConversations = pages.flatMap((p) => p.conversations);+ const grouped = groupConversationsByDate(allConversations);++ expect(grouped).toHaveLength(1);+ expect(grouped[0][1]).toBeInstanceOf(Array);+ });+ });++ describe('addConversation', () => {+ it('adds a new conversation to the existing fake data', () => {+ const newConversation = {+ conversationId: 'new',+ updatedAt: new Date().toISOString(),+ } as TConversation;+ const initialLength = convoData.pages[0].conversations.length;+ const newData = addConversation(convoData, newConversation);+ expect(newData.pages[0].conversations.length).toBe(initialLength + 1);+ expect(newData.pages[0].conversations[0].conversationId).toBe('new');+ });+ });++ describe('updateConversation', () => {+ it('updates an existing conversation within fake data', () => {+ const updatedConversation = {+ ...convoData.pages[0].conversations[0],+ title: 'Updated Title',+ };+ const newData = updateConversation(convoData, updatedConversation);+ expect(newData.pages[0].conversations[0].title).toBe('Updated Title');+ });+ });++ describe('updateConvoFields', () => {+ it('updates specific fields of a conversation in fake data', () => {+ const updatedFields = {+ conversationId: convoData.pages[0].conversations[0].conversationId,+ title: 'Partially Updated Title',+ };+ const newData = updateConvoFields(convoData, updatedFields as TConversation);+ const updatedConversation = newData.pages[0].conversations.find(+ (c) => c.conversationId === updatedFields.conversationId,+ );+ expect(updatedConversation?.title).toBe('Partially Updated Title');+ });+ });++ describe('deleteConversation', () => {+ it('removes a conversation by id from fake data', () => {+ const conversationIdToDelete = convoData.pages[0].conversations[0].conversationId as string;+ const newData = deleteConversation(convoData, conversationIdToDelete);+ const deletedConvoExists = newData.pages[0].conversations.some(+ (c) => c.conversationId === conversationIdToDelete,+ );+ expect(deletedConvoExists).toBe(false);+ });+ });++ describe('findPageForConversation', () => {+ it('finds the correct page and index for a given conversation in fake data', () => {+ const targetConversation = convoData.pages[0].conversations[0];+ const { pageIndex, convIndex } = findPageForConversation(convoData, {+ conversationId: targetConversation.conversationId as string,+ });+ expect(pageIndex).toBeGreaterThanOrEqual(0);+ expect(convIndex).toBeGreaterThanOrEqual(0);+ });+ });+});diff --git a/client/src/utils/convos.ts b/client/src/utils/convos.tsnew file mode 100644index 0000000000..5f2741bd8d--- /dev/null+++ b/client/src/utils/convos.ts@@ -0,0 +1,148 @@+import { parseISO, isToday, isWithinInterval, subDays, getYear } from 'date-fns';+import type {+ TConversation,+ ConversationData,+ ConversationUpdater,+ GroupedConversations,+} from 'librechat-data-provider';++const getGroupName = (date: Date) => {+ const now = new Date();+ if (isToday(date)) {+ return 'Today';+ }+ if (isWithinInterval(date, { start: subDays(now, 7), end: now })) {+ return 'Last 7 days';+ }+ if (isWithinInterval(date, { start: subDays(now, 30), end: now })) {+ return 'Last 30 days';+ }+ return ' ' + getYear(date).toString();+};++export const groupConversationsByDate = (conversations: TConversation[]): GroupedConversations => {+ if (!Array.isArray(conversations)) {+ return [];+ }++ const seenConversationIds = new Set();+ const groups = conversations.reduce((acc, conversation) => {+ if (seenConversationIds.has(conversation.conversationId)) {+ return acc;+ }+ seenConversationIds.add(conversation.conversationId);++ const date = parseISO(conversation.updatedAt);+ const groupName = getGroupName(date);+ if (!acc[groupName]) {+ acc[groupName] = [];+ }+ acc[groupName].push(conversation);+ return acc;+ }, {});++ const sortedGroups = {};+ const dateGroups = ['Today', 'Last 7 days', 'Last 30 days'];+ dateGroups.forEach((group) => {+ if (groups[group]) {+ sortedGroups[group] = groups[group];+ }+ });++ Object.keys(groups)+ .filter((group) => !dateGroups.includes(group))+ .sort()+ .reverse()+ .forEach((year) => {+ sortedGroups[year] = groups[year];+ });++ return Object.entries(sortedGroups);+};++export const addConversation: ConversationUpdater = (data, newConversation) => {+ const newData = JSON.parse(JSON.stringify(data)) as ConversationData;+ const { pageIndex, convIndex } = findPageForConversation(newData, newConversation);++ if (pageIndex !== -1 && convIndex !== -1) {+ return updateConversation(data, newConversation);+ }+ newData.pages[0].conversations.unshift({+ ...newConversation,+ updatedAt: new Date().toISOString(),+ });++ return newData;+};++export function findPageForConversation(+ data: ConversationData,+ conversation: TConversation | { conversationId: string },+) {+ for (let pageIndex = 0; pageIndex < data.pages.length; pageIndex++) {+ const page = data.pages[pageIndex];+ const convIndex = page.conversations.findIndex(+ (c) => c.conversationId === conversation.conversationId,+ );+ if (convIndex !== -1) {+ return { pageIndex, convIndex };+ }+ }+ return { pageIndex: -1, convIndex: -1 }; // Not found+}++export const updateConversation: ConversationUpdater = (data, updatedConversation) => {+ const newData = JSON.parse(JSON.stringify(data));+ const { pageIndex, convIndex } = findPageForConversation(newData, updatedConversation);++ if (pageIndex !== -1 && convIndex !== -1) {+ // Remove the conversation from its current position+ newData.pages[pageIndex].conversations.splice(convIndex, 1);+ // Add the updated conversation to the top of the first page+ newData.pages[0].conversations.unshift({+ ...updatedConversation,+ updatedAt: new Date().toISOString(),+ });+ }++ return newData;+};++export const updateConvoFields: ConversationUpdater = (+ data: ConversationData,+ updatedConversation: Partial<TConversation> & Pick<TConversation, 'conversationId'>,+): ConversationData => {+ const newData = JSON.parse(JSON.stringify(data));+ const { pageIndex, convIndex } = findPageForConversation(+ newData,+ updatedConversation as { conversationId: string },+ );++ if (pageIndex !== -1 && convIndex !== -1) {+ const deleted = newData.pages[pageIndex].conversations.splice(convIndex, 1);+ const oldConversation = deleted[0] as TConversation;++ newData.pages[0].conversations.unshift({+ ...oldConversation,+ ...updatedConversation,+ updatedAt: new Date().toISOString(),+ });+ }++ return newData;+};++export const deleteConversation = (+ data: ConversationData,+ conversationId: string,+): ConversationData => {+ const newData = JSON.parse(JSON.stringify(data));+ const { pageIndex, convIndex } = findPageForConversation(newData, { conversationId });++ if (pageIndex !== -1 && convIndex !== -1) {+ // Delete the conversation from its current page+ newData.pages[pageIndex].conversations.splice(convIndex, 1);+ }++ return newData;+};diff --git a/client/src/utils/index.ts b/client/src/utils/index.tsindex e329ed69dd..0c70e01aee 100644--- a/client/src/utils/index.ts+++ b/client/src/utils/index.ts@@ -1,6 +1,7 @@export * from './json';export * from './files';export * from './latex';+export * from './convos';export * from './presets';export * from './languages';export * from './endpoints';diff --git a/package-lock.json b/package-lock.jsonindex b388cfd890..ff342b5f9b 100644--- a/package-lock.json+++ b/package-lock.json@@ -13,6 +13,9 @@"client","packages/*"],+ "dependencies": {+ "date-fns": "^3.3.1"+ },"devDependencies": {"@playwright/test": "^1.38.1","@typescript-eslint/eslint-plugin": "^5.62.0",@@ -12000,6 +12003,15 @@"node": ">=12"}},+ "node_modules/date-fns": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-3.3.1.tgz",+ "integrity": "sha512-y8e109LYGgoQDveiEBD3DYXKba1jWf5BA8YU1FL5Tvm0BTdEfy54WLCwnuYWZNnzzvALy/QQ4Hov+Q9RVRv+Zw==",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/kossnocorp"+ }+ },"node_modules/debug": {"version": "4.3.4","resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",diff --git a/package.json b/package.jsonindex 526a6d289a..ed9a7ee27e 100644--- a/package.json+++ b/package.json@@ -98,5 +98,8 @@"admin/","packages/"]+ },+ "dependencies": {+ "date-fns": "^3.3.1"}}diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex 6c7f90c672..4c14089d30 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -23,6 +23,8 @@ export const conversations = (pageNumber: string) => `/api/convos?pageNumber=${pexport const conversationById = (id: string) => `/api/convos/${id}`;+export const genTitle = () => '/api/convos/gen_title';+export const updateConversation = () => '/api/convos/update';export const deleteConversation = () => '/api/convos/clear';diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 364856510a..396bcfbd06 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -161,6 +161,10 @@ export enum CacheKeys {* Key for the plugins cache.*/PLUGINS = 'plugins',+ /**+ * Key for the title generation cache.+ */+ GEN_TITLE = 'genTitle',/*** Key for the model config cache.*/diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex f6b4221404..67a1f4218e 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -1,4 +1,5 @@import * as f from './types/files';+import * as q from './types/queries';import * as m from './types/mutations';import * as a from './types/assistants';import * as t from './types';@@ -52,6 +53,10 @@ export function updateConversation(return request.post(endpoints.updateConversation(), { arg: payload });}+export function genTitle(payload: m.TGenTitleRequest): Promise<m.TGenTitleResponse> {+ return request.post(endpoints.genTitle(), payload);+}+export function updateMessage(payload: t.TUpdateMessageRequest): Promise<unknown> {const { conversationId, messageId, text } = payload;if (!conversationId) {@@ -209,3 +214,26 @@ export const deleteFiles = async (files: f.BatchFile[]): Promise<f.DeleteFilesRerequest.deleteWithOptions(endpoints.files(), {data: { files },});++/* conversations */++export const listConversations = (+ params?: q.ConversationListParams,+): Promise<q.ConversationListResponse> => {+ // Assuming params has a pageNumber property+ const pageNumber = params?.pageNumber || '1'; // Default to page 1 if not provided+ return request.get(endpoints.conversations(pageNumber));+};++export const listConversationsByQuery = (+ params?: q.ConversationListParams & { searchQuery?: string },+): Promise<q.ConversationListResponse> => {+ const pageNumber = params?.pageNumber || '1'; // Default to page 1 if not provided+ const searchQuery = params?.searchQuery || ''; // If no search query is provided, default to an empty string+ // Update the endpoint to handle a search query+ if (searchQuery !== '') {+ return request.get(endpoints.search(searchQuery, pageNumber));+ } else {+ return request.get(endpoints.conversations(pageNumber));+ }+};diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.tsindex 318829adaf..11716ac427 100644--- a/packages/data-provider/src/index.ts+++ b/packages/data-provider/src/index.ts@@ -5,6 +5,7 @@ export * from './parsers';/* types (exports schemas from `./types` as they contain needed in other defs) */export * from './types';export * from './types/assistants';+export * from './types/queries';export * from './types/files';export * from './types/mutations';/* query/mutation keys */diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex b0368f5b96..ee368ed399 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -1,6 +1,7 @@export enum QueryKeys {messages = 'messages',allConversations = 'allConversations',+ searchConversations = 'searchConversations',conversation = 'conversation',searchEnabled = 'searchEnabled',user = 'user',diff --git a/packages/data-provider/src/react-query/react-query-service.ts b/packages/data-provider/src/react-query/react-query-service.tsindex 4d7ad00fdf..6517f85f4b 100644--- a/packages/data-provider/src/react-query/react-query-service.ts+++ b/packages/data-provider/src/react-query/react-query-service.ts@@ -85,40 +85,6 @@ export const useGetConversationByIdQuery = ();};-/* like above, but first try the convos query data */-export const useGetConvoIdQuery = (- id: string,- config?: UseQueryOptions<s.TConversation>,-): QueryObserverResult<s.TConversation> => {- const queryClient = useQueryClient();- return useQuery<s.TConversation>(- [QueryKeys.conversation, id],- () => {- const defaultQuery = () => dataService.getConversationById(id);-- const convosQueryKey = [QueryKeys.allConversations, { pageNumber: '1', active: true }];- const convosQuery = queryClient.getQueryData<t.TGetConversationsResponse>(convosQueryKey);-- if (!convosQuery) {- return defaultQuery();- }-- const convo = convosQuery.conversations?.find((c) => c.conversationId === id);- if (convo) {- return convo;- }-- return defaultQuery();- },- {- refetchOnWindowFocus: false,- refetchOnReconnect: false,- refetchOnMount: false,- ...config,- },- );-};-//This isn't ideal because its just a query and we're using mutation, but it was the only way//to make it work with how the Chat component is structuredexport const useGetConversationByIdMutation = (id: string): UseMutationResult<s.TConversation> => {@@ -131,26 +97,6 @@ export const useGetConversationByIdMutation = (id: string): UseMutationResult<s.});};-export const useUpdateConversationMutation = (- id: string,-): UseMutationResult<- t.TUpdateConversationResponse,- unknown,- t.TUpdateConversationRequest,- unknown-> => {- const queryClient = useQueryClient();- return useMutation(- (payload: t.TUpdateConversationRequest) => dataService.updateConversation(payload),- {- onSuccess: () => {- queryClient.invalidateQueries([QueryKeys.conversation, id]);- queryClient.invalidateQueries([QueryKeys.allConversations]);- },- },- );-};-export const useUpdateMessageMutation = (id: string,): UseMutationResult<unknown, unknown, t.TUpdateMessageRequest, unknown> => {@@ -176,26 +122,6 @@ export const useUpdateUserKeysMutation = (): UseMutationResult<});};-export const useDeleteConversationMutation = (- id?: string,-): UseMutationResult<- t.TDeleteConversationResponse,- unknown,- t.TDeleteConversationRequest,- unknown-> => {- const queryClient = useQueryClient();- return useMutation(- (payload: t.TDeleteConversationRequest) => dataService.deleteConversation(payload),- {- onSuccess: () => {- queryClient.invalidateQueries([QueryKeys.conversation, id]);- queryClient.invalidateQueries([QueryKeys.allConversations]);- },- },- );-};-export const useClearConversationsMutation = (): UseMutationResult<unknown> => {const queryClient = useQueryClient();return useMutation(() => dataService.clearAllConversations(), {@@ -228,7 +154,7 @@ export const useGetConversationsQuery = (config?: UseQueryOptions<t.TGetConversationsResponse>,): QueryObserverResult<t.TGetConversationsResponse> => {return useQuery<t.TGetConversationsResponse>(- [QueryKeys.allConversations, { pageNumber, active: true }],+ [QueryKeys.allConversations],() => dataService.getConversations(pageNumber),{refetchOnReconnect: false,diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.tsindex 07a5ace6d2..21aeca8f7a 100644--- a/packages/data-provider/src/types.ts+++ b/packages/data-provider/src/types.ts@@ -47,6 +47,8 @@ export type TPluginAction = {auth?: unknown;};+export type GroupedConversations = [key: string, TConversation[]][];+export type TUpdateUserPlugins = {pluginKey: string;action: string;@@ -102,9 +104,7 @@ export type TUpdateConversationRequest = {title: string;};-export type TUpdateConversationResponse = {- data: TConversation;-};+export type TUpdateConversationResponse = TConversation;export type TDeleteConversationRequest = {conversationId?: string;diff --git a/packages/data-provider/src/types/mutations.ts b/packages/data-provider/src/types/mutations.tsindex 569613f696..0d5d6f7f7c 100644--- a/packages/data-provider/src/types/mutations.ts+++ b/packages/data-provider/src/types/mutations.ts@@ -1,5 +1,13 @@import { TPreset } from '../types';+export type TGenTitleRequest = {+ conversationId: string;+};++export type TGenTitleResponse = {+ title: string;+};+export type PresetDeleteResponse = {acknowledged: boolean;deletedCount: number;diff --git a/packages/data-provider/src/types/queries.ts b/packages/data-provider/src/types/queries.tsnew file mode 100644index 0000000000..81196f00e4--- /dev/null+++ b/packages/data-provider/src/types/queries.ts@@ -0,0 +1,34 @@+import type { InfiniteData } from '@tanstack/react-query';+import type { TMessage, TConversation } from '../schemas';+export type Conversation = {+ id: string;+ createdAt: number;+ participants: string[];+ lastMessage: string;+ conversations: TConversation[];+};++// Parameters for listing conversations (e.g., for pagination)+export type ConversationListParams = {+ limit?: number;+ before?: string | null;+ after?: string | null;+ order?: 'asc' | 'desc';+ pageNumber: string; // Add this line+ conversationId?: string;+};++// Type for the response from the conversation list API+export type ConversationListResponse = {+ conversations: TConversation[];+ pageNumber: string;+ pageSize: string | number;+ pages: string | number;+ messages: TMessage[];+};++export type ConversationData = InfiniteData<ConversationListResponse>;+export type ConversationUpdater = (+ data: ConversationData,+ conversation: TConversation,+) => ConversationData;