Spaces:
Sleeping
Sleeping
File size: 12,808 Bytes
0b355ec | 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 | import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import io from 'socket.io-client';
import './App.css';
const API_BASE = 'http://localhost:5000/api';
const SOCKET_URL = 'http://localhost:5000';
function App() {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [user, setUser] = useState(null);
const [token, setToken] = useState(localStorage.getItem('token'));
const [conversations, setConversations] = useState([]);
const [currentConversation, setCurrentConversation] = useState(null);
const [messages, setMessages] = useState([]);
const [inputMessage, setInputMessage] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isTyping, setIsTyping] = useState(false);
// Login form state
const [loginData, setLoginData] = useState({ username: '', password: '' });
const [loginError, setLoginError] = useState('');
const messagesEndRef = useRef(null);
const socketRef = useRef(null);
// Set up axios defaults
useEffect(() => {
if (token) {
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
checkAuth();
}
}, [token]);
// Socket connection
useEffect(() => {
if (isAuthenticated) {
socketRef.current = io(SOCKET_URL, {
auth: { token }
});
socketRef.current.on('message_received', (message) => {
setMessages(prev => [...prev, message]);
});
socketRef.current.on('typing_indicator', (data) => {
setIsTyping(data.isTyping);
});
return () => {
socketRef.current?.disconnect();
};
}
}, [isAuthenticated, token]);
// Auto scroll to bottom
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
const checkAuth = async () => {
try {
const response = await axios.get(`${API_BASE}/auth/me`);
if (response.data.success) {
setUser(response.data.data);
setIsAuthenticated(true);
loadConversations();
}
} catch (error) {
console.error('Auth check failed:', error);
logout();
}
};
const login = async (e) => {
e.preventDefault();
setLoginError('');
try {
const response = await axios.post(`${API_BASE}/auth/login`, loginData);
if (response.data.success) {
const { token: newToken, user: userData } = response.data.data;
localStorage.setItem('token', newToken);
setToken(newToken);
setUser(userData);
setIsAuthenticated(true);
loadConversations();
}
} catch (error) {
setLoginError(error.response?.data?.message || 'Login failed');
}
};
const loginWithDemo = async () => {
// Try demo login
try {
const response = await axios.post(`${API_BASE}/auth/login`, {
username: 'demo@uga.edu',
password: 'demo123'
});
if (response.data.success) {
const { token: newToken, user: userData } = response.data.data;
localStorage.setItem('token', newToken);
setToken(newToken);
setUser(userData);
setIsAuthenticated(true);
loadConversations();
}
} catch (error) {
// If demo fails, create a mock session
const mockUser = {
id: 'demo-user',
ugaId: '811123456',
firstName: 'Demo',
lastName: 'User',
email: 'demo@uga.edu',
role: 'student',
classification: 'Senior',
major: 'Computer Science'
};
setUser(mockUser);
setIsAuthenticated(true);
setToken('demo-token');
localStorage.setItem('token', 'demo-token');
// Create a demo conversation
setConversations([{
id: 'demo-conv',
title: 'Welcome to UGA Assistant',
category: 'general',
lastActivity: new Date().toISOString()
}]);
setCurrentConversation('demo-conv');
setMessages([{
id: '1',
role: 'assistant',
content: "π Welcome to UGA Assistant! I'm your agentic AI helper.\n\nI can help you with:\n- **Course Registration**: \"Register me for CSCI 1301\"\n- **Financial Services**: \"What's my account balance?\"\n- **Dining Information**: \"What's for lunch at ECV?\"\n- **Housing Services**: \"Book me a study room\"\n- **Campus Information**: \"Show me library hours\"\n\nTry asking me anything about UGA!",
timestamp: new Date().toISOString()
}]);
}
};
const logout = () => {
localStorage.removeItem('token');
setToken(null);
setIsAuthenticated(false);
setUser(null);
setConversations([]);
setCurrentConversation(null);
setMessages([]);
delete axios.defaults.headers.common['Authorization'];
};
const loadConversations = async () => {
try {
const response = await axios.get(`${API_BASE}/chat/conversations`);
if (response.data.success) {
setConversations(response.data.data);
}
} catch (error) {
console.error('Failed to load conversations:', error);
}
};
const loadConversation = async (conversationId) => {
try {
const response = await axios.get(`${API_BASE}/chat/conversations/${conversationId}`);
if (response.data.success) {
setMessages(response.data.data.messages);
setCurrentConversation(conversationId);
}
} catch (error) {
console.error('Failed to load conversation:', error);
}
};
const sendMessage = async (e) => {
e.preventDefault();
if (!inputMessage.trim() || isLoading) return;
const messageText = inputMessage.trim();
setInputMessage('');
setIsLoading(true);
// Add user message immediately
const userMessage = {
id: Date.now(),
role: 'user',
content: messageText,
timestamp: new Date().toISOString()
};
setMessages(prev => [...prev, userMessage]);
try {
const response = await axios.post(`${API_BASE}/chat/message`, {
conversationId: currentConversation,
message: messageText
});
if (response.data.success) {
const { assistantMessage, conversationId } = response.data.data;
// Update conversation if new
if (!currentConversation) {
setCurrentConversation(conversationId);
loadConversations();
}
// Add assistant message
setMessages(prev => [...prev, assistantMessage]);
}
} catch (error) {
console.error('Failed to send message:', error);
// Add error message
setMessages(prev => [...prev, {
id: Date.now(),
role: 'assistant',
content: "Sorry, I'm having trouble connecting to the UGA systems right now. Please try again later.",
timestamp: new Date().toISOString()
}]);
} finally {
setIsLoading(false);
}
};
const newConversation = () => {
setCurrentConversation(null);
setMessages([]);
};
if (!isAuthenticated) {
return (
<div className="login-container">
<div className="login-card">
<div className="logo">
<div className="logo-icon">π</div>
<h1>UGA Assistant</h1>
<p>Test Interface for Agentic AI Chatbot</p>
</div>
<div className="quick-demo">
<button onClick={loginWithDemo} className="demo-button">
π Quick Demo
</button>
<p>Try the system immediately with demo data</p>
</div>
<div className="divider">or</div>
<form onSubmit={login} className="login-form">
<input
type="text"
placeholder="Username (e.g., demo@uga.edu)"
value={loginData.username}
onChange={(e) => setLoginData({...loginData, username: e.target.value})}
required
/>
<input
type="password"
placeholder="Password"
value={loginData.password}
onChange={(e) => setLoginData({...loginData, password: e.target.value})}
required
/>
<button type="submit">Sign In</button>
{loginError && <div className="error">{loginError}</div>}
</form>
<div className="test-accounts">
<h3>Test Accounts:</h3>
<p><strong>Student:</strong> demo@uga.edu / demo123</p>
<p><strong>Faculty:</strong> faculty@uga.edu / faculty123</p>
</div>
</div>
</div>
);
}
return (
<div className="app">
<div className="sidebar">
<div className="user-info">
<div className="avatar">{user.firstName?.[0]}{user.lastName?.[0]}</div>
<div className="user-details">
<div className="name">{user.firstName} {user.lastName}</div>
<div className="role">{user.role} β’ {user.classification || 'Faculty'}</div>
{user.major && <div className="major">{user.major}</div>}
</div>
<button onClick={logout} className="logout-btn">Γ</button>
</div>
<div className="conversations">
<button onClick={newConversation} className="new-conversation">
+ New Conversation
</button>
{conversations.map(conv => (
<div
key={conv.id}
className={`conversation-item ${conv.id === currentConversation ? 'active' : ''}`}
onClick={() => loadConversation(conv.id)}
>
<div className="conv-title">{conv.title}</div>
<div className="conv-category">{conv.category}</div>
</div>
))}
</div>
<div className="quick-actions">
<h3>Quick Actions:</h3>
<button onClick={() => setInputMessage("What's for lunch at ECV today?")}>
π½οΈ Dining Hours
</button>
<button onClick={() => setInputMessage("Help me register for CSCI 1301")}>
π Course Registration
</button>
<button onClick={() => setInputMessage("What's my account balance?")}>
π³ Account Balance
</button>
<button onClick={() => setInputMessage("Book me a study room for tomorrow")}>
π Book Study Room
</button>
</div>
</div>
<div className="chat-area">
<div className="chat-header">
<h2>π€ UGA Assistant</h2>
<span className="status">
{isTyping ? 'β¨οΈ Typing...' : 'β
Online'}
</span>
</div>
<div className="messages">
{messages.map(message => (
<div key={message.id} className={`message ${message.role}`}>
<div className="message-avatar">
{message.role === 'user' ? 'π€' : 'π€'}
</div>
<div className="message-content">
<div className="message-text">
{message.content.split('\n').map((line, i) => (
<div key={i}>{line}</div>
))}
</div>
{message.metadata && (
<div className="message-metadata">
{message.metadata.ugaSystemUsed && (
<span className="system-badge">{message.metadata.ugaSystemUsed}</span>
)}
{message.metadata.agentic && (
<span className="agentic-badge">β‘ Action Executed</span>
)}
</div>
)}
<div className="message-time">
{new Date(message.timestamp).toLocaleTimeString()}
</div>
</div>
</div>
))}
{isLoading && (
<div className="message assistant">
<div className="message-avatar">π€</div>
<div className="message-content">
<div className="typing-indicator">
<span></span><span></span><span></span>
</div>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
<form onSubmit={sendMessage} className="message-input">
<input
type="text"
placeholder="Ask me anything about UGA..."
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
disabled={isLoading}
/>
<button type="submit" disabled={isLoading || !inputMessage.trim()}>
{isLoading ? 'β³' : 'β€'}
</button>
</form>
</div>
</div>
);
}
export default App; |