"use client"; import { useEffect, useState, useRef } from "react"; import { Brain, Send, MessageSquare, Plus, Trash2, Loader2, Wrench } from "lucide-react"; import { createClient } from "@/lib/supabase/client"; import { Button } from "poyraz-ui/atoms"; import { useChat } from "@ai-sdk/react"; interface ChatSession { id: string; title: string; created_at: string; } export default function AIChatPage() { const [supabase] = useState(() => createClient()); const [sessions, setSessions] = useState([]); const [activeSessionId, setActiveSessionId] = useState(null); const messagesEndRef = useRef(null); const { messages, input, setInput, handleInputChange, handleSubmit, append, setMessages, isLoading, stop } = useChat({ api: "/api/chat", body: { sessionId: activeSessionId }, onError: (err) => { console.error(err); } }); // Auto-scroll to bottom const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }; useEffect(() => { scrollToBottom(); }, [messages]); // 1. Fetch Sessions on mount useEffect(() => { const fetchSessions = async () => { const { data: { user } } = await supabase.auth.getUser(); if (!user) return; const { data } = await supabase .from("chat_sessions") .select("*") .eq("user_id", user.id) .order("updated_at", { ascending: false }); if (data) { setSessions(data); if (data.length > 0) { setActiveSessionId(data[0].id); } } }; fetchSessions(); }, [supabase]); // 2. Fetch Messages when session changes useEffect(() => { if (!activeSessionId) { setMessages([]); return; } const fetchMessages = async () => { const { data } = await supabase .from("chat_messages") .select("*") .eq("session_id", activeSessionId) .order("created_at", { ascending: true }); if (data) { // Map Supabase messages to AI SDK format const formattedMessages = data.map((msg: any) => ({ id: msg.id, role: msg.role as 'user' | 'assistant' | 'system', content: msg.content, })); setMessages(formattedMessages); } else { setMessages([]); } }; fetchMessages(); }, [activeSessionId, supabase, setMessages]); const handleNewChat = async () => { setActiveSessionId(null); setMessages([]); }; const handleDeleteSession = async (id: string, e: React.MouseEvent) => { e.stopPropagation(); await supabase.from("chat_sessions").delete().eq("id", id); const updatedSessions = sessions.filter(s => s.id !== id); setSessions(updatedSessions); if (activeSessionId === id) { setActiveSessionId(updatedSessions.length > 0 ? updatedSessions[0].id : null); if (updatedSessions.length === 0) setMessages([]); } }; const customHandleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!(input || "").trim() || isLoading) return; let sessionId = activeSessionId; const currentInput = input || ""; setInput(""); if (!sessionId) { const { data: { user } } = await supabase.auth.getUser(); if (!user) return; const { data: newSess } = await supabase .from("chat_sessions") .insert({ user_id: user.id, title: currentInput.slice(0, 30) + "..." }) .select() .single(); if (newSess) { sessionId = newSess.id; setActiveSessionId(sessionId); setSessions([newSess, ...sessions]); } else { return; } } // Append using AI SDK with explicit body to ensure sessionId is passed immediately append({ role: 'user', content: currentInput }, { body: { sessionId } }); }; return (
{/* Sidebar - Sessions List */}

Geçmiş Sohbetler

{sessions.length === 0 ? (
Henüz sohbet yok.
) : ( sessions.map(session => (
setActiveSessionId(session.id)} className={`group flex items-center justify-between p-3 rounded-md cursor-pointer transition-colors ${activeSessionId === session.id ? 'bg-primary/10 text-primary' : 'hover:bg-muted/50 text-foreground'}`} >
{session.title || "İsimsiz Sohbet"}
)) )}
{/* Main Chat Area */}
{/* Chat Header */}

Ajan Asistan

Sisteme görev ve veri ekleyebilir

{/* Messages */}
{messages.length === 0 ? (

Ajan Asistan'a Hoşgeldiniz

Sadece sorularınızı cevaplamakla kalmaz, komutlarınızla projeler, görevler ve finans kayıtları da oluşturabilir.

) : ( messages.map((msg) => (
{msg.role === 'user' ? ME : }
{msg.content && (
{msg.content}
)} {/* Render Tool Invocations for AI Messages */} {msg.toolInvocations && msg.toolInvocations.map((tool) => (
{tool.state === 'result' ? ( <> {tool.toolName} aracı başarıyla çalıştırıldı. ) : ( <> {tool.toolName} aracı çalıştırılıyor... )}
))}
)) )} {isLoading && messages[messages.length - 1]?.role === 'user' && (
)}
{/* Input Area */}