🔍 feat: Show Messages from Search Result (#2699)

* refactor(Nav): delegate Search-specific variables/hooks to SearchContext

* fix: safely determine firstTodayConvoId if convo is undefined

* chore: remove empty line

* feat: initial render of search messages

* feat: SearchButtons

* update Ko.ts

* update localizations with new key phrases

* chore: localization comparisons

* fix: clear conversation state on searchQuery navigation

* style: search messages view styling

* refactor(Convo): consolidate logic to navigateWithLastTools from useNavigateToConvo

* fix(SearchButtons): styling and correct navigation logic

* fix(SearchBar): invalidate all message queries and invoke `clearText` if onChange value is empty

* refactor(NewChat): consolidate new chat button logic to NewChatButtonIcon

* chore: localizations for Nav date groups

* chore: update comparisons

* fix: early return from sendRequest to avoid quick searchQuery reset

* style: Link Icon

* chore: bump tiktoken, use o200k_base for gpt-4o
This commit is contained in:
Danny Avila 2024-05-14 11:00:01 -04:00 committed by GitHub
parent 638ac5bba6
commit e42709bd1f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
36 changed files with 2742 additions and 234 deletions

View file

@ -0,0 +1,53 @@
import { Suspense } from 'react';
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
import { UnfinishedMessage } from './MessageContent';
import { DelayedRender } from '~/components/ui';
import MarkdownLite from './MarkdownLite';
import { cn } from '~/utils';
import Part from './Part';
const SearchContent = ({ message }: { message: TMessage }) => {
const { messageId } = message;
if (Array.isArray(message.content) && message.content.length > 0) {
return (
<>
{message.content
.filter((part: TMessageContentParts | undefined) => part)
.map((part: TMessageContentParts | undefined, idx: number) => {
if (!part) {
return null;
}
return (
<Part
key={`display-${messageId}-${idx}`}
showCursor={false}
isSubmitting={false}
part={part}
message={message}
/>
);
})}
{message.unfinished && (
<Suspense>
<DelayedRender delay={250}>
<UnfinishedMessage message={message} key={`unfinished-${messageId}`} />
</DelayedRender>
</Suspense>
)}
</>
);
}
return (
<div
className={cn(
'markdown prose dark:prose-invert light w-full break-words',
message.isCreatedByUser ? 'whitespace-pre-wrap dark:text-gray-20' : 'dark:text-gray-70',
)}
>
<MarkdownLite content={message.text ?? ''} />
</div>
);
};
export default SearchContent;

View file

@ -0,0 +1,42 @@
import React from 'react';
import { cn } from '~/utils';
const MinimalMessages = React.forwardRef(
(
props: { children: React.ReactNode; className?: string },
ref: React.ForwardedRef<HTMLDivElement>,
) => {
return (
<div
className={cn(
'relative flex w-full grow overflow-hidden bg-white dark:bg-gray-800',
props.className,
)}
>
<div className="transition-width relative h-full w-full flex-1 overflow-auto bg-white dark:bg-gray-800">
<div className="flex h-full flex-col" role="presentation" tabIndex={0}>
<div className="flex-1 overflow-hidden overflow-y-auto">
<div className="dark:gpt-dark-gray relative h-full">
<div
ref={ref}
style={{
height: '100%',
overflowY: 'auto',
width: '100%',
}}
>
<div className="flex flex-col pb-9 text-sm dark:bg-transparent">
{props.children}
<div className="dark:gpt-dark-gray group h-0 w-full flex-shrink-0 dark:border-gray-800/50" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
},
);
export default MinimalMessages;

View file

@ -0,0 +1,40 @@
import { Link } from 'lucide-react';
import type { TMessage } from 'librechat-data-provider';
import { useLocalize, useNavigateToConvo } from '~/hooks';
import { useSearchContext } from '~/Providers';
import { getConversationById } from '~/utils';
export default function SearchButtons({ message }: { message: TMessage }) {
const localize = useLocalize();
const { searchQueryRes } = useSearchContext();
const { navigateWithLastTools } = useNavigateToConvo();
if (!message.conversationId) {
return null;
}
const clickHandler = (event: React.MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
const conversation = getConversationById(searchQueryRes?.data, message.conversationId);
if (!conversation) {
return;
}
document.title = message.title ?? '';
navigateWithLastTools(conversation);
};
return (
<div className="visible mt-0 flex items-center justify-center gap-1 self-end text-gray-400 lg:justify-start">
<a
className="ml-0 flex cursor-pointer items-center gap-1.5 rounded-md p-1 text-xs hover:text-gray-900 hover:underline dark:text-gray-400/70 dark:hover:text-gray-200 disabled:dark:hover:text-gray-400"
onClick={clickHandler}
title={localize('com_ui_go_to_conversation')}
>
<Link className="icon-sm" />
{message.title}
</a>
</div>
);
}

View file

@ -0,0 +1,61 @@
import { useRecoilValue } from 'recoil';
import { useAuthContext, useLocalize } from '~/hooks';
import type { TMessageProps } from '~/common';
import Icon from '~/components/Chat/Messages/MessageIcon';
import SearchContent from './Content/SearchContent';
import SearchButtons from './SearchButtons';
import SubRow from './SubRow';
import { cn } from '~/utils';
import store from '~/store';
export default function Message({ message }: Pick<TMessageProps, 'message'>) {
const UsernameDisplay = useRecoilValue<boolean>(store.UsernameDisplay);
const { user } = useAuthContext();
const localize = useLocalize();
if (!message) {
return null;
}
const { isCreatedByUser } = message ?? {};
let messageLabel = '';
if (isCreatedByUser) {
messageLabel = UsernameDisplay ? user?.name || user?.username : localize('com_user_message');
} else {
messageLabel = message.sender;
}
return (
<>
<div className="text-token-text-primary w-full border-0 bg-transparent dark:border-0 dark:bg-transparent">
<div className="m-auto justify-center p-4 py-2 text-base md:gap-6 ">
<div className="final-completion group mx-auto flex flex-1 gap-3 text-base md:max-w-3xl md:px-5 lg:max-w-[40rem] lg:px-1 xl:max-w-[48rem] xl:px-5">
<div className="relative flex flex-shrink-0 flex-col items-end">
<div>
<div className="pt-0.5">
<div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">
<Icon message={message} />
</div>
</div>
</div>
</div>
<div
className={cn('relative flex w-11/12 flex-col', isCreatedByUser ? '' : 'agent-turn')}
>
<div className="select-none font-semibold">{messageLabel}</div>
<div className="flex-col gap-1 md:gap-3">
<div className="flex max-w-full flex-grow flex-col gap-0">
<SearchContent message={message} />
</div>
</div>
<SubRow classes="text-xs">
<SearchButtons message={message} />
</SubRow>
</div>
</div>
</div>
</div>
</>
);
}

View file

@ -1,22 +0,0 @@
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);

View file

@ -2,6 +2,7 @@ import { useMemo, memo } from 'react';
import { parseISO, isToday } from 'date-fns';
import { TConversation } from 'librechat-data-provider';
import { groupConversationsByDate } from '~/utils';
import { useLocalize } from '~/hooks';
import Convo from './Convo';
const Conversations = ({
@ -13,12 +14,14 @@ const Conversations = ({
moveToTop: () => void;
toggleNav: () => void;
}) => {
const localize = useLocalize();
const groupedConversations = useMemo(
() => groupConversationsByDate(conversations),
[conversations],
);
const firstTodayConvoId = useMemo(
() => conversations.find((convo) => isToday(parseISO(convo.updatedAt)))?.conversationId,
() =>
conversations.find((convo) => convo && isToday(parseISO(convo.updatedAt)))?.conversationId,
[conversations],
);
@ -37,7 +40,7 @@ const Conversations = ({
paddingLeft: '10px',
}}
>
{groupName}
{localize(groupName) || groupName}
</div>
{convos.map((convo, i) => (
<Convo

View file

@ -1,7 +1,6 @@
import { useRecoilValue } from 'recoil';
import { useParams } from 'react-router-dom';
import { useState, useRef, useMemo } from 'react';
import { EModelEndpoint, LocalStorageKeys } from 'librechat-data-provider';
import { useGetEndpointsQuery } from 'librechat-data-provider/react-query';
import type { MouseEvent, FocusEvent, KeyboardEvent } from 'react';
import { useUpdateConversationMutation } from '~/data-provider';
@ -26,8 +25,8 @@ export default function Conversation({ conversation, retainView, toggleNav, isLa
const updateConvoMutation = useUpdateConversationMutation(currentConvoId ?? '');
const activeConvos = useRecoilValue(store.allConversationsSelector);
const { data: endpointsConfig } = useGetEndpointsQuery();
const { navigateWithLastTools } = useNavigateToConvo();
const { refreshConversations } = useConversations();
const { navigateToConvo } = useNavigateToConvo();
const { showToast } = useToastContext();
const { conversationId, title } = conversation;
@ -51,23 +50,7 @@ export default function Conversation({ conversation, retainView, toggleNav, isLa
// set document title
document.title = title;
// set conversation to the new conversation
if (conversation?.endpoint === EModelEndpoint.gptPlugins) {
let lastSelectedTools = [];
try {
lastSelectedTools =
JSON.parse(localStorage.getItem(LocalStorageKeys.LAST_TOOLS) ?? '') ?? [];
} catch (e) {
// console.error(e);
}
navigateToConvo({
...conversation,
tools: conversation?.tools?.length ? conversation?.tools : lastSelectedTools,
});
} else {
navigateToConvo(conversation);
}
navigateWithLastTools(conversation);
};
const renameHandler = (e: MouseEvent<HTMLButtonElement>) => {

View file

@ -1,7 +1,6 @@
import { useParams } from 'react-router-dom';
import { useRecoilValue, useSetRecoilState } from 'recoil';
import { useRecoilValue } from 'recoil';
import { useCallback, useEffect, useState, useMemo, memo } from 'react';
import type { ConversationListResponse } from 'librechat-data-provider';
import {
useMediaQuery,
useAuthContext,
@ -10,9 +9,10 @@ import {
useNavScrolling,
useConversations,
} from '~/hooks';
import { useSearchInfiniteQuery, useConversationsInfiniteQuery } from '~/data-provider';
import { useConversationsInfiniteQuery } from '~/data-provider';
import { TooltipProvider, Tooltip } from '~/components/ui';
import { Conversations } from '~/components/Conversations';
import { useSearchContext } from '~/Providers';
import { Spinner } from '~/components/svg';
import SearchBar from './SearchBar';
import NavToggle from './NavToggle';
@ -47,26 +47,18 @@ const Nav = ({ navVisible, setNavVisible }) => {
}
}, [isSmallScreen]);
const [pageNumber, setPageNumber] = useState(1);
const { newConversation } = useConversation();
const [showLoading, setShowLoading] = useState(false);
const searchQuery = useRecoilValue(store.searchQuery);
const isSearchEnabled = useRecoilValue(store.isSearchEnabled);
const { newConversation, searchPlaceholderConversation } = useConversation();
const { refreshConversations } = useConversations();
const setSearchResultMessages = useSetRecoilState(store.searchResultMessages);
const { pageNumber, searchQuery, setPageNumber, searchQueryRes } = useSearchContext();
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useConversationsInfiniteQuery(
{ pageNumber: pageNumber.toString(), isArchived: false },
{ enabled: isAuthenticated },
);
const searchQueryRes = useSearchInfiniteQuery(
{ pageNumber: pageNumber.toString(), searchQuery: searchQuery, isArchived: false },
{ enabled: isAuthenticated && !!searchQuery.length },
);
const { containerRef, moveToTop } = useNavScrolling({
setShowLoading,
hasNextPage: searchQuery ? searchQueryRes.hasNextPage : hasNextPage,
@ -81,21 +73,6 @@ const Nav = ({ navVisible, setNavVisible }) => {
[data, searchQuery, searchQueryRes?.data],
);
const onSearchSuccess = useCallback(({ data }: { data: ConversationListResponse }) => {
const res = data;
searchPlaceholderConversation();
setSearchResultMessages(res.messages);
/* disabled due recoil methods not recognized as state setters */
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // Empty dependency array
useEffect(() => {
//we use isInitialLoading here instead of isLoading because query is disabled by default
if (searchQueryRes.data) {
onSearchSuccess({ data: searchQueryRes.data.pages[0] });
}
}, [searchQueryRes.data, searchQueryRes.isInitialLoading, onSearchSuccess]);
const clearSearch = () => {
setPageNumber(1);
refreshConversations();

View file

@ -1,3 +1,5 @@
import { Search } from 'lucide-react';
import { useRecoilValue } from 'recoil';
import { useNavigate } from 'react-router-dom';
import { useGetEndpointsQuery } from 'librechat-data-provider/react-query';
import { TooltipProvider, Tooltip, TooltipTrigger, TooltipContent } from '~/components/ui';
@ -7,6 +9,50 @@ import ConvoIconURL from '~/components/Endpoints/ConvoIconURL';
import { useLocalize, useNewConvo } from '~/hooks';
import { NewChatIcon } from '~/components/svg';
import store from '~/store';
import type { TConversation } from 'librechat-data-provider';
const NewChatButtonIcon = ({ conversation }: { conversation: TConversation | null }) => {
const searchQuery = useRecoilValue(store.searchQuery);
const { data: endpointsConfig } = useGetEndpointsQuery();
if (searchQuery) {
return (
<div className="shadow-stroke relative flex h-7 w-7 items-center justify-center rounded-full bg-white text-black dark:bg-white">
<Search className="h-5 w-5" />
</div>
);
}
let { endpoint = '' } = conversation ?? {};
const iconURL = conversation?.iconURL ?? '';
endpoint = getIconEndpoint({ endpointsConfig, iconURL, endpoint });
const endpointType = getEndpointField(endpointsConfig, endpoint, 'type');
const endpointIconURL = getEndpointField(endpointsConfig, endpoint, 'iconURL');
const iconKey = getIconKey({ endpoint, endpointsConfig, endpointType, endpointIconURL });
const Icon = icons[iconKey];
return (
<div className="h-7 w-7 flex-shrink-0">
{iconURL && iconURL.includes('http') ? (
<ConvoIconURL preset={conversation} endpointIconURL={iconURL} context="nav" />
) : (
<div className="shadow-stroke relative flex h-full items-center justify-center rounded-full bg-white text-black dark:bg-white">
{endpoint &&
Icon &&
Icon({
size: 41,
context: 'nav',
className: 'h-2/3 w-2/3',
endpoint,
endpointType,
iconURL: endpointIconURL,
})}
</div>
)}
</div>
);
};
export default function NewChat({
index = 0,
@ -22,16 +68,7 @@ export default function NewChat({
const navigate = useNavigate();
const localize = useLocalize();
const { data: endpointsConfig } = useGetEndpointsQuery();
const { conversation } = store.useCreateConversationAtom(index);
let { endpoint = '' } = conversation ?? {};
const iconURL = conversation?.iconURL ?? '';
endpoint = getIconEndpoint({ endpointsConfig, iconURL, endpoint });
const endpointType = getEndpointField(endpointsConfig, endpoint, 'type');
const endpointIconURL = getEndpointField(endpointsConfig, endpoint, 'iconURL');
const iconKey = getIconKey({ endpoint, endpointsConfig, endpointType, endpointIconURL });
const Icon = icons[iconKey];
const clickHandler = (event: React.MouseEvent<HTMLAnchorElement>) => {
if (event.button === 0 && !event.ctrlKey) {
@ -53,24 +90,7 @@ export default function NewChat({
onClick={clickHandler}
className="group flex h-10 items-center gap-2 rounded-lg px-2 font-medium hover:bg-gray-200 dark:hover:bg-gray-700"
>
<div className="h-7 w-7 flex-shrink-0">
{iconURL && iconURL.includes('http') ? (
<ConvoIconURL preset={conversation} endpointIconURL={iconURL} context="nav" />
) : (
<div className="shadow-stroke relative flex h-full items-center justify-center rounded-full bg-white text-black dark:bg-white">
{endpoint &&
Icon &&
Icon({
size: 41,
context: 'nav',
className: 'h-2/3 w-2/3',
endpoint,
endpointType,
iconURL: endpointIconURL,
})}
</div>
)}
</div>
<NewChatButtonIcon conversation={conversation} />
<div className="text-token-text-primary grow overflow-hidden text-ellipsis whitespace-nowrap text-sm">
{localize('com_ui_new_chat')}
</div>

View file

@ -1,7 +1,9 @@
import { forwardRef, useState, useCallback, useMemo, Ref } from 'react';
import debounce from 'lodash/debounce';
import { Search, X } from 'lucide-react';
import { useSetRecoilState } from 'recoil';
import debounce from 'lodash/debounce';
import { QueryKeys } from 'librechat-data-provider';
import { useQueryClient } from '@tanstack/react-query';
import { forwardRef, useState, useCallback, useMemo, Ref } from 'react';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import store from '~/store';
@ -12,6 +14,8 @@ type SearchBarProps = {
const SearchBar = forwardRef((props: SearchBarProps, ref: Ref<HTMLDivElement>) => {
const { clearSearch } = props;
const queryClient = useQueryClient();
const clearConvoState = store.useClearConvoState();
const setSearchQuery = useSetRecoilState(store.searchQuery);
const [showClearIcon, setShowClearIcon] = useState(false);
const [text, setText] = useState('');
@ -31,7 +35,17 @@ const SearchBar = forwardRef((props: SearchBarProps, ref: Ref<HTMLDivElement>) =
}
};
const sendRequest = useCallback((value: string) => setSearchQuery(value), [setSearchQuery]);
const sendRequest = useCallback(
(value: string) => {
setSearchQuery(value);
if (!value) {
return;
}
queryClient.invalidateQueries([QueryKeys.messages]);
clearConvoState();
},
[queryClient, clearConvoState, setSearchQuery],
);
const debouncedSendRequest = useMemo(() => debounce(sendRequest, 350), [sendRequest]);
const onChange = (e: React.FormEvent<HTMLInputElement>) => {