'use client'; import React, { useState, useEffect, useRef } from 'react'; import { api } from '../../services/api'; export default function AIChatPanel({ sessionId }) { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const chatEndRef = useRef(null); useEffect(() => { if (sessionId) { loadHistory(); } }, [sessionId]); const loadHistory = async () => { try { const history = await api.getChatHistory(sessionId); if (Array.isArray(history)) setMessages(history); } catch (err) { console.error("Failed to load chat history:", err); } }; const handleSend = async (e) => { e.preventDefault(); if (!input.trim() || !sessionId || loading) return; const userMessage = { role: 'user', content: input }; setMessages((prev) => [...prev, userMessage]); const currentPrompt = input; setInput(''); setLoading(true); try { const res = await api.sendChatMessage(sessionId, 'user', currentPrompt); if (res && res.content) { setMessages((prev) => [...prev, { role: 'assistant', content: res.content }]); } } catch (err) { setMessages((prev) => [...prev, { role: 'assistant', content: "Error communicating with AI agent." }]); } finally { setLoading(false); chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); } }; return (
AI Workspace Assistant
{messages.map((msg, idx) => (
{msg.role}
{msg.content}
))} {loading && (
AI is thinking & generating code...
)}
setInput(e.target.value)} placeholder="Ask AI to generate code..." className="flex-1 bg-slate-800 border border-slate-700 rounded px-3 py-1.5 text-xs text-white focus:outline-none focus:border-blue-500" />
); }