@@ -332,10 +159,10 @@ export default function Agents() {
-
{agent.name}
+
{agent.nome_agente}
- v{agent.version}
+ v{agent.versao_agente}
@@ -349,20 +176,20 @@ export default function Agents() {
Modelo de IA
-
{agent.model}
+
{agent.modelo_ia}
Status
-
- {agent.status === "active" ? "● Ativo" : "○ Inativo"}
+ {agent.status === "ativo" ? "● Ativo" : "○ Inativo"}
diff --git a/src/pages/TestPrompt.tsx b/src/pages/TestPrompt.tsx
index 6dfae44..21acd5f 100644
--- a/src/pages/TestPrompt.tsx
+++ b/src/pages/TestPrompt.tsx
@@ -1,10 +1,11 @@
import { useState, useRef, useEffect } from "react";
+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ScrollArea } from "@/components/ui/scroll-area";
-import { Send, Bot, User, RotateCcw, MessageSquare, Plus, Trash2 } from "lucide-react";
+import { Send, Bot, User, MessageSquare, Plus, Trash2, Loader2 } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import {
Select,
@@ -13,56 +14,108 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
-import { Separator } from "@/components/ui/separator";
-
-type Message = {
- id: string;
- role: "user" | "assistant";
- content: string;
-};
-
-type Conversation = {
- id: string;
- agentId: string;
- agentName: string;
- title: string;
- messages: Message[];
- createdAt: string;
- updatedAt: string;
-};
+import { listAgents } from "@/lib/api/agents";
+import { testAgent, listChats, listMessages, deleteChat } from "@/lib/api/chat";
export default function TestPrompt() {
const [input, setInput] = useState("");
- const [messages, setMessages] = useState
([]);
- const [isLoading, setIsLoading] = useState(false);
const [selectedAgent, setSelectedAgent] = useState("");
- const [conversations, setConversations] = useState([]);
- const [currentConversationId, setCurrentConversationId] = useState(null);
+ const [currentChatId, setCurrentChatId] = useState(null);
const scrollRef = useRef(null);
const { toast } = useToast();
+ const queryClient = useQueryClient();
- // Mock data de agentes
- const agents = [
- { id: "1", name: "Agente de Atendimento" },
- { id: "2", name: "Agente de Vendas" },
- { id: "3", name: "Agente de Análise" },
- ];
+ // Fetch active agents from API
+ const {
+ data: agentsData,
+ isLoading: isLoadingAgents,
+ } = useQuery({
+ queryKey: ["agents-active"],
+ queryFn: () => listAgents(undefined, 1, 100), // Fetch all agents
+ });
- // Carrega conversas do localStorage
- useEffect(() => {
- const stored = localStorage.getItem("test_conversations");
- if (stored) {
- setConversations(JSON.parse(stored));
- }
- }, []);
+ // Filter only active agents
+ const agents =
+ agentsData?.data
+ .filter((agent) => agent.status === "ativo")
+ .map((agent) => ({
+ id: agent.agente_id,
+ name: agent.nome_agente,
+ })) || [];
- // Salva conversas no localStorage
- useEffect(() => {
- if (conversations.length > 0) {
- localStorage.setItem("test_conversations", JSON.stringify(conversations));
- }
- }, [conversations]);
+ // Fetch all chats
+ const {
+ data: chats = [],
+ isLoading: isLoadingChats,
+ } = useQuery({
+ queryKey: ["chats"],
+ queryFn: listChats,
+ });
+ // Fetch messages for current chat
+ const {
+ data: messages = [],
+ isLoading: isLoadingMessages,
+ } = useQuery({
+ queryKey: ["messages", currentChatId],
+ queryFn: () => listMessages(currentChatId!),
+ enabled: !!currentChatId,
+ });
+
+ // Send message mutation
+ const sendMessageMutation = useMutation({
+ mutationFn: ({
+ agentId,
+ chatId,
+ message,
+ }: {
+ agentId: string;
+ chatId: string;
+ message: string;
+ }) => testAgent(agentId, chatId, message),
+ onSuccess: (data) => {
+ // If this was a new chat (chat_id: "0"), store the returned chat_id
+ if (!currentChatId && data.chat_id) {
+ setCurrentChatId(data.chat_id);
+ }
+
+ // Refresh messages and chats list after sending
+ // The queryKey will automatically update when currentChatId changes
+ queryClient.invalidateQueries({ queryKey: ["messages", data.chat_id] });
+ queryClient.invalidateQueries({ queryKey: ["chats"] });
+ },
+ onError: (error: any) => {
+ toast({
+ title: "Erro ao enviar mensagem",
+ description: error.response?.data?.message || "Ocorreu um erro ao enviar a mensagem.",
+ variant: "destructive",
+ });
+ },
+ });
+
+ // Delete chat mutation
+ const deleteChatMutation = useMutation({
+ mutationFn: (chatId: string) => deleteChat(chatId),
+ onSuccess: () => {
+ toast({
+ title: "Conversa excluída",
+ description: "A conversa foi removida com sucesso.",
+ });
+ queryClient.invalidateQueries({ queryKey: ["chats"] });
+ if (currentChatId === currentChatId) {
+ setCurrentChatId(null);
+ }
+ },
+ onError: (error: any) => {
+ toast({
+ title: "Erro ao excluir conversa",
+ description: error.response?.data?.message || "Ocorreu um erro ao excluir a conversa.",
+ variant: "destructive",
+ });
+ },
+ });
+
+ // Auto-scroll to bottom when messages change
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
@@ -71,81 +124,35 @@ export default function TestPrompt() {
const handleNewConversation = () => {
if (!selectedAgent) return;
-
- const agent = agents.find((a) => a.id === selectedAgent);
- const newConversation: Conversation = {
- id: Date.now().toString(),
- agentId: selectedAgent,
- agentName: agent?.name || "Agente",
- title: "Nova Conversa",
- messages: [],
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- };
- setConversations((prev) => [newConversation, ...prev]);
- setCurrentConversationId(newConversation.id);
- setMessages([]);
+ // Reset chat ID to null (indicating a new conversation)
+ // The first message will send chat_id: "0" and the API will return the real chat_id
+ setCurrentChatId(null);
};
- const handleSelectConversation = (conversationId: string) => {
- const conversation = conversations.find((c) => c.id === conversationId);
- if (conversation) {
- setCurrentConversationId(conversationId);
- setSelectedAgent(conversation.agentId);
- setMessages(conversation.messages);
+ const handleSelectConversation = (chatId: string) => {
+ const chat = chats.find((c) => c.id === chatId);
+ if (chat) {
+ setCurrentChatId(chatId);
+ setSelectedAgent(chat.agent_id);
}
};
- const updateConversation = (newMessages: Message[]) => {
- if (!currentConversationId) return;
-
- setConversations((prev) =>
- prev.map((conv) => {
- if (conv.id === currentConversationId) {
- const title =
- newMessages.length > 0
- ? newMessages[0].content.substring(0, 50) + "..."
- : "Nova Conversa";
- return {
- ...conv,
- messages: newMessages,
- title,
- updatedAt: new Date().toISOString(),
- };
- }
- return conv;
- })
- );
- };
-
const handleSend = () => {
if (!input.trim() || !selectedAgent) return;
- const userMessage: Message = {
- id: Date.now().toString(),
- role: "user",
- content: input,
- };
+ // If no chat is selected (new conversation), send chat_id: "0"
+ // The API will return the real chat_id which will be stored in the mutation's onSuccess
+ const chatId = currentChatId || "0";
- const newMessages = [...messages, userMessage];
- setMessages(newMessages);
- updateConversation(newMessages);
+ const message = input.trim();
setInput("");
- setIsLoading(true);
- setTimeout(() => {
- const aiMessage: Message = {
- id: (Date.now() + 1).toString(),
- role: "assistant",
- content:
- "Esta é uma resposta simulada do agente de IA. Em produção, esta resposta seria gerada pelo modelo de IA configurado no agente selecionado.",
- };
- const finalMessages = [...newMessages, aiMessage];
- setMessages(finalMessages);
- updateConversation(finalMessages);
- setIsLoading(false);
- }, 1500);
+ sendMessageMutation.mutate({
+ agentId: selectedAgent,
+ chatId,
+ message,
+ });
};
const handleKeyPress = (e: React.KeyboardEvent) => {
@@ -155,16 +162,8 @@ export default function TestPrompt() {
}
};
- const handleDeleteConversation = (conversationId: string) => {
- setConversations((prev) => prev.filter((c) => c.id !== conversationId));
- if (currentConversationId === conversationId) {
- setCurrentConversationId(null);
- setMessages([]);
- }
- toast({
- title: "Conversa excluída",
- description: "A conversa foi removida com sucesso.",
- });
+ const handleDeleteConversation = (chatId: string) => {
+ deleteChatMutation.mutate(chatId);
};
return (
@@ -176,57 +175,64 @@ export default function TestPrompt() {