import React, { useState, useRef } from "react"; import { ThreadPrimitive, ComposerPrimitive, MessagePrimitive, useMessage, } from "@assistant-ui/react"; import { Sparkles, Send, BookOpen, ChevronRight, RefreshCw, Cpu, Layers, Search, Brain, FileCheck, Volume2, VolumeX, Loader2, Scale, FileText } from "lucide-react"; import Markdown from "react-markdown"; interface Citation { title: string; chapter: string; page_number: number; retrieval_score: number; raw_text: string; } interface Findings { intent: string; intent_reason: string; search_query: string; chunks_found: number; top_sources: string[]; } const ReadAloudButton = ({ text }: { text: string }) => { const [isPlaying, setIsPlaying] = useState(false); const [isLoading, setIsLoading] = useState(false); const audioRef = useRef(null); const handleToggleAudio = async () => { if (isPlaying && audioRef.current) { audioRef.current.pause(); setIsPlaying(false); return; } if (audioRef.current && audioRef.current.src) { audioRef.current.play(); setIsPlaying(true); return; } try { setIsLoading(true); const res = await fetch("/api/tts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text, speaker: "luna" }), }); if (!res.ok) { throw new Error("TTS failed"); } const blob = await res.blob(); const audioUrl = URL.createObjectURL(blob); const audio = new Audio(audioUrl); audioRef.current = audio; audio.onended = () => setIsPlaying(false); audio.onerror = () => { setIsPlaying(false); setIsLoading(false); }; await audio.play(); setIsPlaying(true); } catch (e) { console.error("Audio playback error:", e); } finally { setIsLoading(false); } }; return ( ); }; const UserMessage = () => { const msgState = useMessage() as any; const content = msgState.content || []; return (
{content.map((c: any, i: number) => ( {c.type === "text" ? c.text : ""} ))}
); }; const AssistantMessage = () => { const msgState = useMessage() as any; const content = msgState.content || []; const rawData = msgState.customData || {}; const thinking = rawData.thinking; const findings: Findings = rawData.findings; const citations: Citation[] = rawData.retrieved_chunks || []; const isStreaming = rawData.isStreaming; const isThinkingActive = isStreaming && thinking && (!content || content.length === 0 || !content[0]?.text); const fullText = content.map((c: any) => (c.type === "text" ? c.text : "")).join("\n\n"); // Parse Main Statutory Answer vs Detailed Legal Explanation let mainAnswer = ""; let detailedExplanation = ""; if (fullText.includes("### 📑 Detailed Legal Explanation")) { const parts = fullText.split("### 📑 Detailed Legal Explanation"); mainAnswer = parts[0].replace("### 🏛️ Main Statutory Ruling & Direct Answer", "").trim(); detailedExplanation = parts[1].trim(); } else if (fullText.includes("### 🏛️ Main Statutory Ruling")) { mainAnswer = fullText.replace("### 🏛️ Main Statutory Ruling & Direct Answer", "").trim(); } else { mainAnswer = fullText; } const usage = rawData.usage; return ( {/* 1. Research & Intent Findings Box */} {findings && (
{findings.intent}
{usage && usage.completion_tokens > 0 && ( {usage.completion_tokens} tokens )} {findings.chunks_found > 0 && ( {findings.chunks_found} chunks retrieved )}

{findings.intent_reason}

{findings.top_sources && findings.top_sources.length > 0 && (
{findings.top_sources.map((src: string, idx: number) => ( {src} ))}
)}
)} {/* 2. Collapsible Model Reasoning & Thinking Box */} {thinking && (
{isThinkingActive ? "Thinking in progress..." : `Reasoning & Thought Trace (${thinking.length} chars)`}
{isThinkingActive && ( Live Reasoning )}
{thinking} {isThinkingActive && }
)} {/* 3. Main Statutory Answer Card with Read Aloud */} {mainAnswer && (
Main Statutory Answer
{mainAnswer} {isStreaming && !isThinkingActive && !detailedExplanation && ( )}
)} {/* 4. Detailed In-Depth Legal Explanation Card */} {detailedExplanation && (
In-Depth Explanation & Case Principles
{detailedExplanation} {isStreaming && !isThinkingActive && ( )}
)} {/* 5. Grounded Citation Drawer */} {citations && citations.length > 0 && (
Grounded in {citations.length} Verified Book Excerpt(s)
{citations.map((src, idx) => (
{src.title} (Page {src.page_number}) Score: {src.retrieval_score}
{src.raw_text}
))}
)}
); }; export function Thread({ models, chapters, selectedModel, onSelectModel, selectedChapter, onSelectChapter, onClear, }: { models: Record; chapters: string[]; selectedModel: string; onSelectModel: (m: string) => void; selectedChapter: string; onSelectChapter: (c: string) => void; onClear: () => void; }) { return (
{/* Sidebar with soft dark tones */} {/* Main Thread Viewport */} {/* Header */}
ICAI Paper-2 Business Laws Autonomous Legal RAG
Cloudflare Workers AI
{/* Viewport Messages */}
May 2026 Curriculum Pre-Indexed

How can I assist your legal study today?

Ask any statutory case question, doctrine problem, or chat freely. The AI autonomously routes, traces findings, and cites official study modules.

{/* assistant-ui Composer */}
Built with @assistant-ui/react primitives & Cloudflare Workers AI
); }