@@ -0,0 +1,416 @@
1+"use client";
2+
3+import {
4+ Bot,
5+ ChevronRight,
6+ Loader2,
7+ Search,
8+ SendHorizontal,
9+ User,
10+ Wrench,
11+} from "lucide-react";
12+import { useCallback, useEffect, useRef, useState } from "react";
13+import { Avatar, AvatarFallback } from "@/components/ui/avatar";
14+import { Button } from "@/components/ui/button";
15+import { Card, CardContent } from "@/components/ui/card";
16+import {
17+ Collapsible,
18+ CollapsibleContent,
19+ CollapsibleTrigger,
20+} from "@/components/ui/collapsible";
21+import { ScrollArea } from "@/components/ui/scroll-area";
22+import { Textarea } from "@/components/ui/textarea";
23+import { cn } from "@/lib/utils";
24+
25+interface ToolCall {
26+ id: string;
27+ name: string;
28+ args: Record<string, unknown>;
29+ status: "pending" | "complete";
30+ result?: string;
31+}
32+
33+interface Message {
34+ id: string;
35+ role: "user" | "assistant";
36+ content: string;
37+ reasoning?: string;
38+ toolCalls?: ToolCall[];
39+}
40+
41+export function Chat() {
42+ const [messages, setMessages] = useState<Message[]>([]);
43+ const [input, setInput] = useState("");
44+ const [isStreaming, setIsStreaming] = useState(false);
45+ const messagesEndRef = useRef<HTMLDivElement>(null);
46+ const textareaRef = useRef<HTMLTextAreaElement>(null);
47+
48+ const scrollToBottom = useCallback(() => {
49+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
50+ }, []);
51+
52+ useEffect(() => {
53+ scrollToBottom();
54+ }, [messages, scrollToBottom]);
55+
56+ const handleSubmit = useCallback(
57+ async (e: React.FormEvent) => {
58+ e.preventDefault();
59+ const trimmedInput = input.trim();
60+ if (!trimmedInput || isStreaming) return;
61+
62+ const userMessage: Message = {
63+ id: crypto.randomUUID(),
64+ role: "user",
65+ content: trimmedInput,
66+ };
67+
68+ const assistantMessageId = crypto.randomUUID();
69+
70+ setInput("");
71+ setMessages((prev) => [...prev, userMessage]);
72+ setIsStreaming(true);
73+ textareaRef.current?.focus();
74+
75+ let assistantContent = "";
76+ let assistantReasoning = "";
77+ const toolCallsMap = new Map<string, ToolCall>();
78+
79+ const updateAssistantMessage = () => {
80+ setMessages((prev) => {
81+ const existing = prev.find((m) => m.id === assistantMessageId);
82+ const newMessage: Message = {
83+ id: assistantMessageId,
84+ role: "assistant",
85+ content: assistantContent,
86+ reasoning: assistantReasoning || undefined,
87+ toolCalls:
88+ toolCallsMap.size > 0
89+ ? Array.from(toolCallsMap.values())
90+ : undefined,
91+ };
92+
93+ if (existing) {
94+ return prev.map((m) =>
95+ m.id === assistantMessageId ? newMessage : m,
96+ );
97+ }
98+ return [...prev, newMessage];
99+ });
100+ };
101+
102+ try {
103+ const response = await fetch("/api/stream", {
104+ method: "POST",
105+ headers: { "Content-Type": "application/json" },
106+ body: JSON.stringify({ userInput: trimmedInput }),
107+ });
108+
109+ if (!response.ok) {
110+ throw new Error("Failed to get response");
111+ }
112+
113+ const reader = response.body?.getReader();
114+ if (!reader) throw new Error("No reader available");
115+
116+ const decoder = new TextDecoder();
117+ let buffer = "";
118+
119+ while (true) {
120+ const { done, value } = await reader.read();
121+ if (done) break;
122+
123+ buffer += decoder.decode(value, { stream: true });
124+
125+ // Parse newline-delimited JSON events
126+ const lines = buffer.split("\n");
127+ buffer = lines.pop() ?? ""; // Keep incomplete line in buffer
128+
129+ for (const line of lines) {
130+ if (!line.trim()) continue;
131+
132+ try {
133+ const event = JSON.parse(line);
134+
135+ switch (event.type) {
136+ case "token":
137+ // Accumulate content tokens
138+ assistantContent += event.content;
139+ break;
140+ case "reasoning":
141+ // Accumulate reasoning tokens
142+ assistantReasoning += event.content;
143+ break;
144+ case "tool_call":
145+ toolCallsMap.set(event.id, {
146+ id: event.id,
147+ name: event.name,
148+ args: event.args,
149+ status: "pending",
150+ });
151+ break;
152+ case "tool_result": {
153+ const existing = toolCallsMap.get(event.id);
154+ if (existing) {
155+ toolCallsMap.set(event.id, {
156+ ...existing,
157+ status: "complete",
158+ result: event.result,
159+ });
160+ }
161+ break;
162+ }
163+ }
164+ } catch {
165+ // Ignore parse errors for partial chunks
166+ }
167+ }
168+
169+ // Update UI after processing each chunk for real-time feedback
170+ if (assistantContent || assistantReasoning || toolCallsMap.size > 0) {
171+ updateAssistantMessage();
172+ }
173+ }
174+
175+ // Finalize: ensure assistant message exists even if empty
176+ setMessages((prev) => {
177+ const hasAssistant = prev.some((m) => m.id === assistantMessageId);
178+ if (!hasAssistant) {
179+ return [
180+ ...prev,
181+ {
182+ id: assistantMessageId,
183+ role: "assistant",
184+ content: "I apologize, I could not respond.",
185+ },
186+ ];
187+ }
188+ return prev;
189+ });
190+ } catch (error) {
191+ console.error("Stream error:", error);
192+ setMessages((prev) => [
193+ ...prev,
194+ {
195+ id: assistantMessageId,
196+ role: "assistant",
197+ content:
198+ "Sorry, there was an error processing your request. Please try again.",
199+ },
200+ ]);
201+ } finally {
202+ setIsStreaming(false);
203+ }
204+ },
205+ [input, isStreaming],
206+ );
207+
208+ const handleKeyDown = useCallback(
209+ (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
210+ if (e.key === "Enter" && !e.shiftKey) {
211+ e.preventDefault();
212+ handleSubmit(e);
213+ }
214+ },
215+ [handleSubmit],
216+ );
217+
218+ return (
219+ <div className="flex flex-1 flex-col">
220+ {/* Messages area */}
221+ <ScrollArea className="flex-1 p-4">
222+ <div className="mx-auto max-w-3xl space-y-4">
223+ {messages.length === 0 ? (
224+ <div className="flex h-[60vh] items-center justify-center">
225+ <div className="text-center">
226+ <Bot className="text-muted-foreground mx-auto size-12" />
227+ <h2 className="mt-4 text-xl font-semibold">
228+ How can I help you today?
229+ </h2>
230+ <p className="text-muted-foreground mt-2">
231+ Ask me anything and I'll search the web for answers.
232+ </p>
233+ </div>
234+ </div>
235+ ) : (
236+ messages.map((message) => (
237+ <MessageBubble key={message.id} message={message} />
238+ ))
239+ )}
240+
241+ {isStreaming && !messages.some((m) => m.role === "assistant") && (
242+ <div className="flex gap-3">
243+ <Avatar>
244+ <AvatarFallback>
245+ <Bot className="size-4" />
246+ </AvatarFallback>
247+ </Avatar>
248+ <Card size="sm" className="max-w-[80%]">
249+ <CardContent>
250+ <div className="flex items-center gap-2">
251+ <Loader2 className="size-4 animate-spin" />
252+ <span className="text-muted-foreground text-sm">
253+ Thinking...
254+ </span>
255+ </div>
256+ </CardContent>
257+ </Card>
258+ </div>
259+ )}
260+
261+ <div ref={messagesEndRef} />
262+ </div>
263+ </ScrollArea>
264+
265+ {/* Input area */}
266+ <div className="border-border bg-background/95 supports-backdrop-filter:bg-background/60 border-t p-4 backdrop-blur">
267+ <form onSubmit={handleSubmit} className="mx-auto max-w-3xl">
268+ <div className="bg-muted/50 relative flex items-end gap-2 rounded-2xl p-2">
269+ <Textarea
270+ ref={textareaRef}
271+ value={input}
272+ onChange={(e) => setInput(e.target.value)}
273+ onKeyDown={handleKeyDown}
274+ placeholder="Ask me anything..."
275+ className="min-h-[44px] flex-1 resize-none border-0 bg-transparent focus-visible:ring-0"
276+ disabled={isStreaming}
277+ />
278+ <Button
279+ type="submit"
280+ size="icon"
281+ disabled={!input.trim() || isStreaming}
282+ className="shrink-0"
283+ >
284+ {isStreaming ? (
285+ <Loader2 className="size-4 animate-spin" />
286+ ) : (
287+ <SendHorizontal className="size-4" />
288+ )}
289+ </Button>
290+ </div>
291+ <p className="text-muted-foreground mt-2 text-center text-xs">
292+ Press Enter to send, Shift+Enter for new line
293+ </p>
294+ </form>
295+ </div>
296+ </div>
297+ );
298+}
299+
300+function MessageBubble({ message }: { message: Message }) {
301+ const isUser = message.role === "user";
302+
303+ return (
304+ <div className={cn("flex gap-3", isUser && "flex-row-reverse")}>
305+ <Avatar className={cn(isUser && "bg-primary text-primary-foreground")}>
306+ <AvatarFallback
307+ className={cn(isUser && "bg-primary text-primary-foreground")}
308+ >
309+ {isUser ? <User className="size-4" /> : <Bot className="size-4" />}
310+ </AvatarFallback>
311+ </Avatar>
312+
313+ {isUser ? (
314+ <Card
315+ size="sm"
316+ className="bg-primary text-primary-foreground max-w-[80%]"
317+ >
318+ <CardContent>
319+ <p className="whitespace-pre-wrap">{message.content}</p>
320+ </CardContent>
321+ </Card>
322+ ) : (
323+ <Card size="sm" className="max-w-[80%]">
324+ {/* Reasoning section */}
325+ {message.reasoning && (
326+ <CardContent>
327+ <Collapsible defaultOpen>
328+ <div className="border-muted-foreground/20 bg-muted/30 rounded-lg border p-2">
329+ <CollapsibleTrigger className="text-muted-foreground hover:text-foreground flex w-full items-center gap-1 text-xs transition-colors [&[data-state=open]>svg:first-child]:rotate-90">
330+ <ChevronRight className="size-3 transition-transform" />
331+ <span>Thinking...</span>
332+ </CollapsibleTrigger>
333+ <CollapsibleContent>
334+ <p className="text-muted-foreground mt-2 whitespace-pre-wrap text-xs">
335+ {message.reasoning}
336+ </p>
337+ </CollapsibleContent>
338+ </div>
339+ </Collapsible>
340+ </CardContent>
341+ )}
342+
343+ {/* Tool calls section */}
344+ {message.toolCalls && message.toolCalls.length > 0 && (
345+ <CardContent className="space-y-1">
346+ {message.toolCalls.map((tc) => (
347+ <ToolCallBubble key={tc.id} toolCall={tc} />
348+ ))}
349+ </CardContent>
350+ )}
351+
352+ {/* Main content */}
353+ {message.content && (
354+ <CardContent>
355+ <p className="whitespace-pre-wrap">{message.content}</p>
356+ </CardContent>
357+ )}
358+ </Card>
359+ )}
360+ </div>
361+ );
362+}
363+
364+function ToolCallBubble({ toolCall }: { toolCall: ToolCall }) {
365+ const isSearch = toolCall.name === "search_web";
366+
367+ return (
368+ <Collapsible>
369+ <Card size="sm" className="border-blue-500/20 bg-blue-500/5">
370+ <CardContent>
371+ <div className="flex items-center gap-2">
372+ {toolCall.status === "pending" ? (
373+ <Loader2 className="size-3 animate-spin text-blue-500" />
374+ ) : isSearch ? (
375+ <Search className="size-3 text-blue-500" />
376+ ) : (
377+ <Wrench className="size-3 text-blue-500" />
378+ )}
379+ <span className="text-xs font-medium">
380+ {isSearch ? "Searching" : toolCall.name}
381+ {isSearch &&
382+ typeof toolCall.args.query === "string" &&
383+ toolCall.args.query && (
384+ <span className="text-muted-foreground font-normal">
385+ {" "}
386+ for "{toolCall.args.query}"
387+ </span>
388+ )}
389+ </span>
390+ {toolCall.status === "complete" && (
391+ <span className="text-muted-foreground text-xs">✓</span>
392+ )}
393+ </div>
394+
395+ {toolCall.result && (
396+ <>
397+ <CollapsibleTrigger className="text-muted-foreground hover:text-foreground mt-1 flex items-center gap-1 text-xs transition-colors [&[data-state=open]>svg:first-child]:rotate-90">
398+ <ChevronRight className="size-3 transition-transform" />
399+ <span>View results</span>
400+ </CollapsibleTrigger>
401+ <CollapsibleContent>
402+ <ScrollArea className="mt-2 max-h-48">
403+ <pre className="bg-muted/50 rounded p-2 text-xs">
404+ {toolCall.result.length > 2000
405+ ? `${toolCall.result.slice(0, 2000)}...`
406+ : toolCall.result}
407+ </pre>
408+ </ScrollArea>
409+ </CollapsibleContent>
410+ </>
411+ )}
412+ </CardContent>
413+ </Card>
414+ </Collapsible>
415+ );
416+}