2024-07-25 13:03:38 +00:00
|
|
|
import type { Message } from 'ai';
|
2024-07-10 16:44:39 +00:00
|
|
|
import { useChat } from 'ai/react';
|
2024-07-12 15:25:41 +00:00
|
|
|
import { useAnimate } from 'framer-motion';
|
2024-07-10 16:44:39 +00:00
|
|
|
import { useEffect, useRef, useState } from 'react';
|
2024-07-25 15:28:23 +00:00
|
|
|
import { cssTransition, toast, ToastContainer } from 'react-toastify';
|
2024-07-29 12:37:23 +00:00
|
|
|
import { useMessageParser, usePromptEnhancer, useShortcuts, useSnapScroll } from '~/lib/hooks';
|
2024-07-26 09:09:35 +00:00
|
|
|
import { useChatHistory } from '~/lib/persistence';
|
2024-07-24 15:43:32 +00:00
|
|
|
import { chatStore } from '~/lib/stores/chat';
|
|
|
|
import { workbenchStore } from '~/lib/stores/workbench';
|
2024-07-25 15:28:23 +00:00
|
|
|
import { fileModificationsToHTML } from '~/utils/diff';
|
2024-07-24 15:43:32 +00:00
|
|
|
import { cubicEasingFn } from '~/utils/easings';
|
|
|
|
import { createScopedLogger } from '~/utils/logger';
|
2024-07-10 16:44:39 +00:00
|
|
|
import { BaseChat } from './BaseChat';
|
|
|
|
|
2024-07-24 14:10:39 +00:00
|
|
|
const toastAnimation = cssTransition({
|
|
|
|
enter: 'animated fadeInRight',
|
|
|
|
exit: 'animated fadeOutRight',
|
|
|
|
});
|
|
|
|
|
2024-07-10 16:44:39 +00:00
|
|
|
const logger = createScopedLogger('Chat');
|
|
|
|
|
|
|
|
export function Chat() {
|
2024-07-25 13:03:38 +00:00
|
|
|
const { ready, initialMessages, storeMessageHistory } = useChatHistory();
|
|
|
|
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
{ready && <ChatImpl initialMessages={initialMessages} storeMessageHistory={storeMessageHistory} />}
|
2024-07-29 12:37:23 +00:00
|
|
|
<ToastContainer position="bottom-right" stacked pauseOnFocusLoss transition={toastAnimation} />
|
2024-07-25 13:03:38 +00:00
|
|
|
</>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
interface ChatProps {
|
|
|
|
initialMessages: Message[];
|
|
|
|
storeMessageHistory: (messages: Message[]) => Promise<void>;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function ChatImpl({ initialMessages, storeMessageHistory }: ChatProps) {
|
2024-07-29 12:37:23 +00:00
|
|
|
useShortcuts();
|
|
|
|
|
2024-07-10 16:44:39 +00:00
|
|
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
|
|
|
|
2024-07-25 13:03:38 +00:00
|
|
|
const [chatStarted, setChatStarted] = useState(initialMessages.length > 0);
|
2024-07-10 16:44:39 +00:00
|
|
|
|
|
|
|
const [animationScope, animate] = useAnimate();
|
|
|
|
|
2024-08-01 14:54:59 +00:00
|
|
|
const { messages, isLoading, input, handleInputChange, setInput, stop, append } = useChat({
|
2024-07-10 16:44:39 +00:00
|
|
|
api: '/api/chat',
|
|
|
|
onError: (error) => {
|
2024-07-30 08:31:35 +00:00
|
|
|
logger.error('Request failed\n\n', error);
|
2024-07-25 06:16:16 +00:00
|
|
|
toast.error('There was an error processing your request');
|
2024-07-10 16:44:39 +00:00
|
|
|
},
|
|
|
|
onFinish: () => {
|
|
|
|
logger.debug('Finished streaming');
|
|
|
|
},
|
2024-07-25 13:03:38 +00:00
|
|
|
initialMessages,
|
2024-07-10 16:44:39 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer } = usePromptEnhancer();
|
|
|
|
const { parsedMessages, parseMessages } = useMessageParser();
|
|
|
|
|
|
|
|
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
|
|
|
|
|
2024-08-01 14:54:59 +00:00
|
|
|
useEffect(() => {
|
|
|
|
chatStore.setKey('started', initialMessages.length > 0);
|
|
|
|
}, []);
|
|
|
|
|
2024-07-10 16:44:39 +00:00
|
|
|
useEffect(() => {
|
|
|
|
parseMessages(messages, isLoading);
|
2024-07-29 15:36:21 +00:00
|
|
|
|
|
|
|
if (messages.length > initialMessages.length) {
|
|
|
|
storeMessageHistory(messages).catch((error) => toast.error(error.message));
|
|
|
|
}
|
2024-07-10 16:44:39 +00:00
|
|
|
}, [messages, isLoading, parseMessages]);
|
|
|
|
|
|
|
|
const scrollTextArea = () => {
|
|
|
|
const textarea = textareaRef.current;
|
|
|
|
|
|
|
|
if (textarea) {
|
|
|
|
textarea.scrollTop = textarea.scrollHeight;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-07-18 09:10:12 +00:00
|
|
|
const abort = () => {
|
|
|
|
stop();
|
|
|
|
chatStore.setKey('aborted', true);
|
|
|
|
workbenchStore.abortAllActions();
|
|
|
|
};
|
|
|
|
|
2024-07-10 16:44:39 +00:00
|
|
|
useEffect(() => {
|
|
|
|
const textarea = textareaRef.current;
|
|
|
|
|
|
|
|
if (textarea) {
|
|
|
|
textarea.style.height = 'auto';
|
|
|
|
|
|
|
|
const scrollHeight = textarea.scrollHeight;
|
|
|
|
|
|
|
|
textarea.style.height = `${Math.min(scrollHeight, TEXTAREA_MAX_HEIGHT)}px`;
|
|
|
|
textarea.style.overflowY = scrollHeight > TEXTAREA_MAX_HEIGHT ? 'auto' : 'hidden';
|
|
|
|
}
|
|
|
|
}, [input, textareaRef]);
|
|
|
|
|
|
|
|
const runAnimation = async () => {
|
|
|
|
if (chatStarted) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-08-01 14:54:59 +00:00
|
|
|
await Promise.all([
|
|
|
|
animate('#examples', { opacity: 0, display: 'none' }, { duration: 0.1 }),
|
|
|
|
animate('#intro', { opacity: 0, flex: 1 }, { duration: 0.2, ease: cubicEasingFn }),
|
|
|
|
]);
|
|
|
|
|
|
|
|
chatStore.setKey('started', true);
|
2024-07-10 16:44:39 +00:00
|
|
|
|
|
|
|
setChatStarted(true);
|
|
|
|
};
|
|
|
|
|
2024-08-01 14:54:59 +00:00
|
|
|
const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
|
|
|
|
const _input = messageInput || input;
|
|
|
|
|
|
|
|
if (_input.length === 0 || isLoading) {
|
2024-07-10 16:44:39 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-07-25 15:28:23 +00:00
|
|
|
/**
|
|
|
|
* @note (delm) Usually saving files shouldn't take long but it may take longer if there
|
|
|
|
* many unsaved files. In that case we need to block user input and show an indicator
|
|
|
|
* of some kind so the user is aware that something is happening. But I consider the
|
|
|
|
* happy case to be no unsaved files and I would expect users to save their changes
|
|
|
|
* before they send another message.
|
|
|
|
*/
|
|
|
|
await workbenchStore.saveAllFiles();
|
|
|
|
|
|
|
|
const fileModifications = workbenchStore.getFileModifcations();
|
|
|
|
|
2024-07-18 09:10:12 +00:00
|
|
|
chatStore.setKey('aborted', false);
|
|
|
|
|
2024-07-10 16:44:39 +00:00
|
|
|
runAnimation();
|
2024-07-25 15:28:23 +00:00
|
|
|
|
|
|
|
if (fileModifications !== undefined) {
|
|
|
|
const diff = fileModificationsToHTML(fileModifications);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* If we have file modifications we append a new user message manually since we have to prefix
|
|
|
|
* the user input with the file modifications and we don't want the new user input to appear
|
|
|
|
* in the prompt. Using `append` is almost the same as `handleSubmit` except that we have to
|
|
|
|
* manually reset the input and we'd have to manually pass in file attachments. However, those
|
|
|
|
* aren't relevant here.
|
|
|
|
*/
|
2024-08-01 14:54:59 +00:00
|
|
|
append({ role: 'user', content: `${diff}\n\n${_input}` });
|
2024-07-25 15:28:23 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* After sending a new message we reset all modifications since the model
|
|
|
|
* should now be aware of all the changes.
|
|
|
|
*/
|
|
|
|
workbenchStore.resetAllFileModifications();
|
|
|
|
} else {
|
2024-08-01 14:54:59 +00:00
|
|
|
append({ role: 'user', content: _input });
|
2024-07-25 15:28:23 +00:00
|
|
|
}
|
|
|
|
|
2024-08-01 14:54:59 +00:00
|
|
|
setInput('');
|
|
|
|
|
2024-07-10 16:44:39 +00:00
|
|
|
resetEnhancer();
|
|
|
|
|
|
|
|
textareaRef.current?.blur();
|
|
|
|
};
|
|
|
|
|
2024-07-24 13:47:48 +00:00
|
|
|
const [messageRef, scrollRef] = useSnapScroll();
|
|
|
|
|
2024-07-10 16:44:39 +00:00
|
|
|
return (
|
2024-07-25 13:03:38 +00:00
|
|
|
<BaseChat
|
|
|
|
ref={animationScope}
|
|
|
|
textareaRef={textareaRef}
|
|
|
|
input={input}
|
|
|
|
chatStarted={chatStarted}
|
|
|
|
isStreaming={isLoading}
|
|
|
|
enhancingPrompt={enhancingPrompt}
|
|
|
|
promptEnhanced={promptEnhanced}
|
|
|
|
sendMessage={sendMessage}
|
|
|
|
messageRef={messageRef}
|
|
|
|
scrollRef={scrollRef}
|
|
|
|
handleInputChange={handleInputChange}
|
|
|
|
handleStop={abort}
|
|
|
|
messages={messages.map((message, i) => {
|
|
|
|
if (message.role === 'user') {
|
|
|
|
return message;
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
...message,
|
|
|
|
content: parsedMessages[i] || '',
|
|
|
|
};
|
|
|
|
})}
|
|
|
|
enhancePrompt={() => {
|
|
|
|
enhancePrompt(input, (input) => {
|
|
|
|
setInput(input);
|
|
|
|
scrollTextArea();
|
|
|
|
});
|
|
|
|
}}
|
|
|
|
/>
|
2024-07-10 16:44:39 +00:00
|
|
|
);
|
|
|
|
}
|