Spaces:
Sleeping
Sleeping
Download test-frontend/src/App.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/test-frontend/src/App.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/test-frontend/src/App.js
-
curl -L -o App.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/test-frontend/src/App.js
12.8 kB
| 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; |