diff --git a/app/backend/ChatHistory.ts b/app/backend/ChatHistory.ts index 1f5b845..b7b28c1 100644 --- a/app/backend/ChatHistory.ts +++ b/app/backend/ChatHistory.ts @@ -1,28 +1,30 @@ -// type Message = { -// role: string; -// content:string -// } +type Message = { + role: string; + content:string +} -// type Chat = { -// name: string; -// messages: Message[]; -// timestamp: number; -// }; +type Chat = { + name: string; + messages: Message[]; + timestamp: number; +}; -// export function addMessageToHistory(index: number, chat: Chat): void { -// if (index >= 0 && index < chatHistory.length) { -// chatHistory[index] = chat; -// chatHistory.sort((a, b) => b.timestamp - a.timestamp) -// } -// } +export let chatHistory: Chat[] = []; -// export function removeMessageFromHistory(timestamp: number): void { -// const index = chatHistory.findIndex((msg) => msg.timestamp === timestamp); -// if (index > -1) { -// chatHistory.splice(index, 1); -// console.log(`Removed message with timestamp: ${timestamp}`); -// } else { -// console.log(`Message not found with timestamp: ${timestamp}`); -// } -// } +export function addMessageToHistory(index: number, chat: Chat): void { + if (index >= 0 && index < chatHistory.length) { + chatHistory[index] = chat; + chatHistory.sort((a, b) => b.timestamp - a.timestamp) + } +} + +export function removeMessageFromHistory(timestamp: number): void { + const index = chatHistory.findIndex((msg) => msg.timestamp === timestamp); + if (index > -1) { + chatHistory.splice(index, 1); + console.log(`Removed message with timestamp: ${timestamp}`); + } else { + console.log(`Message not found with timestamp: ${timestamp}`); + } +} diff --git a/app/backend/InputOutputHandler.tsx b/app/backend/InputOutputHandler.tsx index 7986f37..dffc1bf 100644 --- a/app/backend/InputOutputHandler.tsx +++ b/app/backend/InputOutputHandler.tsx @@ -5,50 +5,41 @@ import InputFrontend from "../components/InputFrontend"; import { sendToVoiceRecognition } from "./voice_backend" import axios from "axios"; import { changeHistory, checkCredentials, getHistory } from './database'; -import { useChatHistory } from '../hooks/useChatHistory'; +import { addMessageToHistory, removeMessageFromHistory } from "./ChatHistory"; -const InputOutputBackend: React.FC = () => { +interface InputOutputHandlerProps { + selectedIndex: number; +} + +const InputOutputBackend: React.FC = ({selectedIndex}) => { // # variables type Message = { role: string content: string } + type Chat = { + name?: string + messages: Message[] + timestamp: string + } + // Define state variables for user preferences and messages - const [chatHistory, setChatHistory, setSelectedIndex] = useChatHistory() const [preferredCurrency, setPreferredCurrency] = useState("USD"); const [preferredLanguage, setPreferredLanguage] = useState("english"); const [timeFormat, setTimeFormat] = useState("24-hour"); const [preferredMeasurement, setPreferredMeasurement] = useState("metric"); const [timeZone, setTimeZone] = useState("GMT"); const [dateFormat, setDateFormat] = useState("DD-MM-YYYY"); - const [messages, setMessages] = useState(chatHistory.chats[chatHistory.selectedIndex]?.messages || []); + const [messages, setMessages] = useState([]); const [myBoolean, setMyBoolean] = useState(false); - const [systemMessage, setSystemMessage] = useState("You are a helpful assistant") const apiURL = new URL("http://localhost:5000/interstellar_ai/api/ai_create") if (typeof window !== 'undefined') { apiURL.hostname = window.location.hostname; } else { apiURL.hostname = "localhost" } - - - useEffect(() => { - - console.log("History", chatHistory); - console.log("Messages", messages); - - // Get the current chat's messages - const currentMessages = chatHistory.chats[chatHistory.selectedIndex]?.messages || []; - - // If currentMessages is not empty, update messages only if it's not the same - if (currentMessages.length > 0 && JSON.stringify(currentMessages) !== JSON.stringify(messages)) { - setMessages(currentMessages); - } else if (messages.length === 0) { - setMessages([{ role: "system", content: systemMessage }, { role: "assistant", content: "Hello! How can I help you?" }]); - } -}, [chatHistory, setSelectedIndex]); - + // Update messages when any of the settings change useEffect(() => { if (typeof localStorage !== 'undefined') { @@ -60,14 +51,11 @@ const InputOutputBackend: React.FC = () => { setDateFormat(localStorage.getItem("dateFormat") || "DD-MM-YYYY"); setMyBoolean(localStorage.getItem('myBoolean') === 'true'); } - },[]) - - useEffect(() => { const measurementString = (preferredMeasurement == "Metric") ? "All measurements follow the metric system. Refuse to use any other measurement system." : "All measurements follow the imperial system. Refuse to use any other measurement system."; - const newSystemMessage = myBoolean + const systemMessage = myBoolean ? `You are operating in the timezone: ${timeZone}. Use the ${timeFormat} time format and ${dateFormat} for dates. ${measurementString} The currency is ${preferredCurrency}. @@ -75,20 +63,12 @@ const InputOutputBackend: React.FC = () => { You are only able to change language if the user specifically states you must. Do not answer in multiple languages or multiple measurement systems under any circumstances other than the user requesting it.` : `You are a helpful assistant`; - - setSystemMessage(newSystemMessage) + setMessages([ + { role: "system", content: systemMessage }, + { role: "assistant", content: "Hello! How may I help you?" }, + ]); }, [preferredCurrency, preferredLanguage, timeFormat, preferredMeasurement, timeZone, dateFormat, myBoolean]); - useEffect(() => { - const updateSystemprompt = (prompt: string) => { - setMessages(prevMessages => { - const newMessage = { role: "system", content: prompt } - return [newMessage, ...prevMessages] - }) - } - updateSystemprompt - },[systemMessage]) - const conversationRef = useRef(null) const [copyClicked, setCopyClicked] = useState(false) @@ -200,11 +180,7 @@ const InputOutputBackend: React.FC = () => { }; const addMessage = (role: string, content: string) => { - const newMessage: Message = { role: role, content: content } - setMessages((prevMessages) => [...prevMessages, newMessage]) - const updatedChats = [...chatHistory.chats] - updatedChats[chatHistory.selectedIndex].messages.push(newMessage) - setChatHistory({...chatHistory, chats:updatedChats}) + setMessages(previous => [...previous, { role, content }]) } const handleSendClick = (inputValue: string, override: boolean) => { if (inputValue != "") { diff --git a/app/components/ConversationFrontend.tsx b/app/components/ConversationFrontend.tsx index cd6083f..b120f06 100644 --- a/app/components/ConversationFrontend.tsx +++ b/app/components/ConversationFrontend.tsx @@ -2,7 +2,6 @@ import React, { ForwardedRef, useState, useEffect, useRef } from 'react'; import Markdown from 'react-markdown' import rehypeRaw from 'rehype-raw'; import remarkGfm from 'remark-gfm'; -import { useChatHistory } from '../hooks/useChatHistory'; type Message = { role: string @@ -22,7 +21,6 @@ const ConversationFrontend = React.forwardRef ({ messages, onStopClick, onResendClick, onEditClick, onCopyClick, isClicked }, ref: ForwardedRef) => { const [isScrolling, setIsScrolling] = useState(true); const messagesEndRef = useRef(null); - const [chatHistory, setChatHistory, setSelectedIndex] = useChatHistory() useEffect(() => { const observer = new IntersectionObserver( @@ -63,7 +61,7 @@ const ConversationFrontend = React.forwardRef return (
- {chatHistory.chats[chatHistory.selectedIndex].messages.map((message, index) => { + {messages.map((message, index) => { if (index >= 1) { return ( diff --git a/app/components/History.tsx b/app/components/History.tsx index 297e638..82c1f65 100644 --- a/app/components/History.tsx +++ b/app/components/History.tsx @@ -1,8 +1,11 @@ import React, { useState } from 'react'; -import { useChatHistory } from '../hooks/useChatHistory'; -const History: React.FC = () => { - const [chatHistory, setChatHistory, setSelectedIndex] = useChatHistory() +interface HistoryProps{ + selectedIndex: number; + setSelectedIndex: (index: number) => void; +} + +const History: React.FC = ({selectedIndex, setSelectedIndex}) => { const handleHistoryClick = (index: number) => { setSelectedIndex(index) @@ -13,9 +16,9 @@ const History: React.FC = () => {
diff --git a/app/hooks/useChatHistory.tsx b/app/hooks/useChatHistory.tsx deleted file mode 100644 index b849d79..0000000 --- a/app/hooks/useChatHistory.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { useEffect, useState } from "react" - -interface Message { - role: string - content:string -} - -interface ChatMessages { - name: string - messages: Message[] - timestamp: number - -} - -interface GlobalChatHistory { - chats: ChatMessages[] - selectedIndex: number -} - -let globalChatHistory: GlobalChatHistory = { - chats: [ - { name: "Chat 1", messages: [], timestamp: 4 } - ], - selectedIndex:0 -} -let listeners: ((state: GlobalChatHistory) => void)[] = [] - -const setGlobalState = (newState: GlobalChatHistory): void => { - globalChatHistory = newState; - listeners.forEach((listener) => listener(globalChatHistory)) -} - -export const useChatHistory = (): [GlobalChatHistory, (newState:GlobalChatHistory) => void, (index:number)=>void] => { - const [state, setState] = useState(globalChatHistory) - - useEffect(() => { - console.log("help", globalChatHistory); - - const listener = (newState: GlobalChatHistory) => { - setState(newState) - } - - listeners.push(listener) - - return () => { - listeners = listeners.filter((l) => l!== listener) - } - }, []) - - const setSelectedIndex = (index: number) => { - setGlobalState({...state,selectedIndex:index}) - } - - return [state, setGlobalState, setSelectedIndex] -} \ No newline at end of file