Ui changes and loading state updates. Fixed routing issues and debugged

This commit is contained in:
Harivansh Rathi 2024-12-11 15:46:25 -05:00
parent 94a353993c
commit 61237f02d6
11 changed files with 554 additions and 467 deletions

View file

@ -64,51 +64,59 @@ export const Message: React.FC<MessageProps> = ({ message, isLast }) => {
}; };
return ( return (
<div <div className={cn(
className={cn( 'group relative py-8 first:pt-4 last:pb-4',
'group flex w-full items-start gap-4 px-4', isUser ? 'bg-background' : 'bg-secondary/30'
isUser && 'flex-row-reverse' )}>
)} <div className="mx-auto flex items-start gap-6">
> <Avatar className={cn(
<Avatar className={cn( 'flex h-8 w-8 shrink-0 select-none overflow-hidden rounded-sm',
'flex h-8 w-8 shrink-0 select-none overflow-hidden rounded-full',
isUser
? 'ring-2 ring-secondary/20 hover:ring-secondary/40 transition-all duration-300'
: 'ring-2 ring-purple-500/20 hover:ring-purple-500/40 transition-all duration-300'
)}>
<AvatarFallback className={cn(
'flex h-full w-full items-center justify-center rounded-full text-xs font-medium',
isUser isUser
? 'bg-secondary text-secondary-foreground' ? 'ring-1 ring-secondary/20'
: 'bg-gradient-to-br from-purple-300 to-purple-500 text-white' : 'ring-1 ring-purple-500/20'
)}> )}>
{isUser ? 'You' : 'AI'} <AvatarFallback className={cn(
</AvatarFallback> 'flex h-full w-full items-center justify-center text-xs font-medium',
</Avatar> isUser
? 'bg-secondary text-secondary-foreground'
: 'bg-gradient-to-br from-purple-400 to-purple-600 text-white'
)}>
{isUser ? <User className="h-4 w-4" /> : <Bot className="h-4 w-4" />}
</AvatarFallback>
</Avatar>
<div className={cn('flex flex-col gap-2', isUser ? 'items-end' : 'items-start')}> <div className="flex-1 space-y-4 overflow-hidden">
<div className={cn(
'relative rounded-lg px-4 py-3 text-sm transition-all duration-200 max-w-[800px]',
isUser
? 'bg-gradient-to-r from-purple-400 to-purple-500 text-white shadow-lg shadow-purple-500/20 hover:shadow-purple-500/30 hover:translate-y-[-1px]'
: 'bg-background/60 backdrop-blur-sm shadow-[0_4px_20px_-8px_rgba(0,0,0,0.1)] hover:shadow-[0_8px_30px_-12px_rgba(0,0,0,0.15)] hover:bg-background/80 hover:translate-y-[-1px]'
)}>
<div className={cn( <div className={cn(
'prose prose-sm max-w-none', 'prose prose-sm max-w-none break-words',
isUser ? 'prose-invert' : 'prose-neutral dark:prose-invert', isUser ? 'prose-neutral' : 'prose-neutral',
'prose-p:leading-relaxed prose-p:mb-2 last:prose-p:mb-0' 'prose-p:leading-relaxed prose-pre:bg-secondary/50 prose-pre:border prose-pre:border-border'
)}> )}>
<ReactMarkdown <ReactMarkdown
remarkPlugins={[remarkGfm]} remarkPlugins={[remarkGfm]}
components={{ components={{
pre: ({ node, ...props }) => ( pre: ({ node, ...props }) => (
<div className="overflow-auto rounded-lg bg-muted p-4"> <div className="relative group/code mt-4">
<pre {...props} /> <div className="absolute right-2 top-2 opacity-0 group-hover/code:opacity-100 transition-opacity">
<Button
variant="ghost"
size="sm"
className="h-7 w-7 p-0 hover:bg-secondary"
onClick={() => {
const code = props.children?.[0]?.props?.children?.[0];
if (code) {
navigator.clipboard.writeText(code);
}
}}
>
{messageCopied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
<pre {...props} className="rounded-lg bg-secondary/50 p-4 overflow-x-auto" />
</div> </div>
), ),
code: ({ node, inline, ...props }) => code: ({ node, inline, ...props }) =>
inline ? ( inline ? (
<code className="rounded-sm bg-muted px-1 py-0.5" {...props} /> <code className="rounded-sm bg-secondary/50 px-1 py-0.5" {...props} />
) : ( ) : (
<code {...props} /> <code {...props} />
), ),
@ -120,70 +128,66 @@ export const Message: React.FC<MessageProps> = ({ message, isLast }) => {
{!isUser && usedTools.length > 0 && ( {!isUser && usedTools.length > 0 && (
<> <>
<Separator className="my-2 opacity-30" /> <Separator className="my-4 opacity-30" />
<div className="flex flex-col gap-1 text-xs text-muted-foreground"> <div className="flex flex-col gap-1.5 text-xs text-muted-foreground">
<div className="flex items-center gap-1"> <div className="flex items-center gap-1.5">
<Wrench className="h-3 w-3" /> <Wrench className="h-3 w-3" />
<span className="font-medium">Used Tools:</span> <span className="font-medium">Used Tools:</span>
</div> </div>
{usedTools.map((tool, index) => ( {usedTools.map((tool, index) => (
<div key={index} className="flex items-center gap-1 pl-4"> <div key={index} className="flex items-center gap-1.5 pl-4">
<span>{tool}</span> <span>{tool}</span>
</div> </div>
))} ))}
</div> </div>
</> </>
)} )}
</div>
<div className={cn( <div className={cn(
'flex items-center gap-2 text-xs', 'flex items-center gap-2 text-xs',
'opacity-0 group-hover:opacity-100 transition-opacity duration-200' 'opacity-0 group-hover:opacity-100 transition-opacity duration-200'
)}> )}>
{!isUser && ( {!isUser && (
<> <>
<Tooltip content="Helpful"> <Tooltip content={isLiked ? "Remove like" : "Like message"}>
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
className={cn( className={cn(
"h-6 w-6 p-0 hover:text-purple-500", "h-7 w-7 p-0 hover:text-purple-500",
isLiked && "text-purple-500" isLiked && "text-purple-500"
)} )}
onClick={() => handleFeedback('like')} onClick={() => handleFeedback('like')}
> >
<ThumbsUp className="h-3 w-3" /> <ThumbsUp className="h-3.5 w-3.5" />
</Button> </Button>
</Tooltip> </Tooltip>
<Tooltip content="Not helpful"> <Tooltip content={isDisliked ? "Remove dislike" : "Dislike message"}>
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
className={cn( className={cn(
"h-6 w-6 p-0 hover:text-purple-500", "h-7 w-7 p-0 hover:text-purple-500",
isDisliked && "text-purple-500" isDisliked && "text-purple-500"
)} )}
onClick={() => handleFeedback('dislike')} onClick={() => handleFeedback('dislike')}
> >
<ThumbsDown className="h-3 w-3" /> <ThumbsDown className="h-3.5 w-3.5" />
</Button> </Button>
</Tooltip> </Tooltip>
</> <Tooltip content={messageCopied ? "Copied!" : "Copy message"}>
)} <Button
<Tooltip content={messageCopied ? "Copied!" : "Copy message"}> variant="ghost"
<Button size="sm"
variant="ghost" className="h-7 w-7 p-0 hover:text-purple-500"
size="sm" onClick={handleMessageCopy}
className="h-6 w-6 p-0 hover:text-purple-500" >
onClick={handleMessageCopy} {messageCopied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
> </Button>
{messageCopied ? ( </Tooltip>
<Check className="h-3 w-3" /> </>
) : ( )}
<Copy className="h-3 w-3" /> </div>
)}
</Button>
</Tooltip>
</div> </div>
</div> </div>
</div> </div>

View file

@ -0,0 +1,23 @@
import React from 'react';
import { cn } from '../../lib/utils';
export const TypingIndicator = () => {
return (
<div className="flex items-center gap-1">
<div className="flex gap-1">
{[...Array(3)].map((_, i) => (
<div
key={i}
className={cn(
"h-2 w-2 rounded-full bg-purple-500/40",
"animate-bounce",
i === 0 && "animation-delay-0",
i === 1 && "animation-delay-150",
i === 2 && "animation-delay-300"
)}
/>
))}
</div>
</div>
);
};

View file

@ -5,15 +5,27 @@ import { Sidebar } from '../Sidebar/index';
const DashboardLayout = () => { const DashboardLayout = () => {
return ( return (
<div className="flex h-screen flex-col overflow-hidden bg-secondary/20"> <div className="flex h-screen bg-secondary/20">
<Header /> {/* Fixed header */}
<div className="flex flex-1 overflow-hidden gap-6 p-6 pt-24"> <div className="fixed top-0 left-0 right-0 z-50">
<Sidebar /> <Header />
<main className="flex-1 rounded-2xl bg-background shadow-sm overflow-hidden"> </div>
<div className="h-full">
<Outlet /> {/* Sidebar and main content */}
</div> <div className="flex w-full pt-16">
</main> {/* Fixed sidebar */}
<div className="fixed left-0 top-16 bottom-0 w-[280px] p-4 overflow-y-auto">
<Sidebar />
</div>
{/* Main content area */}
<div className="flex-1 ml-[280px]">
<main className="h-[calc(100vh-4rem)] relative">
<div className="h-full">
<Outlet />
</div>
</main>
</div>
</div> </div>
</div> </div>
); );

View file

@ -2,17 +2,18 @@ import React from 'react';
import { Link, useLocation } from 'react-router-dom'; import { Link, useLocation } from 'react-router-dom';
import { import {
Settings, Settings,
MessageSquarePlus, MessageSquare,
Upload, Upload,
History History
} from 'lucide-react'; } from 'lucide-react';
import { cn } from '../../../lib/utils'; import { cn } from '../../../lib/utils';
import { useLatestChat } from '../../../hooks/useLatestChat';
const sidebarItems = [ const sidebarItems = [
{ {
icon: MessageSquarePlus, icon: MessageSquare,
label: 'Ask a Question', label: 'Chat',
path: '/dashboard/ask' path: '/dashboard/ask?new=true'
}, },
{ {
icon: History, icon: History,
@ -33,22 +34,48 @@ const sidebarItems = [
const Sidebar = () => { const Sidebar = () => {
const location = useLocation(); const location = useLocation();
const { navigateToChat } = useLatestChat();
const isActive = (path: string) => { const isActive = (path: string) => {
if (path === '/dashboard/ask') { if (path.startsWith('/dashboard/ask')) {
return location.pathname.startsWith('/dashboard/ask') || location.pathname === '/dashboard'; return location.pathname.startsWith('/dashboard/ask') || location.pathname === '/dashboard';
} }
return location.pathname === path; return location.pathname === path;
}; };
return ( return (
<div className="w-64 shrink-0"> <div className="h-full">
<div className="rounded-2xl bg-background/70 backdrop-blur-lg shadow-lg h-full p-4"> <div className="flex flex-col h-full space-y-4">
<nav className="space-y-2"> {/* Navigation Links */}
{sidebarItems.map((item) => { <nav className="flex-1 space-y-1">
{sidebarItems.map((item, index) => {
const Icon = item.icon; const Icon = item.icon;
const active = isActive(item.path); const active = isActive(item.path);
if (index === 0) {
// Special handling for Chat button
return (
<button
key={item.path}
onClick={navigateToChat}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200',
active
? 'bg-purple-50/50 text-purple-500'
: 'text-muted-foreground hover:bg-purple-50/30 hover:text-purple-500'
)}
>
<Icon className={cn(
'h-5 w-5',
active
? 'text-purple-500'
: 'text-muted-foreground group-hover:text-purple-500'
)} />
{item.label}
</button>
);
}
return ( return (
<Link <Link
key={item.path} key={item.path}
@ -56,14 +83,14 @@ const Sidebar = () => {
className={cn( className={cn(
'flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200', 'flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200',
active active
? 'bg-gradient-to-r from-purple-400 to-purple-500 text-white shadow-sm hover:from-purple-500 hover:to-purple-600' ? 'bg-purple-50/50 text-purple-500'
: 'text-muted-foreground hover:bg-purple-50/50 hover:text-purple-500' : 'text-muted-foreground hover:bg-purple-50/30 hover:text-purple-500'
)} )}
> >
<Icon className={cn( <Icon className={cn(
'h-5 w-5', 'h-5 w-5',
active active
? 'text-white' ? 'text-purple-500'
: 'text-muted-foreground group-hover:text-purple-500' : 'text-muted-foreground group-hover:text-purple-500'
)} /> )} />
{item.label} {item.label}

View file

@ -0,0 +1,36 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { chatService } from '../lib/chat-service';
export function useChatRouting(chatId: string | undefined, isNewChatRequest: boolean = false) {
const navigate = useNavigate();
const { user } = useAuth();
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!user) return;
// Only initiate loading if we don't have a chatId and it's not a new chat request
if (!chatId && !isNewChatRequest) {
setLoading(true);
const initializeChat = async () => {
try {
const chats = await chatService.getChatInstances(user.id);
if (chats.length > 0) {
navigate(`/dashboard/ask/${chats[0].id}`, { replace: true });
}
} catch (err) {
console.error('Error initializing chat:', err);
} finally {
setLoading(false);
}
};
initializeChat();
}
}, [user, chatId, navigate, isNewChatRequest]);
return { loading };
}

View file

@ -0,0 +1,31 @@
import { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { chatService } from '../lib/chat-service';
export function useLatestChat() {
const navigate = useNavigate();
const { user } = useAuth();
const navigateToChat = useCallback(async () => {
if (!user) return;
try {
const chats = await chatService.getChatInstances(user.id);
if (chats.length > 0) {
// Navigate to most recent chat
navigate(`/dashboard/ask/${chats[0].id}`, { replace: true });
} else {
// No chats exist, go to new chat
navigate('/dashboard/ask?new=true', { replace: true });
}
} catch (err) {
console.error('Error navigating to chat:', err);
// On error, default to new chat
navigate('/dashboard/ask?new=true', { replace: true });
}
}, [user, navigate]);
return { navigateToChat };
}

View file

@ -62,4 +62,31 @@
.gradient-text { .gradient-text {
@apply bg-clip-text text-transparent bg-gradient-to-r from-[#9333EA] to-[#A855F7]; @apply bg-clip-text text-transparent bg-gradient-to-r from-[#9333EA] to-[#A855F7];
} }
/* Animation Delays */
.animation-delay-0 {
animation-delay: 0s;
}
.animation-delay-150 {
animation-delay: 0.15s;
}
.animation-delay-300 {
animation-delay: 0.3s;
}
/* Custom bounce animation */
@keyframes custom-bounce {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-4px);
}
}
.animate-bounce {
animation: custom-bounce 1s infinite;
}
} }

View file

@ -31,7 +31,7 @@ interface N8NResponse {
} }
// Function to send message to n8n webhook and handle response // Function to send message to n8n webhook and handle response
const sendToN8N = async (sessionId: string, message: string): Promise<N8NResponse> => { export const sendToN8N = async (sessionId: string, message: string): Promise<N8NResponse> => {
try { try {
console.log('Sending message to n8n:', { sessionId, message }); console.log('Sending message to n8n:', { sessionId, message });

View file

@ -1,85 +1,54 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Send, Loader2, X, History, MessageSquarePlus, AlertCircle, ArrowDown } from 'lucide-react'; import { Send, Loader2, X, History, MessageSquarePlus, AlertCircle, ArrowDown, Trash2, Bot } from 'lucide-react';
import { Link, useParams, useNavigate } from 'react-router-dom'; import { Link, useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { Button } from '../../components/ui/Button'; import { Button } from '../../components/ui/Button';
import { Message } from '../../components/chat/Message'; import { Message } from '../../components/chat/Message';
import { Avatar, AvatarFallback } from '../../components/ui/Avatar'; import { Avatar, AvatarFallback } from '../../components/ui/Avatar';
import { cn } from '../../lib/utils'; import { TypingIndicator } from '../../components/chat/TypingIndicator';
import { useAuth } from '../../contexts/AuthContext'; import { useAuth } from '../../contexts/AuthContext';
import { chatService } from '../../lib/chat-service'; import { chatService } from '../../lib/chat-service';
import { cn } from '../../lib/utils';
import type { ChatMessage, ChatInstance } from '../../types/supabase'; import type { ChatMessage, ChatInstance } from '../../types/supabase';
import { useChatRouting } from '../../hooks/useChatRouting';
export default function AskQuestion() { export default function AskQuestion() {
const { chatId } = useParams(); const { chatId } = useParams();
const navigate = useNavigate(); const navigate = useNavigate();
const { user } = useAuth(); const { user } = useAuth();
const [searchParams] = useSearchParams();
const isNewChatRequest = searchParams.get('new') === 'true';
const [question, setQuestion] = useState(''); const [question, setQuestion] = useState('');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [messages, setMessages] = useState<ChatMessage[]>([]); const [messages, setMessages] = useState<ChatMessage[]>([]);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [chat, setChat] = useState<ChatInstance | null>(null); const [chat, setChat] = useState<ChatInstance | null>(null);
const [isNewChat, setIsNewChat] = useState(false);
const [hasExistingChats, setHasExistingChats] = useState<boolean | null>(null);
const [isTyping, setIsTyping] = useState(false); const [isTyping, setIsTyping] = useState(false);
const [showScrollButton, setShowScrollButton] = useState(false); const [showScrollButton, setShowScrollButton] = useState(false);
const [isLoadingChat, setIsLoadingChat] = useState(!!chatId);
const messagesEndRef = useRef<HTMLDivElement>(null); const messagesEndRef = useRef<HTMLDivElement>(null);
const scrollAreaRef = useRef<HTMLDivElement>(null); const scrollAreaRef = useRef<HTMLDivElement>(null);
// Check for existing chats and redirect to most recent if on base path // Use the chat routing hook
const { loading: routingLoading } = useChatRouting(chatId, isNewChatRequest);
// Load chat messages
useEffect(() => { useEffect(() => {
if (!user) return; if (!user || !chatId || routingLoading) return;
const checkExistingChats = async () => {
try {
const chats = await chatService.getChatInstances(user.id);
const hasChats = chats.length > 0;
setHasExistingChats(hasChats);
// If we're on the base ask page and there are existing chats,
// redirect to the most recent one
if (hasChats && !chatId && !isNewChat) {
const mostRecentChat = chats[0]; // Chats are already sorted by last_message_at desc
navigate(`/dashboard/ask/${mostRecentChat.id}`);
}
} catch (err) {
console.error('Error checking existing chats:', err);
setHasExistingChats(false);
}
};
checkExistingChats();
}, [user, chatId, navigate, isNewChat]);
useEffect(() => {
if (!user || !chatId) return;
const loadChat = async () => { const loadChat = async () => {
setIsLoadingChat(true);
try { try {
// Don't try to load chat if we're using a temporary ID const [messages, existingChat] = await Promise.all([
if (chatId.startsWith('temp-')) { chatService.getChatMessages(chatId),
// For new chats, create a temporary chat instance chatService.getChatInstance(chatId)
const tempChat: ChatInstance = { ]);
id: chatId,
created_at: '',
user_id: 'system',
title: 'New Chat',
last_message_at: '',
};
setChat(tempChat);
setMessages([]);
return;
}
// Load messages for existing chats
const messages = await chatService.getChatMessages(chatId);
setMessages(messages); setMessages(messages);
// For existing chats, either load from storage or create from messages
const existingChat = await chatService.getChatInstance(chatId);
if (existingChat) { if (existingChat) {
setChat(existingChat); setChat(existingChat);
} else if (messages.length > 0) { } else if (messages.length > 0) {
// Create a chat instance from the first message
const firstMessage = messages[0]; const firstMessage = messages[0];
const chatInstance: ChatInstance = { const chatInstance: ChatInstance = {
id: chatId, id: chatId,
@ -93,14 +62,16 @@ export default function AskQuestion() {
} catch (err) { } catch (err) {
console.error('Error loading chat:', err); console.error('Error loading chat:', err);
setError('Failed to load chat'); setError('Failed to load chat');
} finally {
setIsLoadingChat(false);
} }
}; };
loadChat(); loadChat();
}, [chatId, user]); }, [user, chatId, routingLoading]);
const handleNewChat = () => { const handleNewChat = () => {
setIsNewChat(true); setIsTyping(false);
setChat(null); setChat(null);
setMessages([]); setMessages([]);
setError(null); setError(null);
@ -118,42 +89,46 @@ export default function AskQuestion() {
return words.length < message.split(/\s+/).length ? `${title}...` : title; return words.length < message.split(/\s+/).length ? `${title}...` : title;
}; };
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async () => {
e.preventDefault(); if (!question.trim() || loading) return;
if (!question.trim() || loading || !user) return;
setLoading(true); const userMessage = question.trim();
setQuestion('');
setError(null); setError(null);
setLoading(true);
setIsTyping(true);
try { try {
let currentChatId: string; let currentChatId: string;
// If no chat exists or we're starting a new chat, generate a new session ID // Get or create chat ID
if (!chatId || chatId.startsWith('temp-')) { if (chatId) {
currentChatId = crypto.randomUUID();
// Update URL with the real chat ID
navigate(`/dashboard/ask/${currentChatId}`, { replace: true });
} else {
currentChatId = chatId; currentChatId = chatId;
} else {
const newChat = await chatService.createChatInstance(user!.id, "New Chat");
if (!newChat) {
throw new Error("Failed to create new chat");
}
navigate(`/dashboard/ask/${newChat.id}`, { replace: true });
currentChatId = newChat.id;
} }
// Show typing indicator before sending message // Immediately show the user's message in the UI
setIsTyping(true); const tempUserMessage: ChatMessage = {
id: crypto.randomUUID(),
chat_id: currentChatId,
content: userMessage,
role: 'user',
created_at: new Date().toISOString(),
};
setMessages(prev => [...prev, tempUserMessage]);
// Add user message and get all updated messages including the AI response // Add message and get AI response through chatService
const updatedMessages = await chatService.addMessage(currentChatId, question.trim(), 'user'); const updatedMessages = await chatService.addMessage(currentChatId, userMessage, 'user');
setMessages(updatedMessages); setMessages(updatedMessages);
setQuestion('');
// Reset textarea height to initial state
const textarea = document.querySelector('textarea');
if (textarea) {
textarea.style.height = '40px';
}
} catch (err) { } catch (err) {
setError('Failed to send message');
console.error('Failed to process message:', err); console.error('Failed to process message:', err);
setError('Failed to send message. Please try again.');
} finally { } finally {
setLoading(false); setLoading(false);
setIsTyping(false); setIsTyping(false);
@ -161,7 +136,7 @@ export default function AskQuestion() {
}; };
const clearChat = async () => { const clearChat = async () => {
if (!chatId || isNewChat) return; if (!chatId || isNewChatRequest) return;
try { try {
setError(null); setError(null);
@ -228,8 +203,27 @@ export default function AskQuestion() {
} }
}; };
// Show loading state while checking for existing chats const handleQuestionChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
if (hasExistingChats === null) { setQuestion(e.target.value);
// Reset the height to auto first to get the correct scrollHeight
e.target.style.height = 'auto';
// Calculate new height between min and max
const newHeight = Math.max(
40, // min height
Math.min(e.target.scrollHeight, window.innerHeight * 0.4) // max height
);
e.target.style.height = `${newHeight}px`;
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit(e);
}
};
// Show loading state while checking for existing chats or loading messages
if (routingLoading || isLoadingChat) {
return ( return (
<div className="flex h-full items-center justify-center"> <div className="flex h-full items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /> <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
@ -238,286 +232,203 @@ export default function AskQuestion() {
} }
return ( return (
<div className="flex flex-col h-full"> <div className="relative flex h-[calc(100vh-4rem)] flex-col overflow-hidden bg-background">
{/* Header Container */} {/* Messages */}
<div className="flex-none bg-background rounded-lg m-4"> <div
<div className="flex h-full items-center justify-between px-4"> ref={scrollAreaRef}
<div className="flex items-center gap-2"> className="flex-1 overflow-y-auto scroll-smooth"
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10"> onScroll={handleScroll}
<MessageSquarePlus className="h-4 w-4 text-primary" /> >
</div> {!isLoadingChat && messages.length === 0 ? (
<div> <div className="flex h-full flex-col items-center justify-center">
<h1 className="text-sm font-medium">Ask a Question</h1> <h1 className="mb-10 text-2xl font-bold">
{chat && ( What can I help with?
<p className="text-xs text-muted-foreground line-clamp-1"> </h1>
{chat.title} <div className={cn(
</p> "w-full max-w-3xl transform transition-all duration-300 ease-in-out",
)} loading && messages.length === 0 ? "opacity-0 translate-y-[-20px]" : "opacity-100 translate-y-0"
</div> )}>
</div> <form onSubmit={handleSubmit} className="relative flex flex-col items-end gap-2 px-4">
<div className="flex items-center gap-2"> <div className="relative flex w-full flex-col overflow-hidden rounded-2xl border bg-background shadow-[0_0_15px_rgba(0,0,0,0.1)] dark:shadow-[0_0_15px_rgba(0,0,0,0.3)]">
<Button
variant="ghost"
size="sm"
onClick={handleNewChat}
className="text-muted-foreground hover:text-primary hover:bg-primary/10"
>
<MessageSquarePlus className="mr-2 h-4 w-4" />
New Chat
</Button>
{chatId && !isNewChat && messages.length > 0 && (
<Button
variant="ghost"
size="sm"
onClick={clearChat}
className="text-muted-foreground hover:text-primary hover:bg-primary/10"
>
<X className="mr-2 h-4 w-4" />
Clear chat
</Button>
)}
{hasExistingChats && (
<Link to="/dashboard/history">
<Button
variant="ghost"
size="sm"
className="text-muted-foreground hover:text-primary hover:bg-primary/10"
>
<History className="mr-2 h-4 w-4" />
History
</Button>
</Link>
)}
</div>
</div>
</div>
{/* Main Chat Container */}
<div className="flex-1 bg-background rounded-lg mx-4 overflow-hidden flex flex-col relative">
{/* Messages Container with ref moved to correct div */}
<div
ref={scrollAreaRef}
className="flex-1 overflow-y-auto relative"
>
<div className="flex flex-col space-y-6 p-4">
{error && (
<div className="flex-none mb-4 flex items-center gap-2 rounded-lg bg-destructive/10 p-3 text-sm text-destructive">
<AlertCircle className="h-4 w-4" />
{error}
</div>
)}
{!isNewChat && !chatId ? (
<div className="h-full flex items-center justify-center min-h-[calc(100vh-50rem)]">
<div className="max-w-md w-full space-y-8">
<div className="flex flex-col items-center text-center">
<div className="rounded-full bg-purple-500/20 p-6 mb-8">
<div className="h-16 w-16 rounded-full bg-gradient-to-br from-purple-300 to-purple-500 shadow-lg" />
</div>
<h2 className="text-xl font-semibold mb-2">Welcome to your AI AGENT</h2>
<p className="text-sm text-muted-foreground mb-6">
Start a new chat to begin automating your tasks
</p>
<Button
onClick={handleNewChat}
className="w-full bg-gradient-to-r from-purple-400 to-purple-500 hover:from-purple-500 hover:to-purple-600 text-white mb-8"
>
<MessageSquarePlus className="mr-2 h-5 w-5" />
Start New Chat
</Button>
<div className="w-full text-left">
<p className="text-sm font-medium mb-3">Current Tools:</p>
<div className="space-y-2">
<Button
variant="outline"
className="w-full justify-start text-left"
onClick={() => {
handleNewChat();
setQuestion("Help me draft, analyze, or respond to emails professionally");
}}
>
Email Assistant
</Button>
<Button
variant="outline"
className="w-full justify-start text-left"
onClick={() => {
handleNewChat();
setQuestion("Help me analyze research papers and extract key findings");
}}
>
Research Assistant
</Button>
<Button
variant="outline"
className="w-full justify-start text-left"
onClick={() => {
handleNewChat();
setQuestion("Search and analyze information from my uploaded documents");
}}
>
Vector Database Assistant
</Button>
</div>
</div>
</div>
</div>
</div>
) : messages.length === 0 ? (
<div className="h-full flex items-center justify-center min-h-[calc(100vh-12rem)]">
<div className="max-w-md w-full space-y-8">
<div className="flex flex-col items-center text-center">
<div className="rounded-full bg-purple-500/20 p-6 mb-8">
<div className="h-16 w-16 rounded-full bg-gradient-to-br from-purple-300 to-purple-500 shadow-lg" />
</div>
<h2 className="text-xl font-semibold mb-2">Ask Your First Question</h2>
<p className="text-sm text-muted-foreground mb-6">
Type your question below or choose from the examples
</p>
<div className="w-full space-y-2">
<Button
variant="outline"
className="w-full justify-start text-left"
onClick={() => setQuestion("Help me draft, analyze, or respond to emails professionally")}
>
Email Assistant
</Button>
<Button
variant="outline"
className="w-full justify-start text-left"
onClick={() => setQuestion("Help me analyze research papers and extract key findings")}
>
Research Assistant
</Button>
<Button
variant="outline"
className="w-full justify-start text-left"
onClick={() => setQuestion("Search and analyze information from my uploaded documents")}
>
Vector Database Assistant
</Button>
</div>
</div>
</div>
</div>
) : (
<>
{messages.map((message) => (
<Message
key={message.id}
message={message}
/>
))}
{isTyping && (
<div className="flex w-full items-start gap-3">
<Avatar className="h-8 w-8">
<AvatarFallback className="bg-gradient-to-br from-purple-300 to-purple-500 text-white text-xs font-medium">
AI
</AvatarFallback>
</Avatar>
<div className="flex max-w-3xl items-center space-x-4 rounded-2xl bg-primary/5 px-4 py-3 text-sm shadow-sm">
<div className="flex space-x-2">
<div className="h-2 w-2 animate-bounce rounded-full bg-primary/40 [animation-delay:0ms]" />
<div className="h-2 w-2 animate-bounce rounded-full bg-primary/40 [animation-delay:150ms]" />
<div className="h-2 w-2 animate-bounce rounded-full bg-primary/40 [animation-delay:300ms]" />
</div>
</div>
</div>
)}
<div ref={messagesEndRef} />
</>
)}
</div>
{/* Scroll to Bottom Button */}
{showScrollButton && messages.length > 0 && (
<div className="absolute -left-16 bottom-2 animate-in fade-in duration-1000 slide-in-from-bottom-4">
<Button
onClick={scrollToBottom}
size="sm"
className="rounded-full shadow-lg bg-background hover:bg-accent transition-all duration-200 p-3 h-auto w-auto"
>
<ArrowDown className="h-5 w-5 text-primary" />
</Button>
</div>
)}
</div>
{/* Input Box */}
<div className="flex-none sticky bottom-0 left-0 right-0 p-4 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="relative mx-auto max-w-3xl">
{/* Scroll to Bottom Button */}
{showScrollButton && messages.length > 0 && (
<div className="absolute -left-14 top-1/2 -translate-y-1/2 animate-in fade-in duration-1000 slide-in-from-bottom-4">
<Button
onClick={scrollToBottom}
size="sm"
className="rounded-full shadow-lg bg-background hover:bg-accent transition-all duration-200 p-3 h-auto w-auto"
>
<ArrowDown className="h-5 w-5 text-primary" />
</Button>
</div>
)}
<form onSubmit={handleSubmit}>
<div className="flex items-start gap-2">
<div className="flex-1 relative">
<textarea <textarea
value={question} value={question}
onChange={(e) => { onChange={handleQuestionChange}
setQuestion(e.target.value); onKeyDown={handleKeyDown}
// Reset the height to auto first to get the correct scrollHeight placeholder="Message RagAI..."
e.target.style.height = 'auto';
// Calculate new height between min and max
const newHeight = Math.max(
40, // min height
Math.min(e.target.scrollHeight, window.innerHeight * 0.4) // max height
);
e.target.style.height = `${newHeight}px`;
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit(e);
}
}}
placeholder="Ask me anything..."
rows={1} rows={1}
className={cn( className="min-h-[52px] w-full resize-none border-0 bg-transparent px-4 py-[14px] focus-visible:outline-none disabled:opacity-50"
'w-full rounded-2xl px-4 py-3 text-sm resize-none', style={{
'bg-primary/5 border-primary/10', maxHeight: '200px',
'focus:outline-none focus:ring-2 focus:ring-primary/20', scrollbarWidth: 'none',
'placeholder:text-muted-foreground', msOverflowStyle: 'none'
'min-h-[40px] transition-all duration-200',
'[&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]'
)}
disabled={loading}
style={{
height: '40px',
maxHeight: `${window.innerHeight * 0.4}px` // 40% of viewport height
}} }}
disabled={loading}
/> />
<div className="absolute right-3 top-3 flex items-center gap-2">
{loading ? (
<Button
type="button"
size="icon"
variant="ghost"
className="h-7 w-7 hover:bg-gray-100"
onClick={() => setLoading(false)}
>
<X className="h-4 w-4" />
</Button>
) : (
<Button
type="submit"
size="icon"
className={cn(
"h-8 w-8 rounded-2xl bg-gray-100 text-gray-600 transition-all hover:bg-gray-200",
!question.trim() && "opacity-40 cursor-not-allowed hover:bg-gray-100"
)}
disabled={!question.trim()}
>
<Send className="h-4 w-4" />
</Button>
)}
</div>
</div> </div>
<Button <div className="flex w-full items-center justify-between text-[11px] text-muted-foreground">
type="submit" <div className="flex items-center gap-4">
disabled={loading || !question.trim()} <div className="flex items-center gap-2">
className={cn( <Button
'rounded-full bg-gradient-to-r from-purple-400 to-purple-500 text-white h-10 w-10 p-0 flex-shrink-0', type="button"
'hover:from-purple-500 hover:to-purple-600', variant="ghost"
'focus:outline-none focus:ring-2 focus:ring-primary/20', size="sm"
'disabled:opacity-50' className="h-6 px-2 text-xs hover:bg-purple-50"
)} onClick={handleNewChat}
> >
<MessageSquarePlus className="mr-1 h-3 w-3" />
New Chat
</Button>
</div>
</div>
<p>
AI may produce inaccurate information about people, places, or facts.
</p>
</div>
</form>
</div>
</div>
) : (
<div className="relative mx-auto max-w-3xl px-4 py-4 md:py-8">
{messages.map((message, index) => (
<Message
key={index}
message={message}
loading={loading && index === messages.length - 1 && message.role === 'user'}
/>
))}
{loading && <TypingIndicator />}
</div>
)}
</div>
{/* Input area for when messages exist */}
{messages.length > 0 && (
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-background via-background to-background/0 py-4">
<div className="mx-auto max-w-3xl px-4">
<form onSubmit={handleSubmit} className="relative flex flex-col items-end gap-2">
<div className="relative flex w-full flex-col overflow-hidden rounded-2xl border bg-background shadow-[0_0_15px_rgba(0,0,0,0.1)] dark:shadow-[0_0_15px_rgba(0,0,0,0.3)]">
<textarea
value={question}
onChange={handleQuestionChange}
onKeyDown={handleKeyDown}
placeholder="Message RagAI..."
rows={1}
className="min-h-[52px] w-full resize-none border-0 bg-transparent px-4 py-[14px] focus-visible:outline-none disabled:opacity-50"
style={{
maxHeight: '200px',
scrollbarWidth: 'none',
msOverflowStyle: 'none'
}}
disabled={loading}
/>
<div className="absolute right-3 top-3 flex items-center gap-2">
{loading ? ( {loading ? (
<Loader2 className="h-4 w-4 animate-spin" /> <Button
type="button"
size="icon"
variant="ghost"
className="h-7 w-7 hover:bg-gray-100"
onClick={() => setLoading(false)}
>
<X className="h-4 w-4" />
</Button>
) : ( ) : (
<Send className="h-4 w-4" /> <Button
type="submit"
size="icon"
className={cn(
"h-8 w-8 rounded-2xl bg-gray-100 text-gray-600 transition-all hover:bg-gray-200",
!question.trim() && "opacity-40 cursor-not-allowed hover:bg-gray-100"
)}
disabled={!question.trim()}
>
<Send className="h-4 w-4" />
</Button>
)} )}
</Button> </div>
</div>
<div className="flex w-full items-center justify-between text-[11px] text-muted-foreground">
<div className="flex items-center gap-2">
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 px-2 text-xs hover:bg-purple-50"
onClick={handleNewChat}
>
<MessageSquarePlus className="mr-1 h-3 w-3" />
New Chat
</Button>
{!isNewChatRequest && chatId && (
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 px-2 text-xs text-destructive hover:bg-destructive/10"
onClick={clearChat}
>
<Trash2 className="mr-1 h-3 w-3" />
Delete Chat
</Button>
)}
</div>
<p>
AI may produce inaccurate information about people, places, or facts.
</p>
</div> </div>
</form> </form>
</div> </div>
</div> </div>
</div> )}
{/* Scroll to bottom button */}
{showScrollButton && (
<button
onClick={scrollToBottom}
className="absolute bottom-28 right-8 flex h-8 w-8 items-center justify-center rounded-full bg-purple-500 text-white shadow-lg transition-colors hover:bg-purple-600"
>
<ArrowDown className="h-4 w-4" />
</button>
)}
{/* Error message */}
{error && (
<div className="absolute bottom-28 left-1/2 -translate-x-1/2 flex items-center gap-2 rounded-lg bg-destructive/10 px-4 py-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4" />
{error}
<button
onClick={() => setError(null)}
className="ml-2 rounded-md p-1 hover:bg-destructive/20"
>
<X className="h-4 w-4" />
</button>
</div>
)}
</div> </div>
); );
} }

View file

@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { MessageSquare, Trash2, User, Bot } from 'lucide-react'; import { MessageSquare, Trash2, User, Bot, Loader2 } from 'lucide-react';
import { Button } from '../../components/ui/Button'; import { Button } from '../../components/ui/Button';
import { useAuth } from '../../contexts/AuthContext'; import { useAuth } from '../../contexts/AuthContext';
import { chatService } from '../../lib/chat-service'; import { chatService } from '../../lib/chat-service';
@ -27,6 +27,7 @@ interface ChatWithStats extends ChatInstance {
export default function StudyHistory() { export default function StudyHistory() {
const { user } = useAuth(); const { user } = useAuth();
const navigate = useNavigate();
const [chats, setChats] = useState<ChatWithStats[]>([]); const [chats, setChats] = useState<ChatWithStats[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [chatToDelete, setChatToDelete] = useState<string | null>(null); const [chatToDelete, setChatToDelete] = useState<string | null>(null);
@ -63,10 +64,22 @@ export default function StudyHistory() {
setChatToDelete(null); setChatToDelete(null);
}; };
const handleNewChat = async () => {
try {
const newChat = await chatService.createChatInstance(user!.id, "New Chat");
if (!newChat) {
throw new Error("Failed to create new chat");
}
navigate(`/dashboard/ask/${newChat.id}`, { replace: true });
} catch (err) {
console.error('Failed to create new chat:', err);
}
};
if (loading) { if (loading) {
return ( return (
<div className="flex h-full items-center justify-center"> <div className="flex h-full items-center justify-center">
<div className="text-lg">Loading...</div> <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div> </div>
); );
} }
@ -78,12 +91,13 @@ export default function StudyHistory() {
<h1 className="text-2xl font-bold">Chat History</h1> <h1 className="text-2xl font-bold">Chat History</h1>
<p className="text-muted-foreground">View your past conversations</p> <p className="text-muted-foreground">View your past conversations</p>
</div> </div>
<Link to="/dashboard/ask"> <Button
<Button className="bg-gradient-to-r from-purple-400 to-purple-500 hover:from-purple-500 hover:to-purple-600 text-white"> onClick={handleNewChat}
<MessageSquare className="mr-2 h-4 w-4" /> className="bg-gradient-to-r from-purple-400 to-purple-500 hover:from-purple-500 hover:to-purple-600 text-white"
New Chat >
</Button> <MessageSquare className="mr-2 h-4 w-4" />
</Link> New Chat
</Button>
</div> </div>
{chats.length === 0 ? ( {chats.length === 0 ? (
@ -92,11 +106,12 @@ export default function StudyHistory() {
<p className="mt-1 text-sm text-muted-foreground"> <p className="mt-1 text-sm text-muted-foreground">
Start a new conversation to see it here Start a new conversation to see it here
</p> </p>
<Link to="/dashboard/ask" className="mt-4 inline-block"> <Button
<Button className="bg-gradient-to-r from-purple-400 to-purple-500 hover:from-purple-500 hover:to-purple-600 text-white"> onClick={handleNewChat}
Start a new chat className="mt-4 bg-gradient-to-r from-purple-400 to-purple-500 hover:from-purple-500 hover:to-purple-600 text-white"
</Button> >
</Link> Start a new chat
</Button>
</div> </div>
) : ( ) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3"> <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">

View file

@ -55,7 +55,8 @@ export const AppRouter: React.FC = () => {
</PrivateRoute> </PrivateRoute>
} }
> >
<Route index element={<Navigate to="ask" replace />} /> {/* Redirect /dashboard to /dashboard/ask with new=true to prevent flashing */}
<Route index element={<Navigate to="ask?new=true" replace />} />
<Route path="ask" element={withSuspense(AskQuestion)} /> <Route path="ask" element={withSuspense(AskQuestion)} />
<Route path="ask/:chatId" element={withSuspense(AskQuestion)} /> <Route path="ask/:chatId" element={withSuspense(AskQuestion)} />
<Route path="upload" element={withSuspense(UploadMaterials)} /> <Route path="upload" element={withSuspense(UploadMaterials)} />