Spaces:
Sleeping
Sleeping
File size: 20,708 Bytes
c49440d | 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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | 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<HTMLAudioElement | null>(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 (
<button
onClick={handleToggleAudio}
disabled={isLoading || !text}
className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium transition cursor-pointer border ${
isPlaying
? "bg-emerald-950/40 text-emerald-400 border-emerald-800/50"
: "bg-[#1F2027] text-zinc-300 hover:text-zinc-100 hover:bg-[#282A34] border-[#2E303C]"
} disabled:opacity-50`}
title="Listen via Cloudflare Deepgram Aura-2"
>
{isLoading ? (
<Loader2 className="w-3.5 h-3.5 animate-spin text-sky-400" />
) : isPlaying ? (
<VolumeX className="w-3.5 h-3.5 text-emerald-400" />
) : (
<Volume2 className="w-3.5 h-3.5 text-sky-400" />
)}
<span>{isLoading ? "Generating Speech..." : isPlaying ? "Pause Read Aloud" : "Read Aloud (Aura-2)"}</span>
</button>
);
};
const UserMessage = () => {
const msgState = useMessage() as any;
const content = msgState.content || [];
return (
<MessagePrimitive.Root className="flex flex-col items-end gap-1 w-full my-1">
<div className="max-w-[78%] rounded-2xl rounded-br-sm bg-[#272A34] text-[#F1F3F7] px-4 py-2.5 text-[13.5px] leading-relaxed shadow-sm">
{content.map((c: any, i: number) => (
<span key={i}>{c.type === "text" ? c.text : ""}</span>
))}
</div>
</MessagePrimitive.Root>
);
};
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 (
<MessagePrimitive.Root className="flex flex-col items-start gap-3 w-full my-2">
{/* 1. Research & Intent Findings Box */}
{findings && (
<div className="w-full bg-[#16181E] border border-[#262833] rounded-lg p-3 text-xs flex flex-col gap-2 transition-all">
<div className="flex items-center justify-between">
<span className="flex items-center gap-1.5 font-medium text-sky-400">
<Search className="w-3.5 h-3.5" />
<span>{findings.intent}</span>
</span>
<div className="flex items-center gap-2">
{usage && usage.completion_tokens > 0 && (
<span className="font-mono text-[10.5px] bg-[#1F212B] border border-[#2D303E] px-2 py-0.5 rounded text-sky-300 flex items-center gap-1">
<span className="w-1.5 h-1.5 rounded-full bg-sky-400 animate-pulse" />
{usage.completion_tokens} tokens
</span>
)}
{findings.chunks_found > 0 && (
<span className="font-mono text-[10.5px] bg-[#22242D] border border-[#2E303B] px-2 py-0.5 rounded text-zinc-300">
{findings.chunks_found} chunks retrieved
</span>
)}
</div>
</div>
<p className="text-zinc-400 text-[11.5px] leading-relaxed m-0">
{findings.intent_reason}
</p>
{findings.top_sources && findings.top_sources.length > 0 && (
<div className="flex flex-wrap gap-1.5 pt-1 border-t border-[#23252E]">
{findings.top_sources.map((src: string, idx: number) => (
<span
key={idx}
className="inline-flex items-center gap-1 bg-[#1C1D24] text-zinc-400 border border-[#292B36] text-[10.5px] px-2 py-0.5 rounded"
>
<FileCheck className="w-3 h-3 text-emerald-400" />
{src}
</span>
))}
</div>
)}
</div>
)}
{/* 2. Collapsible Model Reasoning & Thinking Box */}
{thinking && (
<details
open={isThinkingActive}
className="w-full bg-[#18191E] border border-[#2B2D37] rounded-lg overflow-hidden group transition-all"
>
<summary className="flex items-center justify-between px-3 py-2 text-xs font-medium text-zinc-400 cursor-pointer hover:bg-[#202127] transition select-none">
<div className="flex items-center gap-2">
<ChevronRight className="w-3.5 h-3.5 transition-transform group-open:rotate-90 text-sky-400" />
<Brain className={`w-3.5 h-3.5 ${isThinkingActive ? "text-amber-400 animate-pulse" : "text-zinc-400"}`} />
<span>
{isThinkingActive ? "Thinking in progress..." : `Reasoning & Thought Trace (${thinking.length} chars)`}
</span>
</div>
{isThinkingActive && (
<span className="inline-flex items-center gap-1 font-mono text-[10px] text-amber-400/90 bg-amber-950/30 border border-amber-800/40 px-2 py-0.5 rounded">
<span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping" />
Live Reasoning
</span>
)}
</summary>
<div className="p-3 text-[11px] font-mono text-zinc-400 border-t border-[#2B2D37] bg-[#131418] whitespace-pre-wrap leading-relaxed max-h-60 overflow-y-auto">
{thinking}
{isThinkingActive && <span className="inline-block w-1.5 h-3.5 ml-1 bg-amber-400 animate-pulse align-middle" />}
</div>
</details>
)}
{/* 3. Main Statutory Answer Card with Read Aloud */}
{mainAnswer && (
<div className="w-full bg-[#17181F] border border-[#262834] rounded-xl p-4 shadow-sm flex flex-col gap-3">
<div className="flex items-center justify-between border-b border-[#252733] pb-2.5">
<span className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-sky-400">
<Scale className="w-3.5 h-3.5" />
<span>Main Statutory Answer</span>
</span>
<ReadAloudButton text={mainAnswer} />
</div>
<div className="text-[#DCE0E8] text-[14px] leading-relaxed prose prose-invert max-w-none">
<Markdown>{mainAnswer}</Markdown>
{isStreaming && !isThinkingActive && !detailedExplanation && (
<span className="inline-block w-1.5 h-4 ml-1 bg-sky-400 animate-pulse align-middle" />
)}
</div>
</div>
)}
{/* 4. Detailed In-Depth Legal Explanation Card */}
{detailedExplanation && (
<div className="w-full bg-[#15161C] border border-[#232530] rounded-xl p-4 flex flex-col gap-3">
<div className="flex items-center justify-between border-b border-[#242631] pb-2.5">
<span className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-indigo-400">
<FileText className="w-3.5 h-3.5" />
<span>In-Depth Explanation & Case Principles</span>
</span>
<ReadAloudButton text={detailedExplanation} />
</div>
<div className="text-[#CFD3DC] text-[13.5px] leading-relaxed prose prose-invert max-w-none">
<Markdown>{detailedExplanation}</Markdown>
{isStreaming && !isThinkingActive && (
<span className="inline-block w-1.5 h-4 ml-1 bg-sky-400 animate-pulse align-middle" />
)}
</div>
</div>
)}
{/* 5. Grounded Citation Drawer */}
{citations && citations.length > 0 && (
<div className="w-full mt-1 pt-2 border-t border-[#242632]">
<details className="group">
<summary className="text-xs font-medium text-sky-400 hover:text-sky-300 cursor-pointer flex items-center gap-1.5 select-none">
<BookOpen className="w-3.5 h-3.5" />
<span>Grounded in {citations.length} Verified Book Excerpt(s)</span>
</summary>
<div className="mt-2.5 flex flex-col gap-2">
{citations.map((src, idx) => (
<div
key={idx}
className="bg-[#191A20] border border-[#282A35] border-l-2 border-l-sky-400 p-2.5 rounded text-xs"
>
<div className="flex justify-between font-medium text-[#E1E4EA] mb-1">
<span>
{src.title} (Page {src.page_number})
</span>
<span className="font-mono text-[10px] text-zinc-400">
Score: {src.retrieval_score}
</span>
</div>
<div className="text-zinc-400 text-[11.5px] leading-relaxed">
{src.raw_text}
</div>
</div>
))}
</div>
</details>
</div>
)}
</MessagePrimitive.Root>
);
};
export function Thread({
models,
chapters,
selectedModel,
onSelectModel,
selectedChapter,
onSelectChapter,
onClear,
}: {
models: Record<string, string>;
chapters: string[];
selectedModel: string;
onSelectModel: (m: string) => void;
selectedChapter: string;
onSelectChapter: (c: string) => void;
onClear: () => void;
}) {
return (
<div className="flex h-screen w-screen overflow-hidden bg-[#121316] text-[#E4E4E7] font-sans">
{/* Sidebar with soft dark tones */}
<aside className="w-72 min-w-[290px] bg-[#16171B] border-r border-[#24252C] flex flex-col p-4 gap-4 overflow-y-auto">
<div className="flex items-center gap-2.5 pb-3 border-b border-[#24252C]">
<div className="w-8 h-8 rounded-lg bg-[#22242C] border border-[#2E303B] flex items-center justify-center text-sky-400">
<Sparkles className="w-4 h-4" />
</div>
<div>
<h2 className="font-medium text-xs text-[#E1E4EA]">assistant-ui</h2>
<p className="text-[10px] text-zinc-400">ICAI Paper-2 Business Laws</p>
</div>
</div>
{/* Model Selection */}
<div className="flex flex-col gap-1">
<label className="text-[10px] font-semibold text-zinc-400 flex items-center gap-1.5 uppercase tracking-wider">
<Cpu className="w-3 h-3 text-zinc-400" />
Runtime Model
</label>
<select
value={selectedModel}
onChange={(e) => onSelectModel(e.target.value)}
className="w-full bg-[#1F2026] border border-[#2B2D35] hover:border-[#383A45] rounded-md py-1.5 px-2.5 text-xs text-[#E1E4EA] outline-none transition cursor-pointer"
>
{Object.entries(models).map(([name, id]) => (
<option key={id} value={id}>
{name}
</option>
))}
</select>
</div>
{/* Chapter Selection */}
<div className="flex flex-col gap-1">
<label className="text-[10px] font-semibold text-zinc-400 flex items-center gap-1.5 uppercase tracking-wider">
<Layers className="w-3 h-3 text-zinc-400" />
Chapter Scope
</label>
<select
value={selectedChapter}
onChange={(e) => onSelectChapter(e.target.value)}
className="w-full bg-[#1F2026] border border-[#2B2D35] hover:border-[#383A45] rounded-md py-1.5 px-2.5 text-xs text-[#E1E4EA] outline-none transition cursor-pointer"
>
{chapters.map((ch) => (
<option key={ch} value={ch}>
{ch === "All" ? "All 7 Acts & Chapters" : ch}
</option>
))}
</select>
</div>
{/* System Metric Card */}
<div className="flex items-center justify-around bg-[#1B1C22] border border-[#262832] rounded-lg p-2.5">
<div className="flex flex-col items-center">
<span className="font-mono text-xs font-semibold text-[#D4D7DE]">2,110</span>
<span className="text-[9.5px] text-zinc-400">Legal Chunks</span>
</div>
<div className="w-[1px] h-5 bg-[#2A2C37]" />
<div className="flex flex-col items-center">
<span className="font-mono text-xs font-semibold text-sky-400">Cloudflare</span>
<span className="text-[9.5px] text-zinc-400">BGE Embeddings</span>
</div>
</div>
{/* Presets */}
<div className="flex flex-col gap-1.5 flex-grow">
<span className="text-[10px] font-semibold text-zinc-400 uppercase tracking-wider">Preset Questions</span>
{[
{
title: "Max Partners Limit",
desc: "Sec 464 Companies Act rule",
query: "What is the maximum number of partners allowed in a partnership firm?",
},
{
title: "Doctrine of Ultra Vires",
desc: "Ashbury Railway & MOA scope",
query: "Explain the Doctrine of Ultra Vires with consequences and exceptions.",
},
{
title: "Unpaid Seller Rights",
desc: "Lien, Stoppage & Suit remedies",
query: "What are the rights of an unpaid seller against goods and buyer personally?",
},
{
title: "Section 25 Exceptions",
desc: "Natural Love & Time-Barred debt",
query: "What are the exceptions to the rule No Consideration No Contract under Section 25?",
},
].map((item, idx) => (
<button
key={idx}
onClick={() => {
const textarea = document.querySelector("textarea");
if (textarea) {
textarea.value = item.query;
const send = document.querySelector("button[type='submit']") as HTMLButtonElement;
if (send) send.click();
}
}}
className="text-left p-2 rounded-md hover:bg-[#20222A] border border-transparent hover:border-[#2D303B] transition group flex flex-col cursor-pointer"
>
<span className="text-xs font-medium text-[#C8CBD3] group-hover:text-white">
{item.title}
</span>
<span className="text-[10.5px] text-zinc-400">{item.desc}</span>
</button>
))}
</div>
<button
onClick={onClear}
className="flex items-center justify-center gap-1.5 py-1.5 px-3 border border-[#2C2E38] hover:bg-[#22242D] text-zinc-400 hover:text-zinc-200 rounded-md text-xs transition cursor-pointer"
>
<RefreshCw className="w-3 h-3" />
<span>New Thread</span>
</button>
</aside>
{/* Main Thread Viewport */}
<ThreadPrimitive.Root className="flex-1 flex flex-col h-full bg-[#121316]">
{/* Header */}
<header className="h-12 border-b border-[#21232B] flex items-center justify-between px-6 bg-[#141519]/80 backdrop-blur-md">
<div className="flex items-center gap-2">
<span className="text-[10.5px] px-2 py-0.5 rounded bg-[#20222A] border border-[#2D303C] text-zinc-300 font-medium">
ICAI Paper-2 Business Laws
</span>
<span className="text-xs font-medium text-zinc-400">
Autonomous Legal RAG
</span>
</div>
<div className="flex items-center gap-2 text-xs text-zinc-400">
<span className="w-1.5 h-1.5 rounded-full bg-emerald-400" />
<span>Cloudflare Workers AI</span>
</div>
</header>
{/* Viewport Messages */}
<ThreadPrimitive.Viewport className="flex-1 overflow-y-auto px-4 md:px-20 lg:px-36 py-6 flex flex-col gap-5">
<ThreadPrimitive.Empty>
<div className="flex flex-col items-center text-center max-w-lg mx-auto mt-10">
<div className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-[#1C1D24] border border-[#292B36] text-xs text-zinc-400 mb-3">
<BookOpen className="w-3 h-3 text-sky-400" />
<span>May 2026 Curriculum Pre-Indexed</span>
</div>
<h1 className="text-xl font-semibold text-[#E6E8EE] mb-1.5">
How can I assist your legal study today?
</h1>
<p className="text-xs text-zinc-400 leading-relaxed mb-6">
Ask any statutory case question, doctrine problem, or chat freely. The AI autonomously routes, traces findings, and cites official study modules.
</p>
</div>
</ThreadPrimitive.Empty>
<ThreadPrimitive.Messages
components={{
UserMessage,
AssistantMessage,
}}
/>
</ThreadPrimitive.Viewport>
{/* assistant-ui Composer */}
<div className="px-4 md:px-20 lg:px-36 pb-5 pt-2 bg-[#121316]">
<ComposerPrimitive.Root className="flex items-center gap-2 bg-[#1A1B22] border border-[#2B2D38] focus-within:border-zinc-500 rounded-xl px-3.5 py-2 shadow-md transition">
<ComposerPrimitive.Input
placeholder="Ask a legal scenario, doctrine, or section..."
className="flex-1 bg-transparent text-sm text-[#EAECEF] placeholder:text-zinc-500 outline-none resize-none max-h-32"
rows={1}
/>
<ComposerPrimitive.Send className="w-7 h-7 rounded-lg bg-sky-500 hover:bg-sky-400 text-zinc-950 flex items-center justify-center transition disabled:opacity-20 disabled:cursor-not-allowed">
<Send className="w-3.5 h-3.5" />
</ComposerPrimitive.Send>
</ComposerPrimitive.Root>
<div className="text-center text-[10.5px] text-zinc-500 mt-1.5">
Built with @assistant-ui/react primitives & Cloudflare Workers AI
</div>
</div>
</ThreadPrimitive.Root>
</div>
);
}
|