Spaces:
Running
Running
File size: 21,720 Bytes
1904e4c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 |
import { useState, useRef, useEffect } from "react";
import { Send, Plus, PanelLeft, Bot } from "lucide-react";
import { Button } from "@/components/ui/button";
import { apiService, Message as APIMessage } from "@/services/apiService";
import { toast } from "@/components/ui/sonner";
import { ChatBubble } from "@/components/chat/ChatBubble";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";
import { storage, STORAGE_KEYS } from "@/lib/storage";
import { Message, Chat } from "@/types/chat";
import { ProfileModal } from "../modals/ProfileModal";
import { ChatSidebar } from "./ChatSidebar";
import { ChatInputArea } from "./ChatInputArea";
import { WelcomeScreen } from "./WelcomeScreen";
import { DeleteChatDialog } from "./DeleteChatDialog";
interface ChatInterfaceProps {
onOpenSettings: () => void;
onOpenSources: () => void;
}
const WELCOME_MESSAGE = "Hello! I'm Insight AI, How can I help you today?";
const generateId = () => Math.random().toString(36).substring(2, 11);
export const ChatInterface = ({ onOpenSettings, onOpenSources }: ChatInterfaceProps) => {
const [chats, setChats] = useState<Chat[]>(() => {
const savedChats = storage.get<Chat[]>(STORAGE_KEYS.CHATS);
if (savedChats) {
try {
return savedChats.map((chat: any) => ({
...chat,
messages: chat.messages.map((msg: any) => ({
...msg,
timestamp: new Date(msg.timestamp),
sender: msg.sender as "user" | "system"
})),
createdAt: new Date(chat.createdAt),
updatedAt: new Date(chat.updatedAt)
}));
} catch (error) {
console.error("Failed to parse saved chats:", error);
return [];
}
}
return [];
});
const [activeChat, setActiveChat] = useState<Chat | null>(() => {
if (chats.length > 0) {
return chats[0];
}
});
const [inputValue, setInputValue] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [isGeneratingTitle, setIsGeneratingTitle] = useState(false);
const [isProfileModalOpen, setIsProfileModalOpen] = useState(false);
const [chatToDelete, setChatToDelete] = useState<string | null>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
// Save chats to storage whenever they change
if (activeChat && !chats.find(chat => chat.id === activeChat.id)) {
setChats([activeChat, ...chats]);
}
const allChats = activeChat
? [
activeChat,
...chats.filter(chat => chat.id !== activeChat.id)
]
: chats;
storage.set(STORAGE_KEYS.CHATS, allChats);
}, [chats, activeChat]);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(() => {
scrollToBottom();
}, [activeChat?.messages]);
useEffect(() => {
// Focus input when component mounts or when loading ends
if (!isLoading) {
setTimeout(() => {
inputRef.current?.focus();
}, 100);
}
}, [isLoading]);
// Handle new chat and chat selection events
useEffect(() => {
const handleNewChat = () => createNewChat();
const handleSelectChat = (e: Event) => {
const customEvent = e as CustomEvent;
const chatId = customEvent.detail?.chatId;
if (chatId) {
selectChat(chatId);
}
};
const handleDeleteChat = (e: Event) => {
const customEvent = e as CustomEvent;
const chatId = customEvent.detail?.chatId;
if (chatId) {
setChatToDelete(chatId);
}
};
document.addEventListener("insight:new-chat", handleNewChat);
document.addEventListener("insight:select-chat", handleSelectChat);
document.addEventListener("insight:delete-chat", handleDeleteChat);
return () => {
document.removeEventListener("insight:new-chat", handleNewChat);
document.removeEventListener("insight:select-chat", handleSelectChat);
document.removeEventListener("insight:delete-chat", handleDeleteChat);
};
}, [chats, activeChat]);
const generateChatTitle = async (query: string) => {
if (!activeChat || activeChat.title !== "New Chat") return;
setIsGeneratingTitle(true);
try {
const response = await apiService.generateTitle(query);
if (response.title) {
// Update the active chat with the new title
setActiveChat(prevChat => {
if (!prevChat) return null;
const updatedChat = { ...prevChat, title: response.title };
// Update chats list
setChats(prevChats =>
prevChats.map(chat =>
chat.id === updatedChat.id ? updatedChat : chat
)
);
return updatedChat;
});
}
} catch (error) {
console.error("Error generating chat title:", error);
// Fallback to using query as title
if (activeChat.title === "New Chat") {
setActiveChat(prevChat => {
if (!prevChat) return null;
const updatedChat = {
...prevChat,
title: query.slice(0, 30) + (query.length > 30 ? '...' : '')
};
setChats(prevChats =>
prevChats.map(chat =>
chat.id === updatedChat.id ? updatedChat : chat
)
);
return updatedChat;
});
}
} finally {
setIsGeneratingTitle(false);
}
};
const handleSendMessage = async (e?: React.FormEvent) => {
if (e) e.preventDefault();
if (!inputValue.trim() || !activeChat) return;
const userMessage: Message = {
id: generateId(),
content: inputValue,
sender: "user",
timestamp: new Date()
};
const loadingMessage: Message = {
id: generateId(),
content: "",
sender: "system",
timestamp: new Date(),
isLoading: true
};
// Update active chat with new messages
const updatedChat = {
...activeChat,
messages: [...activeChat.messages, userMessage, loadingMessage],
updatedAt: new Date()
};
setActiveChat(updatedChat);
setInputValue("");
setIsLoading(true);
try {
// Prepare chat history for the API
const chatHistory: APIMessage[] = updatedChat.messages
.filter(msg => !msg.isLoading && msg.content) // filter out loading messages
.slice(0, -1) // exclude the loading message we just added
.map(msg => ({
role: msg.sender === "user" ? "user" : "assistant",
content: msg.content
}));
const response = await apiService.queryRulings({
query: userMessage.content,
chat_history: chatHistory
});
// Replace loading message with actual response
const updatedMessages = updatedChat.messages.map(msg =>
msg.id === loadingMessage.id
? {
...msg,
content: response.answer,
isLoading: false,
result: response.retrieved_sources
}
: msg
);
const finalChat = {
...updatedChat,
messages: updatedMessages,
};
setActiveChat(finalChat);
// Update chats list
setChats(prevChats =>
prevChats.map(chat =>
chat.id === finalChat.id ? finalChat : chat
)
);
// Generate title if this is a new chat
if (updatedChat.title === "New Chat" && updatedChat.messages.length <= 3) {
generateChatTitle(userMessage.content);
}
} catch (error) {
console.error("Error querying AI:", error);
// Replace loading message with error
const updatedMessages = updatedChat.messages.map(msg =>
msg.id === loadingMessage.id
? {
...msg,
content: "I'm sorry, I couldn't process your request. Please try again.",
isLoading: false,
error: true
}
: msg
);
setActiveChat({
...updatedChat,
messages: updatedMessages
});
toast.error("Failed to process your request");
} finally {
setIsLoading(false);
// Refocus the input after sending message
setTimeout(() => {
inputRef.current?.focus();
}, 100);
}
};
const createNewChat = () => {
const newChat: Chat = {
id: generateId(),
title: "New Chat",
messages: [
{
id: "welcomems",
content: WELCOME_MESSAGE,
sender: "system" as const,
timestamp: new Date()
}
],
createdAt: new Date(),
updatedAt: new Date()
};
setActiveChat(newChat);
setChats(prev => [newChat, ...prev]);
setTimeout(() => {
inputRef.current?.focus();
}, 100);
setIsSidebarOpen(false);
};
const selectChat = (chatId: string) => {
const selectedChat = chats.find(chat => chat.id === chatId);
if (selectedChat) {
setActiveChat(selectedChat);
setIsSidebarOpen(false);
setTimeout(() => {
inputRef.current?.focus();
}, 100);
}
};
const deleteChat = (chatId: string) => {
const updatedChats = chats.filter(chat => chat.id !== chatId);
setChats(updatedChats);
// If we're deleting the active chat, switch to another one
if (activeChat?.id === chatId) {
setActiveChat(updatedChats.length > 0 ? updatedChats[0] : null);
// If no chats left, create a new one
if (updatedChats.length === 0) {
createNewChat();
}
}
// Clear the chat being deleted
setChatToDelete(null);
};
const handleDeleteMessage = (messageId: string) => {
if (!activeChat) return;
// Find the index of the message to delete
const messageIndex = activeChat.messages.findIndex(msg => msg.id === messageId);
if (messageIndex === -1) return;
// Determine if we need to delete a pair (user message + assistant response)
const isUserMessage = activeChat.messages[messageIndex].sender === "user";
const updatedMessages = [...activeChat.messages];
if (isUserMessage && messageIndex + 1 < updatedMessages.length &&
updatedMessages[messageIndex + 1].sender === "system") {
// Remove both the user message and the following assistant response
updatedMessages.splice(messageIndex, 2);
} else if (!isUserMessage && messageIndex > 0 &&
updatedMessages[messageIndex - 1].sender === "user") {
// Remove both the assistant message and the preceding user message
updatedMessages.splice(messageIndex - 1, 2);
} else {
// Just remove the single message
updatedMessages.splice(messageIndex, 1);
}
const updatedChat = {
...activeChat,
messages: updatedMessages,
updatedAt: new Date()
};
setActiveChat(updatedChat);
// Update chats list
setChats(prevChats =>
prevChats.map(chat =>
chat.id === updatedChat.id ? updatedChat : chat
)
);
};
const handleRegenerateMessage = (messageId: string) => {
if (!activeChat) return;
// Find the system message that needs to be regenerated
const messageIndex = activeChat.messages.findIndex(
msg => msg.id === messageId && msg.sender === "system"
);
if (messageIndex < 0) return;
const message = activeChat.messages[messageIndex];
// Find the last user message before this system message
let userMessageContent = "";
let userMessageIndex = -1;
for (let i = messageIndex - 1; i >= 0; i--) {
if (activeChat.messages[i].sender === "user") {
userMessageContent = activeChat.messages[i].content;
userMessageIndex = i;
break;
}
}
if (!userMessageContent) return;
// Create a new variation
const variationId = generateId();
const now = new Date();
// Prepare the updated message with a loading variation
const variations = message.variations || [];
const existingVariations = variations.map(v => ({ ...v }));
// Create a new variations array with the loading state
const updatedVariations = [
...existingVariations,
{ id: variationId, content: "", timestamp: now }
];
// Update the message with loading state
const updatedMessages = [...activeChat.messages];
updatedMessages[messageIndex] = {
...updatedMessages[messageIndex],
isLoading: true,
variations: updatedVariations,
activeVariation: variationId
};
const updatedChat = {
...activeChat,
messages: updatedMessages
};
setActiveChat(updatedChat);
setIsLoading(true);
// Prepare chat history for the API
// Include only the messages up to the user message that triggered the original response
const chatHistory: APIMessage[] = activeChat.messages
.slice(0, userMessageIndex)
.filter(msg => !msg.isLoading && msg.content)
.map(msg => ({
role: msg.sender === "user" ? "user" : "assistant",
content: msg.content
}));
// Send the API request
apiService.queryRulings({
query: userMessageContent,
chat_history: chatHistory
})
.then(response => {
// Update the variation with the actual response
const finalVariations = updatedMessages[messageIndex].variations!.map(v =>
v.id === variationId
? { ...v, content: response.answer, timestamp: new Date() }
: v
);
const finalMessages = [...updatedMessages];
finalMessages[messageIndex] = {
...finalMessages[messageIndex],
variations: finalVariations,
isLoading: false,
error: false,
result: response.retrieved_sources,
activeVariation: variationId
};
const finalChat = {
...updatedChat,
messages: finalMessages
};
setActiveChat(finalChat);
setChats(prevChats =>
prevChats.map(chat =>
chat.id === finalChat.id ? finalChat : chat
)
);
})
.catch(error => {
console.error("Error regenerating response:", error);
// Remove the failed variation
const finalVariations = updatedMessages[messageIndex].variations!.filter(v =>
v.id !== variationId
);
const finalMessages = [...updatedMessages];
finalMessages[messageIndex] = {
...finalMessages[messageIndex],
variations: finalVariations,
isLoading: false,
activeVariation: finalVariations.length > 0 ? finalVariations[0].id : undefined
};
setActiveChat({
...updatedChat,
messages: finalMessages
});
toast.error("Failed to generate variation");
})
.finally(() => {
setIsLoading(false);
setTimeout(() => {
inputRef.current?.focus();
}, 100);
});
};
const handleSelectVariation = (messageId: string, variationId: string) => {
if (!activeChat) return;
// Find the message
const messageIndex = activeChat.messages.findIndex(msg => msg.id === messageId);
if (messageIndex < 0) return;
// Set the active variation
const updatedMessages = [...activeChat.messages];
updatedMessages[messageIndex] = {
...updatedMessages[messageIndex],
activeVariation: variationId
};
const updatedChat = {
...activeChat,
messages: updatedMessages
};
setActiveChat(updatedChat);
// Update chats list
setChats(prevChats =>
prevChats.map(chat =>
chat.id === updatedChat.id ? updatedChat : chat
)
);
};
const handleRetryMessage = (messageId: string) => {
if (!activeChat) return;
// Find the failed message
const failedMessageIndex = activeChat.messages.findIndex(
msg => msg.id === messageId && msg.error
);
if (failedMessageIndex < 0) return;
// Get the last user message before this failed message
let userMessageContent = "";
for (let i = failedMessageIndex - 1; i >= 0; i--) {
if (activeChat.messages[i].sender === "user") {
userMessageContent = activeChat.messages[i].content;
break;
}
}
if (!userMessageContent) return;
// Remove the failed message
const updatedMessages = [...activeChat.messages];
updatedMessages[failedMessageIndex] = {
...updatedMessages[failedMessageIndex],
isLoading: true,
error: false,
content: ""
};
const updatedChat = {
...activeChat,
messages: updatedMessages
};
setActiveChat(updatedChat);
setIsLoading(true);
// Prepare chat history for the API
const chatHistory: APIMessage[] = updatedChat.messages
.filter(msg => !msg.isLoading && msg.content && updatedChat.messages.indexOf(msg) < failedMessageIndex - 1)
.map(msg => ({
role: msg.sender === "user" ? "user" : "assistant",
content: msg.content
}));
// Retry the query
apiService.queryRulings({
query: userMessageContent,
chat_history: chatHistory
})
.then(response => {
const finalMessages = [...updatedMessages];
finalMessages[failedMessageIndex] = {
...finalMessages[failedMessageIndex],
content: response.answer,
isLoading: false,
error: false,
result: response.retrieved_sources
};
const finalChat = {
...updatedChat,
messages: finalMessages
};
setActiveChat(finalChat);
setChats(prevChats =>
prevChats.map(chat =>
chat.id === finalChat.id ? finalChat : chat
)
);
})
.catch(error => {
console.error("Error retrying query:", error);
const finalMessages = [...updatedMessages];
finalMessages[failedMessageIndex] = {
...finalMessages[failedMessageIndex],
content: "I'm sorry, I couldn't process your request. Please try again.",
isLoading: false,
error: true
};
setActiveChat({
...updatedChat,
messages: finalMessages
});
toast.error("Failed to process your request");
})
.finally(() => {
setIsLoading(false);
setTimeout(() => {
inputRef.current?.focus();
}, 100);
});
};
const openProfileModal = () => {
setIsProfileModalOpen(true);
};
return (
<>
<div className="flex h-full w-full">
{/* Chat Sidebar */}
<ChatSidebar
chats={chats}
activeChat={activeChat}
isGeneratingTitle={isGeneratingTitle}
createNewChat={createNewChat}
selectChat={selectChat}
onRequestDelete={setChatToDelete}
onOpenSettings={onOpenSettings}
onOpenSources={onOpenSources}
openProfileModal={openProfileModal}
isSidebarOpen={isSidebarOpen}
setIsSidebarOpen={setIsSidebarOpen}
/>
{/* Chat Main Area */}
<div className="flex-1 flex flex-col overflow-hidden">
{/* Mobile Header */}
<div className="md:hidden p-2 flex items-center border-b">
<Button variant="ghost" size="icon" onClick={() => setIsSidebarOpen(true)}>
<PanelLeft className="h-5 w-5" />
</Button>
<div className="mx-auto font-medium flex items-center">
<Bot className="h-4 w-4 mr-1.5" />
{activeChat?.title || "New Chat"}
</div>
<Button variant="ghost" size="icon" onClick={createNewChat}>
<Plus className="h-5 w-5" />
</Button>
</div>
{/* Chat Area */}
<div className="relative flex-1 overflow-hidden">
{!activeChat ? (
<WelcomeScreen onCreateNewChat={createNewChat} />
) : (
<>
<div className="h-full overflow-y-auto px-4 pb-32 pt-4">
<div className="max-w-3xl mx-auto space-y-4">
{activeChat.messages.map((message) => (
<ChatBubble
key={message.id}
message={message}
onViewSearchResults={onOpenSources}
onRetry={handleRetryMessage}
onRegenerate={handleRegenerateMessage}
onDelete={handleDeleteMessage}
onSelectVariation={handleSelectVariation}
/>
))}
<div ref={messagesEndRef} />
</div>
</div>
{/* Input Area */}
<ChatInputArea
inputRef={inputRef}
inputValue={inputValue}
setInputValue={setInputValue}
handleSendMessage={handleSendMessage}
isLoading={isLoading}
/>
</>
)}
</div>
</div>
</div>
{/* Profile Modal */}
<ProfileModal isOpen={isProfileModalOpen} onClose={() => setIsProfileModalOpen(false)} />
{/* Delete Chat Confirmation Dialog */}
<DeleteChatDialog
isOpen={chatToDelete !== null}
onOpenChange={() => setChatToDelete(null)}
onDelete={() => chatToDelete && deleteChat(chatToDelete)}
/>
</>
);
};
|