import React, { useState, useEffect } from "react"; import { AnimatedAIChat } from "@/components/ui/animated-ai-chat"; export function App() { const [models, setModels] = useState>({}); const [chapters, setChapters] = useState([]); const [selectedModel, setSelectedModel] = useState("@cf/deepseek-ai/deepseek-r1-distill-qwen-32b"); const [selectedChapter, setSelectedChapter] = useState("All"); const [messages, setMessages] = useState([]); const [isStreaming, setIsStreaming] = useState(false); const [isSessionLoading, setIsSessionLoading] = useState(false); const [groqKeysCount, setGroqKeysCount] = useState(0); // User auth state (stored in localStorage) const [user, setUser] = useState<{ username: string; name: string } | null>(() => { try { const saved = localStorage.getItem("jurisai_user"); return saved ? JSON.parse(saved) : null; } catch { return null; } }); // Sessions list and current session id const [sessions, setSessions] = useState>([]); const [currentSessionId, setCurrentSessionId] = useState(null); // Fetch initial info (models, chapters, groq keys) useEffect(() => { fetch("/api/info") .then((res) => res.json()) .then((data) => { setModels(data.models || {}); setChapters(data.chapters || []); if (data.default_model) setSelectedModel(data.default_model); if (typeof data.groq_keys_count === "number") setGroqKeysCount(data.groq_keys_count); }) .catch((e) => console.error("Error fetching info:", e)); }, []); // Fetch user's session list const loadSessions = async (username?: string) => { try { const u = username || user?.username; const url = u ? `/api/sessions?username=${encodeURIComponent(u)}` : "/api/sessions"; const res = await fetch(url); const data = await res.json(); setSessions(data.sessions || []); } catch (e) { console.error("Error fetching sessions:", e); } }; useEffect(() => { loadSessions(); }, [user]); // Handle URL share / session query parameters useEffect(() => { const params = new URLSearchParams(window.location.search); const sid = params.get("session") || params.get("share"); if (sid) { loadSessionById(sid); } }, []); const loadSessionById = async (sid: string) => { // Immediately select session and show loading skeleton setCurrentSessionId(sid); setMessages([]); setIsSessionLoading(true); try { const res = await fetch(`/api/sessions/${sid}`); if (!res.ok) return; const data = await res.json(); if (data.model) setSelectedModel(data.model); if (data.chapter_filter) setSelectedChapter(data.chapter_filter); if (data.messages && Array.isArray(data.messages)) { setMessages( data.messages.map((m: any) => ({ role: m.role, content: m.content || "", thinking: m.thinking || "", findings: m.findings || null, citations: m.citations || [], usage: m.usage || { completion_tokens: 0 }, })) ); } // Update browser URL without reloading const url = new URL(window.location.href); url.searchParams.set("session", data.id); window.history.replaceState({}, "", url.toString()); } catch (e) { console.error("Error loading session:", e); } finally { setIsSessionLoading(false); } }; const handleDeleteSession = async (sid: string) => { try { await fetch(`/api/sessions/${sid}`, { method: "DELETE" }); // If deleting current session, clear thread if (sid === currentSessionId) { handleClear(); } // Refresh list loadSessions(); } catch (e) { console.error("Error deleting session:", e); } }; const handleAuth = async ( username: string, name?: string, mode: "create" | "login" = "create" ): Promise<{ success: boolean; error?: string }> => { try { const res = await fetch("/api/auth", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, name, mode }), }); const data = await res.json(); if (!res.ok) { return { success: false, error: data.detail || "Authentication failed." }; } setUser(data); localStorage.setItem("jurisai_user", JSON.stringify(data)); loadSessions(data.username); return { success: true }; } catch (e: any) { console.error("Auth error:", e); return { success: false, error: e.message || "Failed to connect to authentication server." }; } }; const handleLogout = () => { setUser(null); localStorage.removeItem("jurisai_user"); loadSessions(""); }; const handleClear = () => { setMessages([]); setCurrentSessionId(null); const url = new URL(window.location.href); url.searchParams.delete("session"); url.searchParams.delete("share"); window.history.replaceState({}, "", url.toString()); }; const handleShareSession = () => { if (!currentSessionId) return; const shareUrl = `${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(currentSessionId)}`; navigator.clipboard.writeText(shareUrl); }; const handleCompactSession = async () => { if (!currentSessionId) return; try { const res = await fetch(`/api/sessions/${currentSessionId}/compact`, { method: "POST" }); if (res.ok) { const data = await res.json(); if (data.session && Array.isArray(data.session.messages)) { setMessages( data.session.messages.map((m: any) => ({ role: m.role, content: m.content || "", thinking: m.thinking || "", findings: m.findings || null, citations: m.citations || [], usage: m.usage || { completion_tokens: 0 }, })) ); } loadSessions(); } } catch (e) { console.error("Compaction failed:", e); } }; const handleSendMessage = async (userText: string) => { const userMsg = { role: "user", content: userText }; const initialAssistantMsg = { role: "assistant", content: "", thinking: "", findings: null, citations: [], usage: { completion_tokens: 0 }, isInterrupted: false, }; const newHistory = [...messages, userMsg]; setMessages([...newHistory, initialAssistantMsg]); setIsStreaming(true); try { const historyPayload = messages.map((m) => ({ role: m.role, content: m.content || "", })); const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: userText, history: historyPayload, model: selectedModel, chapter_filter: selectedChapter, top_k: 5, session_id: currentSessionId || undefined, username: user?.username || undefined, }), }); if (!res.body) { setIsStreaming(false); return; } const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; let answerText = ""; let thinkingText = ""; let findingsData: any = null; let citationsData: any[] = []; let tokenUsage: any = { completion_tokens: 0 }; let hasReceivedDone = false; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const events = buffer.split("\n\n"); buffer = events.pop() || ""; for (const evt of events) { if (!evt.trim()) continue; const lines = evt.split("\n"); let eventType = "message"; let dataStr = ""; for (const line of lines) { if (line.startsWith("event: ")) { eventType = line.slice(7).trim(); } else if (line.startsWith("data: ")) { dataStr = line.slice(6).trim(); } } if (eventType === "session" && dataStr) { try { const obj = JSON.parse(dataStr); if (obj.session_id) { setCurrentSessionId(obj.session_id); const url = new URL(window.location.href); url.searchParams.set("session", obj.session_id); window.history.replaceState({}, "", url.toString()); } } catch (e) {} } else if (eventType === "findings" && dataStr) { try { findingsData = JSON.parse(dataStr); } catch (e) {} } else if (eventType === "thinking" && dataStr) { try { const obj = JSON.parse(dataStr); thinkingText += obj.text || ""; } catch (e) {} } else if (eventType === "token" && dataStr) { try { const obj = JSON.parse(dataStr); answerText += obj.text || ""; } catch (e) {} } else if (eventType === "citations" && dataStr) { try { citationsData = JSON.parse(dataStr); } catch (e) {} } else if (eventType === "usage" && dataStr) { try { const obj = JSON.parse(dataStr); tokenUsage = { ...tokenUsage, ...obj }; } catch (e) {} } else if (eventType === "done") { hasReceivedDone = true; } setMessages((prev) => { const updated = [...prev]; const lastIdx = updated.length - 1; if (lastIdx >= 0 && updated[lastIdx].role === "assistant") { updated[lastIdx] = { ...updated[lastIdx], content: answerText, thinking: thinkingText, findings: findingsData, citations: citationsData, usage: tokenUsage, isInterrupted: false, }; } return updated; }); } } // Check if response ended abruptly or failed to complete const isLikelyAbrupt = !hasReceivedDone && answerText.length > 0 && !answerText.trim().endsWith(".") && !answerText.trim().endsWith("!") && !answerText.trim().endsWith("?") && !answerText.trim().endsWith("`") && !answerText.trim().endsWith("*") && !answerText.trim().endsWith(")"); if (isLikelyAbrupt) { setMessages((prev) => { const updated = [...prev]; const lastIdx = updated.length - 1; if (lastIdx >= 0 && updated[lastIdx].role === "assistant") { updated[lastIdx].isInterrupted = true; } return updated; }); } } catch (e) { console.error("Stream error:", e); setMessages((prev) => { const updated = [...prev]; const lastIdx = updated.length - 1; if (lastIdx >= 0 && updated[lastIdx].role === "assistant") { updated[lastIdx].isInterrupted = true; } return updated; }); } finally { setIsStreaming(false); loadSessions(); } }; return ( ); } export default App;