WIP: Update UI to match Official Style; Vision and Assistants 👷🏽 (#1190)

* wip: initial client side code

* wip: initial api code

* refactor: export query keys from own module, export assistant hooks

* refactor(SelectDropDown): more customization via props

* feat: create Assistant and render real Assistants

* refactor: major refactor of UI components to allow multi-chat, working alongside CreationPanel

* refactor: move assistant routes to own directory

* fix(CreationHeader): state issue with assistant select

* refactor: style changes for form, fix setSiblingIdx from useChatHelpers to use latestMessageParentId, fix render issue with ChatView and change location

* feat: parseCompactConvo: begin refactor of slimmer JSON payloads between client/api

* refactor(endpoints): add assistant endpoint, also use EModelEndpoint as much as possible

* refactor(useGetConversationsQuery): use object to access query data easily

* fix(MultiMessage): react warning of bad state set, making use of effect during render (instead of useEffect)

* fix(useNewConvo): use correct atom key (index instead of convoId) for reset latestMessageFamily

* refactor: make routing navigation/conversation change simpler

* chore: add removeNullishValues for smaller payloads, remove unused fields, setup frontend pinging of assistant endpoint

* WIP: initial complete assistant run handling

* fix: CreationPanel form correctly setting internal state

* refactor(api/assistants/chat): revise functions to working run handling strategy

* refactor(UI): initial major refactor of ChatForm and options

* feat: textarea hook

* refactor: useAuthRedirect hook and change directory name

* feat: add ChatRoute (/c/), make optionsBar absolute and change on textarea height, add temp header

* feat: match new toggle Nav open button to ChatGPT's

* feat: add OpenAI custom classnames

* feat: useOriginNavigate

* feat: messages loading view

* fix: conversation navigation and effects

* refactor: make toggle change nav opacity

* WIP: new endpoint menu

* feat: NewEndpointsMenu complete

* fix: ensure set key dialog shows on endpoint change, and new conversation resets messages

* WIP: textarea styling fix, add temp footer, create basic file handling component

* feat: image file handling (UI)

* feat: PopOver and ModelSelect in Header, remove GenButtons

* feat: drop file handling

* refactor: bug fixes
use SSE at route level
add opts to useOriginNavigate
delay render of unfinishedMessage to avoid flickering
pass params (convoId) to chatHelpers to set messages query data based on param when the route is new (fixes can't continue convo on /new/)
style(MessagesView): matches height to official
fix(SSE): pass paramId and invalidate convos
style(Message): make bg uniform

* refactor(useSSE): setStorage within setConversation updates

* feat: conversationKeysAtom, allConversationsSelector, update convos query data on created message (if new), correctly handle convo deletion (individual)

* feat: add popover select dropdowns to allow options in header while allowing horizontal scroll for mobile

* style(pluginsSelect): styling changes

* refactor(NewEndpointsMenu): make UI components modular

* feat: Presets complete

* fix: preset editing, make by index

* fix: conversations not setting on inital navigation, fix getMessages() based on query param

* fix: changing preset no longer resets latestMessage

* feat: useOnClickOutside for OptionsPopover and fix bug that causes selection of preset when deleting

* fix: revert /chat/ switchToConvo, also use NewDeleteButton in Convo

* fix: Popover correctly closes on close Popover button using custom condition for useOnClickOutside

* style: new message and nav styling

* style: hover/sibling buttons and preset menu scrolling

* feat: new convo header button

* style(Textarea): minor style changes to textarea buttons

* feat: stop/continue generating and hide hoverbuttons when submitting

* feat: compact AI Provider schemas to make json payloads and db saves smaller

* style: styling changes for consistency on chat route

* fix: created usePresetIndexOptions to prevent bugs between /c/ and /chat/ routes when editing presets, removed redundant code from the new dialog

* chore: make /chat/ route default for now since we still lack full image support
This commit is contained in:
Danny Avila 2023-11-16 10:42:24 -05:00 committed by GitHub
parent adbeb46399
commit bac1fb67d2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
171 changed files with 8380 additions and 468 deletions

View file

@ -0,0 +1,366 @@
import { v4 } from 'uuid';
import { useCallback, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useRecoilState, useResetRecoilState, useSetRecoilState } from 'recoil';
import {
QueryKeys,
parseCompactConvo,
getResponseSender,
useGetMessagesByConvoId,
} from 'librechat-data-provider';
import type {
TMessage,
TSubmission,
TEndpointOption,
TConversation,
TGetConversationsResponse,
} from 'librechat-data-provider';
import type { TAskFunction, ExtendedFile } from '~/common';
import { useAuthContext } from './AuthContext';
import useNewConvo from './useNewConvo';
import useUserKey from './useUserKey';
import store from '~/store';
// this to be set somewhere else
export default function useChatHelpers(index = 0, paramId) {
const queryClient = useQueryClient();
const { isAuthenticated } = useAuthContext();
// const tempConvo = {
// endpoint: null,
// conversationId: null,
// jailbreak: false,
// examples: [],
// tools: [],
// };
const { newConversation } = useNewConvo(index);
const { useCreateConversationAtom } = store;
const { conversation, setConversation } = useCreateConversationAtom(index);
const { conversationId, endpoint } = conversation ?? {};
const queryParam = paramId === 'new' ? paramId : conversationId ?? paramId ?? '';
// if (!queryParam && paramId && paramId !== 'new') {
// }
/* Messages: here simply to fetch, don't export and use `getMessages()` instead */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { data: _messages } = useGetMessagesByConvoId(conversationId ?? '', {
enabled: isAuthenticated,
});
const resetLatestMessage = useResetRecoilState(store.latestMessageFamily(index));
const [isSubmitting, setIsSubmitting] = useRecoilState(store.isSubmittingFamily(index));
const [latestMessage, setLatestMessage] = useRecoilState(store.latestMessageFamily(index));
const setSiblingIdx = useSetRecoilState(
store.messagesSiblingIdxFamily(latestMessage?.parentMessageId ?? null),
);
const setMessages = useCallback(
(messages: TMessage[]) => {
queryClient.setQueryData<TMessage[]>([QueryKeys.messages, queryParam], messages);
},
// [conversationId, queryClient],
[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 getConvos = useCallback(() => {
// return queryClient.getQueryData<TGetConversationsResponse>([QueryKeys.allConversations, { pageNumber: '1', active: true }]);
// }, [queryClient]);
const invalidateConvos = useCallback(() => {
queryClient.invalidateQueries([QueryKeys.allConversations, { active: true }]);
}, [queryClient]);
const getMessages = useCallback(() => {
return queryClient.getQueryData<TMessage[]>([QueryKeys.messages, queryParam]);
}, [queryParam, queryClient]);
/* Conversation */
// const setActiveConvos = useSetRecoilState(store.activeConversations);
// const setConversation = useCallback(
// (convoUpdate: TConversation) => {
// _setConversation(prev => {
// const { conversationId: convoId } = prev ?? { conversationId: null };
// const { conversationId: currentId } = convoUpdate;
// if (currentId && convoId && convoId !== 'new' && convoId !== currentId) {
// // for now, we delete the prev convoId from activeConversations
// const newActiveConvos = { [currentId]: true };
// setActiveConvos(newActiveConvos);
// }
// return convoUpdate;
// });
// },
// [_setConversation, setActiveConvos],
// );
const { getExpiry } = useUserKey(endpoint ?? '');
const setSubmission = useSetRecoilState(store.submissionByIndex(index));
const ask: TAskFunction = (
{ text, parentMessageId = null, conversationId = null, messageId = null },
{
editedText = null,
editedMessageId = null,
isRegenerate = false,
isContinued = false,
isEdited = false,
} = {},
) => {
if (!!isSubmitting || text === '') {
return;
}
if (endpoint === null) {
console.error('No endpoint available');
return;
}
conversationId = conversationId ?? conversation?.conversationId ?? null;
if (conversationId == 'search') {
console.error('cannot send any message under search view!');
return;
}
if (isContinued && !latestMessage) {
console.error('cannot continue AI message without latestMessage!');
return;
}
const isEditOrContinue = isEdited || isContinued;
// set the endpoint option
const convo = parseCompactConvo(endpoint, conversation ?? {});
const endpointOption = {
...convo,
endpoint,
key: getExpiry(),
} as TEndpointOption;
const responseSender = getResponseSender(endpointOption);
let currentMessages: TMessage[] | null = getMessages() ?? [];
// construct the query message
// this is not a real messageId, it is used as placeholder before real messageId returned
text = text.trim();
const fakeMessageId = v4();
parentMessageId =
parentMessageId || latestMessage?.messageId || '00000000-0000-0000-0000-000000000000';
if (conversationId == 'new') {
parentMessageId = '00000000-0000-0000-0000-000000000000';
currentMessages = [];
conversationId = null;
}
const currentMsg: TMessage = {
text,
sender: 'User',
isCreatedByUser: true,
parentMessageId,
conversationId,
messageId: isContinued && messageId ? messageId : fakeMessageId,
error: false,
};
// construct the placeholder response message
const generation = editedText ?? latestMessage?.text ?? '';
const responseText = isEditOrContinue
? generation
: '<span className="result-streaming">█</span>';
const responseMessageId = editedMessageId ?? latestMessage?.messageId ?? null;
const initialResponse: TMessage = {
sender: responseSender,
text: responseText,
parentMessageId: isRegenerate ? messageId : fakeMessageId,
messageId: responseMessageId ?? `${isRegenerate ? messageId : fakeMessageId}_`,
conversationId,
unfinished: false,
submitting: true,
isCreatedByUser: false,
isEdited: isEditOrContinue,
error: false,
};
if (isContinued) {
currentMessages = currentMessages.filter((msg) => msg.messageId !== responseMessageId);
}
const submission: TSubmission = {
conversation: {
...conversation,
conversationId,
},
endpointOption,
message: {
...currentMsg,
generation,
responseMessageId,
overrideParentMessageId: isRegenerate ? messageId : null,
},
messages: currentMessages,
isEdited: isEditOrContinue,
isContinued,
isRegenerate,
initialResponse,
};
if (isRegenerate) {
setMessages([...submission.messages, initialResponse]);
} else {
setMessages([...submission.messages, currentMsg, initialResponse]);
}
setLatestMessage(initialResponse);
setSubmission(submission);
};
const regenerate = ({ parentMessageId }) => {
const messages = getMessages();
const parentMessage = messages?.find((element) => element.messageId == parentMessageId);
if (parentMessage && parentMessage.isCreatedByUser) {
ask({ ...parentMessage }, { isRegenerate: true });
} else {
console.error(
'Failed to regenerate the message: parentMessage not found or not created by user.',
);
}
};
const continueGeneration = () => {
if (!latestMessage) {
console.error('Failed to regenerate the message: latestMessage not found.');
return;
}
const messages = getMessages();
const parentMessage = messages?.find(
(element) => element.messageId == latestMessage.parentMessageId,
);
if (parentMessage && parentMessage.isCreatedByUser) {
ask({ ...parentMessage }, { isContinued: true, isRegenerate: true, isEdited: true });
} else {
console.error(
'Failed to regenerate the message: parentMessage not found, or not created by user.',
);
}
};
const stopGenerating = () => {
setSubmission(null);
};
const handleStopGenerating = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
stopGenerating();
};
const handleRegenerate = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
const parentMessageId = latestMessage?.parentMessageId;
if (!parentMessageId) {
console.error('Failed to regenerate the message: parentMessageId not found.');
return;
}
regenerate({ parentMessageId });
};
const handleContinue = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
continueGeneration();
setSiblingIdx(0);
};
const [showBingToneSetting, setShowBingToneSetting] = useRecoilState(
store.showBingToneSettingFamily(index),
);
const [showPopover, setShowPopover] = useRecoilState(store.showPopoverFamily(index));
const [abortScroll, setAbortScroll] = useRecoilState(store.abortScrollFamily(index));
const [autoScroll, setAutoScroll] = useRecoilState(store.autoScrollFamily(index));
const [preset, setPreset] = useRecoilState(store.presetByIndex(index));
const [textareaHeight, setTextareaHeight] = useRecoilState(store.textareaHeightFamily(index));
const [optionSettings, setOptionSettings] = useRecoilState(store.optionSettingsFamily(index));
const [showAgentSettings, setShowAgentSettings] = useRecoilState(
store.showAgentSettingsFamily(index),
);
const [files, setFiles] = useState<ExtendedFile[]>([]);
return {
newConversation,
conversation,
setConversation,
addConvo,
// getConvos,
// setConvos,
isSubmitting,
setIsSubmitting,
getMessages,
setMessages,
setSiblingIdx,
latestMessage,
setLatestMessage,
resetLatestMessage,
ask,
index,
regenerate,
stopGenerating,
handleStopGenerating,
handleRegenerate,
handleContinue,
showPopover,
setShowPopover,
abortScroll,
setAbortScroll,
autoScroll,
setAutoScroll,
showBingToneSetting,
setShowBingToneSetting,
preset,
setPreset,
optionSettings,
setOptionSettings,
showAgentSettings,
setShowAgentSettings,
textareaHeight,
setTextareaHeight,
files,
setFiles,
invalidateConvos,
};
}