xonecas.io
5414
Sa

sat / files

sat / src / components / chat.tsx

18.0 KB
1"use client";
2
3import {
4  Bot,
5  ChevronRight,
6  Info,
7  Loader2,
8  Search,
9  SendHorizontal,
10  User,
11  Wrench,
12} from "lucide-react";
13import { useRouter } from "next/navigation";
14import { useCallback, useEffect, useRef, useState } from "react";
15import {
16  addTurn,
17  type ConversationWithTurns,
18  createConversation,
19  getConversation,
20} from "@/app/actions/conversations";
21import { MarkdownContent } from "@/components/markdown-content";
22import { Avatar, AvatarFallback } from "@/components/ui/avatar";
23import { Button } from "@/components/ui/button";
24import { Card, CardContent } from "@/components/ui/card";
25import {
26  Collapsible,
27  CollapsibleContent,
28  CollapsibleTrigger,
29} from "@/components/ui/collapsible";
30import { ScrollArea } from "@/components/ui/scroll-area";
31import { Textarea } from "@/components/ui/textarea";
32import { cn } from "@/lib/utils";
33
34interface ToolCall {
35  id: string;
36  name: string;
37  args: Record<string, unknown>;
38  status: "pending" | "complete";
39  result?: string;
40}
41
42interface Message {
43  id: string;
44  role: "user" | "assistant" | "system";
45  content: string;
46  reasoning?: string;
47  toolCalls?: ToolCall[];
48}
49
50interface ChatProps {
51  conversationId?: string;
52}
53
54export function Chat({ conversationId }: ChatProps) {
55  const router = useRouter();
56  const [messages, setMessages] = useState<Message[]>([]);
57  const [input, setInput] = useState("");
58  const [isStreaming, setIsStreaming] = useState(false);
59  const [isLoading, setIsLoading] = useState(false);
60  const [currentConversationId, setCurrentConversationId] = useState<
61    string | undefined
62  >(conversationId);
63  const messagesEndRef = useRef<HTMLDivElement>(null);
64  const textareaRef = useRef<HTMLTextAreaElement>(null);
65
66  // Load existing conversation turns
67  useEffect(() => {
68    async function loadConversation() {
69      if (!conversationId) {
70        setMessages([]);
71        setCurrentConversationId(undefined);
72        return;
73      }
74
75      setIsLoading(true);
76      try {
77        const conversation = await getConversation(conversationId);
78        if (conversation) {
79          setCurrentConversationId(conversationId);
80          setMessages(
81            conversation.turns.map(
82              (turn: ConversationWithTurns["turns"][number]) => ({
83                id: turn.id,
84                role: turn.role,
85                content: turn.content,
86                reasoning: turn.reasoning ?? undefined,
87                toolCalls: turn.toolCalls as ToolCall[] | undefined,
88              }),
89            ),
90          );
91        }
92      } catch (error) {
93        console.error("Failed to load conversation:", error);
94      } finally {
95        setIsLoading(false);
96      }
97    }
98
99    loadConversation();
100  }, [conversationId]);
101
102  const handleSubmit = useCallback(
103    async (e: React.FormEvent) => {
104      e.preventDefault();
105      const trimmedInput = input.trim();
106      if (!trimmedInput || isStreaming) return;
107
108      const userMessage: Message = {
109        id: crypto.randomUUID(),
110        role: "user",
111        content: trimmedInput,
112      };
113
114      const assistantMessageId = crypto.randomUUID();
115
116      setInput("");
117      setMessages((prev) => [...prev, userMessage]);
118      setIsStreaming(true);
119      textareaRef.current?.focus();
120
121      let assistantContent = "";
122      let assistantReasoning = "";
123      const toolCallsMap = new Map<string, ToolCall>();
124
125      // Track if we need to navigate after streaming completes
126      let shouldNavigate = false;
127      let newConversationId: string | undefined;
128
129      // Determine conversation ID - create new if needed
130      let activeConversationId = currentConversationId;
131      if (!activeConversationId) {
132        try {
133          const newConversation = await createConversation();
134          activeConversationId = newConversation.id;
135          setCurrentConversationId(activeConversationId);
136          // Mark for navigation after streaming completes (not now, to avoid unmounting)
137          shouldNavigate = true;
138          newConversationId = activeConversationId;
139        } catch (error) {
140          console.error("Failed to create conversation:", error);
141          setIsStreaming(false);
142          return;
143        }
144      }
145
146      // Persist user turn to DB
147      try {
148        await addTurn(activeConversationId, {
149          role: "user",
150          content: trimmedInput,
151        });
152      } catch (error) {
153        console.error("Failed to save user turn:", error);
154      }
155
156      const updateAssistantMessage = () => {
157        setMessages((prev) => {
158          const existing = prev.find((m) => m.id === assistantMessageId);
159          const newMessage: Message = {
160            id: assistantMessageId,
161            role: "assistant",
162            content: assistantContent,
163            reasoning: assistantReasoning || undefined,
164            toolCalls:
165              toolCallsMap.size > 0
166                ? Array.from(toolCallsMap.values())
167                : undefined,
168          };
169
170          if (existing) {
171            return prev.map((m) =>
172              m.id === assistantMessageId ? newMessage : m,
173            );
174          }
175          return [...prev, newMessage];
176        });
177      };
178
179      try {
180        const response = await fetch("/api/stream", {
181          method: "POST",
182          headers: { "Content-Type": "application/json" },
183          body: JSON.stringify({
184            userInput: trimmedInput,
185            conversationId: activeConversationId,
186          }),
187        });
188
189        if (!response.ok) {
190          throw new Error("Failed to get response");
191        }
192
193        const reader = response.body?.getReader();
194        if (!reader) throw new Error("No reader available");
195
196        const decoder = new TextDecoder();
197        let buffer = "";
198
199        while (true) {
200          const { done, value } = await reader.read();
201          if (done) break;
202
203          buffer += decoder.decode(value, { stream: true });
204
205          // Parse newline-delimited JSON events
206          const lines = buffer.split("\n");
207          buffer = lines.pop() ?? ""; // Keep incomplete line in buffer
208
209          for (const line of lines) {
210            if (!line.trim()) continue;
211
212            try {
213              const event = JSON.parse(line);
214
215              switch (event.type) {
216                case "token":
217                  // Accumulate content tokens
218                  assistantContent += event.content;
219                  break;
220                case "reasoning":
221                  // Accumulate reasoning tokens
222                  assistantReasoning += event.content;
223                  break;
224                case "tool_call":
225                  toolCallsMap.set(event.id, {
226                    id: event.id,
227                    name: event.name,
228                    args: event.args,
229                    status: "pending",
230                  });
231                  break;
232                case "tool_result": {
233                  const existing = toolCallsMap.get(event.id);
234                  if (existing) {
235                    toolCallsMap.set(event.id, {
236                      ...existing,
237                      status: "complete",
238                      result: event.result,
239                    });
240                  }
241                  break;
242                }
243                case "summarized": {
244                  // Insert a system notification message
245                  setMessages((prev) => [
246                    ...prev,
247                    {
248                      id: crypto.randomUUID(),
249                      role: "system",
250                      content: `Older messages have been summarized to maintain context (${event.messageCount} messages compressed).`,
251                    },
252                  ]);
253                  break;
254                }
255              }
256            } catch {
257              // Ignore parse errors for partial chunks
258            }
259          }
260
261          // Update UI after processing each chunk for real-time feedback
262          if (assistantContent || assistantReasoning || toolCallsMap.size > 0) {
263            updateAssistantMessage();
264          }
265        }
266
267        // Finalize: ensure assistant message exists even if empty
268        const finalContent =
269          assistantContent || "I apologize, I could not respond.";
270        setMessages((prev) => {
271          const hasAssistant = prev.some((m) => m.id === assistantMessageId);
272          if (!hasAssistant) {
273            return [
274              ...prev,
275              {
276                id: assistantMessageId,
277                role: "assistant",
278                content: finalContent,
279              },
280            ];
281          }
282          return prev;
283        });
284
285        // Persist assistant turn to DB
286        try {
287          await addTurn(activeConversationId, {
288            role: "assistant",
289            content: finalContent,
290            reasoning: assistantReasoning || null,
291            toolCalls:
292              toolCallsMap.size > 0 ? Array.from(toolCallsMap.values()) : null,
293          });
294        } catch (error) {
295          console.error("Failed to save assistant turn:", error);
296        }
297      } catch (error) {
298        console.error("Stream error:", error);
299        const errorContent =
300          "Sorry, there was an error processing your request. Please try again.";
301        setMessages((prev) => [
302          ...prev,
303          {
304            id: assistantMessageId,
305            role: "assistant",
306            content: errorContent,
307          },
308        ]);
309
310        // Persist error response to DB
311        try {
312          await addTurn(activeConversationId, {
313            role: "assistant",
314            content: errorContent,
315          });
316        } catch (persistError) {
317          console.error("Failed to save error turn:", persistError);
318        }
319      } finally {
320        setIsStreaming(false);
321        // Navigate to new conversation URL after streaming completes
322        if (shouldNavigate && newConversationId) {
323          router.push(`/conversation/${newConversationId}`, { scroll: false });
324        }
325      }
326    },
327    [input, isStreaming, currentConversationId, router],
328  );
329
330  const handleKeyDown = useCallback(
331    (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
332      if (e.key === "Enter" && !e.shiftKey) {
333        e.preventDefault();
334        handleSubmit(e);
335      }
336    },
337    [handleSubmit],
338  );
339
340  if (isLoading) {
341    return (
342      <div className="flex flex-1 items-center justify-center">
343        <Loader2 className="text-muted-foreground size-8 animate-spin" />
344      </div>
345    );
346  }
347
348  return (
349    <div className="flex flex-1 flex-col">
350      {/* Messages area */}
351      <ScrollArea className="flex-1 p-4">
352        <div className="mx-auto max-w-3xl space-y-4">
353          {messages.length === 0 ? (
354            <div className="flex h-[60vh] items-center justify-center">
355              <div className="text-center">
356                <Bot className="text-muted-foreground mx-auto size-12" />
357                <h2 className="mt-4 text-xl font-semibold">
358                  How can I help you today?
359                </h2>
360                <p className="text-muted-foreground mt-2">
361                  Ask me anything and I'll search the web for answers.
362                </p>
363              </div>
364            </div>
365          ) : (
366            messages.map((message) => (
367              <MessageBubble key={message.id} message={message} />
368            ))
369          )}
370
371          {isStreaming && !messages.some((m) => m.role === "assistant") && (
372            <div className="flex gap-3">
373              <Avatar>
374                <AvatarFallback>
375                  <Bot className="size-4" />
376                </AvatarFallback>
377              </Avatar>
378              <Card size="sm" className="max-w-[80%]">
379                <CardContent>
380                  <div className="flex items-center gap-2">
381                    <Loader2 className="size-4 animate-spin" />
382                    <span className="text-muted-foreground text-sm">
383                      Thinking...
384                    </span>
385                  </div>
386                </CardContent>
387              </Card>
388            </div>
389          )}
390
391          <div ref={messagesEndRef} />
392        </div>
393      </ScrollArea>
394
395      {/* Input area */}
396      <div className="border-border bg-background/95 supports-backdrop-filter:bg-background/60 border-t p-4 backdrop-blur">
397        <form onSubmit={handleSubmit} className="mx-auto max-w-3xl">
398          <div className="bg-muted/50 relative flex items-end gap-2 rounded-2xl p-2">
399            <Textarea
400              ref={textareaRef}
401              value={input}
402              onChange={(e) => setInput(e.target.value)}
403              onKeyDown={handleKeyDown}
404              placeholder="Ask me anything..."
405              className="min-h-[44px] flex-1 resize-none border-0 bg-transparent focus-visible:ring-0"
406              disabled={isStreaming}
407            />
408            <Button
409              type="submit"
410              size="icon"
411              disabled={!input.trim() || isStreaming}
412              className="shrink-0"
413            >
414              {isStreaming ? (
415                <Loader2 className="size-4 animate-spin" />
416              ) : (
417                <SendHorizontal className="size-4" />
418              )}
419            </Button>
420          </div>
421          <p className="text-muted-foreground mt-2 text-center text-xs">
422            Press Enter to send, Shift+Enter for new line
423          </p>
424        </form>
425      </div>
426    </div>
427  );
428}
429
430function MessageBubble({ message }: { message: Message }) {
431  const isUser = message.role === "user";
432  const isSystem = message.role === "system";
433
434  // System messages are rendered as centered info cards
435  if (isSystem) {
436    return (
437      <div className="flex justify-center">
438        <Card size="sm" className="bg-muted/50 border-dashed">
439          <CardContent className="text-muted-foreground flex items-center gap-2 text-sm">
440            <Info className="size-4" />
441            {message.content}
442          </CardContent>
443        </Card>
444      </div>
445    );
446  }
447
448  return (
449    <div className={cn("flex gap-3", isUser && "flex-row-reverse")}>
450      <Avatar className={cn(isUser && "bg-primary text-primary-foreground")}>
451        <AvatarFallback
452          className={cn(isUser && "bg-primary text-primary-foreground")}
453        >
454          {isUser ? <User className="size-4" /> : <Bot className="size-4" />}
455        </AvatarFallback>
456      </Avatar>
457
458      {isUser ? (
459        <Card size="sm" className="max-w-[80%]">
460          <CardContent>
461            <p className="whitespace-pre-wrap">{message.content}</p>
462          </CardContent>
463        </Card>
464      ) : (
465        <Card size="sm" className="max-w-[80%]">
466          {/* Reasoning section */}
467          {message.reasoning && (
468            <CardContent>
469              {(() => {
470                const lines = message.reasoning.split("\n");
471                const visibleLines = lines.slice(-5).join("\n");
472                const hiddenLines = lines.slice(0, -5).join("\n");
473                const hasHiddenContent = lines.length > 5;
474
475                return (
476                  <Collapsible>
477                    <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">
478                      <ChevronRight className="size-3 transition-transform" />
479                      <span>Show more reasoning</span>
480                    </CollapsibleTrigger>
481                    {hasHiddenContent && (
482                      <CollapsibleContent>
483                        <p className="text-muted-foreground whitespace-pre-wrap text-xs mt-2">
484                          {hiddenLines}
485                        </p>
486                      </CollapsibleContent>
487                    )}
488                    <p className="text-muted-foreground whitespace-pre-wrap text-xs">
489                      {visibleLines}
490                    </p>
491                  </Collapsible>
492                );
493              })()}
494            </CardContent>
495          )}
496
497          {/* Tool calls section */}
498          {message.toolCalls && message.toolCalls.length > 0 && (
499            <CardContent className="space-y-1">
500              {message.toolCalls.map((tc) => (
501                <ToolCallBubble key={tc.id} toolCall={tc} />
502              ))}
503            </CardContent>
504          )}
505
506          {/* Main content */}
507          {message.content && (
508            <CardContent>
509              <MarkdownContent content={message.content} />
510            </CardContent>
511          )}
512        </Card>
513      )}
514    </div>
515  );
516}
517
518function ToolCallBubble({ toolCall }: { toolCall: ToolCall }) {
519  return (
520    <Collapsible className="my-4">
521      <Card size="sm">
522        <CardContent>
523          <div className="flex items-center gap-2">
524            {toolCall.status === "pending" ? (
525              <Loader2 className="size-3 animate-spin" />
526            ) : (
527              <Wrench className="size-3" />
528            )}
529            <span className="text-xs font-medium">
530              Calling {toolCall.name}
531              {typeof toolCall.args.query === "string" &&
532                toolCall.args.query && (
533                  <span className="text-muted-foreground font-normal">
534                    {" "}
535                    with "{toolCall.args.query}"
536                  </span>
537                )}
538            </span>
539            {toolCall.status === "complete" && (
540              <span className="text-muted-foreground text-xs">✓</span>
541            )}
542          </div>
543
544          {toolCall.result && (
545            <>
546              <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">
547                <ChevronRight className="size-3 transition-transform" />
548                <span>View results</span>
549              </CollapsibleTrigger>
550              <CollapsibleContent>
551                <ScrollArea className="mt-2 max-h-48">
552                  <pre className="bg-muted/50 rounded p-2 text-xs">
553                    {toolCall.result.length > 2000
554                      ? `${toolCall.result.slice(0, 2000)}...`
555                      : toolCall.result}
556                  </pre>
557                </ScrollArea>
558              </CollapsibleContent>
559            </>
560          )}
561        </CardContent>
562      </Card>
563    </Collapsible>
564  );
565}